From db27be398676ecdf9de8da500c4edaa4152ab884 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:59:00 +0700 Subject: [PATCH] feat(lyrics): write translation tags as readable text Saved translations and pronunciations were base64, so a .mlrc file or a song's lyrics tag could not be read or fixed by hand. They are now written as plain text under new tag names, still in ID tag form so other players skip them: [x-romanized:12340:bokura wa] [x-translated-words:12340:<00:12.34>We <00:12.60>are<00:13.00>] [x-translated:12340:We are] A value runs to the row's last ']', so only a line break (\n) and a backslash (\\) are escaped, plus '<' (\<) inside word timing. Word timing is enhanced LRC; a time with no word after it ends the word before it, so gaps between words survive. The old x-romaji and x-translation base64 tags are still read by both parsers and are rewritten in the new form the next time the lyrics are saved. Damaged old tags are dropped on that save, as the player already ignored them. .mlrc files now start with [x-mlrc:2]; earlier app versions read the header as a plain tag and show the lyrics, but not the new translations. The Rust download writer uses the same form. New shared parser fixtures and usability rows keep the Dart and Rust readers in step. --- .../test/resources/lyrics_usability_cases.tsv | 2 + lib/services/lyrics_sidecar.dart | 45 ++- lib/services/lyrics_translation.dart | 42 +-- lib/utils/lyric_supplement_tags.dart | 265 ++++++++++++++++++ lib/utils/lyrics_draft.dart | 70 ++--- lib/utils/lyrics_parser.dart | 63 +---- rust_backend/crates/core/src/lyrics/lrc.rs | 93 +++++- .../crates/core/src/lyrics/payloads/tests.rs | 16 +- .../crates/mobile/src/native_lyrics/lrc.rs | 61 ++-- .../crates/mobile/src/native_lyrics/text.rs | 90 ++++++ test/download_lyrics_translation_test.dart | 14 +- test/fixtures/native_lyrics_parsers.json | 158 +++++++++++ test/lyric_supplement_tags_test.dart | 90 ++++++ test/lyrics_draft_test.dart | 44 ++- test/lyrics_sidecar_test.dart | 43 ++- .../lyrics_translation_editor_sheet_test.dart | 13 +- test/lyrics_translation_test.dart | 50 ++-- test/lyrics_translation_ui_test.dart | 18 +- 18 files changed, 901 insertions(+), 276 deletions(-) create mode 100644 lib/utils/lyric_supplement_tags.dart create mode 100644 test/lyric_supplement_tags_test.dart diff --git a/android/app/src/test/resources/lyrics_usability_cases.tsv b/android/app/src/test/resources/lyrics_usability_cases.tsv index c3f661954..8c0c2c053 100644 --- a/android/app/src/test/resources/lyrics_usability_cases.tsv +++ b/android/app/src/test/resources/lyrics_usability_cases.tsv @@ -25,3 +25,5 @@ metadata_and_text true [ti:Title]\n[00:00.00]Actual lyric unicode_text true [00:00.00]<00:00.01> v1: 日本語の歌詞 supplements_only false [x-romaji:1000:YQ==]\n[x-translation:1000:Yg==] supplements_and_text true [x-romaji:1000:YQ==]\n[x-translation:1000:Yg==]\n[00:01.00]Original +readable_supplements_only false [x-romanized:1000:a ]b]\n[x-translated-words:1000:<00:01.00>c<00:02.00>]\n[x-translated:1000:c] +readable_supplements_and_text true [00:01.00]Original\n[x-translated:1000:Translated line] diff --git a/lib/services/lyrics_sidecar.dart b/lib/services/lyrics_sidecar.dart index cad542dd5..716718acd 100644 --- a/lib/services/lyrics_sidecar.dart +++ b/lib/services/lyrics_sidecar.dart @@ -7,6 +7,7 @@ import 'package:mornye/services/platform_bridge.dart'; import 'package:mornye/services/saf_siblings.dart'; import 'package:mornye/utils/desktop_platform.dart'; import 'package:mornye/utils/file_access.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; import 'package:mornye/utils/lyrics_draft.dart'; import 'package:mornye/utils/lyrics_parser.dart'; @@ -15,29 +16,25 @@ import 'package:mornye/utils/lyrics_parser.dart'; /// TTML and lyrics without timing alike, and leaves the song's own file as /// it is. /// -/// Version 1 is UTF-8 LRC: -/// - The first line is `[x-mlrc:1]`. +/// Version 2 is UTF-8 LRC: +/// - The first line is `[x-mlrc:2]`. /// - The lyrics follow as LRC, with word timing as enhanced LRC, a singer as /// a `v1:` prefix and backing vocals as `[bg:...]` rows. -/// - A line's `[x-romaji-words::]`, -/// `[x-romaji::]`, `[x-translation-words::]` -/// and `[x-translation::]` tags follow it. The key is the -/// line's time in milliseconds, so the file also reads as ordinary LRC; in -/// lyrics without timing it is the line's index, counted from 0, and there -/// is no word timing. -/// - Word timing JSON is `[{"text", "startTimeMs", "endTimeMs"}]` in absolute -/// milliseconds; the texts spell the line's pronunciation or translation. +/// - A line's `[x-romanized-words::...]`, `[x-romanized::...]`, +/// `[x-translated-words::...]` and `[x-translated::...]` tags +/// follow it, in the readable form lyric_supplement_tags.dart describes. +/// The key is the line's time in milliseconds, so the file also reads as +/// ordinary LRC; in lyrics without timing it is the line's index, counted +/// from 0, and there is no word timing. +/// +/// Version 1 wrote the same tags with base64 values; it is still read. const mlrcExtension = 'mlrc'; /// `.lrc`, the plain lyrics file other players also read next to a song. const lrcExtension = 'lrc'; -const _mlrcHeader = '[x-mlrc:1]'; +const _mlrcHeader = '[x-mlrc:2]'; const _maxSidecarBytes = 8 * 1024 * 1024; -final _supplementRow = RegExp( - r'^\[x-(romaji-words|romaji|translation-words|translation):(\d+):([^\]]*)\]$', - caseSensitive: false, -); // The LRC ID tags the lyrics parsers drop. final _tagRow = RegExp( r'^\[(ti|ar|al|by|offset|length|re|ve|tool|au|la|encoder|instrumental|x-[a-z0-9_-]+):.*\]$', @@ -85,7 +82,7 @@ String _lrcOf(ParsedLyrics lyrics) { for (final (index, line) in lines.indexed) { out.add(line.text); for (final (kind, payload) in lyricLineSupplements(line)) { - out.add('[x-$kind:$index:$payload]'); + out.add(lyricSupplementRow(kind, index, payload)); } } return out.join('\n'); @@ -100,7 +97,7 @@ String _lrcOf(ParsedLyrics lyrics) { final voice = line.voice == null ? '' : 'v${line.voice!.index + 1}: '; out.add('[${formatLyricsTime(line.time)}]$voice$content'); for (final (kind, payload) in lyricLineSupplements(line)) { - out.add('[x-$kind:${line.time.inMilliseconds}:$payload]'); + out.add(lyricSupplementRow(kind, line.time.inMilliseconds, payload)); } } return out.join('\n'); @@ -144,17 +141,11 @@ Future readMlrc( for (final source in raw.split(RegExp(r'\r\n|\r|\n'))) { final row = source.trim(); if (row.isEmpty) continue; - final supplement = _supplementRow.firstMatch(row); + final supplement = readLyricSupplementTag(row); if (supplement != null) { - try { - final value = utf8.decode(base64.decode(supplement.group(3)!)).trim(); - final kind = supplement.group(1)!.toLowerCase(); - final index = int.parse(supplement.group(2)!); - if (value.isNotEmpty && !kind.endsWith('-words')) { - (supplements[index] ??= {}).putIfAbsent(kind, () => value); - } - } on FormatException { - // A damaged tag must not hide the lyrics. + final (:kind, key: index, :text, words: _) = supplement; + if (index != null && text != null && text.isNotEmpty) { + (supplements[index] ??= {}).putIfAbsent(kind, () => text); } continue; } diff --git a/lib/services/lyrics_translation.dart b/lib/services/lyrics_translation.dart index 48c65fb59..c9cffdb68 100644 --- a/lib/services/lyrics_translation.dart +++ b/lib/services/lyrics_translation.dart @@ -6,6 +6,7 @@ import 'package:crypto/crypto.dart'; import 'package:mornye/services/lyrics_ai_client.dart'; import 'package:mornye/services/lyrics_translation_alignment.dart'; import 'package:mornye/utils/logger.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; import 'package:mornye/utils/lyrics_draft.dart'; import 'package:mornye/utils/lyrics_parser.dart'; import 'package:path_provider/path_provider.dart'; @@ -298,39 +299,17 @@ bool lyricsTranslationUnsaved(ParsedLyrics original, ParsedLyrics shown) { return false; } -/// `[x-romaji-words:...]` and `[x-translation-words:...]` JSON for [words], -/// as both lyrics parsers read it. -/// Empty when a word cannot be given a valid time range. -String lyricWordsSupplement(List words) { - final rows = >[]; - for (var i = 0; i < words.length; i++) { - final word = words[i]; - final start = word.time.inMilliseconds; - final end = - word.end?.inMilliseconds ?? - (i + 1 < words.length ? words[i + 1].time.inMilliseconds : start); - if (word.text.trim().isEmpty || - end < start || - (rows.isNotEmpty && (rows.last['startTimeMs']! as int) > start)) { - return ''; - } - rows.add({'text': word.text, 'startTimeMs': start, 'endTimeMs': end}); - } - return rows.isEmpty ? '' : jsonEncode(rows); -} - -/// The `-words` JSON for [words] timing [text], or empty when they do not +/// The `-words` value for [words] timing [text], or empty when they do not /// spell it: both lyrics parsers drop such timing. String _timedSupplement(String text, List words) => text.isEmpty || words.map((word) => word.text).join() != text ? '' - : lyricWordsSupplement(words); + : encodeLyricWordsTag(words); /// The supplement tags a lyric line written as LRC carries for [line]'s /// translation and pronunciation, with their word timing, as /// (kind, payload) in the order they are written. List<(String, String)> lyricLineSupplements(LyricLine line) { - String encode(String text) => base64.encode(utf8.encode(text)); final romanization = _supplementText(line.romanization); final romanizationWords = _timedSupplement( romanization, @@ -339,18 +318,17 @@ List<(String, String)> lyricLineSupplements(LyricLine line) { final translation = _supplementText(line.translation); final translationWords = _timedSupplement(translation, line.translationWords); return [ - if (romanizationWords.isNotEmpty) - ('romaji-words', encode(romanizationWords)), - if (romanization.isNotEmpty) ('romaji', encode(romanization)), - if (translationWords.isNotEmpty) - ('translation-words', encode(translationWords)), - if (translation.isNotEmpty) ('translation', encode(translation)), + if (romanizationWords.isNotEmpty) ('romaji-words', romanizationWords), + if (romanization.isNotEmpty) ('romaji', encodeLyricTextTag(romanization)), + if (translationWords.isNotEmpty) ('translation-words', translationWords), + if (translation.isNotEmpty) + ('translation', encodeLyricTextTag(translation)), ]; } /// [raw] LRC with each timed line carrying the translation and -/// pronunciation [shown] gives it, as the `[x-translation::...]` and -/// `[x-romaji::...]` tags both lyrics parsers read back, with their +/// pronunciation [shown] gives it, as the `[x-translated::...]` and +/// `[x-romanized::...]` tags both lyrics parsers read back, with their /// `-words` timing, so they stay with the song's file alongside its own /// lyrics. Other lines, tags and supplements stay as they are. Null when /// [raw] is not synced LRC or already holds these. diff --git a/lib/utils/lyric_supplement_tags.dart b/lib/utils/lyric_supplement_tags.dart new file mode 100644 index 000000000..769386b56 --- /dev/null +++ b/lib/utils/lyric_supplement_tags.dart @@ -0,0 +1,265 @@ +import 'dart:convert'; + +import 'package:mornye/utils/lyrics_draft.dart' show formatLyricsTime; +import 'package:mornye/utils/lyrics_parser.dart' show LyricWord; + +/// The translation and pronunciation tags an LRC line carries, written as +/// readable text in ID tag form, so other players skip them: +/// +/// ``` +/// [00:12.34]僕らは +/// [x-romanized:12340:bokura wa] +/// [x-translated-words:12340:<00:12.34>We <00:12.60>are<00:13.00>] +/// [x-translated:12340:We are] +/// ``` +/// +/// - The key is the line's time in milliseconds, or its index from 0 in +/// lyrics without timing. +/// - A value runs to the row's last `]`. `\n` is a line break and `\\` a +/// backslash; in word timing `\<` is a `<`. +/// - Word timing is enhanced LRC in absolute time: each word follows its +/// start, a word ends where the next starts, and a time with no word after +/// it ends the word before it. +/// +/// Earlier versions wrote `x-romaji`, `x-romaji-words`, `x-translation` and +/// `x-translation-words` with base64 values, word timing as base64 JSON; +/// they are still read. +/// +/// Kinds are named `romaji`, `romaji-words`, `translation` and +/// `translation-words` in code, whichever way the file spells them. +const _tagNames = { + 'romaji': 'romanized', + 'romaji-words': 'romanized-words', + 'translation': 'translated', + 'translation-words': 'translated-words', +}; +const _kindsByTag = { + 'romanized': 'romaji', + 'romanized-words': 'romaji-words', + 'translated': 'translation', + 'translated-words': 'translation-words', +}; + +final _row = RegExp( + r'^\[x-(romanized-words|romanized|translated-words|translated|romaji-words|romaji|translation-words|translation):(\d+):(.*)\]$', + caseSensitive: false, +); +final _wordTime = RegExp(r'<(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?>'); + +/// A translation or pronunciation tag read from a row. +typedef LyricSupplementTag = ({ + String kind, + int? key, + + /// The text of a `romaji` or `translation` tag, trimmed; null when it + /// cannot be read. + String? text, + + /// The timing of a `-words` tag; empty when it cannot be read. + List words, +}); + +/// The tag [row] holds, or null when it is no translation or pronunciation +/// tag. +LyricSupplementTag? readLyricSupplementTag(String row) { + final match = _row.firstMatch(row); + if (match == null) return null; + final written = match.group(1)!.toLowerCase(); + final legacy = !_kindsByTag.containsKey(written); + final kind = _kindsByTag[written] ?? written; + final key = int.tryParse(match.group(2)!); + final value = match.group(3)!; + if (kind.endsWith('-words')) { + return ( + kind: kind, + key: key, + text: null, + words: legacy ? _legacyWords(value) : decodeLyricWordsTag(value), + ); + } + String? text; + if (legacy) { + try { + text = utf8.decode(base64.decode(value)).trim(); + } on FormatException { + // Optional damaged metadata must not hide the lyrics. + } + } else { + text = _unescape(value).trim(); + } + return (kind: kind, key: key, text: text, words: const []); +} + +/// The row that writes [payload], a value from [encodeLyricTextTag] or +/// [encodeLyricWordsTag], as a [kind] tag under [key]. +String lyricSupplementRow(String kind, int key, String payload) => + '[x-${_tagNames[kind] ?? kind}:$key:$payload]'; + +/// [text] as a tag value. +String encodeLyricTextTag(String text) => _escape(text, words: false); + +/// [words] as a `-words` tag value. Empty when a word cannot be given a +/// valid time range. +String encodeLyricWordsTag(List words) { + final out = StringBuffer(); + int? lastStart; + int? lastEnd; + for (var i = 0; i < words.length; i++) { + final word = words[i]; + final start = word.time.inMilliseconds; + final end = + word.end?.inMilliseconds ?? + (i + 1 < words.length ? words[i + 1].time.inMilliseconds : start); + if (word.text.trim().isEmpty || + start < 0 || + end < start || + (lastStart != null && lastStart > start)) { + return ''; + } + if (lastEnd != null && lastEnd != start) out.write(_time(lastEnd)); + out + ..write(_time(start)) + ..write(_escape(word.text, words: true)); + lastStart = start; + lastEnd = end; + } + if (lastEnd != null) out.write(_time(lastEnd)); + return out.toString(); +} + +/// The words a `-words` tag value times, or empty when it is damaged. +List decodeLyricWordsTag(String value) { + final segments = <(int, StringBuffer)>[]; + final leading = StringBuffer(); + var i = 0; + while (i < value.length) { + final text = segments.isEmpty ? leading : segments.last.$2; + final char = value[i]; + if (char == r'\' && i + 1 < value.length) { + text.write(_unescaped(value[i + 1])); + i += 2; + continue; + } + final time = char == '<' ? _wordTime.matchAsPrefix(value, i) : null; + if (time != null) { + segments.add((_milliseconds(time), StringBuffer())); + i = time.end; + continue; + } + text.write(char); + i++; + } + if (leading.isNotEmpty) return const []; + final words = <(int, int?, String)>[]; + for (final (time, buffer) in segments) { + final text = buffer.toString(); + if (text.isEmpty) { + // A time with no word after it ends the word before it. + if (words.isEmpty || words.last.$2 != null) return const []; + words.last = (words.last.$1, time, words.last.$3); + continue; + } + if (text.trim().isEmpty) return const []; + if (words.isNotEmpty) { + final (start, end, previous) = words.last; + if (start > time) return const []; + words.last = (start, end ?? time, previous); + } + words.add((time, null, text)); + } + final timed = []; + for (final (start, end, text) in words) { + if (end != null && end < start) return const []; + timed.add( + LyricWord( + time: Duration(milliseconds: start), + end: Duration(milliseconds: end ?? start), + text: text, + ), + ); + } + return timed; +} + +/// Base64 JSON word timing, as earlier versions wrote it. +List _legacyWords(String value) { + try { + final decoded = jsonDecode(utf8.decode(base64.decode(value)).trim()); + if (decoded is! List) return const []; + final words = []; + for (final item in decoded) { + if (item case { + 'text': final String text, + 'startTimeMs': final int start, + 'endTimeMs': final int end, + }) { + if (text.trim().isEmpty || + start < 0 || + end < start || + (words.isNotEmpty && words.last.time.inMilliseconds > start)) { + return const []; + } + words.add( + LyricWord( + time: Duration(milliseconds: start), + end: Duration(milliseconds: end), + text: text, + ), + ); + } else { + return const []; + } + } + return words; + } on FormatException { + return const []; + } +} + +String _time(int ms) => '<${formatLyricsTime(Duration(milliseconds: ms))}>'; + +int _milliseconds(Match time) { + final fraction = time.group(3) ?? '0'; + final ms = switch (fraction.length) { + 1 => int.parse(fraction) * 100, + 2 => int.parse(fraction) * 10, + _ => int.parse(fraction), + }; + return (int.parse(time.group(1)!) * 60 + int.parse(time.group(2)!)) * 1000 + + ms; +} + +String _escape(String text, {required bool words}) { + final out = StringBuffer(); + final lines = text.replaceAll('\r\n', '\n').replaceAll('\r', '\n'); + for (final char in lines.split('')) { + out.write(switch (char) { + r'\' => r'\\', + '\n' => r'\n', + '<' when words => r'\<', + _ => char, + }); + } + return out.toString(); +} + +String _unescape(String value) { + final out = StringBuffer(); + var i = 0; + while (i < value.length) { + if (value[i] == r'\' && i + 1 < value.length) { + out.write(_unescaped(value[i + 1])); + i += 2; + } else { + out.write(value[i]); + i++; + } + } + return out.toString(); +} + +String _unescaped(String char) => switch (char) { + 'n' => '\n', + r'\' || '<' => char, + _ => '\\$char', +}; diff --git a/lib/utils/lyrics_draft.dart b/lib/utils/lyrics_draft.dart index 901eaaa87..ffc05378a 100644 --- a/lib/utils/lyrics_draft.dart +++ b/lib/utils/lyrics_draft.dart @@ -1,4 +1,5 @@ -import 'dart:convert'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; +import 'package:mornye/utils/lyrics_parser.dart' show LyricWord; /// One line of a [LyricsDraft]: its time, its text, and the raw LRC that /// rides along with it (word timing, a singer prefix, translations and @@ -39,8 +40,8 @@ class LyricsDraftLine { /// The line time [content]'s word timing was written for. final Duration? contentTime; - /// `[x-...::...]` translation and pronunciation tags keyed to this - /// line, as (kind, payload). + /// Translation and pronunciation tags keyed to this line, as (kind, + /// payload) in the form [lyricSupplementRow] writes. final List<(String, String)> supplements; /// `[bg:...]` backing vocals sung with this line, as the raw content. @@ -91,10 +92,6 @@ class LyricsDraft { r'^\[(ti|ar|al|by|offset|length|re|ve|tool|au|la|encoder|instrumental|x-[a-z0-9_-]+):.*\]$', caseSensitive: false, ); - static final _supplement = RegExp( - r'^\[x-(romaji-words|romaji|translation-words|translation):(\d+):([^\]]*)\]$', - caseSensitive: false, - ); static final _background = RegExp(r'^\[bg:(.*)\]$', caseSensitive: false); static final _credit = RegExp(r'^Written\s+by\s*:', caseSensitive: false); @@ -137,13 +134,18 @@ class LyricsDraft { } continue; } - final supplement = _supplement.firstMatch(row); + final supplement = readLyricSupplementTag(row); if (supplement != null) { - final ms = int.parse(supplement.group(2)!); - (supplements[ms] ??= []).add(( - supplement.group(1)!.toLowerCase(), - supplement.group(3)!, - )); + // Rewritten in the current form; damaged tags are dropped. + final (:kind, key: ms, :text, :words) = supplement; + final payload = words.isNotEmpty + ? encodeLyricWordsTag(words) + : text != null && text.isNotEmpty + ? encodeLyricTextTag(text) + : ''; + if (ms != null && payload.isNotEmpty) { + (supplements[ms] ??= []).add((kind, payload)); + } continue; } final tag = _idTag.firstMatch(row); @@ -306,7 +308,7 @@ class LyricsDraft { ? line.supplements : _shiftSupplements(line.supplements, delta); for (final (kind, payload) in shifted) { - out.add('[x-$kind:${time.inMilliseconds}:$payload]'); + out.add(lyricSupplementRow(kind, time.inMilliseconds, payload)); } for (final row in line.background) { out.add('[bg:${_shiftWords(row, delta)}]'); @@ -351,33 +353,23 @@ class LyricsDraft { ]; } - /// Pronunciation and translation word timing is absolute JSON; it moves - /// with its line. + /// Pronunciation and translation word timing is absolute; it moves with + /// its line. static String _shiftSupplementWords(String payload, int deltaMs) { - try { - final words = jsonDecode(utf8.decode(base64.decode(payload))); - if (words is! List) return payload; - int shift(Object? value) { - final ms = (value is int ? value : 0) + deltaMs; - return ms < 0 ? 0 : ms; - } - - return base64.encode( - utf8.encode( - jsonEncode([ - for (final word in words) - if (word is Map) - { - ...word, - 'startTimeMs': shift(word['startTimeMs']), - 'endTimeMs': shift(word['endTimeMs']), - }, - ]), - ), - ); - } on FormatException { - return payload; + Duration shift(Duration time) { + final ms = time.inMilliseconds + deltaMs; + return Duration(milliseconds: ms < 0 ? 0 : ms); } + + final shifted = encodeLyricWordsTag([ + for (final word in decodeLyricWordsTag(payload)) + LyricWord( + time: shift(word.time), + end: word.end == null ? null : shift(word.end!), + text: word.text, + ), + ]); + return shifted.isEmpty ? payload : shifted; } } diff --git a/lib/utils/lyrics_parser.dart b/lib/utils/lyrics_parser.dart index 21ee5558a..cb747539d 100644 --- a/lib/utils/lyrics_parser.dart +++ b/lib/utils/lyrics_parser.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:mornye/services/platform_bridge.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; import 'package:xml/xml.dart'; Uint8List _encodeLyricsInBackground(String raw) => @@ -207,10 +208,6 @@ class LyricsParser { r'^\[(ti|ar|al|by|offset|length|re|ve|tool|au|la|encoder|instrumental|x-[a-z0-9_-]+):.*\]$', caseSensitive: false, ); - static final RegExp _supplementTag = RegExp( - r'^\[x-(romaji-words|romaji|translation-words|translation):(\d+):([^\]]*)\]$', - caseSensitive: false, - ); static final RegExp _writerCredit = RegExp( r'^Written\s+by\s*:\s*(.+)$', caseSensitive: false, @@ -385,26 +382,17 @@ class LyricsParser { final background = _backgroundLine.firstMatch(line.trim()); if (background != null) line = background.group(1)!.trim(); - final supplement = _supplementTag.firstMatch(line.trim()); + final supplement = readLyricSupplementTag(line.trim()); if (supplement != null) { - final time = int.tryParse(supplement.group(2)!); - try { - final value = utf8.decode(base64.decode(supplement.group(3)!)).trim(); - if (time != null && value.isNotEmpty) { - final kind = supplement.group(1)!.toLowerCase(); - if (kind.endsWith('-words')) { - final words = _parseSupplementWords(value); - if (words.isNotEmpty) { - (kind == 'romaji-words' ? romanizationWords : translationWords) - .putIfAbsent(time, () => words); - } - } else { - final target = kind == 'romaji' ? romanization : translation; - target.putIfAbsent(time, () => value); - } + final (:kind, key: time, :text, :words) = supplement; + if (time != null) { + if (words.isNotEmpty) { + (kind == 'romaji-words' ? romanizationWords : translationWords) + .putIfAbsent(time, () => words); + } else if (text != null && text.isNotEmpty) { + final target = kind == 'romaji' ? romanization : translation; + target.putIfAbsent(time, () => text); } - } on FormatException { - // Optional corrupt metadata must not hide the original lyrics. } continue; } @@ -584,37 +572,6 @@ class LyricsParser { return matched.map((time, match) => MapEntry(time, match.$2)); } - /// `[x-romaji-words:...]` and `[x-translation-words:...]` JSON. - static List _parseSupplementWords(String raw) { - final value = jsonDecode(raw); - if (value is! List) return const []; - final words = []; - for (final item in value) { - if (item case { - 'text': final String text, - 'startTimeMs': final int start, - 'endTimeMs': final int end, - }) { - if (text.trim().isEmpty || - start < 0 || - end < start || - (words.isNotEmpty && words.last.time.inMilliseconds > start)) { - return const []; - } - words.add( - LyricWord( - time: Duration(milliseconds: start), - end: Duration(milliseconds: end), - text: text, - ), - ); - } else { - return const []; - } - } - return words; - } - static List _shiftWords(List words, int offsetMs) { if (offsetMs == 0 || words.isEmpty) return words; return words diff --git a/rust_backend/crates/core/src/lyrics/lrc.rs b/rust_backend/crates/core/src/lyrics/lrc.rs index d767e8f12..63b864473 100644 --- a/rust_backend/crates/core/src/lyrics/lrc.rs +++ b/rust_backend/crates/core/src/lyrics/lrc.rs @@ -1,8 +1,7 @@ //! LRC lyrics parsing and helpers: timestamps, synced and plain text, and usability checks. -use super::{LyricsLine, LyricsResponse}; +use super::{LyricsLine, LyricsResponse, LyricsWord}; use crate::matching::lowercase; -use base64::{Engine, engine::general_purpose::STANDARD}; use regex::Regex; use std::sync::LazyLock; @@ -207,6 +206,50 @@ pub fn extract_source(raw: &str) -> String { String::new() } +/// A readable tag value, as lib/utils/lyric_supplement_tags.dart writes it: +/// `\n` for a line break, `\\` for a backslash and, in word timing, `\<`. +fn escape_supplement(text: &str, words: bool) -> String { + let mut out = String::new(); + for c in text.replace("\r\n", "\n").replace('\r', "\n").chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '<' if words => out.push_str("\\<"), + _ => out.push(c), + } + } + out +} + +/// Word timing as enhanced LRC: each word after its start, a time with no +/// word after it where a word ends before the next starts. None when a word +/// has no valid time range. +fn supplement_words(words: &[LyricsWord]) -> Option { + let mut out = String::new(); + let mut last: Option<(i64, i64)> = None; + for word in words { + let (start, end) = (word.start_time_ms, word.end_time_ms); + if word.text.trim().is_empty() + || start < 0 + || end < start + || last.is_some_and(|(last_start, _)| last_start > start) + { + return None; + } + if let Some((_, last_end)) = last + && last_end != start + { + out.push_str(&format!("<{}>", timestamp_inline(last_end))); + } + out.push_str(&format!("<{}>", timestamp_inline(start))); + out.push_str(&escape_supplement(&word.text, true)); + last = Some((start, end)); + } + let (_, end) = last?; + out.push_str(&format!("<{}>", timestamp_inline(end))); + Some(out) +} + pub fn with_metadata(lyrics: &LyricsResponse, track: &str, artist: &str) -> String { if lyrics.lines().is_empty() { return String::new(); @@ -229,25 +272,25 @@ pub fn with_metadata(lyrics: &LyricsResponse, track: &str, artist: &str) -> Stri let synced = lyrics.is_synced(); if synced { for line in lyrics.lines() { - if let Some(words) = &line.romanization_words - && !words.is_empty() - && let Ok(json) = serde_json::to_vec(words) + if let Some(words) = line + .romanization_words + .as_deref() + .and_then(supplement_words) { output.push_str(&format!( - "[x-romaji-words:{}:{}]\n", - line.start_time_ms, - STANDARD.encode(json) + "[x-romanized-words:{}:{words}]\n", + line.start_time_ms )); } for (tag, text) in [ - ("x-romaji", &line.romanization), - ("x-translation", &line.translation), + ("x-romanized", &line.romanization), + ("x-translated", &line.translation), ] { if let Some(text) = text.as_deref().filter(|text| !text.trim().is_empty()) { output.push_str(&format!( "[{tag}:{}:{}]\n", line.start_time_ms, - STANDARD.encode(text.trim()) + escape_supplement(text.trim(), false) )); } } @@ -439,13 +482,35 @@ mod tests { fn optional_text_is_safe_metadata_not_lyric_content() { let raw = "[x-romaji:1000:YQ==]\n[x-translation:1000:Yg==]"; assert!(!has_usable_content(raw)); + let raw = "[x-romanized:1000:a ]b]\n[x-translated:1000:<00:01.00>c]"; + assert!(!has_usable_content(raw)); let mut lyrics = LyricsResponse::from_text("[00:01.009]Original", "Apple Music", "Apple Music"); - lyrics.lines.as_mut().unwrap()[0].translation = Some("Text ]\nnext line 日本語".into()); + lyrics.lines.as_mut().unwrap()[0].translation = Some("Text ]\nnext \\ line 日本語".into()); let lrc = with_metadata(&lyrics, "Track", "Artist"); - let encoded = STANDARD.encode("Text ]\nnext line 日本語"); - assert!(lrc.contains(&format!("[x-translation:1009:{encoded}]"))); + assert!(lrc.contains("[x-translated:1009:Text ]\\nnext \\\\ line 日本語]")); assert!(lrc.contains("[00:01.009]Original")); assert!(has_usable_content(&lrc)); } + + #[test] + fn word_timing_is_written_as_enhanced_lrc() { + let word = |text: &str, start_time_ms, end_time_ms| LyricsWord { + text: text.into(), + start_time_ms, + end_time_ms, + }; + let words = [ + word("Ro ", 1000, 1200), + word("", 1200, 1500), + word("ji", 1609, 2000), + ]; + assert_eq!( + supplement_words(&words).as_deref(), + Some("<00:01.00>Ro <00:01.20>\\<00:01.50><00:01.609>ji<00:02.00>") + ); + assert_eq!(supplement_words(&[word("a", 2000, 1000)]), None); + assert_eq!(supplement_words(&[word(" ", 0, 1000)]), None); + assert_eq!(supplement_words(&[]), None); + } } diff --git a/rust_backend/crates/core/src/lyrics/payloads/tests.rs b/rust_backend/crates/core/src/lyrics/payloads/tests.rs index 7714519db..0bf4d3c45 100644 --- a/rust_backend/crates/core/src/lyrics/payloads/tests.rs +++ b/rust_backend/crates/core/src/lyrics/payloads/tests.rs @@ -214,7 +214,7 @@ fn supplements_follow_output_timestamps_in_both_apple_modes() { let start = if word_timing { 1010 } else { 1009 }; assert_eq!(lyrics.lines()[0].start_time_ms, start); let exported = lrc::with_metadata(&lyrics, "Track", "Artist"); - assert!(exported.contains(&format!("[x-romaji:{start}:Um9tYW5pemVk]"))); + assert!(exported.contains(&format!("[x-romanized:{start}:Romanized]"))); assert!(exported.contains(&lrc::timestamp(start))); if word_timing { assert!(exported.contains("<00:01.307>")); @@ -337,19 +337,17 @@ fn romanization_spans_keep_syllables_spaces_and_original_word_times() { assert_eq!(words[2].end_time_ms, 2497); let output = lrc::with_metadata(&lyrics, "Track", "Artist"); - let encoded = output + let written = output .lines() .find_map(|line| { - line.strip_prefix("[x-romaji-words:1010:") + line.strip_prefix("[x-romanized-words:1010:") .and_then(|line| line.strip_suffix(']')) }) .unwrap(); - use base64::Engine; - let decoded = base64::engine::general_purpose::STANDARD - .decode(encoded) - .unwrap(); - let restored: Vec = serde_json::from_slice(&decoded).unwrap(); - assert_eq!(&restored, words); + assert_eq!( + written, + "<00:01.009>Ro<00:01.107>ma <00:01.307><00:02.003>nized<00:02.497>" + ); } #[test] diff --git a/rust_backend/crates/mobile/src/native_lyrics/lrc.rs b/rust_backend/crates/mobile/src/native_lyrics/lrc.rs index ce78805dd..5d4fe6555 100644 --- a/rust_backend/crates/mobile/src/native_lyrics/lrc.rs +++ b/rust_backend/crates/mobile/src/native_lyrics/lrc.rs @@ -1,6 +1,7 @@ use super::text::{ LINE_TIME, Supplements, WORD_TIME, align, decode_supplement, duration, insert_first, parse_int, - parse_words, romanization_words, shift, shift_words, trim, trim_end, vocal_text, + parse_words, romanization_words, shift, shift_words, supplement_words, trim, trim_end, + unescape_supplement, vocal_text, }; use super::{Line, Parsed, Word, has_usable_timing}; use regex::Regex; @@ -11,7 +12,7 @@ static ID_TAG: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)^\[(ti|ar|al|by|offset|length|re|ve|tool|au|la|encoder|instrumental|x-[a-z0-9_-]+):.*\]$").unwrap() }); static SUPPLEMENT: LazyLock = LazyLock::new(|| { - Regex::new(r"(?i)^\[x-(romaji-words|romaji|translation-words|translation):([0-9]+):([^\]]*)\]$") + Regex::new(r"(?i)^\[x-(romanized-words|romanized|translated-words|translated|romaji-words|romaji|translation-words|translation):([0-9]+):(.*)\]$") .unwrap() }); static NEW_LINE: LazyLock = LazyLock::new(|| Regex::new(r"\r\n|\r|\n").unwrap()); @@ -40,23 +41,47 @@ pub(super) fn parse_lrc( line = trim(c.get(1).unwrap().as_str()); } if let Some(c) = SUPPLEMENT.captures(trim(line)) { - if let (Some(time), Some(value)) = (parse_int(&c[2]), decode_supplement(&c[3])) - && !value.is_empty() - { - match c[1].to_ascii_lowercase().as_str() { - kind @ ("romaji-words" | "translation-words") => { - let words = romanization_words(&value); - if !words.is_empty() { - let target = if kind == "romaji-words" { - &mut romaji_words - } else { - &mut translation_words - }; - insert_first(target, time, words); - } + // Earlier versions wrote base64 under the old names. + let written = c[1].to_ascii_lowercase(); + let (kind, readable) = match written.as_str() { + "romanized" => ("romaji", true), + "romanized-words" => ("romaji-words", true), + "translated" => ("translation", true), + "translated-words" => ("translation-words", true), + legacy => (legacy, false), + }; + if let Some(time) = parse_int(&c[2]) { + if kind.ends_with("-words") { + let words = if readable { + supplement_words(&c[3]) + } else { + decode_supplement(&c[3]) + .filter(|value| !value.is_empty()) + .map(|value| romanization_words(&value)) + .unwrap_or_default() + }; + if !words.is_empty() { + let target = if kind == "romaji-words" { + &mut romaji_words + } else { + &mut translation_words + }; + insert_first(target, time, words); + } + } else { + let value = if readable { + Some(trim(&unescape_supplement(&c[3])).to_string()) + } else { + decode_supplement(&c[3]) + }; + if let Some(value) = value.filter(|value| !value.is_empty()) { + let target = if kind == "romaji" { + &mut romaji + } else { + &mut translation + }; + insert_first(target, time, value); } - "romaji" => insert_first(&mut romaji, time, value), - _ => insert_first(&mut translation, time, value), } } continue; diff --git a/rust_backend/crates/mobile/src/native_lyrics/text.rs b/rust_backend/crates/mobile/src/native_lyrics/text.rs index 4cfffe7a6..9e6ba3364 100644 --- a/rust_backend/crates/mobile/src/native_lyrics/text.rs +++ b/rust_backend/crates/mobile/src/native_lyrics/text.rs @@ -142,6 +142,96 @@ pub(super) fn decode_supplement(encoded: &str) -> Option { .ok()?; Some(trim(&String::from_utf8(bytes).ok()?).into()) } +/// A readable tag value: `\n` is a line break, `\\` a backslash and `\<` a +/// `<`. Mirrors lib/utils/lyric_supplement_tags.dart. +pub(super) fn unescape_supplement(value: &str) -> String { + let mut out = String::new(); + let mut chars = value.chars().peekable(); + while let Some(c) = chars.next() { + match (c, chars.peek()) { + ('\\', Some(&next)) => { + chars.next(); + push_unescaped(&mut out, next); + } + _ => out.push(c), + } + } + out +} +fn push_unescaped(out: &mut String, next: char) { + match next { + 'n' => out.push('\n'), + '\\' | '<' => out.push(next), + _ => { + out.push('\\'); + out.push(next); + } + } +} +/// Readable word timing: each word follows its start, a word ends where the +/// next starts, and a time with no word after it ends the word before it. +pub(super) fn supplement_words(value: &str) -> Vec { + let mut leading = String::new(); + let mut segments: Vec<(i64, String)> = Vec::new(); + let mut i = 0; + while let Some(c) = value[i..].chars().next() { + let text = match segments.last_mut() { + Some((_, text)) => text, + None => &mut leading, + }; + if c == '\\' + && let Some(next) = value[i + 1..].chars().next() + { + push_unescaped(text, next); + i += 1 + next.len_utf8(); + continue; + } + if c == '<' + && let Some(time) = WORD_TIME + .captures_at(value, i) + .filter(|time| time.get(0).unwrap().start() == i) + { + i = time.get(0).unwrap().end(); + segments.push((duration(&time), String::new())); + continue; + } + text.push(c); + i += c.len_utf8(); + } + if !leading.is_empty() { + return vec![]; + } + let mut words: Vec = Vec::new(); + for (time, text) in segments { + if text.is_empty() { + match words.last_mut() { + Some(word) if word.end_ms.is_none() => word.end_ms = Some(time), + _ => return vec![], + } + continue; + } + if trim(&text).is_empty() { + return vec![]; + } + if let Some(previous) = words.last_mut() { + if previous.time_ms > time { + return vec![]; + } + previous.end_ms.get_or_insert(time); + } + words.push(Word { + time_ms: time, + end_ms: None, + text, + }); + } + for word in &mut words { + if *word.end_ms.get_or_insert(word.time_ms) < word.time_ms { + return vec![]; + } + } + words +} pub(super) fn romanization_words(raw: &str) -> Vec { let Ok(Value::Array(values)) = serde_json::from_str::(raw) else { return vec![]; diff --git a/test/download_lyrics_translation_test.dart b/test/download_lyrics_translation_test.dart index f4e343084..7806f7b21 100644 --- a/test/download_lyrics_translation_test.dart +++ b/test/download_lyrics_translation_test.dart @@ -96,8 +96,7 @@ http.Response _reply(http.Request request) { } /// The tag a saved translation of the line at [ms] takes. -String _translation(int ms, String text) => - '[x-translation:$ms:${base64Encode(utf8.encode(text))}]'; +String _translation(int ms, String text) => '[x-translated:$ms:$text]'; /// Waits for work that includes real file IO. Future _until(bool Function() done) async { @@ -196,7 +195,7 @@ void main() { await _until(() => sidecar.writes.isNotEmpty); final mlrc = sidecar.writes[_song.source]!; - expect(mlrc, startsWith('[x-mlrc:1]')); + expect(mlrc, startsWith('[x-mlrc:2]')); expect(mlrc, contains(_translation(0, 'es:Hello'))); expect(savedLyrics, isEmpty); }); @@ -230,7 +229,12 @@ void main() { final saved = savedLyrics[_song.source]!; expect(saved, contains(_translation(0, 'Hola amigo'))); - expect(saved, contains('[x-translation-words:0:')); + expect( + saved, + contains( + '[x-translated-words:0:<00:00.00>Hola <00:00.50>amigo<00:01.00>]', + ), + ); expect(requests, isEmpty); }); @@ -260,7 +264,7 @@ void main() { test('leaves lyrics that already carry a translation', () async { final (container: _, :translator, queue: _) = setUpTranslator( sidecar: _Sidecar( - existing: '[x-mlrc:1]\n$_lrc\n${_translation(0, 'Hola')}', + existing: '[x-mlrc:2]\n$_lrc\n${_translation(0, 'Hola')}', ), ); expect(await translator.translate(_song), isNull); diff --git a/test/fixtures/native_lyrics_parsers.json b/test/fixtures/native_lyrics_parsers.json index b4652618b..7ac0a1e95 100644 --- a/test/fixtures/native_lyrics_parsers.json +++ b/test/fixtures/native_lyrics_parsers.json @@ -1627,5 +1627,163 @@ } ] } + }, + { + "name": "readable supplements follow the offset", + "request": { + "operation": "parse_lyrics", + "raw": "[offset:100]\n[00:01.00]Hola mundo\n[x-romanized:1000:o la mun do]\n[x-romanized-words:1000:<00:01.00>o la <00:01.20>mun do<00:01.50>]\n[x-translated-words:1000:<00:01.00>Hello <00:01.40><00:01.50>world<00:02.00>]\n[x-translated:1000:Hello world]\n[00:03.00]Otra\n[x-translated:3000:Another]" + }, + "expected": { + "synced": true, + "wordSynced": false, + "plainText": "Hola mundo\nOtra", + "writers": null, + "provider": null, + "lines": [ + { + "timeMs": 900, + "endMs": null, + "text": "Hola mundo", + "words": [], + "romanization": "o la mun do", + "romanizationWords": [ + { + "timeMs": 900, + "endMs": 1100, + "text": "o la " + }, + { + "timeMs": 1100, + "endMs": 1400, + "text": "mun do" + } + ], + "translation": "Hello world", + "translationWords": [ + { + "timeMs": 900, + "endMs": 1300, + "text": "Hello " + }, + { + "timeMs": 1400, + "endMs": 1900, + "text": "world" + } + ], + "voice": null, + "isBackground": false, + "vocalGroup": 0 + }, + { + "timeMs": 2900, + "endMs": null, + "text": "Otra", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": "Another", + "voice": null, + "isBackground": false, + "vocalGroup": 1 + } + ] + } + }, + { + "name": "readable escapes, damaged timing and first tag wins", + "request": { + "operation": "parse_lyrics", + "raw": "[00:01]Uno\n[x-translated:1000:a ]b \\n c \\\\ d \\x ]\n[x-translation:1000:SWdub3JlZA==]\n[00:02]Dos\n[x-romanized-words:2000:lead<00:02.00>x]\n[x-romanized:2000:x]\n[00:03]Tres\n[x-translated-words:3000:<00:03.00><00:03.50>y]\n[x-translated:3000:y]\n[00:04]Cuatro\n[x-translated-words:4000:<00:04.50>b<00:04.00>a]\n[x-translated:4000:ba]\n[00:05]Cinco\n[x-translated-words:5000:<00:05.00>\\ <00:05.30> <00:05.40>w<00:05.90>]\n[x-translated:5000: w]\n[00:06]Seis\n[x-translated-words:6000:<00:06.00>p \\<00:06.20>q<00:06.80>]\n[x-translated:6000:p <00:06.20>q]" + }, + "expected": { + "synced": true, + "wordSynced": false, + "plainText": "Uno\nDos\nTres\nCuatro\nCinco\nSeis", + "writers": null, + "provider": null, + "lines": [ + { + "timeMs": 1000, + "endMs": null, + "text": "Uno", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": "a ]b \n c \\ d \\x ", + "voice": null, + "isBackground": false, + "vocalGroup": 0 + }, + { + "timeMs": 2000, + "endMs": null, + "text": "Dos", + "words": [], + "romanization": "x", + "romanizationWords": [], + "translation": null, + "voice": null, + "isBackground": false, + "vocalGroup": 1 + }, + { + "timeMs": 3000, + "endMs": null, + "text": "Tres", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": "y", + "voice": null, + "isBackground": false, + "vocalGroup": 2 + }, + { + "timeMs": 4000, + "endMs": null, + "text": "Cuatro", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": "ba", + "voice": null, + "isBackground": false, + "vocalGroup": 3 + }, + { + "timeMs": 5000, + "endMs": null, + "text": "Cinco", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": " w", + "voice": null, + "isBackground": false, + "vocalGroup": 4 + }, + { + "timeMs": 6000, + "endMs": null, + "text": "Seis", + "words": [], + "romanization": null, + "romanizationWords": [], + "translation": "p <00:06.20>q", + "translationWords": [ + { + "timeMs": 6000, + "endMs": 6800, + "text": "p <00:06.20>q" + } + ], + "voice": null, + "isBackground": false, + "vocalGroup": 5 + } + ] + } } ] diff --git a/test/lyric_supplement_tags_test.dart b/test/lyric_supplement_tags_test.dart new file mode 100644 index 000000000..63ae6ac54 --- /dev/null +++ b/test/lyric_supplement_tags_test.dart @@ -0,0 +1,90 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; +import 'package:mornye/utils/lyrics_parser.dart'; + +LyricWord _word(String text, int start, int end) => LyricWord( + time: Duration(milliseconds: start), + end: Duration(milliseconds: end), + text: text, +); + +List<(String, int, int?)> _spans(List words) => [ + for (final word in words) + (word.text, word.time.inMilliseconds, word.end?.inMilliseconds), +]; + +void main() { + test('text is written as it reads and comes back the same', () { + const text = 'Line ]one\nline \\two <3'; + final row = lyricSupplementRow( + 'translation', + 1000, + encodeLyricTextTag(text), + ); + expect(row, r'[x-translated:1000:Line ]one\nline \\two <3]'); + final tag = readLyricSupplementTag(row)!; + expect((tag.kind, tag.key, tag.text), ('translation', 1000, text)); + expect(encodeLyricTextTag('a\r\nb\rc'), r'a\nb\nc'); + }); + + test('word timing is enhanced LRC with its gaps and last end', () { + final words = [ + _word('Hel', 1000, 1300), + _word('lo ', 1300, 1600), + _word('there', 1800, 2009), + ]; + final value = encodeLyricWordsTag(words); + expect( + value, + r'<00:01.00>Hel<00:01.30>lo \<00:01.60><00:01.80>there<00:02.009>', + ); + final tag = readLyricSupplementTag( + lyricSupplementRow('romaji-words', 1000, value), + )!; + expect(tag.kind, 'romaji-words'); + expect(_spans(tag.words), _spans(words)); + }); + + test('a word without an end lasts until the next one starts', () { + expect(_spans(decodeLyricWordsTag('<00:01.00>a <00:01.50>b')), [ + ('a ', 1000, 1500), + ('b', 1500, 1500), + ]); + }); + + test('damaged word timing is dropped', () { + for (final value in [ + 'lead<00:01.00>a', + '<00:01.00><00:01.50>a', + '<00:02.00>a<00:01.00>b', + '<00:01.00>a<00:01.50> <00:02.00>b', + '<00:01.00>a<00:01.50><00:01.60><00:02.00>b', + ]) { + expect(decodeLyricWordsTag(value), isEmpty, reason: value); + } + expect(encodeLyricWordsTag([_word('a', 2000, 1000)]), isEmpty); + expect(encodeLyricWordsTag([_word(' ', 0, 1000)]), isEmpty); + }); + + test('base64 tags of earlier versions are still read', () { + String b64(String text) => base64.encode(utf8.encode(text)); + final text = readLyricSupplementTag('[x-romaji:1000:${b64(' Reading ')}]'); + expect((text!.kind, text.text), ('romaji', 'Reading')); + final words = readLyricSupplementTag( + '[x-translation-words:1000:${b64(jsonEncode([ + {'text': 'Hi', 'startTimeMs': 1000, 'endTimeMs': 1400}, + ]))}]', + ); + expect(words!.kind, 'translation-words'); + expect(_spans(words.words), [('Hi', 1000, 1400)]); + expect(readLyricSupplementTag('[x-translation:1000:%%%]')!.text, isNull); + }); + + test('other rows are not supplement tags', () { + expect(readLyricSupplementTag('[00:01.00]Line'), isNull); + expect(readLyricSupplementTag('[ti:Title]'), isNull); + expect(readLyricSupplementTag('[x-translated:bad:Text]'), isNull); + }); +} diff --git a/test/lyrics_draft_test.dart b/test/lyrics_draft_test.dart index 3cfda9fa9..0c3d956e2 100644 --- a/test/lyrics_draft_test.dart +++ b/test/lyrics_draft_test.dart @@ -12,7 +12,7 @@ void main() { '[ti:Example]', '[ar:Artist]', '[00:01.00]v1: <00:01.00>First <00:01.50>line', - '[x-translation:1000:${_b64('Primera')}]', + '[x-translated:1000:Primera]', '[bg:<00:01.20>(ooh)]', '[00:04.25]Second line', 'Written by: Someone', @@ -25,11 +25,34 @@ void main() { expect(draft.toLrc(), raw); }); + test('base64 tags of earlier versions are written as readable text', () { + final draft = LyricsDraft.parse( + [ + '[00:01.00]Line', + '[x-romaji:1000:${_b64('Rain')}]', + '[x-translation:1000:${_b64('Text ]\nnext \\ line')}]', + '[x-translation:1000:%%%]', + ].join('\n'), + ); + expect( + draft.toLrc(), + [ + '[00:01.00]Line', + '[x-romanized:1000:Rain]', + r'[x-translated:1000:Text ]\nnext \\ line]', + ].join('\n'), + ); + expect( + LyricsParser.parse(draft.toLrc()).lines.single.translation, + 'Text ]\nnext \\ line', + ); + }); + test('a moved line carries its word timing and translation key', () { final draft = LyricsDraft.parse( [ '[00:01.00]<00:01.00>First <00:01.50>line', - '[x-translation:1000:${_b64('Primera')}]', + '[x-translated:1000:Primera]', '[00:04.00]Second', ].join('\n'), ); @@ -43,7 +66,7 @@ void main() { moved.toLrc(), [ '[00:02.00]<00:02.00>First <00:02.50>line', - '[x-translation:2000:${_b64('Primera')}]', + '[x-translated:2000:Primera]', '[00:04.00]Second', ].join('\n'), ); @@ -56,6 +79,7 @@ void main() { }); test('a moved line carries its pronunciation and translation timing', () { + // Earlier versions' base64 JSON, written back readable. String words(int start) => _b64( jsonEncode([ {'text': 'Pri', 'startTimeMs': start, 'endTimeMs': start + 300}, @@ -86,10 +110,10 @@ void main() { moved.toLrc(), [ '[00:02.00]<00:02.00>First <00:02.50>line', - '[x-romaji-words:2000:${words(2000)}]', - '[x-romaji:2000:${_b64('Primera')}]', - '[x-translation-words:2000:${words(2000)}]', - '[x-translation:2000:${_b64('Primera')}]', + '[x-romanized-words:2000:<00:02.00>Pri<00:02.30>mera<00:02.60>]', + '[x-romanized:2000:Primera]', + '[x-translated-words:2000:<00:02.00>Pri<00:02.30>mera<00:02.60>]', + '[x-translated:2000:Primera]', ].join('\n'), ); final line = LyricsParser.parse(moved.toLrc()).lines.single; @@ -110,7 +134,8 @@ void main() { [ '[offset:500]', '[00:02.00]<00:02.00>Line', - '[x-translation:2000:${_b64('Linea')}]', + '[x-translated-words:2000:<00:02.00>Li<00:02.20>nea<00:02.80>]', + '[x-translated:2000:Linea]', ].join('\n'), ); expect(draft.lines.single.time, const Duration(milliseconds: 1500)); @@ -118,7 +143,8 @@ void main() { draft.toLrc(), [ '[00:01.50]<00:01.50>Line', - '[x-translation:1500:${_b64('Linea')}]', + '[x-translated-words:1500:<00:01.50>Li<00:01.70>nea<00:02.30>]', + '[x-translated:1500:Linea]', ].join('\n'), ); }); diff --git a/test/lyrics_sidecar_test.dart b/test/lyrics_sidecar_test.dart index 508a1e556..156bb6913 100644 --- a/test/lyrics_sidecar_test.dart +++ b/test/lyrics_sidecar_test.dart @@ -9,16 +9,14 @@ import 'package:mornye/services/lyrics_sidecar.dart'; import 'package:mornye/services/lyrics_translation.dart'; import 'package:mornye/services/source_metadata_events.dart'; import 'package:mornye/utils/desktop_platform.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; import 'package:mornye/utils/lyrics_parser.dart'; String _encoded(String text) => base64.encode(utf8.encode(text)); Future _parse(String? raw) async => LyricsParser.parse(raw); -final _translationWords = jsonEncode([ - {'text': 'Hola ', 'startTimeMs': 1000, 'endTimeMs': 1400}, - {'text': 'mundo', 'startTimeMs': 1400, 'endTimeMs': 2000}, -]); +const _translationWords = '<00:01.00>Hola <00:01.40>mundo<00:02.00>'; ParsedLyrics _translated(ParsedLyrics lyrics, List translations) => applyLyricsTranslation( @@ -73,12 +71,12 @@ void main() { final mlrc = buildMlrc(raw: raw, shown: shown); expect( mlrc, - '[x-mlrc:1]\n' + '[x-mlrc:2]\n' '[ti:Song]\n' '[00:01.00]Hola\n' - '[x-translation:1000:${_encoded('Hello')}]\n' + '[x-translated:1000:Hello]\n' '[00:02.00]Mundo\n' - '[x-translation:2000:${_encoded('World')}]\n', + '[x-translated:2000:World]\n', ); final read = await readMlrc(mlrc, _parse); expect(read.lines.map((line) => line.translation), ['Hello', 'World']); @@ -138,11 +136,11 @@ void main() { ); expect( mlrc, - '[x-mlrc:1]\n' + '[x-mlrc:2]\n' '[00:01.00]v2: <00:01.00>Hello <00:01.50>world<00:02.00>\n' - '[x-romaji:1000:${_encoded('Hello world')}]\n' - '[x-translation-words:1000:${_encoded(_translationWords)}]\n' - '[x-translation:1000:${_encoded('Hola mundo')}]\n' + '[x-romanized:1000:Hello world]\n' + '[x-translated-words:1000:$_translationWords]\n' + '[x-translated:1000:Hola mundo]\n' '[bg:<00:01.20>ooh<00:01.60>]\n', ); final read = await readMlrc(mlrc, _parse); @@ -154,7 +152,7 @@ void main() { ]); expect(read.lines.first.translation, 'Hola mundo'); expect( - lyricWordsSupplement(read.lines.first.translationWords), + encodeLyricWordsTag(read.lines.first.translationWords), _translationWords, ); expect(read.lines.last.isBackground, isTrue); @@ -173,11 +171,11 @@ void main() { final mlrc = buildMlrc(raw: 'Hola\n\nMundo', shown: shown); expect( mlrc, - '[x-mlrc:1]\n' + '[x-mlrc:2]\n' 'Hola\n' - '[x-translation:0:${_encoded('Hello')}]\n' + '[x-translated:0:Hello]\n' 'Mundo\n' - '[x-translation:1:${_encoded('World')}]\n', + '[x-translated:1:World]\n', ); final read = await readMlrc(mlrc, _parse); expect(read.synced, isFalse); @@ -364,8 +362,7 @@ void main() { _translated(metadata.lyrics, ['Hello']), preferSidecar: false, ); - final tagged = - '[00:01.00]Hola\n[x-translation:1000:${_encoded('Hello')}]'; + const tagged = '[00:01.00]Hola\n[x-translated:1000:Hello]'; expect(target, LyricsSaveTarget.songFile); expect(lrcFile.files[_source], tagged); expect(metadata.rawLyrics, tagged); @@ -378,6 +375,7 @@ void main() { expect(saved, isEmpty); }); + // Version 1 files, with base64 tags, are still read. test('shows what the .mlrc file saved over the song', () async { final sidecar = _MemorySidecar() ..files[_source] = @@ -433,12 +431,11 @@ void main() { _translated(metadata.lyrics, ['Hello']), preferSidecar: preferSidecar, ); - final tagged = - '[00:01.00]Hola\n[x-translation:1000:${_encoded('Hello')}]'; + const tagged = '[00:01.00]Hola\n[x-translated:1000:Hello]'; if (preferSidecar) { expect(target, LyricsSaveTarget.sidecar); expect(saved, isEmpty); - expect(sidecar.files[_source], '[x-mlrc:1]\n$tagged\n'); + expect(sidecar.files[_source], '[x-mlrc:2]\n$tagged\n'); expect(metadata.rawLyrics, '[00:01.00]Hola'); } else { expect(target, LyricsSaveTarget.songFile); @@ -471,9 +468,9 @@ void main() { _translated(metadata.lyrics, ['New']), preferSidecar: false, ); - final tagged = '[00:01.00]Hola\n[x-translation:1000:${_encoded('New')}]'; + const tagged = '[00:01.00]Hola\n[x-translated:1000:New]'; expect(saved, [tagged]); - expect(sidecar.files[_source], '[x-mlrc:1]\n$tagged\n'); + expect(sidecar.files[_source], '[x-mlrc:2]\n$tagged\n'); expect(metadata.lyrics.lines.single.translation, 'New'); }); @@ -498,7 +495,7 @@ void main() { ); expect( sidecar.files[_source], - '[x-mlrc:1]\nHola\n[x-translation:0:${_encoded('Hello')}]\n', + '[x-mlrc:2]\nHola\n[x-translated:0:Hello]\n', ); expect(metadata.lyrics.lines.single.translation, 'Hello'); } else { diff --git a/test/lyrics_translation_editor_sheet_test.dart b/test/lyrics_translation_editor_sheet_test.dart index f888c2516..414b49e01 100644 --- a/test/lyrics_translation_editor_sheet_test.dart +++ b/test/lyrics_translation_editor_sheet_test.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'package:audio_service/audio_service.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -127,13 +125,11 @@ void main() { ); await tester.pumpAndSettle(); - String tag(int ms, String text) => - '[x-translation:$ms:${base64.encode(utf8.encode(text))}]'; expect(saved, [ ( '/music/Album/song.flac', '[00:00.00]Hello there\n' - '${tag(0, 'سلام')}\n' + '[x-translated:0:سلام]\n' '[00:03.00]Second line', ), ]); @@ -240,11 +236,8 @@ void main() { await tester.pumpAndSettle(); expect(saved.length, 1); - expect(saved.single.$2, contains(base64.encode(utf8.encode('سلام تازه')))); - expect( - saved.single.$2, - isNot(contains(base64.encode(utf8.encode('سلام قدیمی')))), - ); + expect(saved.single.$2, contains('[x-translated:0:سلام تازه]')); + expect(saved.single.$2, isNot(contains('سلام قدیمی'))); // The cache now holds the edit, so the old AI text cannot come back. final stored = await cache.read(key); expect(stored?.translations, ['سلام تازه', 'خط دوم']); diff --git a/test/lyrics_translation_test.dart b/test/lyrics_translation_test.dart index 114f5f49e..0e2e56413 100644 --- a/test/lyrics_translation_test.dart +++ b/test/lyrics_translation_test.dart @@ -7,6 +7,7 @@ import 'package:http/testing.dart'; import 'package:mornye/services/lyrics_ai_client.dart'; import 'package:mornye/services/lyrics_translation.dart'; import 'package:mornye/services/lyrics_translation_alignment.dart'; +import 'package:mornye/utils/lyric_supplement_tags.dart'; import 'package:mornye/utils/lyrics_parser.dart'; ParsedLyrics _lyrics(List texts, {int offsetMs = 0}) => ParsedLyrics( @@ -294,12 +295,9 @@ void main() { final updated = lyricsWithTranslations(raw, shown)!; expect(updated, startsWith('[ti:Song]\n')); expect(updated, contains('[00:02.50]<00:02.50>Mundo <00:03.00>bello')); - expect(updated, contains('[x-translation:1000:${encoded('Hello')}]')); - expect( - updated, - contains('[x-translation:2500:${encoded('Beautiful world')}]'), - ); - expect(updated, contains('[x-translation:4000:${encoded('Hello')}]')); + expect(updated, contains('[x-translated:1000:Hello]')); + expect(updated, contains('[x-translated:2500:Beautiful world]')); + expect(updated, contains('[x-translated:4000:Hello]')); final reread = LyricsParser.parse(updated); expect(reread.lines.map((line) => line.text), [ @@ -319,6 +317,7 @@ void main() { }); test('replaces an older translation in place and keeps the rest', () { + // Base64 tags of earlier versions, written back readable. final raw = '[00:01.00]Bonjour\n' '[x-romaji:1000:${encoded('bonjour')}]\n' @@ -332,8 +331,8 @@ void main() { expect( updated, '[00:01.00]Bonjour\n' - '[x-romaji:1000:${encoded('bonjour')}]\n' - '[x-translation:1000:${encoded('Hello')}]\n' + '[x-romanized:1000:bonjour]\n' + '[x-translated:1000:Hello]\n' '[00:02.00]Merci', ); }); @@ -353,8 +352,8 @@ void main() { expect( updated, '[00:01.00]こんにちは\n' - '[x-romaji:1000:${encoded('konnichiwa')}]\n' - '[x-translation:1000:${encoded('Hi')}]\n' + '[x-romanized:1000:konnichiwa]\n' + '[x-translated:1000:Hi]\n' '[00:02.00]Hello', ); final reread = LyricsParser.parse(updated); @@ -379,11 +378,8 @@ void main() { ), ], ); - final words = lyricWordsSupplement(timed.romanizationWords); - expect(jsonDecode(words), [ - {'text': 'konnichi ', 'startTimeMs': 1000, 'endTimeMs': 1400}, - {'text': 'wa', 'startTimeMs': 1400, 'endTimeMs': 1800}, - ]); + final words = encodeLyricWordsTag(timed.romanizationWords); + expect(words, '<00:01.00>konnichi <00:01.40>wa<00:01.80>'); final withWords = lyricsWithTranslations( updated, ParsedLyrics( @@ -393,9 +389,9 @@ void main() { plainText: 'こんにちは', ), )!; - expect(withWords, contains('[x-romaji-words:1000:${encoded(words)}]')); - expect(withWords, contains('[x-romaji:1000:${encoded('konnichi wa')}]')); - expect(withWords, isNot(contains(encoded('konnichiwa')))); + expect(withWords, contains('[x-romanized-words:1000:$words]')); + expect(withWords, contains('[x-romanized:1000:konnichi wa]')); + expect(withWords, isNot(contains('konnichiwa'))); final reworded = lyricsWithTranslations( withWords, ParsedLyrics( @@ -411,7 +407,7 @@ void main() { plainText: 'こんにちは', ), )!; - expect(reworded, isNot(contains('x-romaji-words'))); + expect(reworded, isNot(contains('x-romanized-words'))); }); test('keeps AI translation word timing through a save', () { @@ -442,10 +438,10 @@ void main() { expect(lyricsTranslationUnsaved(lyrics, shown), isTrue); final updated = lyricsWithTranslations(raw, shown)!; - final words = lyricWordsSupplement(timing); - expect(updated, contains('[x-translation-words:1500:${encoded(words)}]')); + final words = encodeLyricWordsTag(timing); + expect(updated, contains('[x-translated-words:1500:$words]')); final reread = LyricsParser.parse(updated); - expect(lyricWordsSupplement(reread.lines.first.translationWords), words); + expect(encodeLyricWordsTag(reread.lines.first.translationWords), words); expect(reread.lines.last.translationWords, isEmpty); // Shown again over the saved file, nothing is left to save. expect(lyricsTranslationUnsaved(reread, display(reread)), isFalse); @@ -453,7 +449,7 @@ void main() { // The file without the timing still needs it saved. final untimed = LyricsParser.parse( - updated.replaceFirst(RegExp(r'\[x-translation-words:[^\]]*\]\n'), ''), + updated.replaceFirst(RegExp(r'\[x-translated-words:[^\]]*\]\n'), ''), ); expect(untimed.lines.first.translation, 'Hello world'); expect(lyricsTranslationUnsaved(untimed, display(untimed)), isTrue); @@ -468,8 +464,8 @@ void main() { plainText: 'Hola mundo', ), )!; - expect(retranslated, isNot(contains('x-translation-words'))); - expect(retranslated, contains(encoded('Hi world'))); + expect(retranslated, isNot(contains('x-translated-words'))); + expect(retranslated, contains(':Hi world]')); }); test('translates lyrics without timing line by line', () { @@ -530,8 +526,8 @@ void main() { edited, clearMissingTranslations: true, )!; - expect(updated, isNot(contains(encoded('Hello')))); - expect(updated, contains('[x-translation:2000:${encoded('Thanks')}]')); + expect(updated, isNot(contains('Hello'))); + expect(updated, contains('[x-translated:2000:Thanks]')); final reread = LyricsParser.parse(updated); expect(reread.lines.map((line) => line.translation), [null, 'Thanks']); }); diff --git a/test/lyrics_translation_ui_test.dart b/test/lyrics_translation_ui_test.dart index 490c96d9b..090f9d3ad 100644 --- a/test/lyrics_translation_ui_test.dart +++ b/test/lyrics_translation_ui_test.dart @@ -722,8 +722,7 @@ void main() { await tester.tap(find.text('Save Translation to File')); await tester.pumpAndSettle(); - String tag(int ms, String text) => - '[x-translation:$ms:${base64.encode(utf8.encode(text))}]'; + String tag(int ms, String text) => '[x-translated:$ms:$text]'; expect(saved, [ ( '/music/Album/song.flac', @@ -752,8 +751,7 @@ void main() { }); } - String tag(String kind, int key, String text) => - '[x-$kind:$key:${base64.encode(utf8.encode(text))}]'; + String tag(int key, String text) => '[x-translated:$key:$text]'; Future< ({ @@ -870,11 +868,11 @@ void main() { expect(saved, isEmpty); expect(sidecar.files, { '/music/Album/song.flac': - '[x-mlrc:1]\n' + '[x-mlrc:2]\n' 'Hello there\n' - '${tag('translation', 0, 'de:Hello there')}\n' + '${tag(0, 'de:Hello there')}\n' 'Second line\n' - '${tag('translation', 1, 'de:Second line')}\n', + '${tag(1, 'de:Second line')}\n', }); expect(metadata.lyrics.lines.map((line) => line.translation), [ 'de:Hello there', @@ -917,11 +915,11 @@ void main() { expect(sidecar.files, { '/music/Album/song.flac': - '[x-mlrc:1]\n' + '[x-mlrc:2]\n' '[00:00.00]Hello there\n' - '${tag('translation', 0, 'de:Hello there')}\n' + '${tag(0, 'de:Hello there')}\n' '[00:03.00]Second line\n' - '${tag('translation', 3000, 'de:Second line')}\n', + '${tag(3000, 'de:Second line')}\n', }); expect(saved, isEmpty); // An automatic save stays quiet.