Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
automix: mixes land where the incoming song arrives
kota-zoa34790fdd7a9
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.ktindex 144bdf95..fdcbfd55 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePolicy.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SeguePolicy.kt@@ -103,7 +103,7 @@ object SeguePolicy {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 Point(val us: Long, val bar: Int, val rank: Double, val boundary: Boolean, val arrives: Boolean = false)/** [score] decides whether a level is good enough; [pick] decides between candidates of one level. */private class Found(val plan: SeguePlan, val score: Double, val swap: Double, val shape: SegueShape? = null, val restoreSec: Double = 0.0, val pick: Double = score)@@ -263,7 +263,7 @@ object SeguePolicy {val plan = plan(e.stretch.startUs, n.stretch.startUs, ga, gb, ratePpm, lengthUs, bars, PulseState.LOCKED, us60(ga), phaseMedian, lanes).copy(echoUs = if (shape == SegueShape.ECHO_TAIL) echoOf(ga.period) else null)val score = score(e.point, n.point, lengthUs, spanUs, phaseMedian, deviation, lanes, pulse, bars, barsB)- val pick = score.total - t.lostPickLocked * skipped(e.point, n.point, lengthUs)+ val pick = score.total - t.lostPickLocked * skipped(e.point, n.point, lengthUs) + (if (n.point.arrives && score.total >= t.thresholdLocked) t.arrivalPick * n.point.rank else 0.0)if (best == null || pick > best.pick) best = Found(plan, score.total, swap, shape, restore(ratePpm, gb.period), pick)}}@@ -306,7 +306,20 @@ object SeguePolicy {return (out.sortedByDescending { it.point.rank }.take(t.candidatesPerSide) + out.sortedByDescending { it.point.us }.take(t.lateCandidates)).distinctBy { it.point.us }}- /** B's stretches from its useful attack; leaving out a start must be worth its note. */+ /** How far B arrives right after a window of [bars] from [bar], 0..1: its level rising past the window. */+ private fun arrival(bar: Int, bars: Int): Double {+ val end = bar + bars+ if (end + 5 > b.bars) return 0.0+ return ((rise(end, bars) - t.arrivalRiseMinDb) / (t.arrivalRiseFullDb - t.arrivalRiseMinDb)).coerceIn(0.0, 1.0)+ }++ /** B's level over the next bars from [end], against the [bars] bars before it. */+ private fun rise(end: Int, bars: Int): Double = sb.levelBars(end, end + 4) - sb.levelBars(max(0, end - bars), end)++ /** No bar next to [end] rises more: the song arrives here, not a bar before or after. */+ private fun sharpest(end: Int, bars: Int): Boolean = rise(end, bars) >= rise(end - 1, bars) && rise(end, bars) >= rise(end + 1, bars)++ /** B's stretches from its useful attack, and where it arrives; leaving out a start must be worth its note. */private fun stretchEntries(bars: Int, phrases: Boolean, tally: Tally): List<Placed> {val startUs = us(b.contentStart)val zone = min(startUs + t.entryZoneUs, us(b.contentEnd) / 3)@@ -316,12 +329,14 @@ object SeguePolicy {val at = us(b.barStarts[bar])if (bar != firstBar && at >= zone) breakval on = boundary(b, bar)- if (phrases && !on && bar != firstBar) continue+ val arrival = if (bar == firstBar) 0.0 else arrival(bar, bars)+ if (phrases && !on && bar != firstBar && arrival == 0.0) continueval s = cached(incomingStretches, b, bar, bars, b.headMetre.toDouble())+ ?: if (arrival > 0.0) Stretches.carried(b, bar, bars, b.headMetre.toDouble(), t) else nullif (s == null) { if (bar + bars < b.bars) tally.refused(listOf(SegueGuard.GRID_RELIABILITY)); continue }val rank = if (bar == firstBar) 1.0- else (if (b.sectionStrength(bar) > 0) t.entryNoteSection else t.entryNoteOther) * (1 - (at - startUs).toDouble() / t.entryZoneUs)- out += Placed(s, Point(s.startUs, bar, rank, on || bar == firstBar))+ else max(arrival, (if (b.sectionStrength(bar) > 0) t.entryNoteSection else t.entryNoteOther) * (1 - (at - startUs).toDouble() / t.entryZoneUs))+ out += Placed(s, Point(s.startUs, bar, rank, on || bar == firstBar, arrives = arrival > 0.0))}return out.sortedByDescending { it.point.rank }.take(t.candidatesPerSide)}@@ -371,7 +386,7 @@ object SeguePolicy {/** Music the listener never hears, the end of one song and the start of the other, 0..1. */private fun skipped(e: Point, n: Point, lengthUs: Long): Double =- ((max(0L, us(a.contentEnd) - (e.us + lengthUs)) + max(0L, n.us - us(b.contentStart))).toDouble() / t.lostFullUs).coerceAtMost(1.0)+ ((max(0L, us(a.contentEnd) - (e.us + lengthUs)) + (if (n.arrives) 0L else max(0L, n.us - us(b.contentStart)))).toDouble() / t.lostFullUs).coerceAtMost(1.0)/** The outgoing song runs long enough past the window for a send to ring out. */private fun rings(exitUs: Long, lengthUs: Long) = us(a.duration) - (exitUs + lengthUs) >= t.sendTailUs@@ -404,6 +419,27 @@ object SeguePolicy {return listOf(fit) + lengths.filter { it != fit }}+ /**+ * Songs that cannot be locked still need not share a long quiet opening: a fade over the end+ * of it, up to where B clearly arrives at its full level, the rest of it left out.+ */+ private fun fadeArrivals(lengthUs: Long): List<Point> {+ val startUs = us(b.contentStart)+ val zone = min(startUs + t.entryZoneUs, us(b.contentEnd) / 3)+ val out = ArrayList<Point>()+ for (bar in 1 until b.bars - 5) {+ val endUs = us(b.barStarts[bar])+ val inUs = endUs - lengthUs+ if (endUs >= zone) break+ if (inUs - startUs < t.fadeArrivalMinSkipUs) continue+ val from = b.barAt(inUs / 1e6)+ if (from < 0 || from >= bar) continue+ if (rise(bar, bar - from) < t.fadeArrivalRiseDb || !sharpest(bar, bar - from) || sb.levelBars(bar, bar + 4) < sb.loud - t.arrivalNearFullDb) continue+ out += Point(inUs, from, 1.0, true, arrives = true)+ }+ return out.sortedBy { it.us }.take(t.candidatesPerSide)+ }+private fun filtered(level: SegueLevel): Found? {val rel = tempoReliability(ga)val lengths = when {@@ -417,7 +453,7 @@ object SeguePolicy {// A fade need not start on a bar: the one that ends with the music keeps the most of the song.val ending = if (a.bars > 0) sequenceOf((us(a.contentEnd) - lengthUs) / 1e6) else emptySequence()val outs = exits(a.barStarts.asSequence() + ending, lengthUs, us(a.contentEnd), phrases = false)- val ins = entries(gb, lengthUs, phrases = false)+ val ins = entries(gb, lengthUs, phrases = false) + fadeArrivals(lengthUs)for (e in outs) for (n in ins) {tally.seen++if (tally.refused(SegueGuards.crossed(SegueClass.FILTERED, measures(e, n, lengthUs, lengthUs), t))) continue@@ -428,7 +464,7 @@ object SeguePolicy {val plan = plan(e.us, n.us, ga, gb, SegueFormat.RATE_NOMINAL, lengthUs, null, PulseState.FREE, null, null, lanes).copy(echoUs = if (shape == SegueShape.ECHO_OUT) ga?.let { echoOf(it.period) } else null)val score = score(e, n, lengthUs, lengthUs, null, 0, lanes)- val pick = score.total - t.lostPickFade * skipped(e, n, lengthUs)+ val pick = score.total - t.lostPickFade * skipped(e, n, lengthUs) + (if (n.arrives && score.total >= t.thresholdFiltered) t.arrivalPick else 0.0)if (best == null || pick > best.pick) best = Found(plan, score.total, at, shape, pick = pick)}if (best != null && best.score >= t.thresholdFiltered) break@@ -518,7 +554,9 @@ object SeguePolicy {pulse: Double = pulseReliability(), barsA: Int? = null, barsB: Int? = null): SegueScore {val a0 = e.us / 1e6; val a1 = (e.us + lengthUs) / 1e6; val b0 = n.us / 1e6; val b1 = (n.us + spanUs) / 1e6val 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))+ // An arrival is heard at the level it arrives at, not at that of the build-up.+ val heard = if (n.arrives) b.barAt(b1) else max(0, n.bar)+ val energy = abs(sa.levelBars(max(0, endBar - 3), endBar + 1) - sb.levelBars(heard, heard + 4))val rhythm = phaseUs?.let { SegueScore.fallingFrom(it.toDouble(), t.rhythmFullUs.toDouble(), t.phaseMedianMaxUs.toDouble()) } ?: 0.0val phrase = phraseNote(a, e, barsA) + phraseNote(b, n, barsB)val notes = listOf(diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueStretch.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueStretch.ktindex 44cc2a82..52f97fd6 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueStretch.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueStretch.kt@@ -83,6 +83,25 @@ internal object Stretches {return Stretch(bar, bars, Grid(first, period, beatCount, share, drift * 1000, 1.0), beats, min(share, down))}+ /**+ * A build-up has too few clear beats of its own to be measured, and the song arrives right after it:+ * the [bars] bars from [bar] take the beat of the bars they lead into, carried back, when it lands+ * on their start. Null when what follows does not hold or does not line up.+ */+ fun carried(s: TrackAnalysis, bar: Int, bars: Int, metre: Double, t: SegueTuning): Stretch? {+ if (bar < 0) return null+ val beatCount = 4 * bars+ for (gap in 0..t.carrySearchBars) {+ val next = measure(s, bar + bars + gap, t.carryFromBars, metre, t) ?: continue+ val period = next.grid.period+ val first = next.grid.first - (beatCount + 4 * gap) * period+ if (abs(first - s.barStarts[bar]) * 1e6 > t.carryMaxOffUs) return null+ return Stretch(bar, bars, Grid(first, period, beatCount, 1.0, next.grid.driftMs, 1.0),+ DoubleArray(beatCount) { first + it * period }, min(next.reliability, t.reliabilityForMiddle))+ }+ return null+ }+/*** How far apart the two stretches' beats fall once the incoming one plays at [rate] from its start* on the outgoing one's start: the sparser beats against the nearest of the denser. Median anddiff --git a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.ktindex a39b32cf..42f8142d 100644--- a/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt+++ b/base/automix/src/main/kotlin/app/myspoti/automix/segue/SegueTuning.kt@@ -10,8 +10,8 @@ package app.myspoti.automix.segue*/data class SegueTuning(// ── Guards: one crossing rejects a candidate, whatever its score ──- /** Largest speed change in the locked class, ppm. [U] range 4–8 %, the top of it: the stretch keeps the pitch, and the bench lost most pairs to this guard. */- val maxRateDeviationPpm: Long = 80_000,+ /** Largest speed change in the locked class, ppm. [I] past the 4–8 % of [U]: the stretch keeps the pitch and most pairs were lost to this guard. To be heard. */+ val maxRateDeviationPpm: Long = 100_000,/** Expected phase error: median [U], against double attacks. */val phaseMedianMaxUs: Long = 20_000,/** Expected phase error: 95th percentile [U]. */@@ -114,6 +114,22 @@ data class SegueTuning(val exitZoneShare: Double = 1.0 / 3.0,/** Entries lie within this much of the first attack [R]. */val entryZoneUs: Long = 40_000_000,+ /**+ * A window that ends where the incoming song arrives, its level rising after it [I]: this rise+ * earns the full note, and less than the smallest earns none. What it leaves out is not lost.+ */+ val arrivalRiseFullDb: Double = 6.0,+ val arrivalRiseMinDb: Double = 2.0,+ /** A build-up's beat carried back from this many bars after it [I], landing this near its start [I]. */+ val carryFromBars: Int = 4,+ val carrySearchBars: Int = 8,+ val carryMaxOffUs: Long = 80_000,+ /** Choosing within a level: what a full arrival is worth over a start [I]. */+ val arrivalPick: Double = 0.5,+ /** A fade reaches for an arrival only for this much rise, leaving out at least this much, to within this of the song's level [I]. */+ val fadeArrivalRiseDb: Double = 10.0,+ val fadeArrivalMinSkipUs: Long = 8_000_000,+ val arrivalNearFullDb: Double = 3.0,/** Best candidates kept per side [I] range 3–8. */val candidatesPerSide: Int = 8,/** The latest exits always tried besides the best-ranked [I]. */diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBench.kt b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBench.ktindex d26045a3..5d64a8c8 100644--- a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBench.kt+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBench.kt@@ -38,6 +38,7 @@ object SegueBench {when (rest.firstOrNull()) {"split" -> printSplit(dir)"tempos" -> tempos(dir, fold)+ "bars" -> bars(dir, fold)"voices" -> voices(dir, fold)"tails" -> tails(dir, fold, limit ?: 12)"matrix" -> matrix(dir, fold, rest.contains("fresh"))@@ -141,6 +142,17 @@ object SegueBench {String.format(L, "\t%.1f\t%.1f\t%.1f\t%.1f", s.duration, s.contentStart, s.contentEnd, s.barStarts.lastOrNull() ?: 0.0))}+ /** Every song's bars: where they start, the phrase and section marks, the level. */+ private fun bars(dir: File, fold: String?) {+ val names = names(dir, fold)+ val songs = analyses(dir, names, false)+ println("song\tbar\tstart\tphrase\tsection\tlevel\tcontentStart")+ for ((n, s) in songs) {+ val st = app.myspoti.automix.MixPlanner.summary(s)+ for (i in 0 until s.bars) println(String.format(L, "%s\t%d\t%.3f\t%d\t%.3f\t%.2f\t%.3f", n, i, s.barStarts[i], s.phrasePos(i), s.sectionStrength(i), st.levelBars(i, i + 1), s.contentStart))+ }+ }+private fun matrix(dir: File, fold: String?, fresh: Boolean) {val names = names(dir, fold)val songs = analyses(dir, names, fresh)diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBenchTest.kt b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBenchTest.ktindex be7c4656..de8dfede 100644--- a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBenchTest.kt+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SegueBenchTest.kt@@ -97,8 +97,8 @@ class SegueBenchTest {val all = SegueCorpus.variations(base)assertTrue(all.size > 80)val v = all.first { it.first == "maxRateDeviationPpm\t1.2" }.second- assertEquals(96_000L, v.maxRateDeviationPpm)- assertEquals(base.copy(maxRateDeviationPpm = 96_000), v)+ assertEquals(120_000L, v.maxRateDeviationPpm)+ assertEquals(base.copy(maxRateDeviationPpm = 120_000), v)assertNotNull(all.first { it.first == "energySigmaDb\t0.8" })for ((_, t) in all) assertNotEquals(base, t)}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.ktindex a6aa9aeb..e93be1a7 100644--- a/base/automix/src/test/kotlin/app/myspoti/automix/segue/SeguePolicyTest.kt+++ b/base/automix/src/test/kotlin/app/myspoti/automix/segue/SeguePolicyTest.kt@@ -33,6 +33,7 @@ class SeguePolicyTest {contentStart: Double = 0.0,contentEnd: Double = duration,barDb: Float = -10f,+ barLevel: ((Int) -> Float)? = null,down: Double = 0.0,risk: (Int) -> Float = { 0f },modelBeats: DoubleArray? = null,@@ -42,7 +43,7 @@ class SeguePolicyTest {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, if (grid && bars) DoubleArray(g.count) { g.beat(it) } else DoubleArray(0), DoubleArray(n) { it * 4 * beat },- FloatArray(n) { barDb }, FloatArray(n) { -16f }, FloatArray(n) { -20f }, FloatArray(n), FloatArray(n), 0, stereo,+ FloatArray(n) { barLevel?.invoke(it) ?: barDb }, FloatArray(n) { -16f }, FloatArray(n) { -20f }, FloatArray(n), FloatArray(n), 0, stereo,if (grid) down 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,modelBeats = modelBeats ?: DoubleArray(0))@@ -173,6 +174,31 @@ class SeguePolicyTest {assertEquals(2, p.lanes.size)}+ /** 24 s of quiet opening, then the song at its full level: bar 12 at 120 BPM. */+ private val arrivesAt24: (Int) -> Float = { if (it < 12) -30f else -10f }++ @Test fun aLockedMixEndsWhereTheSongArrives() {+ // Windows that fit the build-up; the song rises by the rise that earns the full note.+ val d = decide(song("a"), song("b", barLevel = { if (it < 12) -16f else -10f }), tuning = SegueTuning(reliabilityForLong = 2.0))+ assertEquals(d.why, SegueClass.LOCKED, d.level.cls)+ val p = d.plan!!+ val rate = p.incoming.ratePpm.toDouble() / SegueFormat.RATE_NOMINAL+ assertEquals(24_000_000.0, p.incoming.anchorUs + p.span.lengthUs * rate, 50_000.0)+ }++ @Test fun aFadeOfSongsThatCannotBeLockedEndsWhereTheSongArrivesToo() {+ val d = decide(song("a", bpm = 90.0), song("b", bpm = 120.0, barLevel = arrivesAt24), tuning = SegueTuning(maxRateDeviationPpm = 10_000))+ assertEquals(d.why, SegueClass.FILTERED, d.level.cls)+ val p = d.plan!!+ assertEquals(24_000_000L, p.incoming.anchorUs + p.span.lengthUs)+ }++ @Test fun aSmallRiseDoesNotCostAFadeTheOpening() {+ val d = decide(song("a", bpm = 90.0), song("b", bpm = 120.0, barLevel = { if (it < 12) -14f else -10f }), tuning = SegueTuning(maxRateDeviationPpm = 10_000))+ assertEquals(d.why, SegueClass.FILTERED, d.level.cls)+ assertEquals(0L, d.plan!!.incoming.anchorUs)+ }+@Test fun aCutThatSkipsTooMuchLeavesItToAShortFadeAtTheEnd() {val d = decide(song("a", risk = { 1f }), song("b", risk = { 1f }))assertEquals(d.why, SegueLevel.SIMPLE_FADE, d.level)