Skip to content

Native Android client for Spotify, built with Jetpack Compose

Lyrics: translations and romanization from the source (lrc.red, NetEase) before the machine translation, backing vocals and duet voices kept and shown (backing line under its line, the second voice on the other side), Show romanization, Try another source (word-synced and set-aside sources marked), accent- and order-tolerant matching, a source failing three times set aside for 10 min and a no-lyrics answer kept 5 min; the extension lyrics hook takes translation, romanization, voice and background (optional)

kota-zoe58346940db3
diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.kts
index f50346c0..848d1814 100644
--- a/base/app/build.gradle.kts
+++ b/base/app/build.gradle.kts
@@ -117,6 +117,8 @@ dependencies {
testImplementation("junit:junit:4.13.2")
// The real org.json in unit tests (android.jar only has stubs).
testImplementation("org.json:json:20240303")
+ // A real XML pull parser in unit tests (the TTML lyrics parser; the tests skip themselves without it).
+ testImplementation("net.sf.kxml:kxml2:2.3.0")
androidTestImplementation("androidx.test:runner:1.6.2")
androidTestImplementation("androidx.test.ext:junit:1.2.1")
implementation(libs.androidx.core.ktx)
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 550d22d9..c372560f 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
@@ -25,6 +25,8 @@ import java.net.URLEncoder
* Genius (plain text). Off by default.
*
* Fallback results are only kept when title, artist and length match the track.
+ * A provider failing in a row is set aside and a "no lyrics" answer is kept for a while
+ * ([LyricsHealth]); [sources] and [fetchFrom] let the user pick one by hand.
* LRCLIB asks clients to send a descriptive User-Agent; we oblige.
*/
object LyricsApi {
@@ -56,6 +58,9 @@ object LyricsApi {
}
)
private val inFlight = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<Lyrics?>>()
+ private val health = LyricsHealth()
+ // Set while one provider is asked by hand ([fetchFrom]): it is asked even when set aside.
+ private val bypass = ThreadLocal<Boolean>()
private val scope =
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO)
@@ -84,10 +89,10 @@ object LyricsApi {
scope.launch { runCatching { fetch(track) } }
}
- fun forget(track: Track) { cache.remove(track.key); scope.launch { LyricsDisk.drop(track.key) } }
+ fun forget(track: Track) { cache.remove(track.key); health.forgetTrack(track.key); scope.launch { LyricsDisk.drop(track.key) } }
/** A setting changed what is looked for: every song is read again when next shown. */
- fun forgetAll() { cache.clear(); scope.launch { LyricsDisk.clear() } }
+ fun forgetAll() { cache.clear(); health.forgetAll(); scope.launch { LyricsDisk.clear() } }
/** Bumped when the lyrics extensions changed and the cache was dropped: an open lyrics view reads its song again. */
val sourcesTick = kotlinx.coroutines.flow.MutableStateFlow(0L)
@@ -100,6 +105,7 @@ object LyricsApi {
fun sourcesChanged(keepFound: Boolean) {
if (keepFound) synchronized(cache) { cache.values.removeAll { it is Miss } }
else { cache.clear(); LyricsDisk.clear() }
+ health.forgetAll()
sourcesTick.value++
}
@@ -123,6 +129,85 @@ object LyricsApi {
return job.await()
}
+ /**
+ * A provider that can be asked for a song by hand ("Try another source"). [id] goes to
+ * [fetchFrom]; [name] is shown as it is (a brand, not translated); [words]: it can time the
+ * words; [setAside]: why it is not asked by itself for now (a run of failures), null when it is.
+ */
+ data class Source(val id: String, val name: String, val words: Boolean = false, val setAside: String? = null)
+
+ private fun allSetAside(vararg ids: String): String? = ids.map { health.reason(it) }.takeIf { r -> r.all { it != null } }?.first()
+
+ private val WORD_SOURCES = setOf("lyricsplus", "lrcred", "kugou")
+
+ /** The providers that can be tried for [track], in the order the resolver prefers them; the extensions giving lyrics come last (`ext:<id>`). */
+ fun sources(track: Track): List<Source> = buildList {
+ if (track.trackId.isNotBlank()) add(Source("spotify", "Spotify", words = true))
+ add(Source("lyricsplus", "LyricsPlus", true, allSetAside(*LYRICS_PLUS.toTypedArray())))
+ add(Source("lrcred", "lrc.red", true, allSetAside("lrcred")))
+ add(Source("kugou", "Kugou", true, allSetAside("kugou")))
+ add(Source("lrclib", "LRCLIB", false, allSetAside("lrclib")))
+ add(Source("netease", "NetEase", false, allSetAside("netease")))
+ add(Source("genius", "Genius", false, allSetAside("genius")))
+ runCatching { com.music.spotui.extensions.Extensions.lyricsSources() }.getOrDefault(emptyList())
+ .forEach { (id, name) -> add(Source("ext:$id", name)) }
+ }
+
+ /** The [Source.id] the shown [lyrics] came from, or null when it cannot tell (an extension's own provider name). */
+ fun sourceOf(lyrics: Lyrics): String? {
+ val p = lyrics.provider.orEmpty().lowercase()
+ return when {
+ "lyricsplus" in p -> "lyricsplus"
+ "lrc.red" in p -> "lrcred"
+ "kugou" in p -> "kugou"
+ "lrclib" in p -> "lrclib"
+ "netease" in p -> "netease"
+ "genius" in p -> "genius"
+ lyrics.colors != null -> "spotify"
+ else -> null
+ }
+ }
+
+ /**
+ * The lyrics of [track] from the provider [sourceId] alone ([Source.id]), asked at once (a
+ * set-aside provider, a cached "no lyrics" and the cache of the song do not count). What it gives
+ * replaces the song's lyrics in memory and storage; null (nothing changes) when it has none.
+ */
+ suspend fun fetchFrom(track: Track, sourceId: String): Lyrics? = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ val asked = track.title.trim()
+ val title = cleanTitle(track.title)
+ val artist = track.artist.substringBefore(",").trim()
+ val durationMs = track.durationMs
+ val durationSec = (durationMs / 1000).toInt()
+ fun <T> byHand(block: () -> T): T { bypass.set(true); try { return block() } finally { bypass.remove() } }
+ val spotify = if (sourceId in WORD_SOURCES) runCatching { fromSpotify(track) }.getOrNull() else null
+ val found = try {
+ when {
+ sourceId == "spotify" -> fromSpotify(track)
+ sourceId.startsWith("ext:") -> com.music.spotui.extensions.Extensions.lyricsFromExtension(
+ sourceId.removePrefix("ext:"), track.trackId, track.title, track.artist, track.album, durationMs, track.coverUrl)
+ sourceId == "lyricsplus" -> byHand { fromLyricsPlus(asked, title, artist, durationMs) }
+ sourceId == "lrcred" -> byHand { fromLrcRed(asked, title, artist, durationMs) }
+ sourceId == "kugou" -> byHand { fromKugou(title, artist, durationMs) }
+ sourceId == "lrclib" -> byHand {
+ lrclibGet(title, artist, track.album, durationSec)
+ ?: lrclibSearch("$LRCLIB/search?track_name=${enc(title)}&artist_name=${enc(artist)}", title, artist, durationSec)
+ ?: lrclibSearch("$LRCLIB/search?track_name=${enc(title)}", title, artist, durationSec)
+ }
+ sourceId == "netease" -> byHand { fromNetEase(title, artist, durationSec) }
+ sourceId == "genius" -> byHand { fromGenius(title, artist) }
+ else -> null
+ }
+ } catch (e: kotlinx.coroutines.CancellationException) { throw e } catch (e: Exception) { Log.d("LyricsApi", "$sourceId by hand: ${e.javaClass.simpleName}"); null }
+ val lyrics = found?.takeIf { !it.isEmpty } ?: return@withContext null
+ // Words from another recording follow Spotify's own timing when that can be checked, and keep its colours.
+ val chosen = if (lyrics.wordSynced && spotify != null) (alignTo(lyrics, spotify) ?: lyrics).copy(colors = spotify.colors) else lyrics
+ cache[track.key] = chosen
+ LyricsDisk.write(track.key, chosen)
+ Log.d("LyricsApi", "${track.title}: ${chosen.lines.size} lines from ${chosen.provider} (chosen: $sourceId)")
+ chosen
+ }
+
private suspend fun resolve(track: Track): Lyrics? = 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
@@ -201,26 +286,40 @@ object LyricsApi {
private fun encode(l: Lyrics) = JSONObject()
.put("synced", l.synced).put("language", l.language).put("provider", l.provider)
+ .put("trl", l.translationLanguage)
.put("colors", l.colors?.let { JSONArray(listOf(it.background, it.text, it.highlight)) })
.put("lines", JSONArray().also { arr ->
l.lines.forEach { line ->
arr.put(JSONObject().put("t", line.timeMs).put("x", line.text).also { lo ->
- line.words?.let { ws -> lo.put("w", JSONArray().also { wa -> ws.forEach { w -> wa.put(JSONArray(listOf(w.startMs, w.endMs, w.text))) } }) }
+ line.words?.let { ws -> lo.put("w", wordsJson(ws)) }
+ line.translation?.let { lo.put("tr", it) }
+ line.romanization?.let { lo.put("ro", it) }
+ line.voice?.let { lo.put("v", it) }
+ line.background?.let { lo.put("bg", it) }
+ line.backgroundWords?.let { lo.put("bw", wordsJson(it)) }
})
}
})
+ private fun wordsJson(ws: List<LyricWord>) = JSONArray().also { wa -> ws.forEach { w -> wa.put(JSONArray(listOf(w.startMs, w.endMs, w.text))) } }
+
+ private fun wordsOf(wa: JSONArray?) = wa?.let { List(it.length()) { j -> it.getJSONArray(j).let { w -> LyricWord(w.getLong(0), w.getLong(1), w.getString(2)) } } }
+
+ // Entries written before translations, voices and backing vocals existed lack their keys: they read as none.
private fun decode(o: JSONObject): Lyrics {
val colors = o.optJSONArray("colors")?.let { LyricsColors(it.getInt(0), it.getInt(1), it.getInt(2)) }
val lines = o.getJSONArray("lines").let { arr ->
List(arr.length()) { i ->
val lo = arr.getJSONObject(i)
- val words = lo.optJSONArray("w")?.let { wa -> List(wa.length()) { j -> wa.getJSONArray(j).let { LyricWord(it.getLong(0), it.getLong(1), it.getString(2)) } } }
- LyricLine(lo.getLong("t"), lo.getString("x"), words)
+ LyricLine(lo.getLong("t"), lo.getString("x"), wordsOf(lo.optJSONArray("w")),
+ translation = lo.optString("tr").ifEmpty { null }, romanization = lo.optString("ro").ifEmpty { null },
+ voice = if (lo.has("v")) lo.optInt("v") else null, background = lo.optString("bg").ifEmpty { null },
+ backgroundWords = wordsOf(lo.optJSONArray("bw")))
}
}
return Lyrics(lines, o.getBoolean("synced"), o.optString("language").takeIf { it.isNotEmpty() && it != "null" },
- o.optString("provider").takeIf { it.isNotEmpty() && it != "null" }, colors)
+ o.optString("provider").takeIf { it.isNotEmpty() && it != "null" }, colors,
+ translationLanguage = o.optString("trl").takeIf { it.isNotEmpty() && it != "null" })
}
}
@@ -241,9 +340,9 @@ 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) { fromLyricsPlus(asked, title, artist, durationMs) } }
- val red = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { fromLrcRed(asked, title, artist, durationMs) } }
- val kugou = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { fromKugou(title, artist, durationMs) } }
+ 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 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).
@@ -306,18 +405,20 @@ object LyricsApi {
val title = cleanTitle(track.title)
val artist = track.artist.substringBefore(",").trim()
val durationSec = (track.durationMs / 1000).toInt()
- val netease = if (extraSources) async { fromNetEase(title, artist, durationSec) } else null
- val genius = if (extraSources) async { fromGenius(title, artist) } else null
- val exact = async { lrclibGet(title, artist, track.album, durationSec) }
- val fuzzy = async { lrclibSearch("$LRCLIB/search?track_name=${enc(title)}&artist_name=${enc(artist)}", title, artist, durationSec) }
- val lrclib = exact.await() ?: fuzzy.await()
- ?: lrclibSearch("$LRCLIB/search?track_name=${enc(title)}", title, artist, durationSec)
+ val netease = if (extraSources) async { asking("netease", track) { fromNetEase(title, artist, durationSec) } } else null
+ val genius = if (extraSources) async { asking("genius", track) { fromGenius(title, artist) } } else null
+ val lrclib = asking("lrclib", track) {
+ val exact = async { lrclibGet(title, artist, track.album, durationSec) }
+ val fuzzy = async { lrclibSearch("$LRCLIB/search?track_name=${enc(title)}&artist_name=${enc(artist)}", title, artist, durationSec) }
+ exact.await() ?: fuzzy.await()
+ ?: lrclibSearch("$LRCLIB/search?track_name=${enc(title)}", title, artist, durationSec)
+ }
val ne = netease?.await()
- // Synced beats plain.
+ // Synced beats plain; NetEase's translation and romanization follow the lines of LRCLIB when it wins.
when {
- lrclib != null && lrclib.synced -> lrclib
+ lrclib != null && lrclib.synced -> LyricsExtras.carry(lrclib, ne)
ne != null && ne.synced -> ne
- else -> fromKugou(title, artist, track.durationMs) ?: lrclib ?: ne ?: genius?.await()
+ else -> asking("kugou", track) { fromKugou(title, artist, track.durationMs) } ?: lrclib ?: ne ?: genius?.await()
}
}
@@ -342,33 +443,38 @@ object LyricsApi {
// ── 4. NetEase Cloud Music (line-synced LRC) ──
private fun fromNetEase(title: String, artist: String, durationSec: Int): Lyrics? {
- val search = httpGet("https://music.163.com/api/search/get?s=${enc("$title $artist")}&type=1&limit=6", timeoutMs = 6000)
+ val search = httpGet("https://music.163.com/api/search/get?s=${enc("$title $artist")}&type=1&limit=6", timeoutMs = 6000, provider = "netease")
?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null
val songs = search.optJSONObject("result")?.optJSONArray("songs") ?: return null
for (i in 0 until songs.length()) {
val song = songs.optJSONObject(i) ?: continue
val songArtist = song.optJSONArray("artists")?.optJSONObject(0)?.optString("name").orEmpty()
if (!isPlausibleMatch(song.optString("name"), songArtist, (song.optLong("duration") / 1000).toInt(), title, artist, durationSec)) continue
- val o = httpGet("https://music.163.com/api/song/lyric?id=${song.optLong("id")}&lv=1&kv=1&tv=-1", timeoutMs = 6000)
+ // tlyric: a translation (in Chinese), romalrc: the romanization, both timed like the lyrics (rv=-1 asks for the latter).
+ val o = httpGet("https://music.163.com/api/song/lyric?id=${song.optLong("id")}&lv=1&kv=1&tv=-1&rv=-1", timeoutMs = 6000, provider = "netease")
?.let { runCatching { JSONObject(it) }.getOrNull() } ?: continue
val lrc = o.optJSONObject("lrc")?.optString("lyric").orEmpty()
// Credit lines ("作词 : …") come first in NetEase LRC.
- val lines = parseLrc(lrc).filter { it.text.isNotBlank() && !it.text.contains(" : ") }
- if (lines.isEmpty()) continue
- return Lyrics(lines = lines, synced = lines.any { it.timeMs > 0 }, provider = "NetEase Cloud Music")
+ val plain = parseLrc(lrc).filter { it.text.isNotBlank() && !it.text.contains(" : ") }
+ if (plain.isEmpty()) continue
+ val lines = LyricsExtras.attach(plain,
+ parseLrc(o.optJSONObject("tlyric")?.optString("lyric").orEmpty()),
+ parseLrc(o.optJSONObject("romalrc")?.optString("lyric").orEmpty()))
+ return Lyrics(lines = lines, synced = lines.any { it.timeMs > 0 }, provider = "NetEase Cloud Music",
+ translationLanguage = if (lines.any { it.translation != null }) "zh" else null)
}
return null
}
// ── 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)
+ val search = httpGet("https://genius.com/api/search/song?per_page=5&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 html = httpGet(r.optString("url"), timeoutMs = 8000) ?: 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("]")) }
if (lines.isEmpty()) continue
@@ -409,13 +515,13 @@ object LyricsApi {
if (album.isNotBlank()) append("&album_name=").append(enc(album))
if (durationSec > 0) append("&duration=").append(durationSec)
}
- val o = httpGet(url)?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null
+ val o = httpGet(url, provider = "lrclib")?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null
if (!isPlausibleMatch(o.optString("trackName"), o.optString("artistName"), o.optInt("duration"), title, artist, durationSec)) return null
return parseLrclib(o)
}
private fun lrclibSearch(url: String, title: String, artist: String, durationSec: Int): Lyrics? {
- val arr = httpGet(url)?.let { runCatching { JSONArray(it) }.getOrNull() } ?: return null
+ val arr = httpGet(url, provider = "lrclib")?.let { runCatching { JSONArray(it) }.getOrNull() } ?: return null
// Of the plausible candidates, prefer synced lyrics, then the closest duration.
var best: JSONObject? = null
var bestScore = Long.MAX_VALUE
@@ -447,88 +553,195 @@ object LyricsApi {
private fun fromLyricsPlus(asked: String, title: String, artist: String, durationMs: Long): Lyrics? {
val q = "title=${enc(asked)}&artist=${enc(artist)}" + if (durationMs > 0) "&duration=${durationMs / 1000}" else ""
for (base in LYRICS_PLUS) {
- val body = httpGet("$base/v2/lyrics/get?$q", timeoutMs = 5000) ?: continue
+ val body = httpGet("$base/v2/lyrics/get?$q", timeoutMs = 5000, provider = base) ?: continue
val o = runCatching { JSONObject(body) }.getOrNull() ?: continue
val meta = o.optJSONObject("metadata")
if (meta != null && !sameSong(meta.optString("title"), meta.optString("artist"), parseClock(meta.optString("totalDuration")), title, artist, durationMs)) return null
- val arr = o.optJSONArray("lyrics") ?: continue
- val lines = ArrayList<LyricLine>()
- for (i in 0 until arr.length()) {
- val l = arr.optJSONObject(i) ?: continue
- val syl = l.optJSONArray("syllabus")
- val words = syl?.let { s ->
- (0 until s.length()).mapNotNull { j -> s.optJSONObject(j) }
- .filterNot { it.optBoolean("isBackground") }
- .map { w -> val t = w.optLong("time"); LyricWord(t, t + w.optLong("duration"), w.optString("text")) }
- }?.takeIf { it.isNotEmpty() }
- val text = words?.joinToString("") { it.text }?.trim() ?: l.optString("text").trim()
- if (text.isNotEmpty()) lines += LyricLine(l.optLong("time"), text, words)
- }
- if (lines.isEmpty()) continue
- val source = meta?.optString("source").orEmpty()
- return Lyrics(lines, synced = true, language = meta?.optString("language")?.takeIf { it.isNotBlank() },
- provider = if (source.contains("apple", true)) "Apple Music · LyricsPlus" else "LyricsPlus")
+ return lyricsPlusLines(o) ?: continue
}
return null
}
+ /**
+ * LyricsPlus's answer as lyrics. A line's backing vocals (`isBackground` syllables) are kept
+ * apart from its words, `element.singer` ("v1", "v2") says who sings, and `translation` /
+ * `transliteration` (a text, or an object with a `text`) are taken when a line has them.
+ */
+ internal fun lyricsPlusLines(o: JSONObject): Lyrics? {
+ val meta = o.optJSONObject("metadata")
+ val arr = o.optJSONArray("lyrics") ?: return null
+ var translationLanguage: String? = null
+ val lines = ArrayList<LyricLine>()
+ for (i in 0 until arr.length()) {
+ val l = arr.optJSONObject(i) ?: continue
+ val syl = l.optJSONArray("syllabus")
+ val all = syl?.let { s -> (0 until s.length()).mapNotNull { j -> s.optJSONObject(j) } }.orEmpty()
+ fun word(w: JSONObject): LyricWord { val t = w.optLong("time"); return LyricWord(t, t + w.optLong("duration"), w.optString("text")) }
+ var words = all.filterNot { it.optBoolean("isBackground") }.map(::word).takeIf { it.isNotEmpty() }
+ var back = all.filter { it.optBoolean("isBackground") }.map(::word).takeIf { it.isNotEmpty() }
+ // A line of backing vocals only is a line of its own.
+ if (words == null && back != null) { words = back; back = null }
+ val text = words?.joinToString("") { it.text }?.trim() ?: l.optString("text").trim()
+ if (text.isEmpty()) continue
+ val tr = l.opt("translation")
+ val translation = textOf(tr)?.takeIf { LyricsMatch.key(it) != LyricsMatch.key(text) }
+ if (translation != null && translationLanguage == null) translationLanguage = (tr as? JSONObject)?.optString("lang")?.ifBlank { null }
+ val roman = textOf(l.opt("transliteration"))?.takeIf { LyricsMatch.key(it) != LyricsMatch.key(text) }
+ lines += LyricLine(l.optLong("time"), text, words, translation, roman,
+ voice = voiceOf(l.optJSONObject("element")?.optString("singer")),
+ background = back?.joinToString("") { it.text }?.let(::backingText), backgroundWords = back)
+ }
+ if (lines.isEmpty()) return null
+ val source = meta?.optString("source").orEmpty()
+ return Lyrics(lines, synced = true, language = meta?.optString("language")?.takeIf { it.isNotBlank() },
+ provider = if (source.contains("apple", true)) "Apple Music · LyricsPlus" else "LyricsPlus",
+ translationLanguage = translationLanguage.takeIf { lines.any { it.translation != null } })
+ }
+
+ /** A string, or the `text` of an object: what a source gives as a translation or a romanization. */
+ private fun textOf(v: Any?): String? =
+ when (v) { is String -> v; is JSONObject -> v.optString("text"); else -> null }?.trim()?.ifEmpty { null }
+
+ /** "v1" → 1, "v2" → 2; Apple's "v1000" (everyone) → 0; anything else is unknown. */
+ internal fun voiceOf(agent: String?): Int? =
+ agent?.trim()?.removePrefix("v")?.toIntOrNull()?.takeIf { it >= 0 }?.let { if (it >= 1000) 0 else it }
+
+ /** Backing vocals as plain text: "(Woo-hoo)" → "Woo-hoo". */
+ private fun backingText(s: String): String? = s.replace(Regex("\\s+"), " ").trim().removeSurrounding("(", ")").trim().ifEmpty { null }
+
// ── Word by word: lrc.red (Apple Music TTML, found by ISRC) ──
private fun fromLrcRed(asked: String, title: String, artist: String, durationMs: Long): Lyrics? {
- val search = httpGet("https://lrc.red/search.json?q=${enc("$asked $artist")}", timeoutMs = 5000) ?: return null
+ val search = httpGet("https://lrc.red/search.json?q=${enc("$asked $artist")}", timeoutMs = 5000, provider = "lrcred") ?: return null
val hits = runCatching { JSONObject(search).optJSONArray("hits") }.getOrNull() ?: return null
val hit = (0 until hits.length()).mapNotNull { hits.optJSONObject(it) }.firstOrNull {
sameSong(it.optString("title"), it.optString("artist"), (it.optDouble("duration", 0.0) * 1000).toLong(), title, artist, durationMs)
} ?: return null
val isrc = hit.optString("isrc").takeIf { it.isNotBlank() } ?: return null
- val ttml = httpGet("https://lrc.red/s/${enc(isrc)}.ttml", timeoutMs = 6000) ?: return null
- val lines = parseTtml(ttml) ?: return null
- return Lyrics(lines, synced = true, provider = "Apple Music · lrc.red")
+ val ttml = httpGet("https://lrc.red/s/${enc(isrc)}.ttml", timeoutMs = 6000, provider = "lrcred") ?: return null
+ return parseTtml(ttml)?.copy(provider = "Apple Music · lrc.red")
}
- /** Apple Music's TTML: a <p> per line, a timed <span> per word (background voices left out). */
- internal fun parseTtml(xml: String): List<LyricLine>? = runCatching {
- val p = android.util.Xml.newPullParser()
+ /**
+ * Apple Music's TTML: a <p> per line (its `ttm:agent` says who sings), a timed <span> per word,
+ * backing vocals in a `ttm:role="x-bg"` span (kept apart from the line), and a translation and a
+ * romanization either in the head (`translation` / `transliteration`, a `text for="L1"` per line,
+ * the line's `*:key`) or inside the line (`x-translation` / `x-roman` spans). [newParser]: a pull
+ * parser without namespace processing (tests bring their own).
+ */
+ internal fun parseTtml(xml: String, newParser: () -> org.xmlpull.v1.XmlPullParser = { android.util.Xml.newPullParser() }): Lyrics? = runCatching {
+ val p = newParser()
p.setFeature(org.xmlpull.v1.XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
p.setInput(java.io.StringReader(xml))
+ fun attr(name: String) = p.getAttributeValue(null, name)
+ fun lineKey() = (0 until p.attributeCount).firstOrNull { p.getAttributeName(it).let { n -> n == "key" || n.endsWith(":key") } }?.let { p.getAttributeValue(it) }
+ fun tidy(sb: CharSequence) = sb.toString().replace(Regex("\\s+"), " ").trim()
+ // Head: only the first translation and the first transliteration, text by line key.
+ val headTranslation = HashMap<String, String>(); val headRoman = HashMap<String, String>()
+ var translationLanguage: String? = null
+ var headKind = 0; var headSeenTr = false; var headSeenRo = false
+ var headKey: String? = null; var headText = StringBuilder(); var headSkip = 0
+ // Body
val lines = ArrayList<LyricLine>()
var lineStart = -1L
var words: MutableList<LyricWord>? = null
var plain = StringBuilder()
var wordStart = -1L; var wordEnd = 0L; var word = StringBuilder()
- var skipDepth = 0
+ var role: String? = null; var roleDepth = 0
+ var key: String? = null; var voice: Int? = null
+ var bgWords = ArrayList<LyricWord>(); var bgPlain = StringBuilder()
+ var bgStart = -1L; var bgEnd = 0L; var bgWord = StringBuilder(); var bgSpan = longArrayOf(-1, 0)
+ var inTr = StringBuilder(); var inRo = StringBuilder()
var inBody = false
while (true) {
when (p.next()) {
org.xmlpull.v1.XmlPullParser.END_DOCUMENT -> break
org.xmlpull.v1.XmlPullParser.START_TAG -> when {
p.name == "body" -> inBody = true
- !inBody -> {}
- skipDepth > 0 -> skipDepth++
- p.getAttributeValue(null, "ttm:role")?.startsWith("x-") == true -> skipDepth = 1
- p.name == "p" -> { lineStart = clock(p.getAttributeValue(null, "begin")); words = ArrayList(); plain = StringBuilder() }
+ !inBody -> when {
+ headKey != null -> if (headSkip > 0) headSkip++ else if (attr("ttm:role")?.startsWith("x-") == true) headSkip = 1
+ p.name == "translation" -> if (!headSeenTr) { headSeenTr = true; headKind = 1; translationLanguage = attr("xml:lang") } else headKind = -1
+ p.name == "transliteration" -> if (!headSeenRo) { headSeenRo = true; headKind = 2 } else headKind = -1
+ p.name == "text" && headKind > 0 -> { headKey = attr("for"); headText = StringBuilder(); headSkip = 0 }
+ }
+ role != null -> {
+ roleDepth++
+ if (role == "x-bg" && p.name == "span" && roleDepth == 2) { bgStart = clock(attr("begin")); bgEnd = clock(attr("end")); bgWord = StringBuilder() }
+ }
+ attr("ttm:role")?.startsWith("x-") == true -> {
+ role = attr("ttm:role"); roleDepth = 1
+ if (role == "x-bg") bgSpan = longArrayOf(clock(attr("begin")), clock(attr("end")))
+ if (role == "x-translation" && translationLanguage == null) translationLanguage = attr("xml:lang")
+ }
+ p.name == "p" -> {
+ lineStart = clock(attr("begin")); words = ArrayList(); plain = StringBuilder()
+ key = lineKey(); voice = voiceOf(attr("ttm:agent"))
+ bgWords = ArrayList(); bgPlain = StringBuilder(); bgStart = -1; inTr = StringBuilder(); inRo = StringBuilder()
+ }
p.name == "span" && words != null -> {
- wordStart = clock(p.getAttributeValue(null, "begin")); wordEnd = clock(p.getAttributeValue(null, "end")); word = StringBuilder()
+ wordStart = clock(attr("begin")); wordEnd = clock(attr("end")); word = StringBuilder()
}
}
- org.xmlpull.v1.XmlPullParser.TEXT -> if (inBody && skipDepth == 0 && words != null) {
+ org.xmlpull.v1.XmlPullParser.TEXT -> {
val t = p.text
- if (wordStart >= 0) word.append(t)
- // Text between two words (a space): it belongs to the word before it.
- else if (words!!.isNotEmpty()) words!![words!!.lastIndex] = words!!.last().let { it.copy(text = it.text + t) }
- plain.append(t)
+ if (!inBody) { if (headKey != null && headSkip == 0) headText.append(t) }
+ else if (words != null) when (role) {
+ null -> {
+ if (wordStart >= 0) word.append(t)
+ // Text between two words (a space): it belongs to the word before it.
+ else if (words!!.isNotEmpty()) words!![words!!.lastIndex] = words!!.last().let { it.copy(text = it.text + t) }
+ plain.append(t)
+ }
+ "x-bg" -> {
+ bgPlain.append(t)
+ if (bgStart >= 0) bgWord.append(t)
+ else if (bgWords.isNotEmpty()) bgWords[bgWords.lastIndex] = bgWords.last().let { it.copy(text = it.text + t) }
+ }
+ "x-translation" -> inTr.append(t)
+ "x-roman" -> inRo.append(t)
+ }
}
org.xmlpull.v1.XmlPullParser.END_TAG -> when {
- skipDepth > 0 -> skipDepth--
+ !inBody -> when {
+ headKey != null && headSkip > 0 -> headSkip--
+ headKey != null && p.name == "text" -> {
+ val text = tidy(headText).ifEmpty { null }
+ if (text != null) (if (headKind == 1) headTranslation else headRoman)[headKey!!] = text
+ headKey = null
+ }
+ p.name == "translation" || p.name == "transliteration" -> headKind = 0
+ }
+ role != null -> {
+ if (role == "x-bg" && roleDepth == 2 && p.name == "span" && bgStart >= 0) { bgWords.add(LyricWord(bgStart, bgEnd, bgWord.toString())); bgStart = -1 }
+ roleDepth--
+ if (roleDepth == 0) {
+ // One span of backing vocals with no span of words inside: it is the one word.
+ if (role == "x-bg" && bgWords.isEmpty() && bgSpan[0] >= 0 && bgPlain.isNotBlank()) bgWords.add(LyricWord(bgSpan[0], bgSpan[1], bgPlain.toString()))
+ role = null
+ }
+ }
p.name == "span" && wordStart >= 0 -> { words?.add(LyricWord(wordStart, wordEnd, word.toString())); wordStart = -1 }
p.name == "p" && words != null -> {
- val text = plain.toString().replace(Regex("\\s+"), " ").trim()
- if (text.isNotEmpty() && lineStart >= 0) lines += LyricLine(lineStart, text, words!!.takeIf { it.isNotEmpty() })
+ var text = tidy(plain)
+ var foreground: List<LyricWord>? = words!!.takeIf { it.isNotEmpty() }
+ var back: List<LyricWord>? = bgWords.takeIf { it.isNotEmpty() }
+ var backText = backingText(tidy(bgPlain))
+ // A line of backing vocals only is a line of its own.
+ if (text.isEmpty() && backText != null) { text = backText; foreground = back; back = null; backText = null }
+ if (text.isNotEmpty() && lineStart >= 0) {
+ val tr = tidy(inTr).ifEmpty { null } ?: key?.let(headTranslation::get)
+ val ro = tidy(inRo).ifEmpty { null } ?: key?.let(headRoman::get)
+ lines += LyricLine(lineStart, text, foreground,
+ translation = tr?.takeIf { LyricsMatch.key(it) != LyricsMatch.key(text) },
+ romanization = ro?.takeIf { LyricsMatch.key(it) != LyricsMatch.key(text) },
+ voice = voice, background = backText, backgroundWords = back)
+ }
words = null
}
}
}
}
- lines.takeIf { it.isNotEmpty() }
+ if (lines.isEmpty()) null
+ else Lyrics(lines, synced = true, translationLanguage = translationLanguage.takeIf { lines.any { it.translation != null } })
}.getOrNull()
/** TTML times: "11.859", "1:02.345" or "00:01:02.345" → ms. */
@@ -548,12 +761,12 @@ object LyricsApi {
private fun fromKugou(title: String, artist: String, durationMs: Long): Lyrics? {
val search = httpGet("https://lyrics.kugou.com/search?ver=1&man=yes&client=pc&keyword=${enc("$artist - $title")}" +
- (if (durationMs > 0) "&duration=$durationMs" else ""), timeoutMs = 5000) ?: return null
+ (if (durationMs > 0) "&duration=$durationMs" else ""), timeoutMs = 5000, provider = "kugou") ?: return null
val cands = runCatching { JSONObject(search).optJSONArray("candidates") }.getOrNull() ?: return null
val c = (0 until cands.length()).mapNotNull { cands.optJSONObject(it) }.firstOrNull {
sameSong(it.optString("song"), it.optString("singer"), it.optLong("duration"), title, artist, durationMs)
} ?: return null
- val dl = httpGet("https://lyrics.kugou.com/download?ver=1&client=pc&id=${c.optString("id")}&accesskey=${c.optString("accesskey")}&fmt=krc&charset=utf8", timeoutMs = 5000) ?: return null
+ val dl = httpGet("https://lyrics.kugou.com/download?ver=1&client=pc&id=${c.optString("id")}&accesskey=${c.optString("accesskey")}&fmt=krc&charset=utf8", timeoutMs = 5000, provider = "kugou") ?: return null
val content = runCatching { JSONObject(dl).optString("content") }.getOrNull()?.takeIf { it.isNotBlank() } ?: return null
val krc = runCatching {
val raw = android.util.Base64.decode(content, android.util.Base64.DEFAULT)
@@ -578,9 +791,8 @@ object LyricsApi {
* The same song for the word-timed sources: one of its artists is ours, the title is ours
* (asides left out, either may be longer), and the length is within 4 s when both are known.
*/
- private fun sameSong(candTitle: String, candArtist: String, candDurationMs: Long, title: String, artist: String, durationMs: Long): Boolean {
- val a = matchKey(artist)
- if (a.isEmpty() || candArtist.split(',', '&', '、', '/').none { matchKey(it) == a }) return false
+ internal fun sameSong(candTitle: String, candArtist: String, candDurationMs: Long, title: String, artist: String, durationMs: Long): Boolean {
+ if (matchKey(artist).isEmpty() || (candArtist.split(',', '&', '、', '/') + candArtist).none { LyricsMatch.sameArtist(it, artist) }) return false
val t = matchKey(title); val ct = matchKey(cleanTitle(candTitle))
if (t.isEmpty() || !(ct == t || ct.startsWith(t) || t.startsWith(ct))) return false
return durationMs <= 0 || candDurationMs <= 0 || kotlin.math.abs(candDurationMs - durationMs) <= 4_000
@@ -594,19 +806,21 @@ object LyricsApi {
private fun cleanTitle(title: String) =
title.substringBefore(" - ").replace(featTag, "").replace(bracketTag, "").trim()
- private fun matchKey(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
+ // Letters and digits only, accents and case folded away ("Rosalía" is "rosalia").
+ internal fun matchKey(s: String) = LyricsMatch.key(s)
// Exact normalized identity is conservative: ambiguous fallbacks are rejected.
private fun overlaps(a: String, b: String) = a.isNotEmpty() && a == b
/**
- * Fallback hits are only used when they are the same song: same artist, same
- * title (either may carry extras), and a similar length when both are known.
+ * Fallback hits are only used when they are the same song: same artist (accents and the
+ * order of its words aside), same title (either may carry extras), and a similar length
+ * when both are known.
*/
internal fun isPlausibleMatch(
candTitle: String, candArtist: String, candDurationSec: Int,
title: String, artist: String, durationSec: Int,
): Boolean {
- if (!overlaps(matchKey(candArtist), matchKey(artist))) return false
+ if (!LyricsMatch.sameArtist(candArtist, artist)) return false
if (!overlaps(matchKey(cleanTitle(candTitle)), matchKey(title))) return false
return durationSec <= 0 || candDurationSec <= 0 || kotlin.math.abs(candDurationSec - durationSec) <= 3
}
@@ -637,23 +851,57 @@ object LyricsApi {
private fun enc(s: String) = URLEncoder.encode(s, "UTF-8")
- private fun httpGet(spec: String, timeoutMs: Int = 5000): String? = runCatching {
- com.music.spotui.data.DataSaver.check()
- val conn = (URL(spec).openConnection() as HttpURLConnection).apply {
- requestMethod = "GET"
- connectTimeout = timeoutMs
- readTimeout = timeoutMs
- setRequestProperty("User-Agent", UA)
- setRequestProperty("Accept", "application/json, text/html;q=0.9, */*;q=0.8")
+ /**
+ * A GET, its body on a 200, else null. [provider] (the health id, see [LyricsHealth]): a 5xx, a
+ * 429 or an exception counts against it, any other answer (a 404 too) is an answer; a provider
+ * set aside is not asked at all, unless asked for by hand ([fetchFrom]).
+ */
+ private fun httpGet(spec: String, timeoutMs: Int = 5000, provider: String? = null): String? {
+ if (provider != null && bypass.get() != true) health.reason(provider)?.let {
+ Log.d("LyricsApi", "$provider set aside ($it)")
+ health.skipped()
+ return null
}
- try {
- if (conn.responseCode != 200) {
- Log.d("LyricsApi", "HTTP ${conn.responseCode} for $spec")
- return null
+ return runCatching {
+ com.music.spotui.data.DataSaver.check()
+ val conn = (URL(spec).openConnection() as HttpURLConnection).apply {
+ requestMethod = "GET"
+ connectTimeout = timeoutMs
+ readTimeout = timeoutMs
+ setRequestProperty("User-Agent", UA)
+ setRequestProperty("Accept", "application/json, text/html;q=0.9, */*;q=0.8")
+ }
+ try {
+ val code = conn.responseCode
+ if (code != 200) {
+ Log.d("LyricsApi", "HTTP $code for $spec")
+ if (provider == null) health.skipped()
+ else if (code >= 500 || code == 429 || code == 408) health.failed(provider)
+ else health.answered(provider)
+ return null
+ }
+ val body = conn.inputStream.bufferedReader().use { it.readText() }
+ provider?.let(health::answered)
+ body
+ } finally {
+ conn.disconnect()
}
- conn.inputStream.bufferedReader().use { it.readText() }
- } finally {
- conn.disconnect()
+ }.getOrElse {
+ Log.d("LyricsApi", "request failed: ${it.message}")
+ if (provider == null || it is com.music.spotui.data.DataSaver.Blocked) health.skipped() else health.failed(provider)
+ null
}
- }.getOrElse { Log.d("LyricsApi", "request failed: ${it.message}"); null }
+ }
+
+ /**
+ * [provider]'s answer for [track]: not asked again for [LyricsHealth.MISSING_MS] after it had
+ * no lyrics (a failed or skipped request is not "no lyrics": it is asked again).
+ */
+ private inline fun asking(provider: String, track: Track, block: () -> Lyrics?): Lyrics? {
+ if (health.isMissing(track.key, provider)) return null
+ val lostBefore = health.lostCount()
+ val found = block()
+ if (found == null && health.lostCount() == lostBefore) health.noteMissing(track.key, provider)
+ return found
+ }
}
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
new file mode 100644
index 00000000..b2117249
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsExtras.kt
@@ -0,0 +1,41 @@
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.LyricLine
+import com.music.spotui.data.entity.Lyrics
+
+/** Translations and romanizations a source gives apart from the lines (NetEase), and carrying them 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
+
+ /** [lines] with the nearest line of [translations] and of [romanizations] (timed lines of text) as theirs. */
+ fun attach(lines: List<LyricLine>, translations: List<LyricLine>, romanizations: List<LyricLine>): List<LyricLine> {
+ if (translations.isEmpty() && romanizations.isEmpty()) return lines
+ fun near(from: List<LyricLine>, t: Long): String? =
+ from.minByOrNull { kotlin.math.abs(it.timeMs - t) }?.takeIf { kotlin.math.abs(it.timeMs - t) <= TOLERANCE_MS }
+ ?.text?.trim()?.takeIf { it.isNotEmpty() && it != "♪" && it != "//" }
+ return lines.map { l ->
+ if (l.text == "♪") l else l.copy(translation = near(translations, l.timeMs), romanization = near(romanizations, l.timeMs))
+ }
+ }
+
+ private fun LyricLine.hasExtra() = translation != null || romanization != null
+
+ /**
+ * [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.
+ */
+ 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
+ var hit = 0
+ val lines = to.lines.map { l ->
+ val m = LyricsMatch.key(l.text).takeIf { it.isNotEmpty() }?.let { byText[it] }
+ 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 } })
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsHealth.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsHealth.kt
new file mode 100644
index 00000000..4db790a2
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsHealth.kt
@@ -0,0 +1,72 @@
+package com.music.spotui.data.api
+
+import app.myspoti.extensions.Outcome
+import app.myspoti.extensions.SourceCooldown
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * Which lyrics providers answer. One that fails [FAILURES_IN_A_ROW] times in a row (network, a
+ * timeout, a 5xx) is set aside for [SET_ASIDE_MS] ([SourceCooldown], as for the extensions): it is
+ * not asked, so a provider that is down costs no waiting. And "no lyrics for this song" from a
+ * provider is kept for [MISSING_MS] per song and provider, so reopening a song does not ask again.
+ * A failure is never kept as "no lyrics". [clock]: ms, for tests.
+ */
+class LyricsHealth(private val clock: () -> Long = System::currentTimeMillis) {
+ private val cooldown = SourceCooldown(clock)
+ private val streak = ConcurrentHashMap<String, Int>()
+ private val missing = ConcurrentHashMap<String, Long>()
+ private val lost = AtomicLong()
+
+ /** Why [provider] is set aside ("server-down, 540 s left"), or null (it may be asked). */
+ fun reason(provider: String): String? = cooldown.reason(provider)
+
+ /** [provider] answered (found or not found): its failures in a row end. */
+ fun answered(provider: String) {
+ streak.remove(provider)
+ cooldown.note(provider, Outcome.Found)
+ }
+
+ /** A request to [provider] failed. */
+ fun failed(provider: String) {
+ lost.incrementAndGet()
+ val n = streak.merge(provider, 1, Int::plus) ?: 1
+ if (n >= FAILURES_IN_A_ROW) {
+ streak.remove(provider)
+ cooldown.note(provider, Outcome.ServerDown(untilMs = clock() + SET_ASIDE_MS))
+ }
+ }
+
+ /** A request was not made (set aside, data saver): not an answer either. */
+ fun skipped() { lost.incrementAndGet() }
+
+ /** How many requests were lost so far: unchanged around a call that found nothing, it was a real "no lyrics". */
+ fun lostCount(): Long = lost.get()
+
+ private fun key(track: String, provider: String) = "$provider|$track"
+
+ fun isMissing(track: String, provider: String): Boolean {
+ val k = key(track, provider)
+ val at = missing[k] ?: return false
+ if (clock() - at < MISSING_MS) return true
+ missing.remove(k, at)
+ return false
+ }
+
+ fun noteMissing(track: String, provider: String) {
+ if (missing.size > MAX_MISSING) { val now = clock(); missing.entries.removeIf { now - it.value >= MISSING_MS } }
+ missing[key(track, provider)] = clock()
+ }
+
+ /** The song is looked up again (the user asked): its "no lyrics" answers are dropped. */
+ fun forgetTrack(track: String) { missing.keys.removeIf { it.endsWith("|$track") } }
+
+ fun forgetAll() { missing.clear() }
+
+ companion object {
+ const val FAILURES_IN_A_ROW = 3
+ const val SET_ASIDE_MS = 10 * 60_000L
+ const val MISSING_MS = 5 * 60_000L
+ private const val MAX_MISSING = 500
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsMatch.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsMatch.kt
new file mode 100644
index 00000000..18af6627
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsMatch.kt
@@ -0,0 +1,30 @@
+package com.music.spotui.data.api
+
+import java.text.Normalizer
+
+/**
+ * How a catalogue's title and artist are compared with ours: case, accents ("Beyoncé" and
+ * "Beyonce"), punctuation and the order of an artist's words ("Hi Lee" and "Lee Hi") do not matter.
+ */
+object LyricsMatch {
+ // The combining accents only: kana voicing marks and Hangul jamo are not "accents".
+ private val accents = Regex("[̀-ͯ]")
+ private val notWord = Regex("[^\\p{L}\\p{N}\\p{M}]+")
+
+ /** [s] lowercased, without accents, with the few letters that do not decompose spelled out. */
+ fun fold(s: String): String {
+ val plain = Normalizer.normalize(Normalizer.normalize(s, Normalizer.Form.NFD).replace(accents, ""), Normalizer.Form.NFC)
+ return plain.lowercase().replace("ß", "ss").replace("æ", "ae").replace("œ", "oe").replace("ø", "o").replace("đ", "dj").replace("ł", "l")
+ }
+
+ /** Letters and digits of [s] only, folded. */
+ fun key(s: String): String = fold(s).filter { it.isLetterOrDigit() }
+
+ private fun words(s: String): Set<String> = fold(s).split(notWord).filter { it.isNotEmpty() }.toSet()
+
+ /** The same artist: the same letters, or the same set of words in any order. */
+ fun sameArtist(a: String, b: String): Boolean {
+ val ka = key(a)
+ return ka.isNotEmpty() && (ka == key(b) || words(a) == words(b))
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/Lyrics.kt b/base/app/src/main/java/com/music/spotui/data/entity/Lyrics.kt
index 35121711..6b5f6953 100644
--- a/base/app/src/main/java/com/music/spotui/data/entity/Lyrics.kt
+++ b/base/app/src/main/java/com/music/spotui/data/entity/Lyrics.kt
@@ -10,11 +10,21 @@ data class LyricWord(
/**
* One line of lyrics. [timeMs] is the start time in ms (0 for unsynced lyrics);
* [words] is set only when the source is word-synced (karaoke-style highlight).
+ *
+ * What a source may add to a line, all null when it did not: [translation] (in
+ * [Lyrics.translationLanguage]), [romanization] (the line in Latin letters), [voice] (who sings it:
+ * 1 the first singer, 2 the second..., 0 several together) and [background] (the backing vocals
+ * sung over the line, without their brackets; [backgroundWords] when they are timed).
*/
data class LyricLine(
val timeMs: Long,
val text: String,
val words: List<LyricWord>? = null,
+ val translation: String? = null,
+ val romanization: String? = null,
+ val voice: Int? = null,
+ val background: String? = null,
+ val backgroundWords: List<LyricWord>? = null,
)
/** Spotify's per-track lyrics colours (color-lyrics `colors`), ARGB ints. */
@@ -38,7 +48,36 @@ data class Lyrics(
val colors: LyricsColors? = null,
/** False when Spotify only gives a preview (Free cap): the card says "Aperçu des paroles". */
val uncapped: Boolean = true,
+ /** The language of the lines' [LyricLine.translation] (as the source says it: "en", "zh"), null when unknown. */
+ val translationLanguage: String? = null,
) {
val isEmpty: Boolean get() = lines.isEmpty()
val wordSynced: Boolean get() = lines.any { it.words != null }
+
+ /** Some lines carry a romanization from the source. */
+ val hasRomanization: Boolean get() = lines.any { !it.romanization.isNullOrBlank() }
+
+ /** At least two singers share the song: worth showing who sings what. */
+ val hasDuet: Boolean get() = lines.mapNotNull { it.voice }.filter { it > 0 }.distinct().size > 1
+
+ /** Some lines carry backing vocals. */
+ val hasBackground: Boolean get() = lines.any { !it.background.isNullOrBlank() }
+
+ /**
+ * The source's translations when they are in [targetLang] (language tags compared by their
+ * first part), one per line (null: this line has none), else null: then a machine translation
+ * is the way. Null too when the song is already in [targetLang].
+ */
+ fun translationsFor(targetLang: String): List<String?>? {
+ if (!sameLanguage(translationLanguage, targetLang) || sameLanguage(language, targetLang)) return null
+ val out = lines.map { it.translation?.trim()?.ifEmpty { null } }
+ return out.takeIf { o -> o.any { it != null } }
+ }
+
+ companion object {
+ /** "en-US" and "en" are the same language; unknown (null) is no language. */
+ fun sameLanguage(a: String?, b: String?): Boolean =
+ !a.isNullOrBlank() && !b.isNullOrBlank() &&
+ a.substringBefore('-').substringBefore('_').equals(b.substringBefore('-').substringBefore('_'), ignoreCase = true)
+ }
}
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 87fd9316..c36cd967 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
@@ -23,6 +23,21 @@ fun setLyricsWordSync(c: Context, v: Boolean) = prefs(c).edit().putBoolean("lyri
private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
+/**
+ * "Show romanization" under the lyrics' lines (the song in Latin letters), offered when the lyrics
+ * carry one. Off by default; read as state by both looks, so the menu and the lines agree.
+ */
+object LyricsRomanizationPref {
+ private const val KEY = "lyrics_romanization"
+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, false))
+ private set
+
+ fun set(c: Context, value: Boolean) {
+ on = value
+ prefs(c).edit().putBoolean(KEY, value).apply()
+ }
+}
+
/** The bottom bar: fading into the list (the default), or solid black. Read by the bar as state. */
object SolidNavBar {
private const val KEY = "solid_nav_bar"
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 36b46f3f..e2660d7b 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
@@ -1422,6 +1422,19 @@ object Extensions {
if (!hasLyrics()) null
else withTimeoutOrNull(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>> =
+ if (!isReady) emptyList() else providing(Hook.LYRICS).map { (id, rt) -> id to rt.manifest.name }
+
+ /** The lyrics of extension [id] alone (asked even when set aside: the user chose it), or null. */
+ suspend fun lyricsFromExtension(id: String, trackId: String, title: String, artist: String, album: String, durationMs: Long, cover: String?): Lyrics? {
+ val (_, rt) = providing(Hook.LYRICS).firstOrNull { it.first == id } ?: return null
+ val input = trackInfo(trackId, title, artist, album, durationMs, cover).toJson()
+ return withTimeoutOrNull(LYRICS_MS + 1_000) {
+ ask(id, rt, Hook.LYRICS, input, LYRICS_MS) { LyricsResult.parse(it, rt.manifest.name) }.value?.let(LyricsMerge::toLyrics)
+ }
+ }
+
// ── Debug and beta command line (com.music.spotui.cli) ──
/** [hook] of [id] alone, with [input]: its answer as JSON text, null when it has none. */
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 394570a1..ef9ca89e 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
@@ -1,6 +1,7 @@
package com.music.spotui.extensions
import app.myspoti.extensions.LyricsResult
+import com.music.spotui.data.api.LyricsExtras
import com.music.spotui.data.entity.LyricLine
import com.music.spotui.data.entity.LyricWord
import com.music.spotui.data.entity.Lyrics
@@ -65,16 +66,17 @@ object LyricsMerge {
/** 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. */
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)
return when {
- theirs > mine -> fromExtension.copy(colors = own.colors)
- theirs < mine -> own
- isSpotifyComplete(own) -> own
- else -> fromExtension.copy(colors = own.colors)
+ 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) }
}
}
@@ -85,9 +87,11 @@ object LyricsMerge {
timeMs = if (r.synced) l.startMs else 0,
text = l.text,
words = if (r.synced) l.words?.map { w -> LyricWord(w.startMs, w.endMs ?: 0, w.text) } else null,
+ translation = l.translation, romanization = l.romanization, voice = l.voice, background = l.background,
)
},
synced = r.synced,
provider = r.provider,
+ translationLanguage = r.translationLanguage,
)
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/LyricsSourceSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/LyricsSourceSheet.kt
new file mode 100644
index 00000000..ab3e0fae
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/LyricsSourceSheet.kt
@@ -0,0 +1,105 @@
+package com.music.spotui.ui.components
+
+import android.widget.Toast
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.viewmodel.compose.viewModel
+import app.myspoti.engine.R
+import com.music.spotui.data.api.LyricsApi
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+import com.music.spotui.ui.theme.tone
+import com.music.spotui.ui.viewmodel.LyricsViewModel
+
+/**
+ * "Try another source": the providers that can give this song's lyrics, the one shown marked,
+ * the word-timed ones named, the ones set aside for now dimmed. A tap asks that one (the lyrics
+ * shown stay until it answers); the sheet closes on lyrics, and stays with a toast when the
+ * provider had none. Shared by both looks, like the other pickers behind the song options.
+ */
+@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+@Composable
+fun LyricsSourceSheet(onDismiss: () -> Unit, vm: LyricsViewModel = viewModel()) {
+ val context = LocalContext.current
+ val track = remember { SongPlayer.currentLyricsTrack() }
+ if (track == null) { LaunchedEffect(Unit) { onDismiss() }; return }
+ val state by vm.state.collectAsState()
+ val trying by vm.trying.collectAsState()
+ val current = (state as? LyricsViewModel.State.Loaded)?.lyrics?.let { LyricsApi.sourceOf(it) }
+ val sources = remember(track) { vm.sources(track) }
+
+ // The answer to a try: new lyrics close the sheet, a provider with nothing says so.
+ var asked by remember { mutableStateOf<String?>(null) }
+ LaunchedEffect(trying) {
+ val id = trying
+ if (id != null) { asked = id; return@LaunchedEffect }
+ val was = asked ?: return@LaunchedEffect
+ asked = null
+ if (vm.triedNothing.value == was) {
+ val name = sources.firstOrNull { it.id == was }?.name ?: was
+ Toast.makeText(context, context.getString(R.string.lyrics_source_nothing, name), Toast.LENGTH_SHORT).show()
+ } else onDismiss()
+ }
+
+ LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {
+ Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
+ Text(
+ stringResource(R.string.lyrics_other_source), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(20.dp, 8.dp),
+ )
+ sources.forEach { s ->
+ val here = s.id == current
+ val detail = listOfNotNull(
+ if (here) stringResource(R.string.lyrics_source_shown) else null,
+ if (s.words) stringResource(R.string.lyrics_source_words) else null,
+ if (s.setAside != null) stringResource(R.string.lyrics_source_aside) else null,
+ ).joinToString(" · ")
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ // Set aside: dimmed, still tappable (asking by hand ignores the break).
+ .alpha(if (s.setAside != null) 0.45f else 1f)
+ .clickable(enabled = trying == null) { vm.loadFrom(track, s.id) }
+ .padding(20.dp, 12.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(s.name, color = AppText, fontSize = 16.sp)
+ if (detail.isNotEmpty()) Text(detail, color = AppMuted, fontSize = 12.sp)
+ }
+ if (trying == s.id) CircularProgressIndicator(color = AppText, strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
+ else if (here) Icon(Icons.Default.Check, contentDescription = null, tint = AppText)
+ }
+ }
+ }
+ }
+}
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 94a7d93c..2d35dac0 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
@@ -6,9 +6,9 @@
* Changes: LyricsPanel's list, PanelVoice, the gap dots, the loading skeleton and the
* scroll lead / stagger, fed by Myspoti's LyricsViewModel. Myspoti's lyrics are mostly
* line-synced, so a line lights whole (BitChord's line-level path) and the word sweep runs
- * only where a line has words. Romanization, particles, duets, backing vocals,
- * line picking and the player-controls hand-off are left out for now. A translation (the
- * Classic look's, from the same LyricsViewModel) is shown as a smaller, dimmer line under each line.
+ * only where a line has words. Particles and the player-controls hand-off are left out for now.
+ * A line's backing vocals, romanization and translation (the Classic look's, from the same
+ * LyricsViewModel) are smaller, dimmer lines under it; the second singer of a duet sits at the end of the row.
*/
package com.music.spotui.ui.immersive.lyrics
@@ -97,7 +97,9 @@ import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import app.myspoti.engine.R
+import com.music.spotui.data.entity.LyricLine
import com.music.spotui.data.entity.Lyrics
+import com.music.spotui.data.preferences.LyricsRomanizationPref
import com.music.spotui.di.Graph
import com.music.spotui.di.SongPlayer
import com.music.spotui.ui.immersive.Immersive
@@ -192,6 +194,7 @@ fun ImmersiveLyricsPanel(modifier: Modifier = Modifier, contentPadding: PaddingV
LyricsList(
current.lyrics, trackKey, Modifier.fillMaxSize(), contentPadding, vm,
translations = current.translations.takeIf { current.showTranslation },
+ romanizing = LyricsRomanizationPref.on && current.lyrics.hasRomanization,
)
if (selecting) ShareBar(
canShare = picked != null,
@@ -220,6 +223,12 @@ private class PanelLine(
val swept: SweptLine,
/** The line's place in the source's lines (the translation's), or -1 for a break of the panel's own. */
val sourceIndex: Int = -1,
+ /** Who sings it (1, 2...; 0 together), null when the source does not say. */
+ val voice: Int? = null,
+ /** The backing vocals sung over the line, and their word timings where the source has them. */
+ val background: String? = null,
+ val backgroundSwept: SweptLine? = null,
+ val romanization: String? = null,
) {
val isWordSynced: Boolean get() = !isGap && swept.isWordSynced
@@ -250,12 +259,37 @@ private fun panelLines(lyrics: Lyrics, synced: Boolean): List<PanelLine> {
if (synced && isGapText(line.text)) {
out += PanelLine(line.timeMs, "", true, next ?: (line.timeMs + TRAILING_GAP_MS), SweptLine(line.timeMs, ""), index)
} else {
- out += PanelLine(line.timeMs, line.text, false, 0L, line.toSwept(next), index)
+ val background = line.background?.trim()?.takeIf { it.isNotEmpty() }
+ val romanization = line.romanization?.trim()?.takeIf { it.isNotEmpty() && !it.equals(line.text.trim(), ignoreCase = true) }
+ out += PanelLine(
+ line.timeMs, line.text, false, 0L, line.toSwept(next), index,
+ voice = line.voice, background = background,
+ backgroundSwept = if (synced && background != null) backgroundSwept(line, next) else null,
+ romanization = romanization,
+ )
}
}
return out
}
+/** The backing vocals of [line] as the sweep draws them, brackets off the words; null when they are not timed. */
+private fun backgroundSwept(line: LyricLine, nextLineMs: Long?): SweptLine? {
+ val words = line.backgroundWords.orEmpty()
+ .map { it.copy(text = it.text.replace("(", "").replace(")", "")) }
+ .filter { it.text.isNotBlank() }
+ if (words.isEmpty()) return null
+ val text = words.joinToString("") { it.text }.trim()
+ return LyricLine(words.first().startMs, text, words).toSwept(nextLineMs).takeIf { it.isWordSynced }
+}
+
+/**
+ * Which end of the row a line sits at in a duet: true the end (the second singer), false the
+ * start (the first), null for lines sung together, and for every line when the song is no duet,
+ * which then go by their text's direction.
+ */
+private fun endLane(row: PanelLine, duet: Boolean): Boolean? =
+ if (duet && (row.voice == 1 || row.voice == 2)) row.voice == 2 else null
+
// ─── Constants (BitChord's, at its sizes) ───────────────────────────────────────────────
/** How tall a break stands while it is playing; nothing when it is not. */
@@ -321,6 +355,8 @@ private fun LyricsList(
vm: LyricsViewModel,
/** The lines translated, in the source's order; null while no translation is shown. */
translations: List<String>? = null,
+ /** Shows the lines' romanization under them. */
+ romanizing: Boolean = false,
) {
// Lines picked to share (see ImmersiveLyricsPanel): taps select, the follow waits.
val selecting by vm.selecting.collectAsState()
@@ -328,6 +364,7 @@ private fun LyricsList(
val context = androidx.compose.ui.platform.LocalContext.current
val isSynced = remember(lyrics) { lyrics.synced && lyrics.lines.any { it.timeMs > 0L } }
val rows = remember(lyrics, isSynced) { panelLines(lyrics, isSynced) }
+ val duet = remember(lyrics) { lyrics.hasDuet }
val playing = Graph.currentSongState.playingState.value
val head = rememberLyricsPlayhead(trackKey, playing && isSynced)
val clock = head.clock
@@ -494,6 +531,8 @@ private fun LyricsList(
clock = clock,
noteMeasurer = noteMeasurer,
translation = translations?.getOrNull(row.sourceIndex)?.trim()?.takeIf { it.isNotEmpty() && !it.equals(row.text.trim(), ignoreCase = true) },
+ romanizing = romanizing,
+ duet = duet,
onNote = notes[index]?.let { n -> { noteOpen = n } },
// A line Genius explains opens its note; any other starts picking lines to share.
onHold = if (selecting) null else notes[index]?.let { n ->
@@ -542,6 +581,10 @@ private fun PanelRow(
noteMeasurer: TextMeasurer,
/** The line in the reader's language, shown small under it; null when there is none. */
translation: String?,
+ /** The romanization under the line is shown (the row has one to show: see [PanelLine.romanization]). */
+ romanizing: Boolean,
+ /** The song has two singers: see [endLane]. */
+ duet: Boolean,
/** Opens the Genius note on this line; null when Genius has none. */
onNote: (() -> Unit)?,
onHold: (() -> Unit)?,
@@ -597,7 +640,8 @@ private fun PanelRow(
} else {
Immersive.Lyric.copy(fontSize = 26.sp, lineHeight = 33.sp)
}
- val lineStyle = remember(style, row.text) { voiceStyle(style, row.text) }
+ val lane = endLane(row, duet)
+ val lineStyle = remember(style, row.text, lane) { voiceStyle(style, row.text, lane) }
// The stack sits fractionally back and the playing line comes forward to meet you. Rows
// behind the one being scrolled to are the ones that fan out; the ones it is moving away
// from arrive together.
@@ -637,8 +681,9 @@ private fun PanelRow(
.graphicsLayer {
scaleX = scale
scaleY = scale
- // Anchored to the left edge, so the words don't slide sideways under the highlight.
- transformOrigin = TransformOrigin(0f, 0.5f)
+ // Anchored to the left edge (the right one for the second singer), so the words don't
+ // slide sideways under the highlight.
+ transformOrigin = TransformOrigin(if (lane == true) 1f else 0f, 0.5f)
alpha = lineAlpha
// Held back against the list's own movement: the list has already taken this row
// part of the way, so giving back what it has not earned yet is what leaves it
@@ -708,16 +753,34 @@ private fun PanelRow(
browsing = browsing,
glowAlpha = glow,
room = GLOW_ROOM,
+ lane = lane,
modifier = Modifier.fillMaxWidth(),
)
}
- // Smaller and dimmer than the words, and it takes the row's blur and brightness with it.
+ // Under the words, smaller and dimmer, and they take the row's blur and brightness with
+ // them: the backing vocals, then the romanization, then the translation.
+ val romanized = row.romanization.takeIf { romanizing }
+ if (row.background != null) {
+ PanelBackground(
+ row = row, clock = clock, style = secondaryStyle(BACKGROUND_STYLE, lane),
+ isActive = isActive, sung = sung, synced = synced, lane = lane,
+ modifier = Modifier.fillMaxWidth().padding(start = GLOW_ROOM, end = GLOW_ROOM, bottom = if (romanized != null || translation != null) 4.dp else GLOW_ROOM),
+ )
+ }
+ if (romanized != null) {
+ Text(
+ text = romanized,
+ style = secondaryStyle(TRANSLATION_STYLE, lane),
+ color = Immersive.TextSecondary,
+ modifier = Modifier.fillMaxWidth().padding(start = GLOW_ROOM, end = GLOW_ROOM, bottom = if (translation != null) 4.dp else GLOW_ROOM),
+ )
+ }
if (translation != null) {
Text(
text = translation,
- style = TRANSLATION_STYLE,
+ style = secondaryStyle(TRANSLATION_STYLE, lane),
color = Immersive.TextSecondary,
- modifier = Modifier.padding(start = GLOW_ROOM, end = GLOW_ROOM, bottom = GLOW_ROOM),
+ modifier = Modifier.fillMaxWidth().padding(start = GLOW_ROOM, end = GLOW_ROOM, bottom = GLOW_ROOM),
)
}
}
@@ -747,6 +810,14 @@ private fun ShareBar(canShare: Boolean, onCancel: () -> Unit, onShare: () -> Uni
/** A translated line: well below the lyric's 30 sp, so the sung words stay the focus. */
private val TRANSLATION_STYLE = Immersive.Lyric.copy(fontSize = 18.sp, lineHeight = 24.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Medium)
+/** The backing vocals: a little smaller than a translation, and drawn dimmer still (see [PanelBackground]). */
+private val BACKGROUND_STYLE = Immersive.Lyric.copy(fontSize = 20.sp, lineHeight = 26.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Medium)
+private const val BACKGROUND_ALPHA = 0.7f
+
+/** [base] set at the end of the row for the second singer of a duet, at its start otherwise. */
+private fun secondaryStyle(base: TextStyle, lane: Boolean?): TextStyle =
+ if (lane == true) base.copy(textAlign = TextAlign.Right) else base
+
// ─── Genius notes on the lines ───────────────────────────────────────────────────────────
private val NOTE_PILL_COLOR = Color.White.copy(alpha = 0.09f)
@@ -869,11 +940,14 @@ private fun isRtl(text: String): Boolean {
return rtl > ltr
}
-/** The style with an absolute alignment taken from the line's own text direction. */
-private fun voiceStyle(base: TextStyle, text: String): TextStyle {
+/**
+ * The style with an absolute alignment taken from the line's own text direction, or from its
+ * duet [endLane] (true the right edge, false the left) when the song has two singers.
+ */
+private fun voiceStyle(base: TextStyle, text: String, endLane: Boolean? = null): TextStyle {
val rtl = isRtl(text)
return base.copy(
- textAlign = if (rtl) TextAlign.Right else TextAlign.Left,
+ textAlign = if (endLane ?: rtl) TextAlign.Right else TextAlign.Left,
textDirection = if (rtl) TextDirection.Rtl else TextDirection.Ltr,
)
}
@@ -895,6 +969,8 @@ private fun PanelVoice(
browsing: Boolean,
glowAlpha: Float,
room: Dp,
+ /** The duet side: see [endLane]. */
+ lane: Boolean?,
modifier: Modifier = Modifier,
) {
// The line being sung is white; every other one takes a quieter white. Faded across the
@@ -923,6 +999,8 @@ private fun PanelVoice(
glowRoom = room,
feather = isActive,
color = color,
+ alignEnd = lane == true,
+ laneLocked = lane != null,
)
} else {
// No word timings, so there is no sweep to light the words as they are sung: the line
@@ -941,6 +1019,39 @@ private fun PanelVoice(
}
}
+/**
+ * The backing vocals under a line: swept word by word where the source times them, else lit
+ * whole with their line. Smaller than the words and drawn at [BACKGROUND_ALPHA] of them.
+ */
+@Composable
+private fun PanelBackground(
+ row: PanelLine,
+ clock: MutableLongState,
+ style: TextStyle,
+ isActive: Boolean,
+ sung: Boolean,
+ synced: Boolean,
+ lane: Boolean?,
+ modifier: Modifier = Modifier,
+) {
+ val color by animateColorAsState(
+ targetValue = if (isActive || !synced) Color.White else Immersive.TextSecondary.copy(alpha = 0.85f),
+ label = "lyricBackgroundColor",
+ )
+ val dimmer = modifier.graphicsLayer { alpha = BACKGROUND_ALPHA }
+ val swept = row.backgroundSwept
+ if (swept != null && synced) {
+ val tail by animateFloatAsState(if (sung) 1f else UNSUNG_ALPHA, label = "lyricBackgroundTail")
+ SweptLyricLine(
+ line = swept, clock = clock, style = style, dimAlpha = tail, modifier = dimmer,
+ rise = false, color = color, alignEnd = lane == true, laneLocked = lane != null,
+ )
+ } else {
+ val lit by animateFloatAsState(if (!synced || sung || isActive) 1f else UNSUNG_ALPHA, label = "lyricBackgroundLit")
+ Text(text = row.background.orEmpty(), style = style, color = color.copy(alpha = lit), modifier = dimmer)
+ }
+}
+
/**
* A break counts itself out rather than being marked: three dots lighting in turn across the
* interlude, so a long one reads as time running down. The row itself opens and closes with
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
index 06359c7a..71f44310 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
@@ -26,6 +26,8 @@ import androidx.compose.material.icons.rounded.Translate
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.Radio
import androidx.compose.material.icons.rounded.Share
+import androidx.compose.material.icons.rounded.SortByAlpha
+import androidx.compose.material.icons.rounded.SwapHoriz
import androidx.compose.material.icons.rounded.Speed
import androidx.compose.material.icons.rounded.ThumbDownOffAlt
import androidx.compose.runtime.Composable
@@ -85,6 +87,8 @@ fun ImmersiveSongOptionsSheet(
var showCredits by remember { mutableStateOf(false) }
var showSpeed by remember { mutableStateOf(false) }
var showMeaning by remember { mutableStateOf(false) }
+ var showSources by remember { mutableStateOf(false) }
+ if (showSources) { com.music.spotui.ui.components.LyricsSourceSheet(onDismiss = { showSources = false; onDismiss() }); return }
if (showCredits) { CreditsSheet(song = song, onDismiss = { showCredits = false; onDismiss() }); return }
if (showMeaning) {
ImmersiveMeaningSheet(song.spotifyTrackId, song.title, song.singer, null, coverUrl = song.coverUri) { showMeaning = false; onDismiss() }
@@ -202,7 +206,8 @@ fun ImmersiveSongOptionsSheet(
if (nowPlaying && lyricsOpen) {
// The lyrics panel's translation, the Classic look's: same model, shown under each line.
val lyricsVm: com.music.spotui.ui.viewmodel.LyricsViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
- val lyrics = lyricsVm.state.collectAsState().value as? com.music.spotui.ui.viewmodel.LyricsViewModel.State.Loaded
+ val lyricsState = lyricsVm.state.collectAsState().value
+ val lyrics = lyricsState as? com.music.spotui.ui.viewmodel.LyricsViewModel.State.Loaded
val target = com.music.spotui.data.preferences.getLyricTranslateLang(context)
.ifBlank { java.util.Locale.getDefault().language.ifBlank { "en" } }
val sameLanguage = lyrics?.sourceLanguage?.substringBefore('-')
@@ -223,6 +228,21 @@ fun ImmersiveSongOptionsSheet(
onDismiss()
}
}
+ // The lines in Latin letters under them, when the lyrics carry them; lit while it is on.
+ if (lyrics != null && lyrics.lyrics.hasRomanization) {
+ val on = com.music.spotui.data.preferences.LyricsRomanizationPref.on
+ ImmersiveSheetRow(
+ Icons.Rounded.SortByAlpha, stringResource(R.string.lyrics_romanization),
+ tint = if (on) LocalImmersiveSheetTint.current.accent else null,
+ ) {
+ com.music.spotui.data.preferences.LyricsRomanizationPref.set(context, !on)
+ onDismiss()
+ }
+ }
+ // Ask another provider for the lyrics (also when none were found).
+ if (lyricsState !is com.music.spotui.ui.viewmodel.LyricsViewModel.State.Loading) {
+ ImmersiveSheetRow(Icons.Rounded.SwapHoriz, stringResource(R.string.lyrics_other_source)) { showSources = true }
+ }
}
// "Not interested": kept on this phone only; the song leaves the queue and lists skip it.
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 f165bf89..385b8090 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
@@ -102,6 +102,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.TextUnit
@@ -111,6 +112,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import com.music.spotui.data.api.LyricsApi
import com.music.spotui.data.entity.LyricLine
import com.music.spotui.data.entity.Lyrics
+import com.music.spotui.data.preferences.LyricsRomanizationPref
import com.music.spotui.data.preferences.getLyricTranslateLang
import com.music.spotui.data.preferences.isLyricsExtraSources
import com.music.spotui.data.preferences.setLyricsExtraSources
@@ -272,6 +274,10 @@ private fun LyricLineText(
/** Gets the time to play from: the start of the word tapped on a word-synced line. */
onTap: ((Long) -> Unit)?,
modifier: Modifier = Modifier,
+ /** The line in Latin letters, shown under it (and under its backing vocals); null when it is off or there is none. */
+ romanization: String? = null,
+ /** The song has two singers: the second one's lines sit at the end of the row. */
+ duet: Boolean = false,
annotated: Boolean = false,
onHold: (() -> Unit)? = null,
/** Picked to be shared: the line sits on a soft pill. */
@@ -287,6 +293,9 @@ private fun LyricLineText(
var pressAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
val swept = remember(line) { line.toSwept() }
val picked by animateFloatAsState(if (selected) 1f else 0f, tween(180), label = "lyricPicked")
+ // Duet: the second voice at the end of the row (right in left-to-right), the first and the
+ // lines sung together at the start. The text fills the row so its wrapped rows align as one block.
+ val align = if (duet && line.voice == 2) TextAlign.End else TextAlign.Start
val lineModifier = modifier
.fillMaxWidth()
.drawBehind {
@@ -333,8 +342,9 @@ private fun LyricLineText(
fontSize = fontSize,
lineHeight = fontSize * 1.25f,
fontWeight = FontWeight.Bold,
+ textAlign = align,
onTextLayout = { layout = it },
- modifier = underline,
+ modifier = Modifier.fillMaxWidth().then(underline),
)
Text(
text = shown,
@@ -342,8 +352,9 @@ private fun LyricLineText(
fontSize = fontSize,
lineHeight = fontSize * 1.25f,
fontWeight = FontWeight.Bold,
+ textAlign = align,
onTextLayout = { fill = it },
- modifier = Modifier.drawWithContent {
+ modifier = Modifier.fillMaxWidth().drawWithContent {
val l = fill ?: return@drawWithContent
val off = sungChars(words, starts, position()).coerceAtMost(shown.length.toFloat())
if (off <= 0f) return@drawWithContent
@@ -367,8 +378,39 @@ private fun LyricLineText(
fontSize = fontSize,
lineHeight = fontSize * 1.25f,
fontWeight = FontWeight.Bold,
+ textAlign = align,
onTextLayout = { layout = it },
- modifier = underline,
+ modifier = Modifier.fillMaxWidth().then(underline),
+ )
+ }
+ // Under the line, smaller and dimmer: its backing vocals, the romanization, the translation.
+ // They take the line's colour, so they light with it.
+ AnimatedVisibility(
+ visible = !line.background.isNullOrBlank(),
+ enter = expandVertically(tween(260)) + fadeIn(tween(260)),
+ exit = shrinkVertically(tween(260)) + fadeOut(tween(260)),
+ ) {
+ Text(
+ text = line.background.orEmpty(),
+ color = color.copy(alpha = color.alpha * 0.6f),
+ fontSize = (fontSize.value * 0.7f).sp,
+ fontWeight = FontWeight.Medium,
+ textAlign = align,
+ modifier = Modifier.fillMaxWidth().padding(top = 2.dp),
+ )
+ }
+ AnimatedVisibility(
+ visible = !romanization.isNullOrBlank(),
+ enter = expandVertically(tween(260)) + fadeIn(tween(260)),
+ exit = shrinkVertically(tween(260)) + fadeOut(tween(260)),
+ ) {
+ Text(
+ text = romanization.orEmpty(),
+ color = color.copy(alpha = color.alpha * 0.7f),
+ fontSize = 15.sp,
+ fontWeight = FontWeight.Normal,
+ textAlign = align,
+ modifier = Modifier.fillMaxWidth().padding(top = 2.dp),
)
}
AnimatedVisibility(
@@ -381,7 +423,8 @@ private fun LyricLineText(
color = color.copy(alpha = color.alpha * 0.7f),
fontSize = 15.sp,
fontWeight = FontWeight.Normal,
- modifier = Modifier.padding(top = 2.dp),
+ textAlign = align,
+ modifier = Modifier.fillMaxWidth().padding(top = 2.dp),
)
}
}
@@ -425,6 +468,7 @@ fun LyricsScreen(
val position = rememberPosition(playing)
val targetLanguage = getLyricTranslateLang(context).ifBlank { Locale.getDefault().language.ifBlank { "en" } }
var menu by remember { mutableStateOf(false) }
+ var sourcesOpen by remember { mutableStateOf(false) }
// Lines picked to share: a long press on a line, or "Share lyrics" in the menu, starts it.
val selecting by vm.selecting.collectAsState()
val picked by vm.picked.collectAsState()
@@ -501,10 +545,17 @@ fun LyricsScreen(
onReload = { SongPlayer.currentLyricsTrack()?.let { vm.load(it, force = true) } },
canShare = state is LyricsViewModel.State.Loaded,
onShare = { vm.startSelecting() },
+ canRomanize = lyrics?.hasRomanization == true,
+ romanizing = LyricsRomanizationPref.on,
+ onRomanize = { LyricsRomanizationPref.set(context, !LyricsRomanizationPref.on) },
+ canPickSource = state !is LyricsViewModel.State.Loading,
+ onPickSource = { sourcesOpen = true },
)
}
}
+ if (sourcesOpen) com.music.spotui.ui.components.LyricsSourceSheet(onDismiss = { sourcesOpen = false }, vm = vm)
+
when (state) {
is LyricsViewModel.State.Loading ->
Box(Modifier.weight(1f).fillMaxWidth()) {
@@ -532,6 +583,8 @@ fun LyricsScreen(
val active by remember(l) { derivedStateOf { activeIndexFor(l, position()) } }
val notes = remember(l, meaning) { meaning?.let { m -> com.music.spotui.ui.components.notesByLine(m, l.lines.map { it.text }) }.orEmpty() }
val listState = rememberLazyListState()
+ val duet = l.hasDuet
+ val romanizing = LyricsRomanizationPref.on && l.hasRomanization
// Lines near the current one rise in one after the other, the first just
// above it; the rest of the screen's lines have no visible entrance.
val staggerBase = remember(l) { (active - 4).coerceAtLeast(0) }
@@ -567,6 +620,8 @@ fun LyricsScreen(
fontSize = 24.sp,
position = position,
translation = if (state.showTranslation) state.translations?.getOrNull(i) else null,
+ romanization = if (romanizing) line.romanization?.trim()?.takeIf { it.isNotEmpty() && !it.equals(line.text.trim(), ignoreCase = true) } else null,
+ duet = duet,
// Picking lines: a tap selects instead of seeking.
onTap = if (selecting) ({ _ ->
if (!vm.pick(i)) android.widget.Toast.makeText(context, context.getString(R.string.lyrics_select_max, LyricsViewModel.MAX_SHARED_LINES), android.widget.Toast.LENGTH_SHORT).show()
@@ -630,6 +685,11 @@ private fun LyricsMenu(
onReload: () -> Unit,
canShare: Boolean,
onShare: () -> Unit,
+ canRomanize: Boolean,
+ romanizing: Boolean,
+ onRomanize: () -> Unit,
+ canPickSource: Boolean,
+ onPickSource: () -> Unit,
) {
val context = LocalContext.current
var extra by remember { mutableStateOf(isLyricsExtraSources(context)) }
@@ -657,6 +717,12 @@ private fun LyricsMenu(
text = { Text(stringResource(if (translating) R.string.lyrics_fullscreen_translate_button_enabled_readout_value else R.string.lyrics_fullscreen_context_menu_main_page_translate_lyrics_action)) },
onClick = { onDismiss(); onTranslate() },
)
+ // The lines in Latin letters, when the lyrics have them.
+ if (canRomanize) DropdownMenuItem(
+ text = { Text(stringResource(R.string.lyrics_romanization)) },
+ trailingIcon = { if (romanizing) Icon(Icons.Default.Check, contentDescription = null) },
+ onClick = { onDismiss(); onRomanize() },
+ )
// Pick lines of the song and send them as text.
if (canShare) DropdownMenuItem(
text = { Text(stringResource(R.string.lyrics_share)) },
@@ -678,6 +744,7 @@ private fun LyricsMenu(
onReload()
},
)
+ if (canPickSource) DropdownMenuItem(text = { Text(stringResource(R.string.lyrics_other_source)) }, onClick = { onDismiss(); onPickSource() })
DropdownMenuItem(text = { Text(stringResource(R.string.lyrics_reload)) }, onClick = { onDismiss(); onReload() })
}
}
@@ -865,6 +932,7 @@ fun InlineLyrics(
position = position,
translation = null,
onTap = null,
+ duet = l.hasDuet,
)
}
}
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 3ee9ca69..9729a774 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
@@ -24,6 +24,8 @@ class LyricsViewModel constructor() : ViewModel() {
val translating: Boolean = false,
val translationChecked: Boolean = false,
val translationRequested: Boolean = false,
+ /** [translations] are the source's own (human, from the lyrics), not a machine translation. */
+ val translationBySource: Boolean = false,
) : State()
object NotFound : State()
}
@@ -78,11 +80,41 @@ class LyricsViewModel constructor() : ViewModel() {
return true
}
+ // "Try another source": the provider being asked, and the one that had nothing (until the next try).
+ private val _trying = MutableStateFlow<String?>(null)
+ val trying: StateFlow<String?> = _trying
+ private val _triedNothing = MutableStateFlow<String?>(null)
+ val triedNothing: StateFlow<String?> = _triedNothing
+
+ /** The providers that can be asked for [track] by hand ([loadFrom]); [LyricsApi.sourceOf] names the one shown. */
+ fun sources(track: LyricsApi.Track): List<LyricsApi.Source> = LyricsApi.sources(track)
+
+ /**
+ * Shows the lyrics of [track] from the provider [sourceId] ([LyricsApi.Source.id]). The lyrics
+ * shown stay until the new ones arrive; when the provider has none they stay ([triedNothing]).
+ */
+ fun loadFrom(track: LyricsApi.Track, sourceId: String) {
+ if (_trying.value != null) return
+ _trying.value = sourceId
+ _triedNothing.value = null
+ val key = track.key
+ viewModelScope.launch {
+ val lyrics = runCatching { LyricsApi.fetchFrom(track, sourceId) }.getOrNull()
+ // A skip meanwhile: the answer is for the previous song.
+ if (loadedKey == key) {
+ if (lyrics == null) _triedNothing.value = sourceId
+ else _state.value = loadedState(lyrics)
+ }
+ _trying.value = null
+ }
+ }
+
fun load(track: LyricsApi.Track, force: Boolean = false) {
val key = track.key
if (!force && loadedKey == key && _state.value !is State.NotFound) return
loadedKey = key
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 }
@@ -147,6 +179,26 @@ class LyricsViewModel constructor() : ViewModel() {
)
viewModelScope.launch(Dispatchers.IO) {
val lines = cur.lyrics.lines.map { it.text }
+ // The lyrics' own translation (from the source, in this language) first; the machine only fills what it lacks.
+ cur.lyrics.translationsFor(targetLang)?.let { own ->
+ val missing = lines.indices.filter { own[it] == null && lines[it].isNotBlank() && lines[it].trim() != "♪" }
+ val filled: Map<Int, String> = if (missing.isEmpty()) emptyMap()
+ else LyricTranslate.translateLines(missing.map { lines[it] }, targetLang)?.lines?.let { missing.zip(it).toMap() } ?: emptyMap()
+ withContext(Dispatchers.Main) {
+ val latest = _state.value as? State.Loaded ?: return@withContext
+ if (latest.lyrics != cur.lyrics) return@withContext
+ _state.value = latest.copy(
+ translating = false,
+ translationChecked = true,
+ showTranslation = latest.translationRequested,
+ translationRequested = false,
+ translations = lines.indices.map { own[it] ?: filled[it].orEmpty() },
+ translationLanguage = targetLang,
+ translationBySource = true,
+ )
+ }
+ return@launch
+ }
val detectedLanguage = cur.sourceLanguage
?: LyricTranslate.detectLanguage(lines, targetLang)
if (detectedLanguage != null) {
@@ -185,6 +237,7 @@ class LyricsViewModel constructor() : ViewModel() {
translationRequested = false,
translations = result.lines,
translationLanguage = targetLang,
+ translationBySource = false,
sourceLanguage = result.sourceLanguage,
)
}
diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xml
index ac851e46..311bfd05 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Songtext neu laden</string>
<string name="lyrics_select_hint">Tippe auf Zeilen, um auszuwählen, was du teilen möchtest</string>
<string name="lyrics_select_max">Du kannst bis zu %d Zeilen teilen</string>
+ <string name="lyrics_romanization">Romanisierung anzeigen</string>
+ <string name="lyrics_other_source">Andere Quelle versuchen</string>
+ <string name="lyrics_source_shown">Wird angezeigt</string>
+ <string name="lyrics_source_words">Wort für Wort</string>
+ <string name="lyrics_source_aside">Antwortet gerade nicht</string>
+ <string name="lyrics_source_nothing">%1$s hat keinen Songtext zu diesem Lied</string>
<string name="lyrics_fullscreen">Songtext im Vollbild öffnen</string>
<string name="browse_all">Alle ansehen</string>
<string name="home_error">Start konnte nicht geladen werden.\nPrüfe deine Verbindung und versuche es erneut.</string>
diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xml
index 269d36ef..74e7d3bc 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Επαναφόρτωση στίχων</string>
<string name="lyrics_select_hint">Πατήστε στίχους για να επιλέξετε τι θα μοιραστείτε</string>
<string name="lyrics_select_max">Μπορείτε να μοιραστείτε έως %d στίχους</string>
+ <string name="lyrics_romanization">Εμφάνιση ρωμανοποίησης</string>
+ <string name="lyrics_other_source">Δοκιμή άλλης πηγής</string>
+ <string name="lyrics_source_shown">Εμφανίζεται τώρα</string>
+ <string name="lyrics_source_words">Λέξη προς λέξη</string>
+ <string name="lyrics_source_aside">Δεν απαντά προς το παρόν</string>
+ <string name="lyrics_source_nothing">Η πηγή %1$s δεν έχει στίχους για αυτό το τραγούδι</string>
<string name="lyrics_fullscreen">Άνοιγμα στίχων σε πλήρη οθόνη</string>
<string name="browse_all">Εμφάνιση όλων</string>
<string name="home_error">Δεν φορτώθηκε η Αρχική.\nΈλεγξε τη σύνδεσή σου και δοκίμασε ξανά.</string>
diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xml
index 4f51f445..38b1fc39 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Recargar la letra</string>
<string name="lyrics_select_hint">Toca las líneas para elegir lo que quieres compartir</string>
<string name="lyrics_select_max">Puedes compartir hasta %d líneas</string>
+ <string name="lyrics_romanization">Mostrar romanización</string>
+ <string name="lyrics_other_source">Probar otra fuente</string>
+ <string name="lyrics_source_shown">Se muestra ahora</string>
+ <string name="lyrics_source_words">Palabra por palabra</string>
+ <string name="lyrics_source_aside">No responde por ahora</string>
+ <string name="lyrics_source_nothing">%1$s no tiene la letra de esta canción</string>
<string name="lyrics_fullscreen">Abrir la letra a pantalla completa</string>
<string name="browse_all">Ver todo</string>
<string name="home_error">No se pudo cargar Inicio.\nComprueba tu conexión e inténtalo de nuevo.</string>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 437029d2..61489534 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Recharger les paroles</string>
<string name="lyrics_select_hint">Touchez des lignes pour choisir ce que vous partagez</string>
<string name="lyrics_select_max">Vous pouvez partager jusqu\'à %d lignes</string>
+ <string name="lyrics_romanization">Afficher la romanisation</string>
+ <string name="lyrics_other_source">Essayer une autre source</string>
+ <string name="lyrics_source_shown">Affichée</string>
+ <string name="lyrics_source_words">Mot par mot</string>
+ <string name="lyrics_source_aside">Ne répond pas pour le moment</string>
+ <string name="lyrics_source_nothing">%1$s n\'a pas les paroles de cette chanson</string>
<string name="lyrics_fullscreen">Ouvrir les paroles en plein écran</string>
<string name="browse_all">Parcourir tout</string>
<string name="home_error">Impossible de charger l\'accueil.\nVérifiez votre connexion et réessayez.</string>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index e26151c5..77c4fd07 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Ricarica il testo</string>
<string name="lyrics_select_hint">Tocca le righe per scegliere cosa condividere</string>
<string name="lyrics_select_max">Puoi condividere fino a %d righe</string>
+ <string name="lyrics_romanization">Mostra la romanizzazione</string>
+ <string name="lyrics_other_source">Prova un\'altra fonte</string>
+ <string name="lyrics_source_shown">In uso</string>
+ <string name="lyrics_source_words">Parola per parola</string>
+ <string name="lyrics_source_aside">Non risponde per ora</string>
+ <string name="lyrics_source_nothing">%1$s non ha il testo di questo brano</string>
<string name="lyrics_fullscreen">Apri il testo a schermo intero</string>
<string name="browse_all">Sfoglia tutto</string>
<string name="home_error">Impossibile caricare la Home.\nControlla la connessione e riprova.</string>
diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xml
index fe9f1be7..bd5eca70 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Wczytaj tekst ponownie</string>
<string name="lyrics_select_hint">Stuknij wersy, aby wybrać, co udostępnić</string>
<string name="lyrics_select_max">Możesz udostępnić maksymalnie %d wersów</string>
+ <string name="lyrics_romanization">Pokaż romanizację</string>
+ <string name="lyrics_other_source">Spróbuj innego źródła</string>
+ <string name="lyrics_source_shown">Wyświetlane teraz</string>
+ <string name="lyrics_source_words">Słowo po słowie</string>
+ <string name="lyrics_source_aside">Chwilowo nie odpowiada</string>
+ <string name="lyrics_source_nothing">%1$s nie ma tekstu tego utworu</string>
<string name="lyrics_fullscreen">Otwórz tekst na pełnym ekranie</string>
<string name="browse_all">Przeglądaj wszystko</string>
<string name="home_error">Nie udało się wczytać strony głównej.\nSprawdź połączenie i spróbuj ponownie.</string>
diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
index b96eabbe..e6d68c0a 100644
--- a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Recarregar as letras</string>
<string name="lyrics_select_hint">Toque nas linhas para escolher o que partilhar</string>
<string name="lyrics_select_max">Pode partilhar até %d linhas</string>
+ <string name="lyrics_romanization">Mostrar romanização</string>
+ <string name="lyrics_other_source">Tentar outra fonte</string>
+ <string name="lyrics_source_shown">Mostrada agora</string>
+ <string name="lyrics_source_words">Palavra a palavra</string>
+ <string name="lyrics_source_aside">Sem resposta por agora</string>
+ <string name="lyrics_source_nothing">%1$s não tem a letra deste tema</string>
<string name="lyrics_fullscreen">Abrir as letras em ecrã cheio</string>
<string name="browse_all">Ver tudo</string>
<string name="home_error">Não foi possível carregar o Início.\nVerifica a tua ligação e tenta novamente.</string>
diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xml
index 9153acf7..d1ab2944 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Recarregar as letras</string>
<string name="lyrics_select_hint">Toque nas linhas para escolher o que compartilhar</string>
<string name="lyrics_select_max">Você pode compartilhar até %d linhas</string>
+ <string name="lyrics_romanization">Mostrar romanização</string>
+ <string name="lyrics_other_source">Tentar outra fonte</string>
+ <string name="lyrics_source_shown">Mostrada agora</string>
+ <string name="lyrics_source_words">Palavra por palavra</string>
+ <string name="lyrics_source_aside">Sem resposta por enquanto</string>
+ <string name="lyrics_source_nothing">%1$s não tem a letra desta música</string>
<string name="lyrics_fullscreen">Abrir as letras em tela cheia</string>
<string name="browse_all">Ver tudo</string>
<string name="home_error">Não foi possível carregar o Início.\nVerifique sua conexão e tente novamente.</string>
diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xml
index dc267380..8da2c3ac 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Загрузить текст заново</string>
<string name="lyrics_select_hint">Нажимайте на строки, чтобы выбрать, чем поделиться</string>
<string name="lyrics_select_max">Можно поделиться не более чем %d строками</string>
+ <string name="lyrics_romanization">Показать романизацию</string>
+ <string name="lyrics_other_source">Попробовать другой источник</string>
+ <string name="lyrics_source_shown">Показан сейчас</string>
+ <string name="lyrics_source_words">По словам</string>
+ <string name="lyrics_source_aside">Пока не отвечает</string>
+ <string name="lyrics_source_nothing">В источнике %1$s нет текста этой песни</string>
<string name="lyrics_fullscreen">Открыть текст на весь экран</string>
<string name="browse_all">Смотреть все</string>
<string name="home_error">Не удалось загрузить главную.\nПроверьте соединение и повторите попытку.</string>
diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xml
index 4b503d7a..36818b45 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">重新加载歌词</string>
<string name="lyrics_select_hint">点按歌词行以选择要分享的内容</string>
<string name="lyrics_select_max">最多可分享 %d 行</string>
+ <string name="lyrics_romanization">显示罗马音</string>
+ <string name="lyrics_other_source">尝试其他来源</string>
+ <string name="lyrics_source_shown">当前使用</string>
+ <string name="lyrics_source_words">逐字同步</string>
+ <string name="lyrics_source_aside">暂时无响应</string>
+ <string name="lyrics_source_nothing">%1$s 没有这首歌的歌词</string>
<string name="lyrics_fullscreen">全屏打开歌词</string>
<string name="browse_all">浏览全部</string>
<string name="home_error">无法加载首页。\n请检查网络连接后重试。</string>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index cd906369..bf1db917 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -35,6 +35,12 @@
<string name="lyrics_reload">Reload lyrics</string>
<string name="lyrics_select_hint">Tap lines to pick what to share</string>
<string name="lyrics_select_max">You can share up to %d lines</string>
+ <string name="lyrics_romanization">Show romanization</string>
+ <string name="lyrics_other_source">Try another source</string>
+ <string name="lyrics_source_shown">Shown now</string>
+ <string name="lyrics_source_words">Word by word</string>
+ <string name="lyrics_source_aside">Not answering for now</string>
+ <string name="lyrics_source_nothing">%1$s has no lyrics for this song</string>
<string name="lyrics_fullscreen">Open lyrics full screen</string>
<string name="browse_all">Browse all</string>
<string name="home_error">Couldn\'t load Home.\nCheck your connection and try again.</string>
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
new file mode 100644
index 00000000..655e9827
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsExtrasTest.kt
@@ -0,0 +1,66 @@
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.LyricLine
+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. */
+class LyricsExtrasTest {
+ private fun line(t: Long, text: String, tr: String? = null, ro: String? = null) = LyricLine(t, text, translation = tr, romanization = ro)
+
+ @Test fun neteaseStyleLinesGetTheirNearestTranslationAndRomanization() {
+ val lines = listOf(line(1000, "夢ならば"), line(6000, "♪"), line(12000, "今でも"))
+ val out = LyricsExtras.attach(lines,
+ listOf(line(1000, "如果是梦"), line(12100, "至今仍"), line(30000, "far away")),
+ listOf(line(1050, "yume naraba"), line(12000, "//")))
+ assertEquals("如果是梦", out[0].translation)
+ assertEquals("yume naraba", out[0].romanization)
+ assertNull(out[1].translation)
+ assertEquals("至今仍", out[2].translation)
+ assertNull("// means no romanization", out[2].romanization)
+ }
+
+ @Test fun nothingToAttachReturnsTheLinesAsTheyAre() {
+ val lines = listOf(line(1, "a"))
+ assertSame(lines, LyricsExtras.attach(lines, emptyList(), emptyList()))
+ }
+
+ @Test fun anotherSourcesTranslationIsCarriedByLineText() {
+ val to = Lyrics(listOf(line(0, "Hello, world"), line(5, "Bye")), synced = true, provider = "LRCLIB")
+ val from = Lyrics(listOf(line(1, "Hello world", tr = "Bonjour le monde"), line(9, "Other")), synced = true, provider = "NetEase", translationLanguage = "fr")
+ val out = LyricsExtras.carry(to, from)
+ assertEquals("Bonjour le monde", out.lines[0].translation)
+ assertNull(out.lines[1].translation)
+ assertEquals("fr", out.translationLanguage)
+ assertEquals("LRCLIB", out.provider)
+ }
+
+ @Test fun carryKeepsAnExistingTranslationAndIgnoresAMismatch() {
+ val own = Lyrics(listOf(line(0, "a line", tr = "une ligne")), synced = true, translationLanguage = "fr")
+ val other = Lyrics(listOf(line(0, "a line", tr = "eine Zeile")), synced = true, translationLanguage = "de")
+ assertSame(own, LyricsExtras.carry(own, other))
+ val bare = Lyrics(listOf(line(0, "one"), line(1, "two"), line(2, "three")), synced = true)
+ assertSame(bare, LyricsExtras.carry(bare, Lyrics(listOf(line(0, "unrelated", tr = "x")), synced = true, translationLanguage = "fr")))
+ assertSame(bare, LyricsExtras.carry(bare, null))
+ }
+
+ @Test fun sourceTranslationsAreUsedOnlyInTheTargetLanguage() {
+ val l = Lyrics(listOf(line(0, "a", tr = "A"), line(1, "b")), synced = true, language = "ja", translationLanguage = "en-US")
+ assertEquals(listOf("A", null), l.translationsFor("en"))
+ assertNull(l.translationsFor("fr"))
+ // The song already is in that language, or the translation's language is not known: the machine decides.
+ assertNull(l.copy(language = "en").translationsFor("en"))
+ assertNull(l.copy(translationLanguage = null).translationsFor("en"))
+ assertNull(Lyrics(listOf(line(0, "a")), synced = true, translationLanguage = "en").translationsFor("en"))
+ }
+
+ @Test fun duetNeedsTwoDifferentSingers() {
+ fun v(vararg voices: Int?) = Lyrics(voices.mapIndexed { i, v -> LyricLine(i.toLong(), "x", voice = v) }, synced = true)
+ assertEquals(false, v(1, 1, null).hasDuet)
+ assertEquals(true, v(1, 2, 1).hasDuet)
+ assertEquals(false, v(0, 1).hasDuet)
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsHealthTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsHealthTest.kt
new file mode 100644
index 00000000..63c57083
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsHealthTest.kt
@@ -0,0 +1,62 @@
+package com.music.spotui.data.api
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** A provider failing in a row is set aside; "no lyrics" is kept a few minutes per song and provider. */
+class LyricsHealthTest {
+ private var now = 1_000_000L
+ private val h = LyricsHealth { now }
+
+ @Test fun threeFailuresInARowSetAProviderAsideForTenMinutes() {
+ repeat(LyricsHealth.FAILURES_IN_A_ROW - 1) { h.failed("lrclib") }
+ assertNull(h.reason("lrclib"))
+ h.failed("lrclib")
+ assertNotNull(h.reason("lrclib"))
+ now += LyricsHealth.SET_ASIDE_MS - 1_000
+ assertNotNull(h.reason("lrclib"))
+ now += 2_000
+ assertNull(h.reason("lrclib"))
+ }
+
+ @Test fun anAnswerEndsTheRunAndOtherProvidersAreNotAffected() {
+ h.failed("kugou"); h.failed("kugou")
+ h.answered("kugou")
+ h.failed("kugou"); h.failed("kugou")
+ assertNull(h.reason("kugou"))
+ repeat(3) { h.failed("netease") }
+ assertNotNull(h.reason("netease"))
+ assertNull(h.reason("kugou"))
+ }
+
+ @Test fun noLyricsIsKeptForFiveMinutesForThatSongAndProviderOnly() {
+ h.noteMissing("track1", "lyricsplus")
+ assertTrue(h.isMissing("track1", "lyricsplus"))
+ assertFalse(h.isMissing("track1", "lrclib"))
+ assertFalse(h.isMissing("track2", "lyricsplus"))
+ now += LyricsHealth.MISSING_MS - 1
+ assertTrue(h.isMissing("track1", "lyricsplus"))
+ now += 2
+ assertFalse(h.isMissing("track1", "lyricsplus"))
+ }
+
+ @Test fun askingAgainDropsTheSongsAnswers() {
+ h.noteMissing("track1", "lyricsplus"); h.noteMissing("track1", "kugou"); h.noteMissing("track2", "kugou")
+ h.forgetTrack("track1")
+ assertFalse(h.isMissing("track1", "lyricsplus"))
+ assertFalse(h.isMissing("track1", "kugou"))
+ assertTrue(h.isMissing("track2", "kugou"))
+ h.forgetAll()
+ assertFalse(h.isMissing("track2", "kugou"))
+ }
+
+ @Test fun lostRequestsAreCountedSoAFailureIsNeverKeptAsNoLyrics() {
+ val before = h.lostCount()
+ h.failed("genius"); h.skipped()
+ assertEquals(before + 2, h.lostCount())
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsMatchTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsMatchTest.kt
new file mode 100644
index 00000000..92f42fcb
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsMatchTest.kt
@@ -0,0 +1,48 @@
+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
+
+/** How catalogue titles and artists are compared with ours: accents and the order of an artist's words do not matter. */
+class LyricsMatchTest {
+ @Test fun accentsAndCaseAreFoldedAway() {
+ assertEquals("beyonce", LyricsMatch.key("Beyoncé"))
+ assertEquals("rosalia", LyricsMatch.key("ROSALÍA"))
+ assertEquals("strasse", LyricsMatch.key("Straße"))
+ assertEquals("djordje", LyricsMatch.key("Đorđe"))
+ }
+
+ @Test fun kanaAndHangulKeepTheirLength() {
+ // Voiced kana and Hangul syllables are not "accents": they are not decomposed away.
+ assertEquals("がっこう", LyricsMatch.key("がっこう"))
+ assertTrue(LyricsMatch.key("가나다").length == 3)
+ assertFalse(LyricsMatch.key("か") == LyricsMatch.key("が"))
+ }
+
+ @Test fun sameArtistIgnoresAccentsAndWordOrder() {
+ assertTrue(LyricsMatch.sameArtist("Beyoncé", "Beyonce"))
+ assertTrue(LyricsMatch.sameArtist("Lee Hi", "Hi Lee"))
+ assertTrue(LyricsMatch.sameArtist("Jay-Z", "Jay Z"))
+ assertTrue(LyricsMatch.sameArtist("AC/DC", "ACDC"))
+ }
+
+ @Test fun differentArtistsStayDifferent() {
+ assertFalse(LyricsMatch.sameArtist("Cher", "Cherry"))
+ assertFalse(LyricsMatch.sameArtist("Lee Hi", "Lee"))
+ assertFalse(LyricsMatch.sameArtist("", ""))
+ }
+
+ @Test fun plausibleMatchSeesThroughAccentsAndArtistOrderButKeepsTheLengthLimit() {
+ assertTrue(LyricsApi.isPlausibleMatch("Rosalía", "Rosalía", 200, "Rosalia", "Rosalia", 200))
+ assertTrue(LyricsApi.isPlausibleMatch("Hello", "Hi Lee", 200, "Hello", "Lee Hi", 201))
+ assertFalse(LyricsApi.isPlausibleMatch("Hello", "Hi Lee", 205, "Hello", "Lee Hi", 200))
+ }
+
+ @Test fun sameSongForTheWordTimedSources() {
+ assertTrue(LyricsApi.sameSong("Déjà Vu", "Beyoncé, Jay-Z", 240_000, "Deja Vu", "Beyonce", 241_000))
+ assertTrue(LyricsApi.sameSong("Thunderstruck", "AC/DC", 292_000, "Thunderstruck", "AC/DC", 292_000))
+ assertFalse(LyricsApi.sameSong("Déjà Vu", "Beyoncé", 240_000, "Deja Vu", "Beyonce", 250_000))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsSourcesParseTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsSourcesParseTest.kt
new file mode 100644
index 00000000..0ef96102
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsSourcesParseTest.kt
@@ -0,0 +1,98 @@
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.Lyrics
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.xmlpull.v1.XmlPullParser
+
+/** What the sources give besides the words: translations, romanizations, who sings, backing vocals. */
+class LyricsSourcesParseTest {
+ // A real pull parser needs kxml2 (android.jar only has stubs): without it these tests are skipped.
+ private fun ttml(xml: String): Lyrics? {
+ val parser = runCatching { Class.forName("org.kxml2.io.KXmlParser").getDeclaredConstructor().newInstance() as XmlPullParser }.getOrNull()
+ assumeTrue("kxml2 is not on the test classpath", parser != null)
+ return LyricsApi.parseTtml(xml) { parser!! }
+ }
+
+ private val head = """<tt xmlns="http://www.w3.org/ns/ttml" xmlns:lrc="http://lrc.red/lyric-ttml-internal" xmlns:ttm="http://www.w3.org/ns/ttml#metadata">"""
+
+ @Test fun headTranslationAndTransliterationAreAttachedByLineKey() {
+ val l = ttml("""$head<head><metadata><ttm:agent type="person" xml:id="v1"/>
+ <sourceMetadata><translations><translation xml:lang="en-US"><text for="L1">If it were a dream</text><text for="L2">Still now</text></translation></translations>
+ <transliterations><transliteration xml:lang="ja-Latn"><text for="L1"><span begin="0.0" end="1.0">yume</span> <span begin="1.0" end="2.0">naraba</span><span ttm:role="x-bg"><span begin="2.0" end="3.0">(ah)</span></span></text></transliteration></transliterations>
+ </sourceMetadata></metadata></head>
+ <body><div><p begin="0:01.000" end="0:03.000" lrc:key="L1" ttm:agent="v1"><span begin="0:01.000" end="0:02.000">夢</span><span begin="0:02.000" end="0:03.000">ならば</span></p>
+ <p begin="0:04.000" end="0:06.000" lrc:key="L2" ttm:agent="v2"><span begin="0:04.000" end="0:06.000">今でも</span></p></div></body></tt>""")!!
+ assertEquals(2, l.lines.size)
+ assertEquals("夢ならば", l.lines[0].text)
+ assertEquals("If it were a dream", l.lines[0].translation)
+ assertEquals("yume naraba", l.lines[0].romanization)
+ assertEquals("Still now", l.lines[1].translation)
+ assertNull(l.lines[1].romanization)
+ assertEquals("en-US", l.translationLanguage)
+ assertEquals(listOf(1, 2), l.lines.map { it.voice })
+ assertTrue(l.hasDuet)
+ assertEquals(1000L, l.lines[0].timeMs)
+ }
+
+ @Test fun backingVocalsAreKeptApartFromTheLine() {
+ val l = ttml("""$head<body><div><p begin="1.000" end="4.000" ttm:agent="v1"><span begin="1.000" end="2.000">I'm</span> <span begin="2.000" end="3.000">ready</span> <span ttm:role="x-bg"><span begin="3.000" end="3.500">(Woo-</span><span begin="3.500" end="4.000">hoo)</span></span></p></div></body></tt>""")!!
+ val line = l.lines.single()
+ assertEquals("I'm ready", line.text)
+ assertEquals(listOf("I'm ", "ready "), line.words!!.map { it.text }.map { it.trimEnd() + " " })
+ assertEquals("Woo-hoo", line.background)
+ assertEquals(listOf(3000L to 3500L, 3500L to 4000L), line.backgroundWords!!.map { it.startMs to it.endMs })
+ assertNull(l.translationLanguage)
+ }
+
+ @Test fun inlineTranslationAndRomanSpansAreTaken() {
+ val l = ttml("""$head<body><div><p begin="1.0" end="3.0"><span begin="1.0" end="3.0">안녕</span><span ttm:role="x-translation" xml:lang="en">Hello</span><span ttm:role="x-roman">annyeong</span></p></div></body></tt>""")!!
+ assertEquals("안녕", l.lines[0].text)
+ assertEquals("Hello", l.lines[0].translation)
+ assertEquals("annyeong", l.lines[0].romanization)
+ assertEquals("en", l.translationLanguage)
+ }
+
+ @Test fun aTransliterationThatIsTheLineItselfIsDropped() {
+ val l = ttml("""$head<head><metadata><transliterations><transliteration xml:lang="ko-Latn"><text for="L1"><span begin="0" end="1">Hello there</span></text></transliteration></transliterations></metadata></head>
+ <body><div><p begin="1.0" end="3.0" lrc:key="L1"><span begin="1.0" end="3.0">Hello there</span></p></div></body></tt>""")!!
+ assertNull(l.lines[0].romanization)
+ }
+
+ @Test fun lyricsPlusKeepsBackingVocalsVoicesAndTranslations() {
+ val o = JSONObject("""{"metadata":{"source":"qApple","language":"ja"},"lyrics":[
+ {"time":1000,"duration":2000,"text":"I'm ready (Woo-hoo)","syllabus":[{"time":1000,"duration":500,"text":"I'm "},{"time":1500,"duration":500,"text":"ready "},{"time":2000,"duration":300,"text":"(Woo-","isBackground":true},{"time":2300,"duration":300,"text":"hoo)","isBackground":true}],
+ "element":{"singer":"v2"},"translation":{"text":"Je suis prêt","lang":"fr"},"transliteration":{"text":"aimu redi"}},
+ {"time":5000,"duration":1000,"text":"(Ooh)","syllabus":[{"time":5000,"duration":1000,"text":"(Ooh)","isBackground":true}],"element":{"singer":"v1000"}}]}""")
+ val l = LyricsApi.lyricsPlusLines(o)!!
+ val a = l.lines[0]
+ assertEquals("I'm ready", a.text)
+ assertEquals(2, a.words!!.size)
+ assertEquals("Woo-hoo", a.background)
+ assertEquals(2, a.voice)
+ assertEquals("Je suis prêt", a.translation)
+ assertEquals("aimu redi", a.romanization)
+ assertEquals("fr", l.translationLanguage)
+ // A line of backing vocals only is a line of its own, sung by everyone.
+ val b = l.lines[1]
+ assertEquals("(Ooh)", b.text)
+ assertNull(b.background)
+ assertEquals(0, b.voice)
+ assertEquals("Apple Music · LyricsPlus", l.provider)
+ }
+
+ @Test fun lyricsPlusWithoutExtrasIsAsBefore() {
+ val l = LyricsApi.lyricsPlusLines(JSONObject("""{"lyrics":[{"time":0,"duration":1000,"text":"a b","syllabus":[{"time":0,"duration":500,"text":"a "},{"time":500,"duration":500,"text":"b"}]}]}"""))!!
+ val line = l.lines.single()
+ assertEquals("a b", line.text)
+ assertNull(line.translation); assertNull(line.voice); assertNull(line.background)
+ assertNull(l.translationLanguage)
+ }
+
+ @Test fun voiceNames() {
+ assertEquals(1, LyricsApi.voiceOf("v1")); assertEquals(0, LyricsApi.voiceOf("v1000"))
+ assertNull(LyricsApi.voiceOf("narrator")); assertNull(LyricsApi.voiceOf(null))
+ }
+}
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 a3f16797..7e31d2c2 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
@@ -95,4 +95,24 @@ class HookDispatchTest {
assertEquals(1, LyricsMerge.rank(plain))
assertEquals(listOf("one", "two"), plain.lines.map { it.text })
}
+
+ @Test fun anExtensionsTranslationAndVoicesReachTheAppsLyrics() {
+ val r = LyricsResult.parse("""{"translationLanguage":"en","lines":[{"time":1000,"text":"a","translation":"A","romanization":"ei","voice":2,"background":"oh"}]}""", "Ext")!!
+ val l = LyricsMerge.toLyrics(r)
+ assertEquals("en", l.translationLanguage)
+ val line = l.lines.single()
+ assertEquals("A", line.translation)
+ assertEquals("ei", line.romanization)
+ assertEquals(2, line.voice)
+ assertEquals("oh", line.background)
+ }
+
+ @Test fun theChosenLyricsKeepTheTranslationOfTheOneThatLost() {
+ val translated = Lyrics(listOf(LyricLine(1000, "line", translation = "ligne")), synced = true, provider = "NetEase", translationLanguage = "fr")
+ val own = Lyrics(listOf(LyricLine(1000, "line", listOf(LyricWord(1000, 1200, "line")))), synced = true, provider = "LyricsPlus")
+ val chosen = LyricsMerge.choose(own, translated)!!
+ assertEquals("LyricsPlus", chosen.provider)
+ assertEquals("ligne", chosen.lines[0].translation)
+ assertEquals("fr", chosen.translationLanguage)
+ }
}
diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
index 14afbeb8..69d5df89 100644
--- a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
@@ -264,7 +264,7 @@ private fun runScript(rt: ExtensionRuntime, m: Manifest, hookName: String, track
if (l == null) println("— empty lyrics ($ms ms)")
else {
println("✓ ${l.lines.size} lines from ${l.provider}, synced=${l.synced}, word by word=${l.wordSynced} ($ms ms)")
- l.lines.take(8).forEach { println(" [${it.startMs}] ${it.text}") }
+ l.lines.take(8).forEach { println(" [${it.startMs}] ${it.text}" + listOfNotNull(it.translation, it.romanization, it.voice?.let { v -> "voice $v" }, it.background?.let { b -> "bg: $b" }).joinToString("") { x -> " | $x" }) }
}
}
Hook.AUDIO_SOURCE -> AudioStream.parse(out).let { a ->
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Hooks.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Hooks.kt
index 52417869..6b407cd6 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Hooks.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Hooks.kt
@@ -27,9 +27,17 @@ data class TrackInfo(
fun toJson(): String = ExtJson.encodeToString(serializer(), this)
}
-/** An extension's lyrics, checked: at most [MAX_LINES] lines, times in milliseconds. */
-data class LyricsResult(val provider: String, val synced: Boolean, val lines: List<Line>) {
- data class Line(val startMs: Long, val endMs: Long?, val text: String, val words: List<Word>?)
+/**
+ * An extension's lyrics, checked: at most [MAX_LINES] lines, times in milliseconds. A line may add
+ * a [Line.translation] (in [translationLanguage]), a [Line.romanization], who sings it
+ * ([Line.voice]) and backing vocals ([Line.background]); a wrong type for one of them is ignored,
+ * never an error.
+ */
+data class LyricsResult(val provider: String, val synced: Boolean, val lines: List<Line>, val translationLanguage: String? = null) {
+ data class Line(
+ val startMs: Long, val endMs: Long?, val text: String, val words: List<Word>?,
+ val translation: String? = null, val romanization: String? = null, val voice: Int? = null, val background: String? = null,
+ )
data class Word(val startMs: Long, val endMs: Long?, val text: String)
val wordSynced: Boolean get() = synced && lines.any { !it.words.isNullOrEmpty() }
@@ -38,8 +46,9 @@ data class LyricsResult(val provider: String, val synced: Boolean, val lines: Li
const val MAX_LINES = 3_000
/**
- * `{ provider?, synced?, lines: [{ time?, end?, text, words?: [{ time, end?, text }] }] }`,
- * or `{ provider?, plain: "text" }`. Null when there is nothing to show.
+ * `{ provider?, synced?, translationLanguage?, lines: [{ time?, end?, text, words?: [{ time, end?, text }],
+ * translation?, romanization?, voice?, background? }] }`, or `{ provider?, plain: "text" }`.
+ * Null when there is nothing to show.
*/
fun parse(json: String, fallbackProvider: String): LyricsResult? {
val o = runCatching { ExtJson.parseToJsonElement(json).jsonObject }.getOrNull() ?: throw ExtensionException("lyrics: not an object")
@@ -57,10 +66,28 @@ data class LyricsResult(val provider: String, val synced: Boolean, val lines: Li
val wo = w.jsonObject
Word(ms(wo["time"]) ?: throw ExtensionException("lyrics: a word without its time"), ms(wo["end"]), text(wo["text"]))
}
- Line(ms(l["time"]) ?: 0, ms(l["end"]), text(l["text"]), words?.takeIf { it.isNotEmpty() })
+ Line(
+ ms(l["time"]) ?: 0, ms(l["end"]), text(l["text"]), words?.takeIf { it.isNotEmpty() },
+ translation = optText(l["translation"]), romanization = optText(l["romanization"]),
+ voice = voice(l["voice"]), background = optText(l["background"]),
+ )
}
val synced = (o["synced"] as? JsonPrimitive)?.booleanOrNull ?: raw.any { (it as JsonObject)["time"] != null }
- return LyricsResult(provider, synced, lines).takeIf { lines.any { it.text.isNotBlank() } }
+ val language = (o["translationLanguage"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.takeIf { LANGUAGE.matches(it) }
+ return LyricsResult(provider, synced, lines, language).takeIf { lines.any { it.text.isNotBlank() } }
+ }
+
+ private val LANGUAGE = Regex("[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8}){0,2}")
+
+ /** An optional text: a string, trimmed, 500 characters at most; anything else is none. */
+ private fun optText(e: kotlinx.serialization.json.JsonElement?): String? =
+ (e as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.take(500)?.ifBlank { null }
+
+ /** Who sings: 1, 2... (0: together) as a number, "2" or "v2"; anything else is unknown. */
+ private fun voice(e: kotlinx.serialization.json.JsonElement?): Int? {
+ val p = e as? JsonPrimitive ?: return null
+ val n = p.longOrNull ?: p.contentOrNull?.trim()?.removePrefix("v")?.toLongOrNull() ?: return null
+ return n.takeIf { it in 0..99 }?.toInt()
}
private fun ms(e: kotlinx.serialization.json.JsonElement?): Long? =
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/LyricsResultTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/LyricsResultTest.kt
new file mode 100644
index 00000000..fdf2953f
--- /dev/null
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/LyricsResultTest.kt
@@ -0,0 +1,44 @@
+package app.myspoti.extensions
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/** The optional fields of a lyrics line are additive: absent or of a wrong type, they are no error. */
+class LyricsResultTest {
+ @Test fun translationRomanizationVoiceAndBackgroundAreRead() {
+ val r = LyricsResult.parse(
+ """{"translationLanguage":"en-US","lines":[
+ {"time":1000,"text":"안녕","translation":" Hello ","romanization":"annyeong","voice":2,"background":"(ooh)"},
+ {"time":2000,"text":"b","voice":"v1"}]}""", "Ext")!!
+ assertEquals("en-US", r.translationLanguage)
+ val a = r.lines[0]
+ assertEquals("Hello", a.translation)
+ assertEquals("annyeong", a.romanization)
+ assertEquals(2, a.voice)
+ assertEquals("(ooh)", a.background)
+ assertEquals(1, r.lines[1].voice)
+ assertNull(r.lines[1].translation)
+ }
+
+ @Test fun nothingBecomesAnErrorForAnExtensionThatSendsNoneOrWrongOnes() {
+ val plain = LyricsResult.parse("""{"lines":[{"time":1,"text":"a"}]}""", "Ext")!!
+ assertNull(plain.translationLanguage)
+ assertNull(plain.lines[0].translation); assertNull(plain.lines[0].voice)
+ val odd = LyricsResult.parse(
+ """{"translationLanguage":"not a language!","lines":[{"time":1,"text":"a","translation":5,"romanization":["x"],"voice":"loud","background":{"a":1}},
+ {"time":2,"text":"b","translation":" ","voice":1000}]}""", "Ext")!!
+ assertNull(odd.translationLanguage)
+ val line = odd.lines[0]
+ assertNull(line.translation); assertNull(line.romanization); assertNull(line.voice); assertNull(line.background)
+ assertNull(odd.lines[1].translation)
+ assertNull(odd.lines[1].voice)
+ assertEquals(listOf("a", "b"), odd.lines.map { it.text })
+ }
+
+ @Test fun plainLyricsHaveNone() {
+ val r = LyricsResult.parse("""{"plain":"one\ntwo","translationLanguage":"fr"}""", "Ext")!!
+ assertNull(r.translationLanguage)
+ assertNull(r.lines[0].translation)
+ }
+}
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index 7d30755b..625f7514 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -216,8 +216,14 @@ Asked among the app's own lyrics sources. Return one of:
{ time: 1500, // ms from the start; missing = 0
end: 4000, // optional ms
text: 'line', // 500 characters at most
- words: [ { time: 1500, end: 1900, text: 'word' } ] // optional, `time` required, 200 at most
- } ] }
+ words: [ { time: 1500, end: 1900, text: 'word' } ], // optional, `time` required, 200 at most
+ translation: 'translated line', // optional, in `translationLanguage`
+ romanization: 'line in latin letters', // optional
+ voice: 2, // optional: who sings, 1 = first singer, 2 = second..., 0 = together
+ background: 'ooh' // optional: backing vocals sung over the line, 500 characters at most
+ } ],
+ translationLanguage: 'en' // optional: the language of the `translation`s ('en', 'pt-BR')
+}
```
or `{ provider?, plain: 'text\nof the song' }` for unsynced lyrics (one line per row; used only
@@ -225,6 +231,15 @@ when `lines` is absent). At most 3000 lines (more is an error). Times are number
strings, in milliseconds. Lyrics with no non-blank text count as no answer. Word-by-word display
needs `synced` and at least one line with `words`.
+`translation`, `romanization`, `voice`, `background` and `translationLanguage` are optional and
+additive: leave them out and nothing changes, and one of the wrong type (a number for a text, a
+`voice` that is not a number, `"v2"` or `"2"`) is ignored, never an error. A `translation` is shown in
+place of Myspoti's machine translation only when `translationLanguage` is sent and is the language
+the reader asked for (the first part of the tag decides: `en` covers `en-US`); lines without one are
+machine translated. `voice` marks a duet when at least two different singers appear; `romanization`
+is for scripts that are not Latin (Japanese, Korean, Chinese, Cyrillic...). An older Myspoti
+simply does not read these fields.
+
Action: `lyrics.provide` (normal). Usually you also need `network`.
### `audio-source`