Skip to content

Native Android client for Spotify, built with Jetpack Compose

automix: take voices from timed lyrics when a song has them

kota-zo9f53f7c03de6
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
index 23a085ee..f854613b 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
@@ -151,6 +151,17 @@ object LyricsApi {
sourcesTick.value++
}
+ /** What is already here for [track], from memory or storage, whole: asks no one. */
+ fun known(track: Track): Lyrics? {
+ val found = when (val c = cache[track.key]) {
+ is Lyrics -> c
+ is Partial -> null
+ is Miss -> null
+ else -> LyricsDisk.read(track.key)
+ }
+ return found?.takeIf { it.synced && it.uncapped && !it.isEmpty }
+ }
+
suspend fun fetch(track: Track): Lyrics? {
when (val c = cache[track.key]) {
is Lyrics -> return c
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 9b59b2bc..c0483bca 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -743,8 +743,10 @@ object LocalPlayer {
segueWork = work
segueWorker.execute {
runCatching {
- val d = com.music.spotui.automix.AutoMix.decide(ra, rb, from, sameAlbum, listener)
- work.note = "segue ${d.level} ${d.shape ?: ""} ${d.fingerprint?.take(12) ?: ""}${if (d.attempts.isEmpty()) "" else ": ${d.why}"}"
+ val sungA = sung(a, ra); val sungB = sung(b, rb)
+ val d = com.music.spotui.automix.AutoMix.decide(sungA, sungB, from, sameAlbum, listener)
+ val voices = "voices ${if (sungA.voiceKnown) "lyrics" else "estimate"}/${if (sungB.voiceKnown) "lyrics" else "estimate"}"
+ work.note = "segue ${d.level} ${d.shape ?: ""} ${d.fingerprint?.take(12) ?: ""} $voices${if (d.attempts.isEmpty()) "" else ": ${d.why}"}"
work.plan = app.myspoti.automix.segue.SeguePolicy.timing(d)
}.onFailure { work.note = "segue failed: $it"; work.plan = null }
work.done = true
@@ -752,6 +754,15 @@ object LocalPlayer {
return false
}
+ /** [analysis] with its voices from the song's timed lyrics, when they are already here. On the plan's thread. */
+ private fun sung(t: LocalTrack, analysis: app.myspoti.automix.TrackAnalysis): app.myspoti.automix.TrackAnalysis {
+ val lyrics = com.music.spotui.data.api.LyricsApi.known(com.music.spotui.data.api.LyricsApi.Track(spotifyId(t), t.title, t.artist, t.album, t.durationMs)) ?: return analysis
+ val lines = lyrics.lines.map { l ->
+ app.myspoti.automix.SungSpans.Line(l.timeMs, l.words?.lastOrNull()?.endMs?.takeIf { it > 0 }, l.text.isNotBlank())
+ }
+ return app.myspoti.automix.SungSpans.of(lines, analysis.duration)?.let(analysis::withSung) ?: analysis
+ }
+
/** The plan for two analysed songs, once [segueDecided]. With the data plans on, null means the policy chose plain playback. */
private fun choosePlan(ra: app.myspoti.automix.TrackAnalysis, rb: app.myspoti.automix.TrackAnalysis, earliest: Double): app.myspoti.automix.MixPlan? {
if (!com.music.spotui.automix.AutoMix.segueActive) return com.music.spotui.automix.AutoMix.planAfter(ra, rb, earliest)
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/SungSpans.kt b/base/automix/src/main/kotlin/app/myspoti/automix/SungSpans.kt
new file mode 100644
index 00000000..99e29417
--- /dev/null
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/SungSpans.kt
@@ -0,0 +1,31 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix
+
+import kotlin.math.min
+
+/** Where a song is sung, read from its timed lyrics. Better than the spectral estimate wherever a song has them. */
+object SungSpans {
+ /** A line's start, in ms; [lastWordEndMs] when its words are timed; [sung]: it has words at all. */
+ class Line(val startMs: Long, val lastWordEndMs: Long?, val sung: Boolean)
+
+ /** Fewer timed lines than this says little about the song. */
+ private const val MIN_LINES = 5
+ /** A line whose end is unknown is taken to last until the next one, but no longer than this. */
+ private const val LONGEST_LINE_MS = 7_000L
+ private const val LAST_LINE_MS = 4_000L
+
+ /** The spans in seconds, or null when these lines cannot be trusted for a song of [durationSec]: too few, or running past its end. */
+ fun of(lines: List<Line>, durationSec: Double): List<Pair<Double, Double>>? {
+ val sorted = lines.sortedBy { it.startMs }
+ if (sorted.count { it.sung } < MIN_LINES) return null
+ // Lyrics of another version of the song; a little past the end is only a late last line.
+ if (sorted.last().startMs / 1000.0 > durationSec + 2) return null
+ return sorted.indices.filter { sorted[it].sung }.map { i ->
+ val line = sorted[i]
+ val end = line.lastWordEndMs?.takeIf { it > line.startMs }
+ ?: sorted.getOrNull(i + 1)?.let { min(it.startMs, line.startMs + LONGEST_LINE_MS) }
+ ?: (line.startMs + LAST_LINE_MS)
+ line.startMs / 1000.0 to end / 1000.0
+ }
+ }
+}
diff --git a/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt b/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt
index 54a17f5c..788dbc03 100644
--- a/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt
+++ b/base/automix/src/main/kotlin/app/myspoti/automix/TrackAnalysis.kt
@@ -1,6 +1,9 @@
/* SPDX-License-Identifier: GPL-3.0-only */
package app.myspoti.automix
+import kotlin.math.max
+import kotlin.math.min
+
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.InputStream
@@ -64,8 +67,23 @@ class TrackAnalysis(
val modelBeats: DoubleArray = DoubleArray(0),
/** How sure the model is of a downbeat at each bar start, 0..1; empty without the model. */
val barDownConfidence: FloatArray = FloatArray(0),
+ /** [barVocalRisk] comes from the song's timed lyrics, not from the spectral estimate. Not stored: lyrics come and go. */
+ val voiceKnown: Boolean = false,
) {
val bars get() = barStarts.size
+
+ /** This analysis with its voices taken from [spans], seconds from the song's start where it is known to be sung. */
+ fun withSung(spans: List<Pair<Double, Double>>): TrackAnalysis {
+ val sorted = spans.filter { it.second > it.first }.sortedBy { it.first }
+ val risk = FloatArray(bars) { i ->
+ val from = barStarts[i]; val to = barEnd(i)
+ val sung = sorted.sumOf { (a, b) -> max(0.0, min(to, b) - max(from, a)) }
+ if (to > from && sung / (to - from) >= SUNG_BAR_SHARE) SUNG_RISK else UNSUNG_RISK
+ }
+ return TrackAnalysis(duration, contentStart, contentEnd, loudnessDb, key, keyStrength, bpm, steady, head, tail, beats, barStarts,
+ barDb, barLowDb, barHighDb, barCentre, barNovelty, phraseOffset, stereo, headDown, tailDown, note, risk, audioKey, barBassDb,
+ headPhase, tailPhase, headMetre, tailMetre, modelBeats, barDownConfidence, voiceKnown = true)
+ }
/** 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) } }
@@ -122,6 +140,11 @@ class TrackAnalysis(
}
companion object {
+ /** A bar with this share of it sung counts as sung. */
+ private const val SUNG_BAR_SHARE = 0.3
+ private const val SUNG_RISK = 0.95f
+ private const val UNSUNG_RISK = 0.02f
+
const val VERSION = 4_10
fun read(input: InputStream): TrackAnalysis? {
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.kt
index 663a21b4..30bc89f8 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
@@ -157,7 +157,11 @@ object SeguePolicy {
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 vocalReliability() = when {
+ a.voiceKnown && b.voiceKnown -> 1.0
+ 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
diff --git a/base/automix/src/test/kotlin/app/myspoti/automix/SungSpansTest.kt b/base/automix/src/test/kotlin/app/myspoti/automix/SungSpansTest.kt
new file mode 100644
index 00000000..8cfded85
--- /dev/null
+++ b/base/automix/src/test/kotlin/app/myspoti/automix/SungSpansTest.kt
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package app.myspoti.automix
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class SungSpansTest {
+ private fun line(start: Long, wordEnd: Long? = null, sung: Boolean = true) = SungSpans.Line(start, wordEnd, sung)
+ private val five = listOf(line(1_000), line(3_000), line(5_000), line(7_000), line(9_000))
+
+ @Test fun aLineLastsUntilTheNextOne() {
+ val spans = SungSpans.of(five, 180.0)!!
+ assertEquals(5, spans.size)
+ assertEquals(1.0 to 3.0, spans[0])
+ }
+
+ @Test fun timedWordsSayWhereALineEnds() {
+ val spans = SungSpans.of(listOf(line(1_000, 2_200)) + five.drop(1), 180.0)!!
+ assertEquals(1.0 to 2.2, spans[0])
+ }
+
+ @Test fun aLongGapIsNotSung() {
+ val spans = SungSpans.of(five + line(60_000), 180.0)!!
+ assertEquals(9.0 to 16.0, spans[4])
+ }
+
+ @Test fun anEmptyLineIsABreak() {
+ val spans = SungSpans.of(five + line(11_000, sung = false) + line(20_000), 180.0)!!
+ assertEquals(9.0 to 11.0, spans[4])
+ assertEquals(6, spans.size)
+ }
+
+ @Test fun tooFewLinesOrLinesPastTheEndAreNotTrusted() {
+ assertNull(SungSpans.of(five.take(4), 180.0))
+ assertNull(SungSpans.of(five + line(200_000), 180.0))
+ }
+}
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.kt
index 60ad4e48..ed9b98d2 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
@@ -30,13 +30,15 @@ object SegueBench {
fun run(dir: File, args: List<String>) {
val fold = args.firstOrNull { it.startsWith("fold=") }?.removePrefix("fold=")
val limit = args.firstOrNull { it.startsWith("limit=") }?.removePrefix("limit=")?.toInt()
- val rest = args.filter { !it.contains('=') }
+ val rest = args.filter { !it.contains('=') && it != "sung" }
+ sung = "sung" in args
tuning = args.firstOrNull { it.startsWith("with=") }?.removePrefix("with=")?.split(',')?.fold(SegueTuning()) { t, kv ->
val (k, v) = kv.split(':'); SegueCorpus.withValue(t, k, v.toDouble())
} ?: SegueTuning()
when (rest.firstOrNull()) {
"split" -> printSplit(dir)
"tempos" -> tempos(dir, fold)
+ "voices" -> voices(dir, fold)
"tails" -> tails(dir, fold, limit ?: 12)
"matrix" -> matrix(dir, fold, rest.contains("fresh"))
"measure" -> measure(dir, fold, limit ?: 100, args.firstOrNull { it.startsWith("only=") }?.removePrefix("only="))
@@ -55,7 +57,16 @@ object SegueBench {
return all.filter { split[it] == fold }
}
- private fun analyses(dir: File, names: List<String>, fresh: Boolean = false) = names.associateWith { BenchCache.analysis(dir, it, fresh).analysis }
+ /** With the `sung` argument, each song's voices come from `sung/<id>.tsv`, as they do on the phone when lyrics are known. */
+ private var sung = false
+
+ private fun analysis(dir: File, name: String, fresh: Boolean = false): TrackAnalysis {
+ val a = BenchCache.analysis(dir, name, fresh).analysis
+ val spans = File(dir, "sung/$name.tsv").takeIf { sung && it.exists() } ?: return a
+ return a.withSung(spans.readLines().filter { it.isNotBlank() }.map { l -> l.split('\t').let { it[0].toDouble() to it[1].toDouble() } })
+ }
+
+ private fun analyses(dir: File, names: List<String>, fresh: Boolean = false) = names.associateWith { analysis(dir, it, fresh) }
private fun printSplit(dir: File) {
val rows = SegueCorpus.read(File(dir, "names.txt"))
@@ -114,6 +125,13 @@ object SegueBench {
tmp.deleteRecursively()
}
+ /** Each song's bars and how likely a voice is on them. */
+ private fun voices(dir: File, fold: String?) {
+ val names = names(dir, fold)
+ for ((name, s) in analyses(dir, names, false)) for (i in 0 until s.bars)
+ println(String.format(L, "%s\t%.3f\t%.3f\t%.3f", name, s.barStarts[i], s.barEnd(i), s.barVocalRisk.getOrElse(i) { 0f }))
+ }
+
/** Each song's tempo as the grid has it, at both ends. */
private fun tempos(dir: File, fold: String?) {
val names = names(dir, fold)
@@ -257,7 +275,7 @@ object SegueBench {
val cache = HashMap<String, FloatArray>()
for (pair in asked) {
val (x, y) = pair.split(',')
- val d = SeguePolicy.decide(request(BenchCache.analysis(dir, x).analysis, BenchCache.analysis(dir, y).analysis))
+ val d = SeguePolicy.decide(request(analysis(dir, x), analysis(dir, y)))
val p = d.plan
println("$x,$y ${d.level} ${d.fingerprint ?: ""} | ${d.why}")
if (p == null) continue
diff --git a/docs/automix/segue-design.md b/docs/automix/segue-design.md
index 025ed1bf..35881a4b 100644
--- a/docs/automix/segue-design.md
+++ b/docs/automix/segue-design.md
@@ -301,3 +301,7 @@ Four shapes use them. `ECHO_OUT` throws the outgoing song into the echo on the d
## What is skipped
The level a pair reaches is still judged on `score`, but the candidate within a level is chosen on `pick`: the score less a cost for the music nobody hears, the end of one song and the start of the other. Taking this out of the score keeps a locked mix from losing its level because it skips an intro. Fades pay more for it than locked mixes, which have a reason to skip. The latest exits always stay in the running, including those with a voice that lasts to the end, so the choice between the two is the score's. Fades run 4, 6 or 8 s.
+
+## Voices from lyrics
+
+The spectral estimate in `barVocalRisk` mostly sees that a bar could hold a voice: on the bench corpus, checked against the songs' timed lyrics, it finds about a third of the sung bars at the threshold the policy uses, and lowering the threshold only approaches "every bar". When a song's timed lyrics are already on the device, `withSung` replaces it for that decision and nothing is fetched for it. On the corpus, with both songs' lyrics known, locked mixes where two voices meet for over 2 s fall from 53 % to under 1 %, windows get shorter by themselves, and the share of pairs reaching a locked level goes from 25 % to 19 %: these are the mixes that could not avoid a clash. The numbers are not an independent test, since the lyrics that judge are also the ones used, and a song without lyrics gets the estimate as before. The journal says which was used.