Skip to content

Native Android client for Spotify, built with Jetpack Compose

Lyrics come sooner and fuller: an extension's time counts from when its call runs and an early answer found without it is shown and asked again rather than kept, the app's own lines show at once and a better answer replaces them in place, the playing song's are asked before the next one's, the Immersive panel reloads when the lyrics extensions change, word-by-word lines light up with the same lead as line-timed ones and a word with no end no longer fills across a pause, Genius finds songs whose artist it writes with brackets or co-artists and is asked last when nothing else has the song unless the extra sources were turned off, and backing vocals and duet singers of LyricsPlus and lrc.red are carried onto the chosen lyrics, which win a tie at the same level

kota-zo8351b4aae1e9
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 6ea302bf..e77ca741 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
@@ -50,9 +50,12 @@ object LyricsApi {
// "not found" is often just a timeout, not a fact.
private class Miss(val at: Long = System.currentTimeMillis())
private const val MISS_RETRY_MS = 120_000L
+ // The lyrics found while an extension had still not answered (cut short behind its other calls):
+ // shown, not stored, and the song asked again after MISS_RETRY_MS, when it may answer.
+ private class Partial(val lyrics: Lyrics, val at: Long = System.currentTimeMillis())
// Newest MEMORY_MAX tracks only; the older ones are on storage (LyricsDisk) or asked for again.
private const val MEMORY_MAX = 100
- private val cache: MutableMap<String, Any> = java.util.Collections.synchronizedMap( // Lyrics | Miss
+ private val cache: MutableMap<String, Any> = java.util.Collections.synchronizedMap( // Lyrics | Partial | Miss
object : LinkedHashMap<String, Any>(128, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Any>) = size > MEMORY_MAX
}
@@ -67,26 +70,65 @@ object LyricsApi {
/** Set by the settings: also ask NetEase and Genius when nothing better is found. */
@Volatile var extraSources: Boolean = false
+ /**
+ * Set by the settings: the user turned the extra sources off by hand. Until then Genius is still
+ * asked as the last resort, when no other source (extensions included) has any lyrics.
+ */
+ @Volatile var extraSourcesOff: Boolean = false
+
/** Set by the settings: lyrics timed word by word first (karaoke), line by line otherwise. */
@Volatile var wordSync: Boolean = true
/** How long a word-synced source is waited for before the line-synced ones answer instead. */
private const val WORD_WAIT_MS = 4_000L
- /** Lyrics to show while better ones are looked for (track key → Spotify's line-timed lyrics). */
+ /**
+ * The last lyrics shown while better ones are looked for (track key → the app's own lines); read
+ * a song's own with [earlyFor]: the next song's prefetch publishes its own a moment later.
+ */
val early = kotlinx.coroutines.flow.MutableStateFlow<Pair<String, Lyrics>?>(null)
+ private val earlyByKey = java.util.concurrent.ConcurrentHashMap<String, Lyrics>()
+
+ /** What [track] can show while its lyrics are still looked for, or null. */
+ fun earlyFor(track: Track): Lyrics? = earlyByKey[track.key]
+ private fun showEarly(track: Track, lyrics: Lyrics) {
+ earlyByKey[track.key] = lyrics
+ early.value = track.key to lyrics
+ }
+
+ fun cached(track: Track): Lyrics? = when (val c = cache[track.key]) {
+ is Lyrics -> c
+ is Partial -> c.lyrics
+ else -> null
+ }
- fun cached(track: Track): Lyrics? = cache[track.key] as? Lyrics
+ /** Whether [track]'s lyrics were found with every source's answer: nothing better is to come. */
+ fun settled(track: Track): Boolean = cache[track.key] is Lyrics
+
+ private fun wanted(track: Track): Boolean {
+ if (track.title.isBlank() && track.trackId.isBlank()) return false
+ return when (val c = cache[track.key]) {
+ is Lyrics -> false
+ is Miss -> System.currentTimeMillis() - c.at >= MISS_RETRY_MS
+ is Partial -> System.currentTimeMillis() - c.at >= MISS_RETRY_MS
+ else -> true
+ }
+ }
- /** Warm the cache in the background (current track and the next one). */
- fun prefetch(track: Track) {
- if (track.title.isBlank() && track.trackId.isBlank()) return
- val c = cache[track.key]
- if (c is Lyrics) return
- if (c is Miss && System.currentTimeMillis() - c.at < MISS_RETRY_MS) return
+ // The song to warm once a song's lyrics are found ([prefetch]'s `then`), by that song's key.
+ private val after = java.util.concurrent.ConcurrentHashMap<String, Track>()
+
+ /**
+ * Warm the cache in the background: [track] (the current one), then [then] (the next one) once
+ * [track]'s are found. An extension answers one call at a time: the next song's asked together
+ * with the playing one's went first at times, and the playing one's were cut short.
+ */
+ fun prefetch(track: Track, then: Track? = null) {
+ if (!wanted(track)) { after.remove(track.key); then?.let { prefetch(it) }; return }
+ if (then != null) after[track.key] = then
if (inFlight.containsKey(track.key)) return
- scope.launch { runCatching { fetch(track) } }
+ scope.launch { runCatching { fetch(track) }; after.remove(track.key)?.let { prefetch(it) } }
}
fun forget(track: Track) { cache.remove(track.key); health.forgetTrack(track.key); scope.launch { LyricsDisk.drop(track.key) } }
@@ -103,7 +145,7 @@ object LyricsApi {
* lyrics found too, from memory and storage, so the new set of sources answers. Off the main thread.
*/
fun sourcesChanged(keepFound: Boolean) {
- if (keepFound) synchronized(cache) { cache.values.removeAll { it is Miss } }
+ if (keepFound) synchronized(cache) { cache.values.removeAll { it is Miss || it is Partial } }
else { cache.clear(); LyricsDisk.clear() }
health.forgetAll()
sourcesTick.value++
@@ -112,6 +154,7 @@ object LyricsApi {
suspend fun fetch(track: Track): Lyrics? {
when (val c = cache[track.key]) {
is Lyrics -> return c
+ is Partial -> if (System.currentTimeMillis() - c.at < MISS_RETRY_MS) return c.lyrics
is Miss -> if (System.currentTimeMillis() - c.at < MISS_RETRY_MS) return null
}
// One request per track even when the card and the full screen ask together.
@@ -121,7 +164,10 @@ object LyricsApi {
LyricsDisk.read(track.key)?.also { cache[track.key] = it } ?: resolve(track)
}.also { created ->
inFlight[track.key] = created
- created.invokeOnCompletion { inFlight.remove(track.key, created) }
+ created.invokeOnCompletion {
+ inFlight.remove(track.key, created)
+ after.remove(track.key)?.let { prefetch(it) }
+ }
created.start()
}
}
@@ -208,26 +254,44 @@ object LyricsApi {
chosen
}
- private suspend fun resolve(track: Track): Lyrics? = coroutineScope {
+ private suspend fun resolve(track: Track): Lyrics? = try { coroutineScope {
// Extensions that provide lyrics are asked at the same time as the app's own sources
// (each within its time limit); the better answer is kept (LyricsMerge), Spotify's own
- // complete lyrics first at the same level, and then the extensions are not waited for.
+ // complete lyrics first at the same level. Only when those have backing vocals too are
+ // the extensions not waited for. A failure: they did not answer in time (null: none had lyrics).
val ext = if (extensionsAsked()) async {
runCatching {
com.music.spotui.extensions.Extensions.lyricsFor(track.trackId, track.title, track.artist, track.album, track.durationMs, track.coverUrl)
- }.getOrNull()
+ }
} else null
val own = if (wordSync) wordFirst(track) else fromSpotify(track) ?: lineFallbacks(track)
- val fromExt = when {
+ val answer = when {
ext == null -> null
- own != null && com.music.spotui.extensions.LyricsMerge.rank(own) == 3 && com.music.spotui.extensions.LyricsMerge.isSpotifyComplete(own) -> { ext.cancel(); null }
- else -> ext.await()
+ own != null && com.music.spotui.extensions.LyricsMerge.level(own) == 3 && com.music.spotui.extensions.LyricsMerge.isSpotifyComplete(own) &&
+ LyricsExtras.hasBacks(own) -> { ext.cancel(); null }
+ else -> {
+ // An extension's time counts from when its call runs, which can be a while behind its
+ // other calls: the app's own lines are shown meanwhile (reported: lyrics only after a refresh).
+ own?.let { showEarly(track, it) }
+ ext.await()
+ }
+ }
+ var result = com.music.spotui.extensions.LyricsMerge.choose(own, answer?.getOrNull())
+ // Nothing anywhere: Genius's plain text, unless the user turned the extra sources off.
+ if (result == null && !extraSources && !extraSourcesOff)
+ result = asking("genius", track) { fromGenius(cleanTitle(track.title), track.artist.substringBefore(",").trim()) }
+ val pending = answer?.isFailure == true
+ cache[track.key] = when {
+ result == null -> Miss()
+ pending -> Partial(result)
+ else -> result
}
- val result = com.music.spotui.extensions.LyricsMerge.choose(own, fromExt)
- cache[track.key] = result ?: Miss()
- result?.let { LyricsDisk.write(track.key, it) }
- Log.d("LyricsApi", "${track.title}: ${result?.let { "${it.lines.size} lines from ${it.provider}, synced=${it.synced}, words=${it.wordSynced}" } ?: "none"}")
+ if (!pending) result?.let { LyricsDisk.write(track.key, it) }
+ Log.d("LyricsApi", "${track.title}: ${result?.let { "${it.lines.size} lines from ${it.provider}, synced=${it.synced}, words=${it.wordSynced}" } ?: "none"}" +
+ if (pending) " (the extensions did not answer in time)" else "")
result
+ } } finally {
+ earlyByKey.remove(track.key)
}
/**
@@ -324,6 +388,28 @@ object LyricsApi {
/** Whether lyrics extensions are installed and running (false in unit tests: no app). */
private fun extensionsAsked(): Boolean = runCatching { com.music.spotui.extensions.Extensions.hasLyrics() }.getOrDefault(false)
+ /**
+ * [block] (blocking requests) waited for [ms] at most: a request going on past it is left to end
+ * on its own, its answer unused. A time limit around the request itself never cut it (nothing
+ * in it suspends), so a slow source held the lines of the next ones for up to 20 s.
+ */
+ private suspend fun <T> within(ms: Long, block: () -> T?): T? =
+ kotlinx.coroutines.withTimeoutOrNull(ms) { scope.async { block() }.await() }
+
+ /**
+ * [to] with the backing vocals (and the singers) of the first of [asked] that has them, put on
+ * the same lines, when [to] has none: Spotify never times them apart, LyricsPlus and lrc.red
+ * (Apple Music's) do, and they are asked anyway.
+ */
+ private suspend fun withBacks(to: Lyrics, vararg asked: kotlinx.coroutines.Deferred<Lyrics?>): Lyrics {
+ if (LyricsExtras.hasBacks(to)) return to
+ for (a in asked) {
+ val from = a.await()?.takeIf { LyricsExtras.hasBacks(it) } ?: continue
+ return LyricsExtras.carry(to, from)
+ }
+ return to
+ }
+
/**
* "Word by word" (the setting): the sources with each word's time come first — Spotify's own
* when it has them, then LyricsPlus, lrc.red and Kugou, asked together; the line-synced
@@ -338,16 +424,19 @@ object LyricsApi {
val artist = track.artist.substringBefore(",").trim()
val durationMs = track.durationMs
val spotify = async { fromSpotify(track) }
- val plus = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { asking("lyricsplus", track) { fromLyricsPlus(asked, title, artist, durationMs) } } }
- val red = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { asking("lrcred", track) { fromLrcRed(asked, title, artist, durationMs) } } }
- val kugou = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { asking("kugou", track) { fromKugou(title, artist, durationMs) } } }
+ val plus = async { within(WORD_WAIT_MS) { asking("lyricsplus", track) { fromLyricsPlus(asked, title, artist, durationMs) } } }
+ val red = async { within(WORD_WAIT_MS) { asking("lrcred", track) { fromLrcRed(asked, title, artist, durationMs) } } }
+ val kugou = async { within(WORD_WAIT_MS) { asking("kugou", track) { fromKugou(title, artist, durationMs) } } }
val sp = spotify.await()
- if (sp != null && sp.wordSynced && sp.uncapped) return@coroutineScope sp.also { plus.cancel(); red.cancel(); kugou.cancel() }
- // Shown at once while the word timings are looked for (reported: lyrics slow to come).
- if (sp != null) early.value = track.key to sp
+ // Shown at once while the word timings or the backing vocals are looked for (reported: lyrics slow to come).
+ if (sp != null) showEarly(track, sp)
+ if (sp != null && sp.wordSynced && sp.uncapped) {
+ kugou.cancel()
+ return@coroutineScope withBacks(sp, plus, red)
+ }
val words = (plus.await() ?: red.await() ?: kugou.await())?.takeIf { it.wordSynced }
when {
- words != null -> alignTo(words, sp)?.copy(colors = sp?.colors) ?: sp
+ words != null -> alignTo(words, sp)?.copy(colors = sp?.colors)?.let { withBacks(it, plus, red) } ?: sp
sp != null -> sp
else -> lineFallbacks(track)
}
@@ -466,12 +555,14 @@ object LyricsApi {
// ── 5. Genius (plain text from the song page) ──
private fun fromGenius(title: String, artist: String): Lyrics? {
- val search = httpGet("https://genius.com/api/search/song?per_page=5&q=${enc("$title $artist")}", timeoutMs = 6000, provider = "genius")
+ // Translation and romanization pages take some of the first hits.
+ val search = httpGet("https://genius.com/api/search/song?per_page=10&q=${enc("$title $artist")}", timeoutMs = 6000, provider = "genius")
?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null
val hits = search.optJSONObject("response")?.optJSONArray("sections")?.optJSONObject(0)?.optJSONArray("hits") ?: return null
for (i in 0 until hits.length()) {
val r = hits.optJSONObject(i)?.optJSONObject("result") ?: continue
- if (!isPlausibleMatch(r.optString("title"), r.optString("artist_names"), 0, title, artist, 0)) continue
+ val primary = r.optJSONObject("primary_artist")?.optString("name").orEmpty()
+ if (!geniusMatch(r.optString("title"), r.optString("artist_names"), primary, title, artist)) continue
val html = httpGet(r.optString("url"), timeoutMs = 8000, provider = "genius") ?: continue
val text = geniusText(html) ?: continue
val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() && !(it.startsWith("[") && it.endsWith("]")) }
@@ -481,29 +572,64 @@ object LyricsApi {
return null
}
+ /**
+ * A Genius hit is the song: one of its artists is ours and its title is ours, either without
+ * what Genius adds in brackets ("Kendrick Lamar (Ft. Rihanna)", "IU (아이유)", a romanized title
+ * "夜に駆ける (Yoru Ni Kakeru)") or co-artists ("Stromae & Pomme"). The titles must still be the
+ * same ("Hello Again" is not "Hello"): Genius gives no length to tell two songs apart.
+ */
+ internal fun geniusMatch(candTitle: String, artistNames: String, primaryArtist: String, title: String, artist: String): Boolean {
+ val names = artistNames.replace(geniusAside, "")
+ val artists = names.split(',', '&', '/') + names + primaryArtist.replace(geniusAside, "")
+ if (matchKey(artist).isEmpty() || artists.none { it.isNotBlank() && LyricsMatch.sameArtist(it.trim(), artist) }) return false
+ fun bare(t: String) = cleanTitle(t).let { c -> matchKey(c.replace(lastAside, "")).ifEmpty { matchKey(c) } }
+ return overlaps(bare(candTitle), bare(title))
+ }
+
+ private val geniusAside = Regex("""\s*\([^)]*\)""")
+ private val lastAside = Regex("""\s*\([^)]*\)\s*$""")
+
private val geniusContainer = Regex("<div[^>]*data-lyrics-container=\"true\"[^>]*>", RegexOption.IGNORE_CASE)
+ // Above the lyrics, in the first container: the contributors, the translations and the song's description.
+ private val geniusHeader = Regex("<div[^>]*data-exclude-from-selection=\"true\"[^>]*>", RegexOption.IGNORE_CASE)
// Built once: tidy() runs on every line of a parsed song and every word of a word-synced one.
private val spaces = Regex("\\s+")
private val htmlBreak = Regex("<br\\s*/?>", RegexOption.IGNORE_CASE)
+ /** Where the div whose content starts at [from] closes (nested divs balanced), or -1. */
+ private fun divEnd(html: String, from: Int): Int {
+ var depth = 1
+ var i = from
+ while (i < html.length) {
+ when {
+ html.startsWith("<div", i, ignoreCase = true) -> depth++
+ html.startsWith("</div", i, ignoreCase = true) -> { depth--; if (depth == 0) return i }
+ }
+ i++
+ }
+ return -1
+ }
+
+ /** [part] without Genius's header blocks (see [geniusHeader]). */
+ internal fun withoutGeniusHeader(part: String): String {
+ var out = part
+ while (true) {
+ val m = geniusHeader.find(out) ?: return out
+ val end = divEnd(out, m.range.last + 1).takeIf { it >= 0 } ?: return out
+ val close = out.indexOf('>', end).takeIf { it >= 0 } ?: return out
+ out = out.removeRange(m.range.first, close + 1)
+ }
+ }
+
/** The lyrics containers of a Genius song page, as plain text (nested divs balanced). */
internal fun geniusText(html: String): String? {
val parts = geniusContainer.findAll(html).mapNotNull { m ->
- var depth = 1
- var i = m.range.last + 1
- val start = i
- while (i < html.length && depth > 0) {
- when {
- html.startsWith("<div", i, ignoreCase = true) -> depth++
- html.startsWith("</div", i, ignoreCase = true) -> { depth--; if (depth == 0) return@mapNotNull html.substring(start, i) }
- }
- i++
- }
- null
+ val start = m.range.last + 1
+ divEnd(html, start).takeIf { it >= 0 }?.let { html.substring(start, it) }
}.toList()
if (parts.isEmpty()) return null
return parts.joinToString("\n") { part ->
- androidx.core.text.HtmlCompat.fromHtml(part.replace(htmlBreak, "\n"), androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY)
+ androidx.core.text.HtmlCompat.fromHtml(withoutGeniusHeader(part).replace(htmlBreak, "\n"), androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY)
.toString()
}.trim().takeIf { it.isNotEmpty() }
}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsExtras.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsExtras.kt
index b2117249..9bc2953b 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsExtras.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsExtras.kt
@@ -1,9 +1,13 @@
package com.music.spotui.data.api
import com.music.spotui.data.entity.LyricLine
+import com.music.spotui.data.entity.LyricWord
import com.music.spotui.data.entity.Lyrics
-/** Translations and romanizations a source gives apart from the lines (NetEase), and carrying them between sources. */
+/**
+ * Translations and romanizations a source gives apart from the lines (NetEase), and carrying them,
+ * the backing vocals and the singers between sources.
+ */
object LyricsExtras {
/** How far a translated line may sit from its line (ms) and still be its translation. */
private const val TOLERANCE_MS = 500L
@@ -20,22 +24,103 @@ object LyricsExtras {
}
private fun LyricLine.hasExtra() = translation != null || romanization != null
+ private fun LyricLine.hasBacks() = !background.isNullOrBlank()
+
+ /** Some lines of [lyrics] have backing vocals of their own. */
+ fun hasBacks(lyrics: Lyrics): Boolean = lyrics.lines.any { it.hasBacks() }
+
+ // What a line sings in brackets: Spotify keeps the backing vocals in the line ("Stay (stay)").
+ private val aside = Regex("""\s*\([^()]*\)""")
+ private val spaces = Regex("\\s+")
+
+ /**
+ * Each line of [to] with its line in [from] (null: none), by the text of the line, the brackets
+ * left out when that is what makes them differ; a line sung several times goes with the same
+ * time it is sung in [from] (the third chorus with the third).
+ */
+ private fun pair(to: Lyrics, from: Lyrics): List<LyricLine?> {
+ val byText = HashMap<String, MutableList<LyricLine>>()
+ for (l in from.lines) LyricsMatch.key(l.text).takeIf { it.isNotEmpty() }?.let { byText.getOrPut(it) { ArrayList() }.add(l) }
+ val seen = HashMap<String, Int>()
+ return to.lines.map { l ->
+ val k = LyricsMatch.key(l.text).takeIf { it in byText }
+ ?: LyricsMatch.key(l.text.replace(aside, "")).takeIf { it in byText }
+ ?: return@map null
+ val n = seen.merge(k, 1, Int::plus)!! - 1
+ byText.getValue(k).let { it.getOrNull(n) ?: it.last() }
+ }
+ }
/**
- * [to] with the translations and romanizations of [from] (another source, same song), matched
- * by the text of the line, when [to] has none of its own and at least a third of its lines are found.
+ * [to] with what [from] (another source, same song) has and it lacks, each only when at least a
+ * third of [to]'s lines are found in [from]:
+ * - the translations and romanizations, when [to] has none of its own;
+ * - the backing vocals, when [to] has none apart: their words moved by the gap between the two
+ * lines (the sources' recordings may start apart), and taken out of a line of [to] that sings
+ * them in brackets;
+ * - who sings each line, when [from] has two singers and [to] says nothing of them.
*/
fun carry(to: Lyrics, from: Lyrics?): Lyrics {
- if (from == null || to.lines.any { it.hasExtra() }) return to
- val byText = HashMap<String, LyricLine>()
- for (l in from.lines) if (l.hasExtra()) byText.putIfAbsent(LyricsMatch.key(l.text), l)
- if (byText.isEmpty()) return to
+ if (from == null) return to
+ val wantsExtras = to.lines.none { it.hasExtra() } && from.lines.any { it.hasExtra() }
+ val wantsBacks = !hasBacks(to) && hasBacks(from)
+ val wantsVoices = to.lines.all { it.voice == null } && from.hasDuet
+ if (!wantsExtras && !wantsBacks && !wantsVoices) return to
+ val pairs = pair(to, from)
+ var out = to
+ if (wantsExtras) out = carryExtras(out, from, pairs)
+ if (pairs.count { it != null } * 3 < to.lines.size) return out
+ if (wantsBacks) out = carryBacks(out, pairs)
+ if (wantsVoices) out = out.copy(lines = out.lines.mapIndexed { i, l -> pairs[i]?.voice?.let { l.copy(voice = it) } ?: l })
+ return out
+ }
+
+ private fun carryExtras(to: Lyrics, from: Lyrics, pairs: List<LyricLine?>): Lyrics {
var hit = 0
- val lines = to.lines.map { l ->
- val m = LyricsMatch.key(l.text).takeIf { it.isNotEmpty() }?.let { byText[it] }
+ val lines = to.lines.mapIndexed { i, l ->
+ val m = pairs[i]?.takeIf { it.hasExtra() }
if (m == null) l else { hit++; l.copy(translation = m.translation, romanization = m.romanization) }
}
if (hit * 3 < to.lines.size) return to
return to.copy(lines = lines, translationLanguage = from.translationLanguage.takeIf { lines.any { it.translation != null } })
}
+
+ private fun carryBacks(to: Lyrics, pairs: List<LyricLine?>): Lyrics {
+ var changed = false
+ val lines = to.lines.mapIndexed { i, l ->
+ val m = pairs[i]?.takeIf { it.hasBacks() } ?: return@mapIndexed l
+ val sungInBrackets = aside.findAll(l.text).joinToString("") { it.value }
+ // Brackets saying something else than the backing vocals: the line is left as it is.
+ if (sungInBrackets.isNotEmpty() && LyricsMatch.key(sungInBrackets) != LyricsMatch.key(m.background.orEmpty())) return@mapIndexed l
+ val shift = l.timeMs - m.timeMs
+ changed = true
+ l.copy(
+ text = if (sungInBrackets.isEmpty()) l.text else l.text.replace(aside, "").replace(spaces, " ").trim(),
+ words = if (sungInBrackets.isEmpty()) l.words else l.words?.let(::outsideBrackets)?.takeIf { it.isNotEmpty() },
+ background = m.background,
+ backgroundWords = if (!to.synced) null else m.backgroundWords?.map { w ->
+ w.copy(startMs = (w.startMs + shift).coerceAtLeast(0), endMs = if (w.endMs > 0) (w.endMs + shift).coerceAtLeast(0) else 0)
+ },
+ )
+ }
+ return if (changed) to.copy(lines = lines) else to
+ }
+
+ /** The words of a line sung outside its brackets (a word half inside keeps its outer part). */
+ internal fun outsideBrackets(words: List<LyricWord>): List<LyricWord> {
+ val out = ArrayList<LyricWord>()
+ var depth = 0
+ for (w in words) {
+ val before = depth
+ depth = (depth + w.text.count { it == '(' } - w.text.count { it == ')' }).coerceAtLeast(0)
+ val kept = when {
+ before == 0 && '(' !in w.text -> w.text
+ before == 0 -> w.text.substringBefore('(')
+ depth == 0 -> w.text.substringAfterLast(')')
+ else -> ""
+ }
+ if (kept.isNotBlank()) out += w.copy(text = kept)
+ }
+ return out
+ }
}
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
index 5c346b2e..0328f507 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
@@ -16,6 +16,8 @@ private const val KEY_CROSSFADE = "crossfade_seconds"
/** Extra lyrics sources (NetEase, Genius) when Spotify and LRCLIB have none. Off by default. */
fun isLyricsExtraSources(c: Context): Boolean = prefs(c).getBoolean(KEY_LYRICS_EXTRA, false)
fun setLyricsExtraSources(c: Context, v: Boolean) = prefs(c).edit().putBoolean(KEY_LYRICS_EXTRA, v).apply()
+/** The extra sources were turned off by hand (never touched: Genius is still the last resort). */
+fun isLyricsExtraSourcesOff(c: Context): Boolean = prefs(c).let { it.contains(KEY_LYRICS_EXTRA) && !it.getBoolean(KEY_LYRICS_EXTRA, false) }
/** Lyrics timed word by word first (karaoke); off: line by line, Spotify's first. */
fun isLyricsWordSync(c: Context): Boolean = prefs(c).getBoolean("lyrics_word_sync", true)
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 1b7568a0..11d7cbe3 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -246,6 +246,8 @@ object SongPlayer {
boundState = state
com.music.spotui.data.api.LyricsApi.extraSources =
com.music.spotui.data.preferences.isLyricsExtraSources(Graph.app)
+ com.music.spotui.data.api.LyricsApi.extraSourcesOff =
+ com.music.spotui.data.preferences.isLyricsExtraSourcesOff(Graph.app)
com.music.spotui.data.api.LyricsApi.wordSync =
com.music.spotui.data.preferences.isLyricsWordSync(Graph.app)
restoreLastTrack(state)
@@ -756,8 +758,8 @@ object SongPlayer {
val lookups = app.myspoti.power.EnergySettings.state.value.policy.allowBackgroundLookups
// Lyrics are warmed in the background too (the next song's are there when it starts), but not on a metered network.
if (!isBuffering && playing && lookups && (mv.inForeground || !com.music.spotui.data.DataSaver.metered)) {
- com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(song))
- _nowPlaying.value.next?.let { com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(it)) }
+ // The next song's once the playing one's are found: an extension answers one call at a time.
+ com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(song), then = _nowPlaying.value.next?.let { lyricsTrack(it) })
}
if (!isBuffering && playing && mv.inForeground && lookups) {
// The next song's clip is looked up now, so its button is there when it starts. The
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index 33d5ee71..1b761519 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
@@ -1569,10 +1569,18 @@ object Extensions {
api.raw.request(method, url, body, headers).let { app.myspoti.extensions.RawRequest.response(it.status, it.headers, it.body) }
}
- /** Lyrics asked with a time limit of their own, for the app's lyrics resolver. */
- suspend fun lyricsFor(trackId: String, title: String, artist: String, album: String, durationMs: Long, cover: String?): Lyrics? =
- if (!hasLyrics()) null
- else withTimeoutOrNull(LYRICS_MS + 1_000) { lyrics(trackInfo(trackId, title, artist, album, durationMs, cover)) }
+ /**
+ * Lyrics asked for the app's lyrics resolver. Each extension's time counts from when its call
+ * runs, which may wait up to 30 s behind its earlier calls (ExtensionRuntime's queue: a song's
+ * audio looked up, the next song's lyrics); counted from the request, its answer was cut short.
+ * The limit here only ends a call past both, by an exception: the resolver then knows the
+ * extensions did not answer in time, where null is that none had lyrics.
+ */
+ suspend fun lyricsFor(trackId: String, title: String, artist: String, album: String, durationMs: Long, cover: String?): Lyrics? {
+ if (!hasLyrics()) return null
+ val queueMs = 30_000L
+ return kotlinx.coroutines.withTimeout(queueMs + 2 * LYRICS_MS + 1_000) { lyrics(trackInfo(trackId, title, artist, album, durationMs, cover)) }
+ }
/** The running extensions giving lyrics, in their order: (id, name). For the "Try another source" list. */
fun lyricsSources(): List<Pair<String, String>> =
diff --git a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
index ef9ca89e..94169178 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt
@@ -53,30 +53,39 @@ object HookDispatch {
/**
* Lyrics from extensions next to the app's own: the extensions' answer is used when it is at
- * least as good (word by word > line by line > plain text), except against Spotify's own complete
- * lyrics, which stay first at the same level (they are what the official app shows, with colours).
+ * least as good (word by word > line by line > plain text; at the same level, with backing vocals
+ * or a duet the other lacks), except against Spotify's own complete lyrics, which stay first at
+ * the same level otherwise (they are what the official app shows, with colours).
*/
object LyricsMerge {
- fun rank(l: Lyrics): Int = when {
+ /** Word by word 3, line by line 2, plain text 1. */
+ fun level(l: Lyrics): Int = when {
l.synced && l.wordSynced -> 3
l.synced -> 2
else -> 1
}
+ /** [level] first; at the same level, backing vocals of their own, then two singers, win the tie. */
+ fun rank(l: Lyrics): Int = level(l) * 4 + (if (LyricsExtras.hasBacks(l)) 2 else 0) + (if (l.hasDuet) 1 else 0)
+
/** Whether [own] is Spotify's own, complete lyrics. */
fun isSpotifyComplete(own: Lyrics?): Boolean = own != null && own.colors != null && own.uncapped
- /** The better of the two; translations and romanizations the other one carries are kept when the chosen has none. */
+ /** The better of the two; the translations, backing vocals and singers the other one carries are kept when the chosen has none. */
fun choose(own: Lyrics?, fromExtension: Lyrics?): Lyrics? {
if (fromExtension == null || fromExtension.isEmpty) return own
if (own == null || own.isEmpty) return fromExtension
- val mine = rank(own)
- val theirs = rank(fromExtension)
+ val keptOwn = LyricsExtras.carry(own, fromExtension)
+ val tookTheirs = fromExtension.copy(colors = own.colors).let { LyricsExtras.carry(it, own) }
+ val mine = level(own)
+ val theirs = level(fromExtension)
return when {
- theirs > mine -> fromExtension.copy(colors = own.colors).let { LyricsExtras.carry(it, own) }
- theirs < mine -> LyricsExtras.carry(own, fromExtension)
- isSpotifyComplete(own) -> LyricsExtras.carry(own, fromExtension)
- else -> fromExtension.copy(colors = own.colors).let { LyricsExtras.carry(it, own) }
+ theirs > mine -> tookTheirs
+ theirs < mine -> keptOwn
+ // The same level: the one with backing vocals or a duet, once each has what it could take from the other.
+ rank(tookTheirs) != rank(keptOwn) -> if (rank(tookTheirs) > rank(keptOwn)) tookTheirs else keptOwn
+ isSpotifyComplete(own) -> keptOwn
+ else -> tookTheirs
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
index b60f1b07..f530422c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
@@ -162,10 +162,10 @@ fun ImmersiveLyricsPanel(modifier: Modifier = Modifier, contentPadding: PaddingV
// currentTrackId is plain data, not Compose state: a skip whose title and artist are the same
// (or that reports its id after them) would never re-run this. The playing item's uri is state.
val playingUri = SongPlayer.nowPlaying.value.uri
- LaunchedEffect(title, artist, playingUri, SongPlayer.currentTrackId) {
- SongPlayer.currentLyricsTrack()?.let(vm::load)
- }
- val state by vm.state.collectAsState()
+ // Loaded as the Classic look does: read again when the lyrics extensions changed (they finish
+ // starting after the app: the song not found by then stayed so until the panel was reopened).
+ val state = com.music.spotui.ui.screens.rememberLyricsState(vm, title, artist)
+ com.music.spotui.ui.screens.KeepScreenOnForLyrics(Graph.currentSongState.playingState.value && state is LyricsViewModel.State.Loaded)
val trackKey = "$playingUri|${SongPlayer.currentTrackId}|$title|$artist"
val selecting by vm.selecting.collectAsState()
val picked by vm.picked.collectAsState()
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index be993f79..f01202e2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -326,6 +326,7 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> U
lyricsExtra = it
com.music.spotui.data.preferences.setLyricsExtraSources(ctx, it)
com.music.spotui.data.api.LyricsApi.extraSources = it
+ com.music.spotui.data.api.LyricsApi.extraSourcesOff = !it
com.music.spotui.data.api.LyricsApi.forgetAll()
},
detail = stringResource(R.string.lyrics_extra_summary),
diff --git a/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt
index d80385bd..7bebca31 100644
--- a/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt
@@ -256,15 +256,23 @@ data class SweptLine(
}
}
+/**
+ * The longest a word whose end is unknown is taken to be sung. Spotify's own word timings (and
+ * an extension's words without `end`) give only starts: run up to the next word, a word before a
+ * pause filled slowly across all of it and finished late next to line-timed lyrics (reported).
+ */
+private const val UNKNOWN_WORD_MAX_MS = 700L
+
/**
* Myspoti's lyric line as the sweep draws it. A word whose end is unknown (0) runs until
- * the next word starts, or [nextLineMs] for the last one.
+ * the next word starts, or [nextLineMs] for the last one, for [UNKNOWN_WORD_MAX_MS] at most.
*/
fun com.music.spotui.data.entity.LyricLine.toSwept(nextLineMs: Long? = null): SweptLine {
val source = words.orEmpty()
val swept = source.mapIndexed { index, word ->
val next = source.getOrNull(index + 1)?.startMs ?: nextLineMs ?: (word.startMs + 500L)
- SweptWord(word.startMs, if (word.endMs > word.startMs) word.endMs else next, word.text.trim())
+ val end = if (word.endMs > word.startMs) word.endMs else minOf(next, word.startMs + UNKNOWN_WORD_MAX_MS)
+ SweptWord(word.startMs, end, word.text.trim())
}.filter { it.text.isNotEmpty() }
return SweptLine(timeMs, text, swept)
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
index 45d66953..9875cd78 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
@@ -172,6 +172,12 @@ private fun rememberPosition(running: Boolean): () -> Long {
}
}
+/**
+ * How early a line turns current and a word lights, the same for both: words lit only when sung,
+ * after their line had turned current early, looked late next to line-timed lyrics (reported).
+ */
+private const val LINE_LEAD_MS = 150L
+
private fun activeIndexFor(lyrics: Lyrics, positionMs: Long): Int {
if (!lyrics.synced) return -1
// Binary search: last line starting at or before the position.
@@ -180,7 +186,7 @@ private fun activeIndexFor(lyrics: Lyrics, positionMs: Long): Int {
var found = -1
while (lo <= hi) {
val mid = (lo + hi) ushr 1
- if (lyrics.lines[mid].timeMs <= positionMs + 150) { found = mid; lo = mid + 1 } else hi = mid - 1
+ if (lyrics.lines[mid].timeMs <= positionMs + LINE_LEAD_MS) { found = mid; lo = mid + 1 } else hi = mid - 1
}
return found
}
@@ -232,6 +238,20 @@ internal fun rememberLyricsState(vm: LyricsViewModel, title: String, artist: Str
return vm.state.collectAsState().value
}
+/**
+ * The screen stays on while [active] (the lyrics shown and the song playing), unless turned off in
+ * the settings ([com.music.spotui.data.preferences.LyricsKeepAwakePref]). Both looks.
+ */
+@Composable
+internal fun KeepScreenOnForLyrics(active: Boolean) {
+ val view = androidx.compose.ui.platform.LocalView.current
+ val on = active && com.music.spotui.data.preferences.LyricsKeepAwakePref.on
+ DisposableEffect(view, on) {
+ if (on) view.keepScreenOn = true
+ onDispose { if (on) view.keepScreenOn = false }
+ }
+}
+
/**
* Keeps the active line about a third down the view, like Spotify. A manual scroll
* pauses the follow for 3 s.
@@ -353,7 +373,7 @@ private fun LyricLineText(
onTextLayout = { fill = it },
modifier = Modifier.fillMaxWidth().drawWithContent {
val l = fill ?: return@drawWithContent
- val off = sungChars(words, starts, position()).coerceAtMost(shown.length.toFloat())
+ val off = sungChars(words, starts, position() + LINE_LEAD_MS).coerceAtMost(shown.length.toFloat())
if (off <= 0f) return@drawWithContent
if (off >= shown.length) { drawContent(); return@drawWithContent }
val whole = off.toInt()
@@ -463,6 +483,7 @@ fun LyricsScreen(
val bg by animateColorAsState(palette.background, tween(300), label = "lyricsBg")
val playing = com.music.spotui.di.Graph.currentSongState.playingState.value
val position = rememberPosition(playing)
+ KeepScreenOnForLyrics(playing && lyrics != null)
val targetLanguage = getLyricTranslateLang(context).ifBlank { Locale.getDefault().language.ifBlank { "en" } }
var menu by remember { mutableStateOf(false) }
var sourcesOpen by remember { mutableStateOf(false) }
@@ -736,6 +757,8 @@ private fun LyricsMenu(
extra = !extra
setLyricsExtraSources(context, extra)
LyricsApi.extraSources = extra
+ // Turned off by hand: Genius is no longer asked even when nothing else has the song.
+ LyricsApi.extraSourcesOff = !extra
onDismiss()
onReload()
},
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index 67ed6a91..24ec9e5a 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -171,6 +171,7 @@ fun SettingsScreen(navController: NavController) {
lyricsExtra = it
com.music.spotui.data.preferences.setLyricsExtraSources(ctx, it)
com.music.spotui.data.api.LyricsApi.extraSources = it
+ com.music.spotui.data.api.LyricsApi.extraSourcesOff = !it
com.music.spotui.data.api.LyricsApi.forgetAll()
},
)
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
index 29d985d0..5b06cd43 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
@@ -121,14 +121,27 @@ class LyricsViewModel constructor() : ViewModel() {
stopSelecting()
_triedNothing.value = null
if (force) LyricsApi.forget(track)
- // Already resolved (prefetched while the track started): no loading flash.
- LyricsApi.cached(track)?.let { _state.value = loadedState(it); return }
- // Read again (the setting changed): the lyrics shown stay until the new ones replace them.
- if (!(force && _state.value is State.Loaded)) _state.value = State.Loading
- // Spotify's own lines shown as soon as they are there; the word-timed ones replace them.
+ // Already resolved (prefetched while the track started): no loading flash. Found while an
+ // extension had not answered: shown, and asked again (its answer replaces them).
+ val cached = LyricsApi.cached(track)
+ if (cached != null) {
+ _state.value = loadedState(cached)
+ if (LyricsApi.settled(track)) return
+ } else if (!(force && _state.value is State.Loaded)) {
+ // Read again (the setting changed): the lyrics shown stay until the new ones replace them.
+ _state.value = State.Loading
+ }
+ // The app's own lines shown as soon as they are there (another, better early answer replaces
+ // them too); the final ones replace them. Read by song: the next song's prefetch publishes in between.
val earlyJob = viewModelScope.launch {
- LyricsApi.early.collect { e ->
- if (e != null && e.first == key && loadedKey == key && _state.value is State.Loading) _state.value = loadedState(e.second)
+ var shownEarly: Lyrics? = null
+ LyricsApi.early.collect {
+ val e = LyricsApi.earlyFor(track) ?: return@collect
+ val shown = (_state.value as? State.Loaded)?.lyrics
+ if (loadedKey == key && e != shown && (_state.value is State.Loading || (shown != null && shown === shownEarly))) {
+ shownEarly = e
+ _state.value = loadedState(e)
+ }
}
}
viewModelScope.launch(Dispatchers.IO) {
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsExtrasTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsExtrasTest.kt
index 655e9827..246bdbe1 100644
--- a/base/app/src/test/java/com/music/spotui/data/api/LyricsExtrasTest.kt
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsExtrasTest.kt
@@ -1,13 +1,14 @@
package com.music.spotui.data.api
import com.music.spotui.data.entity.LyricLine
+import com.music.spotui.data.entity.LyricWord
import com.music.spotui.data.entity.Lyrics
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Test
-/** Translations and romanizations: attached by time, carried between sources, chosen for a target language. */
+/** Translations, romanizations, backing vocals and singers: attached by time, carried between sources, chosen for a target language. */
class LyricsExtrasTest {
private fun line(t: Long, text: String, tr: String? = null, ro: String? = null) = LyricLine(t, text, translation = tr, romanization = ro)
@@ -63,4 +64,44 @@ class LyricsExtrasTest {
assertEquals(true, v(1, 2, 1).hasDuet)
assertEquals(false, v(0, 1).hasDuet)
}
+
+ @Test fun backingVocalsAreCarriedOntoTheSameLinesMovedByTheGapBetweenTheSources() {
+ val to = Lyrics(listOf(
+ LyricLine(1000, "Stay (stay)", words = listOf(LyricWord(1000, 0, "Stay "), LyricWord(1400, 0, "(stay)"))),
+ LyricLine(5000, "Go away"), LyricLine(9000, "Come back"),
+ ), synced = true, provider = "Spotify")
+ val from = Lyrics(listOf(
+ LyricLine(1200, "Stay", background = "stay", backgroundWords = listOf(LyricWord(1500, 1800, "stay"))),
+ LyricLine(5200, "Go away"), LyricLine(9200, "Come back"),
+ ), synced = true, provider = "LyricsPlus")
+ val out = LyricsExtras.carry(to, from)
+ assertEquals("Spotify", out.provider)
+ assertEquals("Stay", out.lines[0].text)
+ assertEquals(listOf("Stay "), out.lines[0].words!!.map { it.text })
+ assertEquals("stay", out.lines[0].background)
+ assertEquals(listOf(LyricWord(1300, 1600, "stay")), out.lines[0].backgroundWords)
+ assertNull(out.lines[1].background)
+ }
+
+ @Test fun bracketsSayingSomethingElseAndTooFewMatchesLeaveTheLinesAlone() {
+ val to = Lyrics(listOf(LyricLine(0, "Hello (intro)"), LyricLine(1, "World")), synced = true)
+ val from = Lyrics(listOf(LyricLine(0, "Hello", background = "ooh"), LyricLine(1, "World")), synced = true)
+ assertEquals("Hello (intro)", LyricsExtras.carry(to, from).lines[0].text)
+ assertNull(LyricsExtras.carry(to, from).lines[0].background)
+ val unrelated = Lyrics(listOf(LyricLine(0, "one"), LyricLine(1, "two"), LyricLine(2, "three"), LyricLine(3, "four")), synced = true)
+ assertSame(unrelated, LyricsExtras.carry(unrelated, Lyrics(listOf(LyricLine(0, "one", background = "oh")), synced = true)))
+ }
+
+ @Test fun theSingersAreCarriedFromADuet() {
+ val to = Lyrics(listOf(LyricLine(0, "mine"), LyricLine(1, "yours")), synced = true)
+ val from = Lyrics(listOf(LyricLine(0, "mine", voice = 1), LyricLine(1, "yours", voice = 2)), synced = true)
+ assertEquals(listOf(1, 2), LyricsExtras.carry(to, from).lines.map { it.voice })
+ }
+
+ @Test fun onlyTheWordsSungOutsideTheBracketsAreKept() {
+ fun w(vararg t: String) = t.mapIndexed { i, s -> LyricWord(i.toLong(), 0, s) }
+ assertEquals(listOf("Oh ", "baby"), LyricsExtras.outsideBrackets(w("Oh ", "(yeah ", "yeah) ", "baby")).map { it.text })
+ assertEquals(listOf("Go ", "on"), LyricsExtras.outsideBrackets(w("Go ", "(go)", "on")).map { it.text })
+ assertEquals(listOf("Run"), LyricsExtras.outsideBrackets(w("Run(run)")).map { it.text })
+ }
}
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsGeniusMatchTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsGeniusMatchTest.kt
new file mode 100644
index 00000000..d5f2f938
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsGeniusMatchTest.kt
@@ -0,0 +1,41 @@
+package com.music.spotui.data.api
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Genius's search hits against the playing track: what Genius adds in brackets and co-artists do not count. */
+class LyricsGeniusMatchTest {
+ @Test fun featuredArtistsInBracketsAreLeftOut() {
+ assertTrue(LyricsApi.geniusMatch("LOYALTY.", "Kendrick Lamar (Ft. Rihanna)", "Kendrick Lamar", "LOYALTY.", "Kendrick Lamar"))
+ assertTrue(LyricsApi.geniusMatch("Despacito (Remix)", "Luis Fonsi & Daddy Yankee (Ft. Justin Bieber)", "Luis Fonsi", "Despacito (Remix)", "Luis Fonsi"))
+ }
+
+ @Test fun coArtistsAndNativeNamesMatchTheFirstArtist() {
+ assertTrue(LyricsApi.geniusMatch("Ma Meilleure Ennemie", "Stromae & Pomme", "Stromae", "Ma Meilleure Ennemie", "Stromae"))
+ assertTrue(LyricsApi.geniusMatch("Blueming", "IU (아이유)", "IU (아이유)", "Blueming", "IU"))
+ assertTrue(LyricsApi.geniusMatch("CARNIVAL", "¥\$, Kanye West & Ty Dolla \$ign (Ft. Rich The Kid & Playboi Carti)", "¥\$", "CARNIVAL", "Kanye West"))
+ }
+
+ @Test fun theirPrimaryArtistIsEnough() {
+ assertTrue(LyricsApi.geniusMatch("Song", "Someone Else", "Our Artist", "Song", "Our Artist"))
+ }
+
+ @Test fun aRomanizedTitleInBracketsIsLeftOut() {
+ assertTrue(LyricsApi.geniusMatch("夜に駆ける (Yoru Ni Kakeru)", "YOASOBI", "YOASOBI", "夜に駆ける", "YOASOBI"))
+ }
+
+ @Test fun anotherSongOrArtistIsStillRejected() {
+ assertFalse("Hello and Hello Again are distinct songs", LyricsApi.geniusMatch("Hello Again", "Adele", "Adele", "Hello", "Adele"))
+ assertFalse(LyricsApi.geniusMatch("Hello", "Lionel Richie", "Lionel Richie", "Hello", "Adele"))
+ assertFalse("Cher and Cherry are distinct artists", LyricsApi.geniusMatch("Hello", "Cherry (Ft. Cher)", "Cherry", "Hello", "Cher"))
+ assertFalse(LyricsApi.geniusMatch("Skyfall", "Adele", "Adele", "Hello", "Adele"))
+ }
+
+ @Test fun theHeaderAboveTheLyricsIsLeftOut() {
+ val part = """<div data-exclude-from-selection="true" class="h"><div>354 Contributors</div><div>Translations</div></div>[Verse 1]<br/>First line"""
+ assertEquals("[Verse 1]<br/>First line", LyricsApi.withoutGeniusHeader(part))
+ assertEquals("plain", LyricsApi.withoutGeniusHeader("plain"))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
index 7e31d2c2..69f149b6 100644
--- a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
+++ b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt
@@ -89,10 +89,10 @@ class HookDispatchTest {
assertEquals("P", l.provider)
assertEquals(listOf(1500L, 2500L), l.lines.map { it.timeMs })
assertEquals(1700L, l.lines[0].words!![0].endMs)
- assertEquals(3, LyricsMerge.rank(l))
+ assertEquals(3, LyricsMerge.level(l))
val plain = LyricsMerge.toLyrics(LyricsResult.parse("""{"plain":"one\ntwo"}""", "Ext")!!)
assertEquals("Ext", plain.provider)
- assertEquals(1, LyricsMerge.rank(plain))
+ assertEquals(1, LyricsMerge.level(plain))
assertEquals(listOf("one", "two"), plain.lines.map { it.text })
}
@@ -115,4 +115,17 @@ class HookDispatchTest {
assertEquals("ligne", chosen.lines[0].translation)
assertEquals("fr", chosen.translationLanguage)
}
+
+ @Test fun atTheSameLevelBackingVocalsOrADuetWinTheTie() {
+ fun lines(vararg t: String) = t.mapIndexed { i, s -> LyricLine(i * 1000L, s) }
+ val own = Lyrics(lines("a", "b", "c"), synced = true, provider = "LRCLIB")
+ val backs = Lyrics(lines("x", "y", "z").mapIndexed { i, l -> if (i == 0) l.copy(background = "ooh") else l }, synced = true, provider = "Ext")
+ assertEquals("Ext", LyricsMerge.choose(own, backs)?.provider)
+ // Spotify's complete lyrics stay first, unless the other one has what they lack.
+ val spotify = own.copy(provider = "Spotify", colors = LyricsColors(0, 0, 0))
+ assertEquals("Ext", LyricsMerge.choose(spotify, backs)?.provider)
+ assertEquals("Spotify", LyricsMerge.choose(spotify, backs.copy(lines = lines("x", "y", "z")))?.provider)
+ val duet = own.copy(lines = own.lines.mapIndexed { i, l -> l.copy(voice = i % 2 + 1) })
+ assertEquals("LRCLIB", LyricsMerge.choose(duet, backs.copy(lines = lines("x", "y", "z")))?.provider)
+ }
}
diff --git a/base/app/src/test/java/com/music/spotui/ui/look/SweptLyricTimingTest.kt b/base/app/src/test/java/com/music/spotui/ui/look/SweptLyricTimingTest.kt
new file mode 100644
index 00000000..af365be5
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/look/SweptLyricTimingTest.kt
@@ -0,0 +1,31 @@
+package com.music.spotui.ui.look
+
+import com.music.spotui.data.entity.LyricLine
+import com.music.spotui.data.entity.LyricWord
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** How long the sweep takes a word to be sung, its end known or not. */
+class SweptLyricTimingTest {
+ @Test fun aWordWithNoEndDoesNotFillAcrossThePauseAfterIt() {
+ // Spotify's word timings: starts only (end = start). "Stay" is followed by 4 s of silence.
+ val line = LyricLine(1_000, "Stay here", listOf(LyricWord(1_000, 1_000, "Stay "), LyricWord(5_000, 5_000, "here")))
+ val swept = line.toSwept(nextLineMs = 9_000)
+ assertEquals(1_700L, swept.words[0].endMs)
+ assertEquals(5_700L, swept.words[1].endMs)
+ // Fully lit well before the next word, not only as it starts.
+ assertEquals(4f, swept.revealedChars(1_700), 0.01f)
+ }
+
+ @Test fun aWordWithNoEndStillEndsAtTheNextOneWhenItComesSooner() {
+ val line = LyricLine(0, "one two", listOf(LyricWord(0, 0, "one "), LyricWord(300, 0, "two")))
+ val swept = line.toSwept(nextLineMs = 400)
+ assertEquals(300L, swept.words[0].endMs)
+ assertEquals(400L, swept.words[1].endMs)
+ }
+
+ @Test fun aKnownEndIsKeptEvenWhenLong() {
+ val line = LyricLine(0, "Oh", listOf(LyricWord(0, 3_000, "Oh")))
+ assertEquals(3_000L, line.toSwept(nextLineMs = 5_000).words[0].endMs)
+ }
+}