Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
AutoMix: segue policy, guards, score and fallback order
kota-zob0df1d7759c6
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/Analyzer.kt b/base/automix/src/main/kotlin/app/myspoti/automix/Analyzer.ktindex ac30de09..08fb6a21 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/Analyzer.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/Analyzer.kt@@ -118,7 +118,7 @@ object Analyzer {val barStarts = starts.toDoubleArray()val bars = barStarts.sizeval barDb = FloatArray(bars); val barLow = FloatArray(bars); val barHigh = FloatArray(bars); val barMid = FloatArray(bars)- val barOnset = FloatArray(bars); val barCentre = FloatArray(bars); val absoluteCentre = FloatArray(bars)+ val barOnset = FloatArray(bars); val barCentre = FloatArray(bars); val absoluteCentre = FloatArray(bars); val barBass = FloatArray(bars)val barChroma = Array(bars) { FloatArray(12) }val centreMedian = if (f.stereo) percentile(f.centre, 0.5) else 0ffor (i in 0 until bars) {@@ -126,7 +126,7 @@ object Analyzer {val b = if (i + 1 < bars) barStarts[i + 1] else min(contentEnd, a + 4 * 60 / bpm)val fa = (a * FPS).toInt().coerceIn(0, n - 1); val fb = (b * FPS).toInt().coerceIn(fa + 1, n)barDb[i] = powerMean(f.rmsDb, fa, fb); barLow[i] = powerMean(f.lowDb, fa, fb)- barHigh[i] = powerMean(f.highDb, fa, fb); barMid[i] = powerMean(f.midDb, fa, fb)+ barHigh[i] = powerMean(f.highDb, fa, fb); barMid[i] = powerMean(f.midDb, fa, fb); barBass[i] = powerMean(f.bassDb, fa, fb)var o = 0.0; for (j in fa until fb) o += env[j]; barOnset[i] = (o / (fb - fa)).toFloat()val ca = (a * Features.CHROMA_FPS).toInt().coerceIn(0, f.chroma.size - 1)val cb = (b * Features.CHROMA_FPS).toInt().coerceIn(ca + 1, f.chroma.size)@@ -150,13 +150,48 @@ object Analyzer {return g.beat(Math.round(g.index(bar)).toInt())}val headDown = downOn(head, headSpan); val tailDown = downOn(tail, tailSpan)+ // How clearly those votes chose one phase: 0 for four equal phases or no vote, 1 for a single one.+ fun metre(g: Grid?, span: Pair<Double, Double>): Float {+ if (g == null) return 0f+ val vote = DoubleArray(4)+ for ((t, v) in modelDowns) if (t in max(span.first, g.first - g.period)..min(span.second, g.last + g.period)) {+ val k = Math.round(g.index(t)).toInt()+ if (abs(g.beat(k) - t) < g.period * 0.3) vote[Math.floorMod(k, 4)] += max(0f, v).toDouble()+ }+ val sum = vote.sum()+ return if (sum <= 0) 0f else (((vote.max() / sum) - 0.25) / 0.75).toFloat().coerceIn(0f, 1f)+ }val novelty = novelty(arrayOf(barDb, barLow, barMid, barHigh, barOnset), barChroma)val phraseOffset = phraseOffset(novelty)val vocalRisk = VocalRisk.estimate(barDb, barMid, absoluteCentre, barCentre, f.stereo)val (key, keyStrength) = key(f, level, gate)val loud = loudness(f.rmsDb, peak - 20f)return TrackAnalysis(f.durationSec, contentStart, contentEnd, loud, key, keyStrength, bpm, steady, head, tail,- beats, barStarts, barDb, barLow, barHigh, barCentre, novelty, phraseOffset, f.stereo, headDown, tailDown, why.toString().trimEnd(' ', ';'), vocalRisk)+ beats, barStarts, barDb, barLow, barHigh, barCentre, novelty, phraseOffset, f.stereo, headDown, tailDown, why.toString().trimEnd(' ', ';'), vocalRisk,+ signalKey(mid, side), barBass, phaseStats(head, mb, headSpan), phaseStats(tail, mb, tailSpan), metre(head, headSpan), metre(tail, tailSpan))+ }++ /** The model's beats against a grid: median and 95th percentile of their distance; null with too few to tell. */+ private fun phaseStats(g: Grid?, modelBeats: DoubleArray, span: Pair<Double, Double>): PhaseStats? {+ if (g == null) return null+ val gaps = modelBeats.filter { it in max(span.first, g.first - g.period / 2)..min(span.second, g.last + g.period / 2) }+ .map { t -> abs(t - g.beat(Math.round(g.index(t)).toInt())) }.filter { it < g.period * 0.25 }.sorted()+ if (gaps.size < 8) return null+ return PhaseStats(Math.round(gaps[gaps.size / 2] * 1e6), Math.round(gaps[(gaps.size * 0.95).toInt().coerceAtMost(gaps.size - 1)] * 1e6))+ }++ /** SHA-256 of the signal the analysis read. */+ private fun signalKey(mid: FloatArray, side: FloatArray?): String {+ val digest = java.security.MessageDigest.getInstance("SHA-256")+ val bytes = java.nio.ByteBuffer.allocate(64 * 1024).order(java.nio.ByteOrder.LITTLE_ENDIAN)+ for (signal in listOfNotNull(mid, side)) {+ for (v in signal) {+ bytes.putFloat(v)+ if (!bytes.hasRemaining()) { digest.update(bytes.array(), 0, bytes.position()); bytes.clear() }+ }+ }+ digest.update(bytes.array(), 0, bytes.position())+ return digest.digest().joinToString("") { "%02x".format(it) }}/**diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/Features.kt b/base/automix/src/main/kotlin/app/myspoti/automix/Features.ktindex 6c8ab421..bad714bf 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/Features.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/Features.kt@@ -1,6 +1,8 @@/* SPDX-License-Identifier: GPL-3.0-only */package app.myspoti.automix+import kotlin.math.ceil+import kotlin.math.floorimport kotlin.math.lnimport kotlin.math.log10import kotlin.math.log2@@ -19,6 +21,8 @@ class Features private constructor(val bassOnset: FloatArray,/** Band levels in dB per onset frame: low (< 180 Hz), mid (180 Hz – 2.5 kHz), high (> 2.5 kHz), all. */val lowDb: FloatArray, val midDb: FloatArray, val highDb: FloatArray, val rmsDb: FloatArray,+ /** Level in dB per onset frame of the band where two bass lines mask each other ([SegueTuning.BASS_LOW_HZ] to [SegueTuning.BASS_HIGH_HZ]). */+ val bassDb: FloatArray,/** Pitch-class profile, 12 values per chroma frame ([CHROMA_HOP] samples apart). */val chroma: Array<FloatArray>,/** Voice-band (300 Hz – 3.4 kHz) level of the mid signal over the side signal, in dB per chroma frame. */@@ -62,10 +66,12 @@ class Features private constructor(val bassBands = (0 until BANDS).count { edges[it + 1] * binHz <= 150.0 }.coerceAtLeast(2)val lowBin = (LOW_HZ / binHz).toInt()val highBin = (HIGH_HZ / binHz).toInt()+ val bassFrom = ceil(app.myspoti.automix.segue.SegueTuning.BASS_LOW_HZ / binHz).toInt().coerceAtLeast(1)+ val bassTo = floor(app.myspoti.automix.segue.SegueTuning.BASS_HIGH_HZ / binHz).toInt()val onset = FloatArray(frames)val bassOnset = FloatArray(frames)- val lowDb = FloatArray(frames); val midDb = FloatArray(frames); val highDb = FloatArray(frames); val rmsDb = FloatArray(frames)+ val lowDb = FloatArray(frames); val midDb = FloatArray(frames); val highDb = FloatArray(frames); val rmsDb = FloatArray(frames); val bassDb = FloatArray(frames)var chromaResult: Triple<Array<FloatArray>, FloatArray, Boolean>? = nullval budget = max(1, threads)val slices = max(1, budget - 1)@@ -82,13 +88,14 @@ class Features private constructor(val start = f * HOPfor (i in 0 until N) frame[i] = (mid.getOrElse(start + i) { 0f }) * win[i]fft.magnitudes(frame, mag, re, im)- var low = 0.0; var mi = 0.0; var hi = 0.0+ var low = 0.0; var mi = 0.0; var hi = 0.0; var ba = 0.0for (k in 1..N / 2) {val p = mag[k] * mag[k]when { k < lowBin -> low += p; k < highBin -> mi += p; else -> hi += p }+ if (k in bassFrom..bassTo) ba += p}// Power to dB of a full-scale sine ~ 0 dB (Hann window sum N/2, one-sided spectrum).- lowDb[f] = db(low / POWER_NORM); midDb[f] = db(mi / POWER_NORM); highDb[f] = db(hi / POWER_NORM); rmsDb[f] = db((low + mi + hi) / POWER_NORM)+ lowDb[f] = db(low / POWER_NORM); midDb[f] = db(mi / POWER_NORM); highDb[f] = db(hi / POWER_NORM); rmsDb[f] = db((low + mi + hi) / POWER_NORM); bassDb[f] = db(ba / POWER_NORM)for (b in 0 until BANDS) {var s = 0.0for (k in edges[b] until edges[b + 1]) s += mag[k]@@ -108,7 +115,7 @@ class Features private constructor(}val (chroma, centre, stereo) = chromaResult!!- return Features(onset, bassOnset, lowDb, midDb, highDb, rmsDb, chroma, centre, stereo, mid.size.toDouble() / RATE)+ return Features(onset, bassOnset, lowDb, midDb, highDb, rmsDb, bassDb, chroma, centre, stereo, mid.size.toDouble() / RATE)}private fun chromaAndCentre(mid: FloatArray, side: FloatArray?, cancelled: () -> Boolean): Triple<Array<FloatArray>, FloatArray, Boolean> {diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/MixPlan.kt b/base/automix/src/main/kotlin/app/myspoti/automix/MixPlan.ktindex 81fde57e..9963ba0e 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/MixPlan.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/MixPlan.kt@@ -35,6 +35,8 @@ class MixPlan(val matchA: Double = 1.0,/** A FADE between tempos too far apart: B without its bass until a hand-over at [swapAt], A's top end closing. */val filtered: Boolean = false,+ /** The data plan this timing was read from; when set, the engine plays its lanes, not [levels]. */+ val segue: app.myspoti.automix.segue.SeguePlan? = null,) {enum class Style {/** Beat-matched blend over several bars with a bass swap. */diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/MixPlanner.kt b/base/automix/src/main/kotlin/app/myspoti/automix/MixPlanner.ktindex 30c40d6c..c3be3a1c 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/MixPlanner.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/MixPlanner.kt@@ -197,7 +197,7 @@ object MixPlanner {}/** Bass changes on a shared downbeat, near a local arrival when one exists, otherwise halfway. */- private fun bassSwapBar(b: TrackAnalysis, sb: Summary, gb: Grid, entry: Double, bars: Int, barA: Double, speed: Double): Double {+ internal fun bassSwapBar(b: TrackAnalysis, sb: Summary, gb: Grid, entry: Double, bars: Int, barA: Double, speed: Double): Double {var chosen = if (bars >= 4) floor(bars / 2.0) else bars / 2.0var score = 0.0for (k in max(1, ceil(bars * 0.25).toInt())..floor(bars * 0.75).toInt()) {@@ -359,7 +359,7 @@ object MixPlanner {* Cheap per-song quantities, once per immutable analysis: no sorting, powers, whole-song scans* or level windows in the candidate loop. Values do not reference the weak map's key.*/- private class Summary(a: TrackAnalysis) {+ internal class Summary(a: TrackAnalysis) {val loud = a.barDb.sortedArray().let { if (it.isEmpty()) -20.0 else it[(it.size * 0.7).toInt()].toDouble() }private val level = prefix(a.barDb)private val low = prefix(a.barLowDb)@@ -419,7 +419,7 @@ object MixPlanner {}}private val summaries = WeakHashMap<TrackAnalysis, Summary>()- private fun summary(a: TrackAnalysis): Summary = synchronized(summaries) { summaries.getOrPut(a) { Summary(a) } }+ internal fun summary(a: TrackAnalysis): Summary = synchronized(summaries) { summaries.getOrPut(a) { Summary(a) } }private fun nearestBar(a: TrackAnalysis, t: Double): Int {val i = a.barAt(t)diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt b/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.ktindex 9ffebefb..d661f890 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt@@ -6,6 +6,9 @@ import java.io.DataOutputStreamimport java.io.InputStreamimport java.io.OutputStream+/** Distance of measured beats from a grid: its median and 95th percentile, microseconds. */+data class PhaseStats(val medianUs: Long, val p95Us: Long)+/*** What AutoMix knows of a song. Times in seconds of the song's own timeline.*@@ -47,8 +50,21 @@ class TrackAnalysis(* model: centred instruments may also score. Mono is uncertain rather than assumed voice-free.*/val barVocalRisk: FloatArray = FloatArray(barStarts.size),+ /** SHA-256 of the decoded analysis signal: what identifies the audio, whatever its source. */+ val audioKey: String = "",+ /** Level (dB) per bar of the band where two bass lines mask each other. */+ val barBassDb: FloatArray = barLowDb,+ /** How far the model's beats sit from the [head] and [tail] grids; null when too few could be measured. */+ val headPhase: PhaseStats? = null,+ val tailPhase: PhaseStats? = null,+ /** How clearly the downbeats' votes chose one phase on each grid, 0..1 (0: no evidence). */+ val headMetre: Float = 0f,+ val tailMetre: Float = 0f,) {val bars get() = barStarts.size+ /** Identify the grids a plan relies on: a new analysis with another grid invalidates the plan. */+ val headGridKey: String? by lazy(LazyThreadSafetyMode.PUBLICATION) { head?.let { gridKey(it, headDown) } }+ val tailGridKey: String? by lazy(LazyThreadSafetyMode.PUBLICATION) { tail?.let { gridKey(it, tailDown) } }private val sections by lazy(LazyThreadSafetyMode.PUBLICATION) { Sections.detect(barNovelty) }/** Strong local structural changes in bars; no named verse/chorus labels are inferred. */@@ -86,11 +102,14 @@ class TrackAnalysis(for (a in listOf(barDb, barLowDb, barHighDb, barCentre, barNovelty)) a.forEach(o::writeFloat)o.writeInt(phraseOffset); o.writeBoolean(stereo); o.writeDouble(headDown); o.writeDouble(tailDown); o.writeUTF(note.take(2000))for (bar in 0 until bars) o.writeFloat(barVocalRisk.getOrElse(bar) { 0f })+ o.writeUTF(audioKey)+ for (bar in 0 until bars) o.writeFloat(barBassDb.getOrElse(bar) { -60f })+ writePhase(o, headPhase); writePhase(o, tailPhase); o.writeFloat(headMetre); o.writeFloat(tailMetre)o.flush()}companion object {- const val VERSION = 4_08+ const val VERSION = 4_09fun read(input: InputStream): TrackAnalysis? {val i = DataInputStream(input)@@ -104,10 +123,24 @@ class TrackAnalysis(val arrays = List(5) { FloatArray(n) { i.readFloat() } }val phrase = i.readInt(); val stereo = i.readBoolean(); val headDown = i.readDouble(); val tailDown = i.readDouble(); val note = i.readUTF()val vocal = FloatArray(n) { i.readFloat() }+ val audioKey = i.readUTF()+ val bass = FloatArray(n) { i.readFloat() }+ val headPhase = readPhase(i); val tailPhase = readPhase(i); val headMetre = i.readFloat(); val tailMetre = i.readFloat()return TrackAnalysis(duration, cs, ce, loud, key, ks, bpm, steady, head, tail, beats, starts,- arrays[0], arrays[1], arrays[2], arrays[3], arrays[4], phrase, stereo, headDown, tailDown, note, vocal)+ arrays[0], arrays[1], arrays[2], arrays[3], arrays[4], phrase, stereo, headDown, tailDown, note, vocal,+ audioKey, bass, headPhase, tailPhase, headMetre, tailMetre)}+ private fun gridKey(g: Grid, down: Double): String = app.myspoti.automix.segue.SegueCodec.hex(+ "${Math.round(g.first * 1e6)}|${Math.round(g.period * 1e9)}|${g.count}|${if (down.isNaN()) "-" else Math.round(down * 1e6).toString()}".toByteArray())++ private fun writePhase(o: DataOutputStream, p: PhaseStats?) {+ o.writeBoolean(p != null)+ if (p != null) { o.writeLong(p.medianUs); o.writeLong(p.p95Us) }+ }++ private fun readPhase(i: DataInputStream): PhaseStats? = if (!i.readBoolean()) null else PhaseStats(i.readLong(), i.readLong())+private fun writeGrid(o: DataOutputStream, g: Grid?) {o.writeBoolean(g != null)if (g != null) { o.writeDouble(g.first); o.writeDouble(g.period); o.writeInt(g.count); o.writeDouble(g.steadiness); o.writeDouble(g.driftMs); o.writeDouble(g.contrast) }diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueCompiler.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueCompiler.ktnew file mode 100644index 00000000..9884ecac--- /dev/null+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueCompiler.kt@@ -0,0 +1,97 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.log10+import kotlin.math.roundToInt+import kotlin.math.roundToLong+import kotlin.math.sin+import kotlin.math.sqrt++/** Writes each class's treatment as lanes: every curve the engine plays is data in the plan. */+internal class SegueCompiler(private val t: SegueTuning) {+ private fun knot(x: Double, value: Double?, form: KnotForm = KnotForm.Ramp) = SeguePlan.Knot(+ (x * SegueFormat.T_MAX).roundToInt().coerceIn(0, SegueFormat.T_MAX),+ value?.let { (it * SegueFormat.VALUE_SCALE).roundToLong() }, form)++ /** Sorted, one knot per position (the last written), covering the window, the first knot a step. */+ private fun lane(side: LaneSide, target: Target, knots: List<SeguePlan.Knot>): SeguePlan.Lane {+ val one = knots.withIndex().groupBy { it.value.t }.toSortedMap().values.map { it.last().value }+ val first = one.first().copy(form = KnotForm.Step)+ return SeguePlan.Lane(side, target, target.unit, listOf(first) + one.drop(1))+ }++ private fun db(gain: Double): Double? = if (gain <= 1e-4) null else 20 * log10(gain)+ private fun smooth(x: Double): Double { val u = x.coerceIn(0.0, 1.0); return u * u * (3 - 2 * u) }++ /** Both level lanes from gains, with the summed squared gains bounded by one. */+ private fun levels(positions: List<Double>, gains: (Double) -> Pair<Double, Double>): List<SeguePlan.Lane> {+ val a = ArrayList<SeguePlan.Knot>(); val b = ArrayList<SeguePlan.Knot>()+ for (x in positions.distinct().sorted()) {+ val (ga, gb) = gains(x)+ val power = ga * ga + gb * gb+ val scale = if (power > 1) 1 / sqrt(power) else 1.0+ a += knot(x, db(ga * scale)); b += knot(x, db(gb * scale))+ }+ return listOf(lane(LaneSide.OUTGOING, Target.LEVEL, a), lane(LaneSide.INCOMING, Target.LEVEL, b))+ }++ private fun positions(vararg extra: Double): List<Double> =+ List(t.curveKnots + 1) { it.toDouble() / t.curveKnots } + extra.toList()++ private fun matched(x: Double, swap: Double, matchA: Double, matchB: Double, a: Double, b: Double): Pair<Double, Double> {+ // A eased towards B over the first half, B brought back to its own level after the swap.+ val down = 1 - (1 - matchA) * smooth(x / t.matchEaseShare)+ val up = if (x <= swap || swap >= 1) matchB else matchB + (1 - matchB) * smooth((x - swap) / (1 - swap))+ return a * down to b * up+ }++ /** Bass swapped at one point, level ramps; the top ends hand over too. */+ fun locked(swap: Double, beatShare: Double, matchA: Double, matchB: Double, eq: Boolean): List<SeguePlan.Lane> {+ val out = ArrayList(levels(positions(swap)) { x ->+ val after = ((x - swap) / (1 - swap)).coerceIn(0.0, 1.0)+ val ga = if (x < swap) 1.0 else cos(PI / 2 * after)+ val gb = if (x < swap) t.incomingBedGain * sin(PI / 2 * (x / swap)) else t.incomingBedGain + (1 - t.incomingBedGain) * after+ matched(x, swap, matchA, matchB, ga, gb)+ })+ if (eq) {+ val end = (swap + beatShare * t.bassSwapBeats).coerceAtMost(1.0)+ out += bassHandOver(swap, end)+ out += lane(LaneSide.OUTGOING, Target.SHELF_TOP, listOf(knot(0.0, 0.0), knot(t.outgoingTopFrom, 0.0), knot(1.0, t.outgoingTopDb)))+ out += lane(LaneSide.INCOMING, Target.SHELF_TOP, listOf(knot(0.0, t.incomingTopDb), knot(swap, 0.0), knot(1.0, 0.0)))+ }+ return out+ }++ private fun bassHandOver(from: Double, to: Double): List<SeguePlan.Lane> = listOf(+ lane(LaneSide.OUTGOING, Target.SHELF_BOTTOM, listOf(knot(0.0, 0.0), knot(from, 0.0), knot(to, t.bassKillDb), knot(1.0, t.bassKillDb))),+ lane(LaneSide.INCOMING, Target.SHELF_BOTTOM, listOf(knot(0.0, t.bassKillDb), knot(from, t.bassKillDb), knot(to, 0.0), knot(1.0, 0.0))),+ )++ /** The outgoing song filtered away, a limited overlap, the incoming one rising without its bass. */+ fun filtered(swap: Double, beatShare: Double, matchA: Double, matchB: Double, eq: Boolean): List<SeguePlan.Lane> {+ val out = ArrayList(levels(positions(swap)) { x ->+ val after = ((x - swap) / (1 - swap)).coerceIn(0.0, 1.0)+ val ga = if (x < swap) 1.0 else cos(PI / 2 * after)+ val gb = if (x < swap) t.filteredBedGain * sin(PI / 2 * (x / swap)) else t.filteredBedGain + (1 - t.filteredBedGain) * after+ matched(x, swap, matchA, matchB, ga, gb)+ })+ if (eq) {+ out += bassHandOver(swap, (swap + beatShare * t.bassSwapBeats).coerceAtMost(1.0))+ out += lane(LaneSide.INCOMING, Target.SHELF_TOP, listOf(knot(0.0, t.filteredIncomingTopDb), knot(swap, 0.0), knot(1.0, 0.0)))+ out += lane(LaneSide.OUTGOING, Target.SWEEP_HZ, listOf(knot(0.0, null), knot(swap, null), knot(1.0, t.sweepClosedHz, KnotForm.Octave)))+ out += lane(LaneSide.OUTGOING, Target.SWEEP_PEAK, listOf(knot(0.0, null), knot(swap, null), knot(1.0, t.sweepPeakRatio)))+ }+ return out+ }++ /** A cut: an anti-click fade and nothing else. */+ fun hard(): List<SeguePlan.Lane> = listOf(+ lane(LaneSide.OUTGOING, Target.LEVEL, listOf(knot(0.0, 0.0), knot(1.0, null))),+ lane(LaneSide.INCOMING, Target.LEVEL, listOf(knot(0.0, null), knot(1.0, 0.0))),+ )++ /** A plain equal-power fade. */+ fun fade(): List<SeguePlan.Lane> = levels(positions()) { x -> cos(PI / 2 * x) to sin(PI / 2 * x) }+}diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueGuards.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueGuards.ktnew file mode 100644index 00000000..fa7083b8--- /dev/null+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueGuards.kt@@ -0,0 +1,41 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++enum class SegueGuard { RATE, PHASE_MEDIAN, PHASE_P95, DRIFT, GRID_RELIABILITY, VOICE, CONTENT_CUT, MIN_PLAYED, LOUDNESS_JUMP, ALBUM }++/** The treatments a plan can have. Scores are comparable only within one of them. */+enum class SegueClass { LOCKED, FILTERED, HARD, FADE }++/** What the guards read of a candidate, measured apart from any score. */+data class SegueMeasures(+ val rateDeviationPpm: Long = 0,+ /** Null: the phase could not be measured, which a locked candidate cannot accept. */+ val phaseMedianUs: Long? = 0,+ val phaseP95Us: Long? = 0,+ val driftBeats: Double = 0.0,+ val gridReliable: Boolean = true,+ val voiceOverlapUs: Long = 0,+ val contentCutUs: Long = 0,+ val contentCutShare: Double = 0.0,+ val playedUs: Long = Long.MAX_VALUE,+ val loudnessJumpDb: Double = 0.0,+ val albumContinuity: Boolean = false,+)++object SegueGuards {+ /** Every guard the candidate crosses for [cls]. Any one rejects it; nothing compensates. */+ fun crossed(cls: SegueClass, m: SegueMeasures, t: SegueTuning): List<SegueGuard> = buildList {+ if (m.albumContinuity) add(SegueGuard.ALBUM)+ if (m.contentCutUs > t.contentCutMaxUs || m.contentCutShare > t.contentCutMaxShare) add(SegueGuard.CONTENT_CUT)+ if (m.playedUs < t.minPlayedUs) add(SegueGuard.MIN_PLAYED)+ if (cls != SegueClass.HARD && m.voiceOverlapUs > t.voiceOverlapMaxUs) add(SegueGuard.VOICE)+ if (cls == SegueClass.LOCKED) {+ if (m.rateDeviationPpm > t.maxRateDeviationPpm) add(SegueGuard.RATE)+ if (m.phaseMedianUs == null || m.phaseMedianUs > t.phaseMedianMaxUs) add(SegueGuard.PHASE_MEDIAN)+ if (m.phaseP95Us == null || m.phaseP95Us > t.phaseP95MaxUs) add(SegueGuard.PHASE_P95)+ if (m.driftBeats > t.driftMaxBeats) add(SegueGuard.DRIFT)+ }+ if ((cls == SegueClass.LOCKED || cls == SegueClass.HARD) && !m.gridReliable) add(SegueGuard.GRID_RELIABILITY)+ if (cls == SegueClass.HARD && m.loudnessJumpDb > t.loudnessJumpMaxDb) add(SegueGuard.LOUDNESS_JUMP)+ }+}diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePolicy.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePolicy.ktnew file mode 100644index 00000000..9d01e913--- /dev/null+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePolicy.kt@@ -0,0 +1,420 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++import app.myspoti.automix.Grid+import app.myspoti.automix.MixPlan+import app.myspoti.automix.MixPlanner+import app.myspoti.automix.TrackAnalysis+import kotlin.math.abs+import kotlin.math.floor+import kotlin.math.hypot+import kotlin.math.ln+import kotlin.math.max+import kotlin.math.min+import kotlin.math.pow+import kotlin.math.roundToInt+import kotlin.math.roundToLong++/** The fallback order. Normal playback is not a failure: no effect beats a bad effect. */+enum class SegueLevel(val cls: SegueClass?) {+ LOCKED_LONG(SegueClass.LOCKED),+ LOCKED_SHORT(SegueClass.LOCKED),+ LOCKED_BEAT(SegueClass.LOCKED),+ FILTERED(SegueClass.FILTERED),+ HARD(SegueClass.HARD),+ SIMPLE_FADE(SegueClass.FADE),+ NORMAL(null),+}++enum class SegueCause { NO_GRID, TEMPO_OUT_OF_REACH, BASS_NOT_MANAGED, LENGTH_NOT_ALLOWED, NO_CANDIDATE, GUARDS, BELOW_THRESHOLD, INVALID_PLAN, ALBUM_CONTINUITY }++/** Why a level was not used: every level above the chosen one has one. */+data class SegueAttempt(val level: SegueLevel, val cause: SegueCause, val detail: String = "") {+ override fun toString() = if (detail.isEmpty()) "$level: $cause" else "$level: $cause ($detail)"+}++/** The policy's answer: the level, the plan (none for normal playback), and why the levels above failed. */+class SegueDecision(+ val level: SegueLevel,+ val plan: SeguePlan?,+ val attempts: List<SegueAttempt>,+ val score: Double? = null,+ /** Where the bass changes hands, 0..1 of the window. */+ val swapShare: Double = 0.5,+ /** Seconds the incoming song takes to return to its own tempo. */+ val restoreSec: Double = 0.0,+) {+ val why: String get() = attempts.joinToString("; ")+ val fingerprint: String? get() = plan?.let(SegueCodec::fingerprint)+}++class SegueRequest(+ val a: TrackAnalysis,+ val b: TrackAnalysis,+ /** Nothing may begin before this point of A: its preparation lead is already counted. */+ val earliestExitUs: Long = 0,+ val listenerRate: Long = SegueFormat.RATE_NOMINAL,+ /** The listener's settings may only tighten the guards. */+ val maxRatePpm: Long? = null,+ val maxBars: Int? = null,+ val eq: Boolean = true,+ val harmonic: Boolean = true,+ /** Both songs are on one album: a junction without silence is left to play as it is. */+ val sameAlbum: Boolean = false,+ val tuning: SegueTuning = SegueTuning(),+)++/**+ * Generates candidates, rejects by guards, scores, keeps the best if it clears its class's threshold,+ * otherwise moves to the next level. Deterministic: the same request gives the same plan.+ */+object SeguePolicy {+ val ORIGIN = SeguePlan.Origin("myspoti-segue-1", "uncalibrated")++ fun decide(r: SegueRequest): SegueDecision = Run(r).decide()++ /** The plan's timing as the players need it. */+ fun timing(d: SegueDecision): MixPlan? {+ val p = d.plan ?: return null+ val style = when (d.level.cls) {+ SegueClass.LOCKED -> MixPlan.Style.BLEND+ SegueClass.HARD -> MixPlan.Style.CUT+ else -> MixPlan.Style.FADE+ }+ val rate = p.incoming.ratePpm.toDouble() / SegueFormat.RATE_NOMINAL+ val beats = if (p.span.unitKind == UnitKind.BAR) (p.span.musicalUnits ?: 0) * 4 else p.span.musicalUnits ?: 0+ return MixPlan(style, p.outgoing.anchorUs / 1e6, p.incoming.anchorUs / 1e6, p.span.lengthUs / 1e6, rate, beats,+ d.swapShare, if (beats > 0) 1.0 / beats else 0.1, 1.0, d.restoreSec,+ "segue ${d.level}" + (d.score?.let { String.format(java.util.Locale.ROOT, " score %.2f", it) } ?: "") ++ (if (d.attempts.isEmpty()) "" else " | ${d.why}"),+ filtered = d.level == SegueLevel.FILTERED, segue = p)+ }++ /** Checks a plan against the analyses it must match; a non-empty answer means it is recomputed. */+ fun stale(p: SeguePlan, a: TrackAnalysis, b: TrackAnalysis): List<SegueViolation> {+ val (fa, fb) = facts(a, b)+ return SegueValidator.stale(p, fa, fb)+ }++ internal fun facts(a: TrackAnalysis, b: TrackAnalysis) =+ SegueSideFacts(a.audioKey, a.tailGridKey, us(a.duration)) to SegueSideFacts(b.audioKey, b.headGridKey, us(b.duration))++ private fun us(seconds: Double): Long = (seconds * 1e6).roundToLong()++ private class Point(val us: Long, val bar: Int, val rank: Double, val boundary: Boolean)++ private class Found(val plan: SeguePlan, val score: Double, val swap: Double)++ private class Run(val r: SegueRequest) {+ val a = r.a; val b = r.b; val t = r.tuning+ val sa = MixPlanner.summary(a); val sb = MixPlanner.summary(b)+ val compiler = SegueCompiler(t)+ val ga: Grid? = a.tail?.takeIf { !a.tailDown.isNaN() }+ val gb: Grid? = b.head?.takeIf { !b.headDown.isNaN() }+ val attempts = ArrayList<SegueAttempt>()+ val keyDistance = if (r.harmonic) MixPlanner.keyDistance(a, b) else 0.0+ val zoneStartUs = us(a.contentStart + (sa.musicEnd - a.contentStart) * (1 - t.exitZoneShare))++ fun decide(): SegueDecision {+ if (albumContinuity()) {+ val out = SegueLevel.values().filter { it != SegueLevel.NORMAL }.map { SegueAttempt(it, SegueCause.ALBUM_CONTINUITY) }+ return SegueDecision(SegueLevel.NORMAL, null, out)+ }+ for (level in SegueLevel.values()) {+ if (level == SegueLevel.NORMAL) break+ val found = attempt(level) ?: continue+ val problems = SegueValidator.against(found.plan, facts(a, b).first, facts(a, b).second)+ if (problems.isNotEmpty()) { attempts += SegueAttempt(level, SegueCause.INVALID_PLAN, problems.joinToString(",")); continue }+ return SegueDecision(level, found.plan, attempts.toList(), found.score, found.swap,+ if (level.cls == SegueClass.LOCKED) restore(found.plan.incoming.ratePpm, gb!!.period) else 0.0)+ }+ return SegueDecision(SegueLevel.NORMAL, null, attempts.toList())+ }++ private fun albumContinuity(): Boolean {+ if (!r.sameAlbum) return false+ val silenceA = us(a.duration - a.contentEnd); val silenceB = us(b.contentStart)+ return silenceA <= t.gaplessMaxSilenceUs && silenceB <= t.gaplessMaxSilenceUs+ }++ private fun fail(level: SegueLevel, cause: SegueCause, detail: String = ""): Found? {+ attempts += SegueAttempt(level, cause, detail); return null+ }++ private fun attempt(level: SegueLevel): Found? = when (level) {+ SegueLevel.LOCKED_LONG -> locked(level, listOf(t.lockedLongBars), phrases = true)+ SegueLevel.LOCKED_SHORT -> locked(level, listOf(t.lockedMiddleBars, t.lockedShortBars), phrases = true)+ SegueLevel.LOCKED_BEAT -> if (!r.eq) fail(level, SegueCause.BASS_NOT_MANAGED) else locked(level, listOf(t.lockedShortBars), phrases = false)+ SegueLevel.FILTERED -> filtered(level)+ SegueLevel.HARD -> hard(level)+ SegueLevel.SIMPLE_FADE -> simple(level)+ SegueLevel.NORMAL -> null+ }++ // ── Reliability: an uncertain measure weighs less ──+ private fun tempoReliability(g: Grid?): Double = g?.steadiness?.coerceIn(0.0, 1.0) ?: 0.0+ private fun pulseReliability() = min(min(tempoReliability(ga), tempoReliability(gb)), min(a.tailMetre, b.headMetre).toDouble())+ private fun structureReliability(s: TrackAnalysis, bar: Int) = max(s.sectionStrength(bar), t.reliabilityPhraseFallback)+ private fun vocalReliability() = if (a.stereo && b.stereo) t.reliabilityVocalStereo else t.reliabilityVocalMono+ private fun keyReliability() = if (a.key >= 0 && b.key >= 0) min(a.keyStrength, b.keyStrength).coerceIn(0.0, 1.0) else 0.0++ private fun reliable(g: Grid?) = g != null && g.count >= t.gridMinBeats && g.steadiness >= t.gridMinSteadiness && g.driftMs <= t.gridMaxDriftMs++ // ── Candidates ──+ private fun boundary(s: TrackAnalysis, bar: Int) = bar >= 0 && (s.phrasePos(bar) == 0 || s.sectionStrength(bar) > 0)++ /** A's points where a window of [lengthUs] fits, instrumental endings first. */+ private fun exits(times: Sequence<Double>, lengthUs: Long, limitUs: Long, phrases: Boolean): List<Point> {+ val zone = max(zoneStartUs, r.earliestExitUs)+ return times.map { it to us(it) }.filter { (_, u) -> u >= zone && u + lengthUs <= limitUs }.mapNotNull { (time, u) ->+ val bar = a.barAt(time + 0.05)+ val on = boundary(a, bar)+ if (phrases && !on) null else Point(u, bar, instrumentalAfter(bar) + u.toDouble() / max(1L, limitUs) * 1e-3, on)+ }.sortedByDescending { it.rank }.take(t.candidatesPerSide).toList()+ }++ private fun instrumentalAfter(bar: Int): Double {+ if (a.bars == 0 || bar < 0) return 0.0+ var risk = 0.0; var n = 0+ for (i in bar until a.bars) { risk += a.barVocalRisk.getOrElse(i) { 0f }; n++ }+ return 1 - risk / max(1, n)+ }++ private fun gridTimes(g: Grid, down: Double, from: Double, to: Double): Sequence<Double> {+ val bar = 4 * g.period+ return generateSequence(MixPlanner.firstDown(g, down, from)) { it + bar }.takeWhile { it <= to }+ }++ /** B's useful attack, its first boundaries; leaving out a start must be worth its note. */+ private fun entries(g: Grid?, spanUs: Long, phrases: Boolean): List<Point> {+ val limit = us(b.contentEnd)+ val startUs = us(b.contentStart)+ val first: Double = if (g != null) MixPlanner.firstDown(g, b.headDown, b.contentStart - 0.08) else b.contentStart+ val out = ArrayList<Point>()+ out += Point(us(first), b.barAt(first + 0.05), 1.0, true)+ if (g != null) {+ val zone = min(us(b.contentStart) + t.entryZoneUs, limit / 3)+ var at = first + 4 * g.period+ while (us(at) < zone && at < g.last) {+ val bar = b.barAt(at + 0.05)+ val on = boundary(b, bar)+ if (on || !phrases) {+ val base = if (b.sectionStrength(bar) > 0) t.entryNoteSection else t.entryNoteOther+ out += Point(us(at), bar, base * (1 - (us(at) - startUs).toDouble() / t.entryZoneUs), on)+ }+ at += 4 * g.period+ }+ }+ val last = if (g != null) min(limit, us(g.last + g.period)) else limit+ return out.filter { it.us + spanUs <= last }.sortedByDescending { it.rank }.take(t.candidatesPerSide)+ }++ // ── Levels ──+ private fun locked(level: SegueLevel, barsAsked: List<Int>, phrases: Boolean): Found? {+ if (ga == null || gb == null) return fail(level, SegueCause.NO_GRID, if (ga == null) "outgoing" else "incoming")+ val m = MixPlanner.tempoMatch(ga.bpm, gb.bpm)+ val ratePpm = (m.speed * SegueFormat.RATE_NOMINAL).roundToLong()+ val deviation = abs(ratePpm - SegueFormat.RATE_NOMINAL)+ val limit = min(t.maxRateDeviationPpm, r.maxRatePpm ?: Long.MAX_VALUE)+ if (deviation > limit) return fail(level, SegueCause.TEMPO_OUT_OF_REACH, String.format(java.util.Locale.ROOT, "%.1f %%", deviation / 1e4))+ // The lower the reliability, the shorter the window.+ val rel = pulseReliability()+ val cap = if (rel >= t.reliabilityForLong) t.lockedLongBars else if (rel >= t.reliabilityForMiddle) t.lockedMiddleBars else t.lockedShortBars+ val allowed = barsAsked.filter { it <= cap && it <= (r.maxBars ?: Int.MAX_VALUE) && (m.beatsPerB == 1.0 || it <= t.halfDoubleMaxBars) }+ if (allowed.isEmpty()) return fail(level, SegueCause.LENGTH_NOT_ALLOWED, "reliability ${"%.2f".format(java.util.Locale.ROOT, rel)}")+ val barA = 4 * ga.period+ val phaseMedian = phase(a.tailPhase?.medianUs, b.headPhase?.medianUs)+ val phaseP95 = phase(a.tailPhase?.p95Us, b.headPhase?.p95Us)+ val drift = hypot(ga.driftMs, gb.driftMs) / 1000 / ga.period+ val tally = Tally()+ var best: Found? = null+ for (bars in allowed) {+ val lengthUs = us(bars * barA)+ val spanUs = lengthUs * ratePpm / SegueFormat.RATE_NOMINAL+ val outs = exits(gridTimes(ga, a.tailDown, max(a.contentStart, ga.first), min(sa.musicEnd, ga.last)), lengthUs, min(us(a.contentEnd), us(ga.last + ga.period)), phrases)+ val ins = entries(gb, spanUs, phrases)+ for (e in outs) for (n in ins) {+ tally.seen+++ val base = measures(e, n, lengthUs, spanUs).copy(rateDeviationPpm = deviation, phaseMedianUs = phaseMedian, phaseP95Us = phaseP95,+ driftBeats = drift, gridReliable = reliable(ga) && reliable(gb))+ if (tally.refused(SegueGuards.crossed(SegueClass.LOCKED, base, t))) continue+ val swap = MixPlanner.bassSwapBar(b, sb, gb, n.us / 1e6, bars, barA, m.speed) / bars+ val beatShare = 1.0 / (bars * 4)+ val lanes = compiler.locked(swap, beatShare, matchA(), matchB(), r.eq)+ val plan = plan(e.us, n.us, ga, gb, ratePpm, lengthUs, bars, PulseState.LOCKED, us60(ga), phaseMedian, lanes)+ val score = score(e, n, lengthUs, spanUs, phaseMedian, deviation, lanes)+ if (best == null || score.total > best.score) best = Found(plan, score.total, swap)+ }+ }+ return settle(level, tally, best, t.thresholdLocked)+ }++ private fun filtered(level: SegueLevel): Found? {+ val rel = tempoReliability(ga)+ val lengths = when {+ rel >= t.reliabilityForLong -> listOf(t.filteredLongUs, t.filteredMiddleUs, t.filteredShortUs)+ rel >= t.reliabilityForMiddle -> listOf(t.filteredMiddleUs, t.filteredShortUs)+ else -> listOf(t.filteredShortUs)+ }+ val tally = Tally()+ var best: Found? = null+ for (lengthUs in lengths) {+ val outs = exits(a.barStarts.asSequence(), lengthUs, us(a.contentEnd), phrases = false)+ val ins = entries(gb, lengthUs, phrases = false)+ for (e in outs) for (n in ins) {+ tally.seen+++ if (tally.refused(SegueGuards.crossed(SegueClass.FILTERED, measures(e, n, lengthUs, lengthUs), t))) continue+ val lanes = compiler.filtered(t.filteredSwapShare, min(1.0, 0.4 * 1e6 / lengthUs), matchA(), matchB(), r.eq)+ val plan = plan(e.us, n.us, ga, gb, SegueFormat.RATE_NOMINAL, lengthUs, null, PulseState.FREE, null, null, lanes)+ val score = score(e, n, lengthUs, lengthUs, null, 0, lanes)+ if (best == null || score.total > best.score) best = Found(plan, score.total, t.filteredSwapShare)+ }+ }+ return settle(level, tally, best, t.thresholdFiltered)+ }++ private fun hard(level: SegueLevel): Found? {+ if (ga == null) return fail(level, SegueCause.NO_GRID, "outgoing")+ val tally = Tally()+ var best: Found? = null+ val residual = phase(a.tailPhase?.medianUs, b.headPhase?.medianUs)+ val outs = exits(gridTimes(ga, a.tailDown, max(a.contentStart, ga.first), min(sa.musicEnd, ga.last)), t.microFadeUs, us(a.contentEnd), phrases = true)+ val ins = entries(gb, t.microFadeUs, phrases = true)+ for (e in outs) for (n in ins) {+ tally.seen+++ val jump = abs(sa.levelBars(e.bar - 2, e.bar) - sb.levelBars(n.bar, n.bar + 2))+ val m = measures(e, n, t.microFadeUs, t.microFadeUs).copy(gridReliable = reliable(ga), loudnessJumpDb = jump, voiceOverlapUs = 0)+ if (tally.refused(SegueGuards.crossed(SegueClass.HARD, m, t))) continue+ val lanes = compiler.hard()+ val plan = plan(e.us, n.us, ga, gb, SegueFormat.RATE_NOMINAL, t.microFadeUs, null, PulseState.LOOSE, us60(ga), residual, lanes)+ val score = score(e, n, t.microFadeUs, t.microFadeUs, null, 0, lanes)+ if (best == null || score.total > best.score) best = Found(plan, score.total, 0.0)+ }+ return settle(level, tally, best, t.thresholdHard)+ }++ /** From a safe point: a bar start when there is one near, otherwise the planned time. */+ private fun simple(level: SegueLevel): Found? {+ val endUs = min(us(sa.musicEnd), us(a.contentEnd))+ val lengthUs = min(t.simpleFadeUs, endUs - r.earliestExitUs)+ if (lengthUs <= 0 || us(b.contentEnd) - us(b.contentStart) < lengthUs) return fail(level, SegueCause.NO_CANDIDATE)+ val targetUs = max(r.earliestExitUs, endUs - lengthUs)+ val bar = a.barStarts.lastOrNull { us(it) in r.earliestExitUs..targetUs && targetUs - us(it) <= t.simpleFadeUs }+ val exitUs = bar?.let(::us) ?: targetUs+ val entryTime = gb?.let { MixPlanner.firstDown(it, b.headDown, b.contentStart - 0.08) } ?: b.contentStart+ val e = Point(exitUs, a.barAt(exitUs / 1e6 + 0.05), 1.0, true)+ val n = Point(us(entryTime), b.barAt(entryTime + 0.05), 1.0, true)+ val tally = Tally().also { it.seen = 1 }+ if (tally.refused(SegueGuards.crossed(SegueClass.FADE, measures(e, n, lengthUs, lengthUs), t))) return settle(level, tally, null, 0.0)+ return Found(plan(exitUs, n.us, ga, gb, SegueFormat.RATE_NOMINAL, lengthUs, null, PulseState.FREE, null, null, compiler.fade()), 0.0, 0.5)+ }++ private fun settle(level: SegueLevel, tally: Tally, best: Found?, threshold: Double): Found? = when {+ tally.seen == 0 -> fail(level, SegueCause.NO_CANDIDATE)+ best == null -> fail(level, SegueCause.GUARDS, tally.toString())+ best.score < threshold -> fail(level, SegueCause.BELOW_THRESHOLD, String.format(java.util.Locale.ROOT, "%.2f < %.2f", best.score, threshold))+ else -> best+ }++ private class Tally {+ var seen = 0+ private val counts = java.util.EnumMap<SegueGuard, Int>(SegueGuard::class.java)+ fun refused(crossed: List<SegueGuard>): Boolean {+ for (g in crossed) counts[g] = (counts[g] ?: 0) + 1+ return crossed.isNotEmpty()+ }+ override fun toString() = counts.entries.joinToString(",") { "${it.key}×${it.value}" } + " of $seen"+ }++ // ── Measures ──+ private fun phase(x: Long?, y: Long?): Long? = if (x == null || y == null) null else hypot(x.toDouble(), y.toDouble()).roundToLong()++ private fun measures(e: Point, n: Point, lengthUs: Long, spanUs: Long): SegueMeasures {+ val a0 = e.us / 1e6; val a1 = (e.us + lengthUs) / 1e6+ val co = if (sa.maxVoice == 0f || sb.maxVoice == 0f) MixPlanner.CoVocal.NONE+ else MixPlanner.coVocal(a, a0, a1, b, n.us / 1e6, (n.us + spanUs) / 1e6)+ val musicUs = us(sa.musicEnd - a.contentStart)+ val cutUs = max(0L, us(sa.musicEnd) - (e.us + lengthUs))+ return SegueMeasures(voiceOverlapUs = (co.total * 1e6).roundToLong(), contentCutUs = cutUs,+ contentCutShare = if (musicUs > 0) cutUs.toDouble() / musicUs else 1.0, playedUs = e.us - us(a.contentStart))+ }++ private fun score(e: Point, n: Point, lengthUs: Long, spanUs: Long, phaseUs: Long?, deviationPpm: Long, lanes: List<SeguePlan.Lane>): SegueScore {+ val a0 = e.us / 1e6; val a1 = (e.us + lengthUs) / 1e6; val b0 = n.us / 1e6; val b1 = (n.us + spanUs) / 1e6+ val endBar = a.barAt(a1)+ val energy = abs(sa.levelBars(max(0, endBar - 3), endBar + 1) - sb.levelBars(max(0, n.bar), max(0, n.bar) + 4))+ val rhythm = phaseUs?.let { SegueScore.fallingFrom(it.toDouble(), t.rhythmFullUs.toDouble(), t.phaseMedianMaxUs.toDouble()) } ?: 0.0+ val phrase = (if (e.boundary) 0.5 else 0.0) + if (n.boundary) 0.5 else 0.0+ val notes = listOf(+ SegueNote("rhythm", t.weightRhythm, pulseReliability(), rhythm),+ SegueNote("phrase", t.weightPhrase, min(structureReliability(a, e.bar), structureReliability(b, n.bar)), phrase),+ SegueNote("energy", t.weightEnergy, 1.0, SegueScore.gaussian(energy, t.energySigmaDb)),+ SegueNote("exit", t.weightExit, vocalReliability(), exitQuality(e, endBar)),+ SegueNote("entry", t.weightEntry, min(structureReliability(b, n.bar), 1.0), n.rank.coerceIn(0.0, 1.0)),+ SegueNote("key", if (r.harmonic) t.weightKey else 0.0, keyReliability(), 1 - keyDistance / 2),+ )+ val overlap = if (sa.maxVoice == 0f || sb.maxVoice == 0f) 0.0 else MixPlanner.vocalOverlap(a, a0, a1, b, b0, b1)+ val effects = lanes.count { it.target == Target.SWEEP_HZ || it.target == Target.SEND_ROOM || it.target == Target.SEND_ECHO }+ val defects = listOf(+ SegueDefect("speed", t.penaltySpeed, SegueScore.risingFrom(deviationPpm.toDouble(), t.rateCostFreePpm.toDouble(), t.maxRateDeviationPpm.toDouble())),+ SegueDefect("voice", t.penaltyVoice, overlap * lengthUs / t.voiceOverlapMaxUs),+ SegueDefect("bass", t.penaltyBass, commonBass(e.us, n.us, lengthUs, spanUs, lanes)),+ SegueDefect("lost", t.penaltyLost, max(0L, us(sa.musicEnd) - (e.us + lengthUs)).toDouble() / t.contentCutMaxUs),+ SegueDefect("sobriety", t.penaltySobriety, effects.toDouble() / t.sobrietyFullEffects),+ )+ return SegueScore(notes, defects)+ }++ /** The voice is over, or dies early in the window: leaving on it is what the listener hears. */+ private fun exitQuality(e: Point, endBar: Int): Double {+ if (e.bar < 0 || endBar < e.bar) return 0.0+ val mid = (e.bar + endBar + 1) / 2+ var risk = 0.0; var n = 0+ for (i in mid..endBar) { risk += a.barVocalRisk.getOrElse(i) { 0f }; n++ }+ return 1 - risk / max(1, n)+ }++ /** The bass energy the two songs still have in common once levels and shelves are applied, 0..1. */+ private fun commonBass(e: Long, n: Long, lengthUs: Long, spanUs: Long, lanes: List<SeguePlan.Lane>): Double {+ fun curve(side: LaneSide, target: Target) = lanes.firstOrNull { it.side == side && it.target == target }?.let(::LaneCurve)+ val levelA = curve(LaneSide.OUTGOING, Target.LEVEL); val levelB = curve(LaneSide.INCOMING, Target.LEVEL)+ val shelfA = curve(LaneSide.OUTGOING, Target.SHELF_BOTTOM); val shelfB = curve(LaneSide.INCOMING, Target.SHELF_BOTTOM)+ var common = 0.0; var total = 0.0+ for (step in 0 until t.bassSampleSteps) {+ val x = (step + 0.5) / t.bassSampleSteps+ val u = x * SegueFormat.T_MAX+ val ba = a.barAt((e + lengthUs * x) / 1e6); val bb = b.barAt((n + spanUs * x) / 1e6)+ val ea = if (ba < 0) 0.0 else 10.0.pow((a.barBassDb.getOrElse(ba) { -60f } + (levelA?.value(u) ?: 0.0) + (shelfA?.value(u) ?: 0.0)) / 10)+ val eb = if (bb < 0) 0.0 else 10.0.pow((b.barBassDb.getOrElse(bb) { -60f } + (levelB?.value(u) ?: 0.0) + (shelfB?.value(u) ?: 0.0)) / 10)+ common += min(ea, eb); total += max(ea, eb)+ }+ return if (total > 0) common / total else 0.0+ }++ // ── Plans ──+ private fun us60(g: Grid) = (g.bpm * 1e6).roundToLong()++ private fun plan(exitUs: Long, entryUs: Long, g: Grid?, h: Grid?, ratePpm: Long, lengthUs: Long, bars: Int?, state: PulseState, tempo: Long?, residual: Long?, lanes: List<SeguePlan.Lane>) =+ SeguePlan(ORIGIN,+ SeguePlan.Side(a.audioKey, if (g != null) a.tailGridKey else null, exitUs, SegueFormat.RATE_NOMINAL, r.listenerRate),+ SeguePlan.Side(b.audioKey, if (h != null) b.headGridKey else null, entryUs, ratePpm, r.listenerRate),+ SeguePlan.Span(lengthUs, bars, UnitKind.BAR, Clock.ELAPSED),+ SeguePlan.Pulse(state, tempo, residual), lanes)++ private fun matchB(): Double {+ val d = a.loudnessDb - b.loudnessDb+ return if (d < -t.loudnessMatchFromDb) 10.0.pow(max(d, -t.loudnessMatchToDb) / 20) else 1.0+ }++ private fun matchA(): Double {+ val d = a.loudnessDb - b.loudnessDb+ return if (d > t.loudnessMatchFromDb) 10.0.pow(-min(d, t.loudnessMatchToDb) / 20) else 1.0+ }++ private fun restore(ratePpm: Long, period: Double): Double {+ val dev = abs(ratePpm - SegueFormat.RATE_NOMINAL).toDouble() / SegueFormat.RATE_NOMINAL+ if (dev < 1e-4) return 0.0+ return (max(t.restoreMinBeats, dev / t.restoreRatePerBeat) * period * 10).roundToInt() / 10.0+ }+ }+}diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueScore.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueScore.ktnew file mode 100644index 00000000..7f0d3bcc--- /dev/null+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueScore.kt@@ -0,0 +1,27 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++import kotlin.math.exp++/** A term rewarded: its weight, how far its measurement can be trusted, and its note, all 0..1 but the weight. */+data class SegueNote(val name: String, val weight: Double, val reliability: Double, val note: Double)++/** A term punished: its penalty and its defect, 0..1. */+data class SegueDefect(val name: String, val penalty: Double, val defect: Double)++/** score = Σ weight × reliability × note − Σ penalty × defect. An uncertain measure weighs less; it does not count as average. */+class SegueScore(val notes: List<SegueNote>, val defects: List<SegueDefect>) {+ val total: Double = notes.sumOf { it.weight * it.reliability.coerceIn(0.0, 1.0) * it.note.coerceIn(0.0, 1.0) } -+ defects.sumOf { it.penalty * it.defect.coerceIn(0.0, 1.0) }++ companion object {+ /** Full up to [full], falling to 0 at [zero]. */+ fun fallingFrom(value: Double, full: Double, zero: Double): Double =+ if (value <= full) 1.0 else if (value >= zero || zero <= full) 0.0 else (zero - value) / (zero - full)++ /** 0 up to [free], rising to 1 at [full]. */+ fun risingFrom(value: Double, free: Double, full: Double): Double = 1.0 - fallingFrom(value, free, full)++ fun gaussian(distance: Double, sigma: Double): Double = exp(-distance * distance / (2 * sigma * sigma))+ }+}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.ktnew file mode 100644index 00000000..e98f1218--- /dev/null+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt@@ -0,0 +1,140 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++/**+ * Every number of the segue policy, in one place. None is a result: each is a starting parameter to+ * confirm by measurement (docs/automix/segue-design.md). Labels: `[U]` usual order of magnitude,+ * `[I]` design proposal, `[R]` reused from a value already in this repository. Where the design+ * gives a range, the cautious end is the start value and the range is noted. A data class, so the+ * measurement harness can vary each value.+ */+data class SegueTuning(+ // ── Guards: one crossing rejects a candidate, whatever its score ──+ /** Largest speed change in the locked class, ppm. [U] range 4–8 %; a semitone is about 6 %. */+ val maxRateDeviationPpm: Long = 40_000,+ /** Expected phase error: median [U], against double attacks. */+ val phaseMedianMaxUs: Long = 20_000,+ /** Expected phase error: 95th percentile [U]. */+ val phaseP95MaxUs: Long = 40_000,+ /** Drift over the window, in beats [I]: an unstable grid is rejected. */+ val driftMaxBeats: Double = 0.1,+ /** Least grid reliability: beats [R], share of beats on the grid [R], drift over 8 beats in ms [R]. */+ val gridMinBeats: Int = 16,+ val gridMinSteadiness: Double = 0.6,+ val gridMaxDriftMs: Double = 30.0,+ /** Two voices at comparable levels, tolerated total [I] range 1–2 s. */+ val voiceOverlapMaxUs: Long = 1_000_000,+ /** Content removed at the end of a song: share of it [I] range 20–30 %, and a cap [I]. */+ val contentCutMaxShare: Double = 0.20,+ val contentCutMaxUs: Long = 60_000_000,+ /** Least playing time before a song may leave [I] range 30–60 s. */+ val minPlayedUs: Long = 60_000_000,+ /** Loudness jump at a cut [U]. */+ val loudnessJumpMaxDb: Double = 3.0,+ /** No more silence than this at both sides of a junction: the album means it to run on [I]. */+ val gaplessMaxSilenceUs: Long = 300_000,++ // ── Score: weights and penalties. Strong 1.0, medium 0.5, weak 0.2, weak-to-medium 0.35: all [I] ──+ val weightRhythm: Double = 1.0,+ val weightPhrase: Double = 1.0,+ val penaltySpeed: Double = 0.5,+ val weightEnergy: Double = 0.5,+ val penaltyVoice: Double = 1.0,+ val weightExit: Double = 0.5,+ val weightEntry: Double = 0.5,+ val penaltyBass: Double = 0.5,+ val weightKey: Double = 0.2,+ val penaltyLost: Double = 0.35,+ val penaltySobriety: Double = 0.2,++ // ── Shapes of the score's terms ──+ /** Phase error under which the rhythm term is full [U] range 10–20 ms; it reaches 0 at [phaseMedianMaxUs]. */+ val rhythmFullUs: Long = 10_000,+ /** Speed change under which it costs nothing, ppm [U] range 2–3 %. */+ val rateCostFreePpm: Long = 20_000,+ /** Width of the energy continuity Gaussian, dB [U] range 3–6. */+ val energySigmaDb: Double = 3.0,+ /** Entry note on a later section, and anywhere else [I]; the first attack scores 1. */+ val entryNoteSection: Double = 0.6,+ val entryNoteOther: Double = 0.3,+ /** Effects at which the sobriety defect is full [I]. */+ val sobrietyFullEffects: Int = 3,+ /** Points sampled along the window for the common bass energy [I]. */+ val bassSampleSteps: Int = 32,++ // ── Reliability of what cannot state its own [I] ──+ /** Structure where only the fallback phrase grid speaks, no local boundary. */+ val reliabilityPhraseFallback: Double = 0.3,+ /** Voice heuristic: stereo uses the centre of the image, mono has much less to go on. */+ val reliabilityVocalStereo: Double = 0.6,+ val reliabilityVocalMono: Double = 0.2,+ /** Reliability from which the longest, then the middle length is allowed. */+ val reliabilityForLong: Double = 0.8,+ val reliabilityForMiddle: Double = 0.6,++ // ── Class thresholds: the score a class's best candidate must reach ──+ /** Same value as the earlier blend floor [R]; its scale differs, so this is a proposal to measure. */+ val thresholdLocked: Double = 0.5,+ /** [I] */+ val thresholdFiltered: Double = 0.25,+ /** [I] */+ val thresholdHard: Double = 0.25,++ // ── Placement ──+ /** Locked lengths in bars [U]. */+ val lockedLongBars: Int = 16,+ val lockedMiddleBars: Int = 8,+ val lockedShortBars: Int = 4,+ /** Half or double time: two grooves meeting every other beat, kept short [R]. */+ val halfDoubleMaxBars: Int = 8,+ /** Filtered fade lengths [U] range 4–12 s; the middle one is [I]. */+ val filteredLongUs: Long = 12_000_000,+ val filteredMiddleUs: Long = 8_000_000,+ val filteredShortUs: Long = 4_000_000,+ /** Exits lie in this last share of the song. */+ val exitZoneShare: Double = 1.0 / 3.0,+ /** Entries lie within this much of the first attack [R]. */+ val entryZoneUs: Long = 40_000_000,+ /** Best candidates kept per side [I] range 3–8. */+ val candidatesPerSide: Int = 8,+ /** Anti-click fade of a cut [U] range 5–30 ms. */+ val microFadeUs: Long = 30_000,+ /** Plain short fade [R]. */+ val simpleFadeUs: Long = 6_000_000,++ // ── Lane shapes ──+ /** Band "off", dB [R]. */+ val bassKillDb: Double = -30.0,+ /** The bass changes hands over this many beats [R], within this share of the window [R]. */+ val bassSwapBeats: Int = 1,+ /** Outgoing top end: from this share of the window, down to this level [R]. */+ val outgoingTopFrom: Double = 0.7,+ val outgoingTopDb: Double = -15.0,+ /** Incoming top end held back until the swap [R]. */+ val incomingTopDb: Double = -6.0,+ /** Incoming fader at the swap [R]. */+ val incomingBedGain: Double = 0.8,+ /** Filtered: bass hand-over [R], incoming top end [R], incoming fader at the hand-over [R]. */+ val filteredSwapShare: Double = 0.6,+ val filteredIncomingTopDb: Double = -9.0,+ val filteredBedGain: Double = 0.6,+ /** Filtered: the outgoing song's filter closes to this cutoff [I] with this accent [I]. */+ val sweepClosedHz: Double = 400.0,+ val sweepPeakRatio: Double = 1.2,+ /** Knots per equal-power curve [I]: enough that the steps between them are not heard. */+ val curveKnots: Int = 16,+ /** Loudness gap left alone, and the largest one corrected, dB [R]. */+ val loudnessMatchFromDb: Double = 1.5,+ val loudnessMatchToDb: Double = 6.0,+ /** The louder outgoing song is brought down over this share of the window [R]. */+ val matchEaseShare: Double = 0.5,+ /** 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,+) {+ companion object {+ /** The band where two bass lines mask each other [U]. Fixed at analysis: not varied by the harness. */+ const val BASS_LOW_HZ = 20.0+ const val BASS_HIGH_HZ = 150.0+ }+}diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SeguePolicyTest.kt b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SeguePolicyTest.ktnew file mode 100644index 00000000..623a71e6--- /dev/null+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SeguePolicyTest.kt@@ -0,0 +1,341 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.automix.segue++import app.myspoti.automix.Grid+import app.myspoti.automix.MixPlan+import app.myspoti.automix.PhaseStats+import app.myspoti.automix.TrackAnalysis+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream++class SeguePolicyTest {+ /** A controlled song: 240 s, one bar every 2 s at 120 BPM unless told otherwise. */+ private fun song(+ key: String = "audio",+ duration: Double = 240.0,+ bpm: Double = 120.0,+ grid: Boolean = true,+ tail: Grid? = null,+ steadiness: Double = 1.0,+ phase: PhaseStats? = PhaseStats(3_000, 6_000),+ metre: Float = 1f,+ bars: Boolean = true,+ loudness: Double = -10.0,+ stereo: Boolean = true,+ musicKey: Int = 0,+ contentStart: Double = 0.0,+ contentEnd: Double = duration,+ barDb: Float = -10f,+ risk: (Int) -> Float = { 0f },+ ): TrackAnalysis {+ val beat = 60 / bpm+ val n = if (bars) (duration / 2).toInt() else 0+ val g = Grid(0.0, beat, (duration / beat).toInt(), steadiness, 0.0, 1.0)+ return TrackAnalysis(duration, contentStart, contentEnd, loudness, musicKey, 1.0, bpm, grid,+ if (grid) g else null, if (grid) tail ?: g else null, DoubleArray(0), DoubleArray(n) { it * 2.0 },+ FloatArray(n) { barDb }, FloatArray(n) { -16f }, FloatArray(n) { -20f }, FloatArray(n), FloatArray(n), 0, stereo,+ if (grid) 0.0 else Double.NaN, if (grid) tail?.first ?: 0.0 else Double.NaN, barVocalRisk = FloatArray(n, risk),+ audioKey = key, barBassDb = FloatArray(n) { -18f }, headPhase = phase, tailPhase = phase, headMetre = metre, tailMetre = metre)+ }++ private fun decide(a: TrackAnalysis, b: TrackAnalysis, earliest: Long = 0, sameAlbum: Boolean = false, eq: Boolean = true, tuning: SegueTuning = SegueTuning()) =+ SeguePolicy.decide(SegueRequest(a, b, earliest, eq = eq, sameAlbum = sameAlbum, tuning = tuning))++ private fun assertCause(d: SegueDecision, level: SegueLevel, cause: SegueCause) =+ assertTrue(d.why, d.attempts.any { it.level == level && it.cause == cause })++ // ── Guards: each defect injected alone rejects the candidate, whatever the score ──++ private val t = SegueTuning()++ private fun assertRejectsAlone(guard: SegueGuard, m: SegueMeasures, cls: SegueClass = SegueClass.LOCKED) =+ assertEquals(listOf(guard), SegueGuards.crossed(cls, m, t))++ @Test fun aCleanCandidateCrossesNothing() {+ for (c in SegueClass.values()) assertEquals(emptyList<SegueGuard>(), SegueGuards.crossed(c, SegueMeasures(), t))+ }+ @Test fun rateGuard() = assertRejectsAlone(SegueGuard.RATE, SegueMeasures(rateDeviationPpm = t.maxRateDeviationPpm + 1))+ @Test fun phaseMedianGuard() = assertRejectsAlone(SegueGuard.PHASE_MEDIAN, SegueMeasures(phaseMedianUs = t.phaseMedianMaxUs + 1))+ @Test fun phaseP95Guard() = assertRejectsAlone(SegueGuard.PHASE_P95, SegueMeasures(phaseP95Us = t.phaseP95MaxUs + 1))+ @Test fun unmeasuredPhaseIsNotAcceptedAsAverage() {+ assertTrue(SegueGuard.PHASE_MEDIAN in SegueGuards.crossed(SegueClass.LOCKED, SegueMeasures(phaseMedianUs = null), t))+ assertTrue(SegueGuard.PHASE_P95 in SegueGuards.crossed(SegueClass.LOCKED, SegueMeasures(phaseP95Us = null), t))+ }+ @Test fun driftGuard() = assertRejectsAlone(SegueGuard.DRIFT, SegueMeasures(driftBeats = t.driftMaxBeats + 0.01))+ @Test fun gridGuard() = assertRejectsAlone(SegueGuard.GRID_RELIABILITY, SegueMeasures(gridReliable = false))+ @Test fun voiceGuard() = assertRejectsAlone(SegueGuard.VOICE, SegueMeasures(voiceOverlapUs = t.voiceOverlapMaxUs + 1))+ @Test fun contentGuardShare() = assertRejectsAlone(SegueGuard.CONTENT_CUT, SegueMeasures(contentCutShare = t.contentCutMaxShare + 0.01))+ @Test fun contentGuardSeconds() = assertRejectsAlone(SegueGuard.CONTENT_CUT, SegueMeasures(contentCutUs = t.contentCutMaxUs + 1))+ @Test fun playedGuard() = assertRejectsAlone(SegueGuard.MIN_PLAYED, SegueMeasures(playedUs = t.minPlayedUs - 1))+ @Test fun loudnessGuard() = assertRejectsAlone(SegueGuard.LOUDNESS_JUMP, SegueMeasures(loudnessJumpDb = t.loudnessJumpMaxDb + 0.1), SegueClass.HARD)+ @Test fun albumGuard() = assertRejectsAlone(SegueGuard.ALBUM, SegueMeasures(albumContinuity = true))++ @Test fun aHighScoreCannotBuyAGuardBack() {+ // The best-scoring pair in every other respect, with two voices over the whole window.+ val perfect = decide(song(), song())+ assertEquals(SegueLevel.LOCKED_LONG, perfect.level)+ val voices = decide(song(risk = { 1f }), song(key = "b", risk = { 1f }))+ assertCause(voices, SegueLevel.LOCKED_LONG, SegueCause.GUARDS)+ assertTrue(voices.why, voices.why.contains("VOICE"))+ assertFalse(voices.level.cls == SegueClass.LOCKED)+ }++ @Test fun guardsAppliedOnlyToTheirClass() {+ assertEquals(emptyList<SegueGuard>(), SegueGuards.crossed(SegueClass.FILTERED, SegueMeasures(rateDeviationPpm = t.maxRateDeviationPpm + 1, gridReliable = false, phaseMedianUs = null), t))+ assertEquals(emptyList<SegueGuard>(), SegueGuards.crossed(SegueClass.HARD, SegueMeasures(voiceOverlapUs = t.voiceOverlapMaxUs + 1), t))+ }++ // ── Score ──++ @Test fun theScoreFollowsItsFormula() {+ val s = SegueScore(listOf(SegueNote("x", 2.0, 0.5, 0.5), SegueNote("y", 1.0, 1.0, 1.0)), listOf(SegueDefect("z", 0.5, 0.5)))+ assertEquals(2.0 * 0.5 * 0.5 + 1.0 - 0.25, s.total, 1e-12)+ }++ @Test fun anUncertainMeasureWeighsLessInsteadOfCountingAsAverage() {+ val trusted = SegueScore(listOf(SegueNote("x", 1.0, 1.0, 0.9)), emptyList()).total+ val unknown = SegueScore(listOf(SegueNote("x", 1.0, 0.0, 0.9)), emptyList()).total+ assertEquals(0.0, unknown, 1e-12)+ assertTrue(trusted > unknown)+ }++ @Test fun shapesOfTheTerms() {+ assertEquals(1.0, SegueScore.fallingFrom(5.0, 10.0, 20.0), 1e-12)+ assertEquals(0.5, SegueScore.fallingFrom(15.0, 10.0, 20.0), 1e-12)+ assertEquals(0.0, SegueScore.fallingFrom(25.0, 10.0, 20.0), 1e-12)+ assertEquals(0.0, SegueScore.risingFrom(5.0, 10.0, 20.0), 1e-12)+ assertEquals(1.0, SegueScore.gaussian(0.0, 3.0), 1e-12)+ assertTrue(SegueScore.gaussian(3.0, 3.0) < 0.7)+ }++ // ── Fallback: each level is reached by a synthetic situation, its cause recorded ──++ @Test fun level1LockedLong() {+ val d = decide(song("a"), song("b"))+ assertEquals(SegueLevel.LOCKED_LONG, d.level)+ val p = d.plan!!+ assertEquals(t.lockedLongBars, p.span.musicalUnits)+ assertEquals(32_000_000L, p.span.lengthUs)+ assertEquals(PulseState.LOCKED, p.pulse.state)+ assertTrue(d.attempts.isEmpty())+ assertEquals(120_000_000L, p.pulse.tempoMicroPerMinute)+ }++ @Test fun level2LockedShortWhenReliabilityShortensTheWindow() {+ val d = decide(song("a", metre = 0.7f), song("b", metre = 0.7f))+ assertEquals(SegueLevel.LOCKED_SHORT, d.level)+ assertEquals(t.lockedMiddleBars, d.plan!!.span.musicalUnits)+ assertCause(d, SegueLevel.LOCKED_LONG, SegueCause.LENGTH_NOT_ALLOWED)+ }++ @Test fun level3LockedOnADownbeatWhenNoPhraseBoundaryFits() {+ // Phrase boundaries fall at 176 s and 192 s; this checked grid lies strictly between them.+ val tail = Grid(178.0, 0.5, 26, 1.0, 0.0, 1.0)+ val d = decide(song("a", duration = 200.0, tail = tail), song("b"))+ assertEquals(d.why, SegueLevel.LOCKED_BEAT, d.level)+ assertCause(d, SegueLevel.LOCKED_LONG, SegueCause.NO_CANDIDATE)+ assertCause(d, SegueLevel.LOCKED_SHORT, SegueCause.NO_CANDIDATE)+ assertEquals(t.lockedShortBars, d.plan!!.span.musicalUnits)+ }++ @Test fun level3NeedsTheBassManaged() {+ val tail = Grid(178.0, 0.5, 26, 1.0, 0.0, 1.0)+ val d = decide(song("a", duration = 200.0, tail = tail), song("b"), eq = false)+ assertCause(d, SegueLevel.LOCKED_BEAT, SegueCause.BASS_NOT_MANAGED)+ }++ @Test fun level4FilteredWhenTemposAreOutOfReach() {+ val d = decide(song("a"), song("b", bpm = 100.0))+ assertEquals(d.why, SegueLevel.FILTERED, d.level)+ assertCause(d, SegueLevel.LOCKED_LONG, SegueCause.TEMPO_OUT_OF_REACH)+ val p = d.plan!!+ assertEquals(PulseState.FREE, p.pulse.state)+ assertEquals(SegueFormat.RATE_NOMINAL, p.incoming.ratePpm)+ assertTrue(p.span.lengthUs in t.filteredShortUs..t.filteredLongUs)+ assertTrue(p.lanes.any { it.target == Target.SWEEP_HZ && it.side == LaneSide.OUTGOING })+ }++ @Test fun level5HardWhenAnyOverlapWouldHaveTwoVoices() {+ val d = decide(song("a", risk = { 1f }), song("b", risk = { 1f }))+ assertEquals(d.why, SegueLevel.HARD, d.level)+ assertCause(d, SegueLevel.FILTERED, SegueCause.GUARDS)+ val p = d.plan!!+ assertEquals(t.microFadeUs, p.span.lengthUs)+ assertEquals(PulseState.LOOSE, p.pulse.state)+ assertEquals(2, p.lanes.size)+ }++ @Test fun hardNeedsCloseLoudness() {+ val d = decide(song("a", risk = { 1f }, barDb = -10f), song("b", risk = { 1f }, barDb = -20f))+ assertCause(d, SegueLevel.HARD, SegueCause.GUARDS)+ assertTrue(d.why, d.why.contains("LOUDNESS_JUMP"))+ }++ @Test fun level6SimpleFadeWithoutAnyGridOrBar() {+ val d = decide(song("a", grid = false, bars = false), song("b", grid = false, bars = false))+ assertEquals(d.why, SegueLevel.SIMPLE_FADE, d.level)+ assertCause(d, SegueLevel.LOCKED_LONG, SegueCause.NO_GRID)+ assertCause(d, SegueLevel.FILTERED, SegueCause.NO_CANDIDATE)+ assertCause(d, SegueLevel.HARD, SegueCause.NO_GRID)+ val p = d.plan!!+ assertEquals(PulseState.FREE, p.pulse.state)+ assertNull(p.outgoing.gridKey)+ assertEquals(t.simpleFadeUs, p.span.lengthUs)+ }++ @Test fun level7NormalPlaybackWithEveryCauseRecorded() {+ val d = decide(song("a", duration = 45.0), song("b"))+ assertEquals(SegueLevel.NORMAL, d.level)+ assertNull(d.plan)+ assertNull(SeguePolicy.timing(d))+ assertEquals(SegueLevel.values().toList().dropLast(1), d.attempts.map { it.level })+ assertTrue(d.why, d.why.contains("MIN_PLAYED"))+ }++ @Test fun albumContinuityIsLeftToPlayNatively() {+ val joined = decide(song("a"), song("b"), sameAlbum = true)+ assertEquals(SegueLevel.NORMAL, joined.level)+ assertTrue(joined.attempts.all { it.cause == SegueCause.ALBUM_CONTINUITY })+ // The same album with real silence at the junction is mixed.+ val gap = decide(song("a", contentEnd = 235.0), song("b"), sameAlbum = true)+ assertNotEquals(SegueLevel.NORMAL, gap.level)+ }++ // ── Placement ──++ @Test fun theWindowStaysWithinTheLastThirdAndBothSongs() {+ val d = decide(song("a"), song("b", bpm = 118.0))+ val p = d.plan!!+ assertTrue(p.outgoing.anchorUs >= 160_000_000)+ assertTrue(SegueValidator.windowEnd(p, p.outgoing) <= 240_000_000)+ assertEquals(emptyList<SegueViolation>(), SegueValidator.structural(p))+ }++ @Test fun anInstrumentalEndingIsPreferred() {+ // A's voice stops at bar 100 (200 s): leaving there beats leaving earlier over the voice.+ val d = decide(song("a", risk = { if (it < 100) 1f else 0f }), song("b"))+ assertEquals(SegueLevel.LOCKED_LONG, d.level)+ assertTrue(d.plan!!.toString(), d.plan!!.outgoing.anchorUs >= 192_000_000)+ }++ @Test fun nothingStartsBeforeTheEarliestExit() {+ val d = decide(song("a"), song("b"), earliest = 200_000_000)+ assertTrue(d.plan!!.outgoing.anchorUs >= 200_000_000)+ }++ @Test fun theRateIsAnExactIntegerAndLocksHalfTimeToo() {+ val p = decide(song("a"), song("b", bpm = 118.0)).plan!!+ assertEquals(Math.round(120.0 / 118.0 * 1e6), p.incoming.ratePpm)+ assertEquals(SegueFormat.RATE_NOMINAL, p.outgoing.ratePpm)+ assertEquals(SegueLevel.LOCKED_SHORT, decide(song("a"), song("b", bpm = 60.0)).level)+ }++ @Test fun listenerSettingsOnlyTighten() {+ val a = song("a"); val b = song("b", bpm = 118.0)+ assertEquals(SegueLevel.FILTERED, SeguePolicy.decide(SegueRequest(a, b, maxRatePpm = 1_000)).level)+ assertEquals(SegueLevel.LOCKED_LONG, SeguePolicy.decide(SegueRequest(a, b, maxRatePpm = 200_000)).level)+ assertEquals(SegueLevel.LOCKED_SHORT, SeguePolicy.decide(SegueRequest(a, b, maxBars = 8)).level)+ }++ @Test fun theListenerRateIsCarriedWithoutChangingTheAlignment() {+ val p = SeguePolicy.decide(SegueRequest(song("a"), song("b", bpm = 118.0), listenerRate = 1_250_000)).plan!!+ assertEquals(1_250_000L, p.outgoing.listenerRate)+ assertEquals(1_250_000L, p.incoming.listenerRate)+ assertEquals(32_000_000L, p.span.lengthUs)+ }++ @Test fun withoutTheEqOnlyLevelsAreWritten() {+ val p = decide(song("a"), song("b"), eq = false).plan!!+ assertTrue(p.lanes.all { it.target == Target.LEVEL })+ }++ // ── Lanes ──++ @Test fun lanesBoundPowerEndCleanAndHandTheBassOver() {+ for (d in listOf(decide(song("a"), song("b")), decide(song("a"), song("b", bpm = 100.0)), decide(song("a", grid = false, bars = false), song("b", grid = false, bars = false)))) {+ val p = d.plan!!+ val la = LaneCurve(p.lanes.first { it.side == LaneSide.OUTGOING && it.target == Target.LEVEL })+ val lb = LaneCurve(p.lanes.first { it.side == LaneSide.INCOMING && it.target == Target.LEVEL })+ assertEquals(0.0, la.value(0.0), 1e-3); assertTrue(lb.isNull(0.0))+ assertTrue(la.isNull(SegueFormat.T_MAX.toDouble())); assertEquals(0.0, lb.value(SegueFormat.T_MAX.toDouble()), 1e-3)+ for (i in 0..16) {+ val u = i * SegueFormat.T_MAX / 16.0+ val power = Math.pow(10.0, la.value(u) / 10) + Math.pow(10.0, lb.value(u) / 10)+ assertTrue("${d.level} at $i: $power", power <= 1.0 + 1e-3)+ }+ }+ val p = decide(song("a"), song("b")).plan!!+ val ba = LaneCurve(p.lanes.first { it.side == LaneSide.OUTGOING && it.target == Target.SHELF_BOTTOM })+ val bb = LaneCurve(p.lanes.first { it.side == LaneSide.INCOMING && it.target == Target.SHELF_BOTTOM })+ assertEquals(0.0, ba.value(0.0), 1e-9); assertEquals(t.bassKillDb, bb.value(0.0), 1e-9)+ assertEquals(t.bassKillDb, ba.value(SegueFormat.T_MAX.toDouble()), 1e-9); assertEquals(0.0, bb.value(SegueFormat.T_MAX.toDouble()), 1e-9)+ }++ @Test fun aLouderIncomingSongComesBackToItsOwnLevelInsideTheWindow() {+ val d = decide(song("a", loudness = -14.0), song("b", loudness = -9.0))+ val lb = LaneCurve(d.plan!!.lanes.first { it.side == LaneSide.INCOMING && it.target == Target.LEVEL })+ assertEquals(0.0, lb.value(SegueFormat.T_MAX.toDouble()), 1e-3)+ }++ @Test fun timingReadsThePlanForThePlayers() {+ val d = decide(song("a"), song("b", bpm = 118.0))+ val m = SeguePolicy.timing(d)!!+ val p = d.plan!!+ assertEquals(MixPlan.Style.BLEND, m.style)+ assertEquals(p.outgoing.anchorUs / 1e6, m.exitA, 1e-9)+ assertEquals(p.incoming.anchorUs / 1e6, m.entryB, 1e-9)+ assertEquals(32.0, m.length, 1e-9)+ assertEquals(120.0 / 118.0, m.speedB, 1e-6)+ assertTrue(m.restoreSec > 0)+ assertEquals(p, m.segue)+ assertEquals(MixPlan.Style.CUT, SeguePolicy.timing(decide(song("a", risk = { 1f }), song("b", risk = { 1f })))!!.style)+ val filtered = SeguePolicy.timing(decide(song("a"), song("b", bpm = 100.0)))!!+ assertEquals(MixPlan.Style.FADE, filtered.style); assertTrue(filtered.filtered)+ }++ // ── Determinism and invalidation ──++ @Test fun identicalRunsGiveTheSameFingerprint() {+ val cases = listOf(song("a") to song("b"), song("a") to song("b", bpm = 118.0), song("a") to song("b", bpm = 100.0),+ song("a", risk = { 1f }) to song("b", risk = { 1f }), song("a", grid = false, bars = false) to song("b", grid = false, bars = false))+ for ((x, y) in cases) {+ val one = decide(x, y); val two = decide(x, y)+ assertNotNull(one.fingerprint)+ assertEquals(one.fingerprint, two.fingerprint)+ assertEquals(one.why, two.why)+ assertEquals(SegueCodec.encode(one.plan!!), SegueCodec.encode(two.plan!!))+ }+ }++ @Test fun aChangedAudioOrGridForcesARecalculation() {+ val a = song("a"); val b = song("b")+ val p = decide(a, b).plan!!+ assertEquals(emptyList<SegueViolation>(), SeguePolicy.stale(p, a, b))+ assertEquals(listOf(SegueViolation.STALE_OUTGOING_AUDIO), SeguePolicy.stale(p, song("other"), b))+ assertEquals(listOf(SegueViolation.STALE_INCOMING_AUDIO), SeguePolicy.stale(p, a, song("other")))+ val moved = song("a", tail = Grid(0.01, 0.5, 480, 1.0, 0.0, 1.0))+ assertEquals(listOf(SegueViolation.STALE_OUTGOING_GRID), SeguePolicy.stale(p, moved, b))+ assertNotEquals(p.outgoing.gridKey, decide(moved, b).plan!!.outgoing.gridKey)+ }++ @Test fun theNewAnalysisFieldsSurviveTheCache() {+ val s = song("audio-key", phase = PhaseStats(1234, 5678), metre = 0.42f)+ val out = ByteArrayOutputStream(); s.write(out)+ val back = TrackAnalysis.read(ByteArrayInputStream(out.toByteArray()))!!+ assertEquals("audio-key", back.audioKey)+ assertEquals(PhaseStats(1234, 5678), back.headPhase); assertEquals(PhaseStats(1234, 5678), back.tailPhase)+ assertEquals(0.42f, back.headMetre, 1e-6f); assertEquals(0.42f, back.tailMetre, 1e-6f)+ assertEquals(-18f, back.barBassDb[3], 1e-6f)+ assertEquals(s.tailGridKey, back.tailGridKey)+ val none = song("x", phase = null)+ val o2 = ByteArrayOutputStream(); none.write(o2)+ assertNull(TrackAnalysis.read(ByteArrayInputStream(o2.toByteArray()))!!.headPhase)+ }+}diff --git a/docs/automix/segue-design.md b/docs/automix/segue-design.mdindex b8753252..7706abde 100644--- a/docs/automix/segue-design.md+++ b/docs/automix/segue-design.md@@ -110,3 +110,81 @@ 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 targetmust state its own in `Target`.++## Analysis the policy reads++Each quantity carries a reliability: an uncertain measure weighs less, it is not treated as an average.++| Quantity | Role | Reliability |+|---|---|---|+| Tempo and stability (`Grid`) | Whether alignment is possible; half and double time are explicit in `tempoMatch` | The grid's `steadiness` |+| Beats and metre | An alignment one beat off sounds wrong | `headMetre`/`tailMetre`: how clearly the downbeat votes chose one phase |+| Phase (`PhaseStats`) | Expected double attack: median and 95th percentile distance of the model's beats from the grid | Absent with too few beats, and then a locked candidate is refused |+| Structure and phrases | A change is expected at the end of a phrase | `sectionStrength`, or `reliabilityPhraseFallback` where only the fallback phrase grid speaks |+| Energy per bar | Avoids sudden drops or jumps | Direct measurement: 1 |+| Voice-like activity | Two voices together are hard to follow | `reliabilityVocalStereo`/`Mono`: a heuristic, not vocal separation, at bar resolution (about 2 s), which makes a limit of 1 s coarse |+| Key | Reduces clashes; fragile to detect. The engine time-stretches and keeps the pitch, so speed does not move the key | `keyStrength`, 0 when unknown |+| Spectrum (`barBassDb`, 20–150 Hz) | Two bass lines mask and interfere | Direct measurement |++`audioKey` hashes the decoded analysis signal. A different decoder may give a different hash: the+plan is then recomputed, which costs nothing but a calculation.++## Policy++Order: generate candidates, reject by guards, score, keep the best if it clears its class's+threshold, otherwise go to the next level. A crossed guard can never be bought back by good notes.+Choosing a pair is joint: pairs (exit, entry) are evaluated, at most `candidatesPerSide` per side,+and the same request always gives the same plan.++| Level | Class | Requires |+|---|---|---|+| `LOCKED_LONG` | locked | Reachable tempos, reliable grids, phrases on both sides, the longest length |+| `LOCKED_SHORT` | locked | The same, shorter |+| `LOCKED_BEAT` | locked | Any shared downbeat, and only if the bass is managed |+| `FILTERED` | filtered | No alignment; filtered exit, limited overlap, progressive entry, without two voices |+| `HARD` | hard | Clear boundaries, close loudness, on a downbeat; an anti-click fade alone |+| `SIMPLE_FADE` | fade | A short fade from a safe point |+| `NORMAL` | none | Plain playback. Not a failure: no effect beats a bad effect |++Each level left behind records its cause in `SegueDecision.attempts`, outside the fingerprint.++The score is `Σ weight × reliability × note − Σ penalty × defect`. Notes and defects run from 0 to 1.+Scores compare only within a class; between classes the fallback order decides.++| Term | Kind | Role | Form |+|---|---|---|---|+| Rhythm | Note, strong | Makes the passage forgettable | Falls from `rhythmFullUs` to `phaseMedianMaxUs` |+| Phrase | Note, strong | Makes the sections coincide | 0.5 per side on a boundary |+| Energy | Note, medium | Avoids holes in the tension | Gaussian on the level gap, `energySigmaDb` |+| Exit | Note, medium | Leaves at the end of a phrase or on a calm section | Share without voice in the window's second half |+| Entry | Note, medium | Avoids entering mid-phrase | 1 on the first attack, less on a later section, less with the time skipped |+| Key | Note, weak | Reduces clashes | Distance on the wheel of fifths |+| Speed | Defect, medium | Prefers the least alteration | Rises from `rateCostFreePpm` to the guard |+| Voice | Defect, strong | Goes beyond the guard | Overlap weighted by audibility, over `voiceOverlapMaxUs` |+| Bass | Defect, medium | Limits masking | Common energy over total energy, 20–150 Hz, after levels and shelves |+| Lost | Defect, weak to medium | Prefers keeping the music | Seconds removed over `contentCutMaxUs` |+| Sobriety | Defect, weak | Avoids gratuitous effects | Effect lanes over `sobrietyFullEffects` |++`SegueTuning.kt` documents each parameter, with its label and range, and is the only place for them.++### Parameters that were not in the design's tables++These had no value or only a word, and were added as proposals to measure. All are `[I]` unless+marked `[R]`, reused from this repository.++| Parameter | Value | Why it is needed |+|---|---|---|+| Strong, medium, weak, weak to medium | 1.0, 0.5, 0.2, 0.35 | The design names the weights qualitatively |+| `gridMinBeats`, `gridMinSteadiness`, `gridMaxDriftMs` | 16, 0.6, 30 ms `[R]` | The design leaves the grid's reliability floor to measurement; these are the existing `Grid.reliable` |+| `thresholdLocked` | 0.5 `[R]` | The earlier blend floor, on a different scale |+| `thresholdFiltered`, `thresholdHard` | 0.25 | Each class needs a threshold |+| `contentCutMaxUs` | 60 s | The design caps the cut in seconds without a value |+| `gaplessMaxSilenceUs` | 300 ms | What counts as a junction without silence |+| `entryNoteSection`, `entryNoteOther` | 0.6, 0.3 | A later entry must score below the first attack |+| `sobrietyFullEffects`, `bassSampleSteps`, `curveKnots` | 3, 32, 16 | Normalisation and sampling |+| `reliabilityPhraseFallback`, `reliabilityVocalStereo`, `reliabilityVocalMono` | 0.3, 0.6, 0.2 | Measures with no confidence of their own |+| `reliabilityForLong`, `reliabilityForMiddle` | 0.8, 0.6 | The lower the reliability, the shorter the window |+| `filteredMiddleUs` | 8 s | Between the design's 4 and 12 s |+| `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 |