-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlyrics.ts
More file actions
759 lines (701 loc) Β· 25.4 KB
/
Copy pathlyrics.ts
File metadata and controls
759 lines (701 loc) Β· 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import { invoke } from "@tauri-apps/api/core";
export type LyricsFormat = "plain" | "lrc" | "enhanced_lrc" | "ttml";
export type LyricsSource = "embedded" | "lrc_file" | "api" | "manual";
/**
* Sub-provider identifier returned by the backend on API-sourced rows.
* Matches `waveflow_syncedlyrics::Provider::as_str()`. Pre-1.5.1 cached
* rows AND non-API tiers (embedded / sidecar / manual) leave the field
* `null` β the UI then renders the broad `source` label without a
* provider chip.
*/
export type LyricsProvider =
"lrclib" | "genius" | "net_ease" | "megalobiz" | "musixmatch";
/**
* Stable list of providers the picker UI cycles through. Mirrors
* `Provider::defaults()` order on the backend β Musixmatch first
* because it's the only word-timed source, then LRCLIB, then the
* query-based fallbacks. `refetchLyrics` accepts any of these
* strings as the override; an `undefined` override re-runs the full
* waterfall.
*/
export const LYRICS_PROVIDERS: LyricsProvider[] = [
"musixmatch",
"lrclib",
"net_ease",
"megalobiz",
"genius",
];
export interface LyricsPayload {
track_id: number;
content: string;
format: LyricsFormat;
source: LyricsSource;
/**
* Sub-provider that produced this row when `source === "api"`. One
* of `LYRICS_PROVIDERS`, or `null` / absent for embedded / sidecar
* / manual / pre-1.5.1 rows. The lyrics panel reads this to render
* an accurate badge (e.g. "Genius" instead of the hardcoded
* "LRCLIB" the panel previously always showed) and to drive the
* default selection of the provider picker.
*/
provider?: LyricsProvider | null;
/**
* Set by `save_lyrics` when the user picked destination = `"tag"`
* but the audio container can't carry the chosen format (currently
* TTML on MP3/ID3v2). The DB cache is still updated; the UI
* surfaces a toast so the user knows the file itself wasn't
* touched. Absent on every other return path.
*/
tag_write_skipped?: boolean;
/**
* Set by `save_lyrics` when the user picked destination = `"sidecar"`
* but the chosen format can't ride a `.lrc` / `.txt` companion
* (TTML β neither extension carries the XML markup the reader
* expects). DB cache is still updated. Absent on every other return
* path.
*/
sidecar_write_skipped?: boolean;
}
/** Cache-only lookup. Returns null when no row exists yet. */
export function getLyrics(trackId: number): Promise<LyricsPayload | null> {
return invoke<LyricsPayload | null>("get_lyrics", { trackId });
}
/**
* Three-tier lookup: cache β embedded tag β LRCLIB.
* Caches the first hit. Returns null if every tier failed.
*/
export function fetchLyrics(trackId: number): Promise<LyricsPayload | null> {
return invoke<LyricsPayload | null>("fetch_lyrics", { trackId });
}
/**
* Fetch + cache lyrics for a now-playing Web Radio song.
*
* Radio has no library row (negative sentinel id, live stream), so the
* regular `fetchLyrics` waterfall can't help β this keys a dedicated
* `radio_lyrics` cache by the (artist, title) parsed from the ICY title
* and queries the external providers. `trackId` is the radio sentinel id
* (echoed into the payload, never a cache key). Returns null when the
* song has no lyrics, when offline with nothing cached, or on a
* transient provider error. The lyrics may be synced (LRC) but the panel
* renders them statically β the live stream position can't align to a
* song the listener joined mid-play.
*/
export function fetchRadioLyrics(
artist: string,
title: string,
trackId: number,
): Promise<LyricsPayload | null> {
return invoke<LyricsPayload | null>("fetch_radio_lyrics", {
artist,
title,
trackId,
});
}
/**
* Force a re-fetch for a single track, dropping the cached row first
* so the waterfall (or single-provider query below) is guaranteed to
* re-query.
*
* - `provider = undefined` β re-runs the full waterfall identical to
* the legacy "Clear + Refetch" gesture.
* - `provider = "<id>"` β bypasses local tiers (embedded / sidecar)
* and queries ONLY the named provider. A miss caches an empty row
* attributed to the requested provider so the badge reflects what
* the user just tried β picking a different provider and trying
* again is then the natural next step (issue #284).
*/
export function refetchLyrics(
trackId: number,
provider?: LyricsProvider,
): Promise<LyricsPayload | null> {
return invoke<LyricsPayload | null>("refetch_lyrics", {
trackId,
provider: provider ?? null,
});
}
/**
* Read a `.lrc` (or text) file from disk and store it as the track's
* lyrics, replacing whatever was cached. Format is detected from the
* content (LRC if it has `[mm:ssβ¦]` timestamps).
*/
export function importLrcFile(
trackId: number,
filePath: string,
): Promise<LyricsPayload> {
return invoke<LyricsPayload>("import_lrc_file", { trackId, filePath });
}
/** Drop the cached lyrics row so the next fetch re-runs the waterfall. */
export function clearLyrics(trackId: number): Promise<void> {
return invoke<void>("clear_lyrics", { trackId });
}
/**
* Write a serialized lyrics payload (already trimmed + format-encoded)
* to an arbitrary on-disk path. Used by the Lyrics Editor "Save to
* fileβ¦" affordance so the user can ship the LRC/TXT as a sidecar
* next to the song file (the in-tag + cache-only options stay
* available via the existing `saveLyrics` flow). The caller is
* expected to resolve `targetPath` via the Tauri save dialog
* (`@tauri-apps/plugin-dialog`'s `save()`); the backend re-validates
* the parent directory exists before writing.
*/
export function exportLyricsToPath(
targetPath: string,
content: string,
): Promise<void> {
return invoke<void>("export_lyrics_to_path", {
targetPath,
content,
});
}
/**
* Read the per-profile Musixmatch translation target language.
* `null` when the user hasn't opted in β the lyrics fetch waterfall
* then runs without translation enrichment.
*/
export function getLyricsTranslationLang(): Promise<string | null> {
return invoke<string | null>("get_lyrics_translation_lang");
}
/**
* Persist the per-profile Musixmatch translation target language.
* Pass `null` to clear (default: no translation). The backend
* whitelists the value against the WaveFlow UI locale set; passing
* anything else rejects with an error so a typo can't silently
* disable the feature.
*/
export function setLyricsTranslationLang(
lang: string | null,
): Promise<string | null> {
return invoke<string | null>("set_lyrics_translation_lang", { lang });
}
/**
* Read the per-profile "prefer LRCLIB" flag. `true` makes the on-demand
* lyrics waterfall try the online providers (LRCLIB / Musixmatch / the
* fallback chain) before the track's own embedded + sidecar lyrics
* (issue #378). Default `false` β local lyrics win.
*/
export function getPreferLrclib(): Promise<boolean> {
return invoke<boolean>("get_prefer_lrclib");
}
/**
* Persist the per-profile "prefer LRCLIB" flag. `false` clears the row
* and restores the local-first default.
*/
export function setPreferLrclib(enabled: boolean): Promise<void> {
return invoke<void>("set_prefer_lrclib", { enabled });
}
/**
* Where the user wants the editor's output to land. The frontend
* pre-fills the segmented control with the app-wide default
* (`getLyricsDefaultDestination`) and lets the user override
* per-save. Backend mirrors the enum in `LyricsDestination`.
*/
export type LyricsDestination = "tag" | "sidecar" | "db_only";
export interface SaveLyricsPayload {
content: string;
format: "plain" | "lrc" | "enhanced_lrc" | "ttml";
/**
* `tag` embeds in USLT/LYRICS/Β©lyr (current default, TTML silently
* skipped on MP3 β see `tag_write_skipped`). `sidecar` writes a
* sibling `.lrc` / `.txt` next to the audio file (issue #201).
* `db_only` updates the WaveFlow cache and leaves the filesystem
* untouched.
*/
destination: LyricsDestination;
}
/**
* Persist user-edited lyrics for a track. Always upserts the cache
* row (source = manual); the on-disk side-effect depends on
* `destination`.
*/
export function saveLyrics(
trackId: number,
payload: SaveLyricsPayload,
): Promise<LyricsPayload> {
return invoke<LyricsPayload>("save_lyrics", { trackId, payload });
}
/**
* Read the app-wide default destination the editor pre-fills with.
* Missing setting β `"tag"` so pre-#201 behaviour is preserved.
*/
export function getLyricsDefaultDestination(): Promise<LyricsDestination> {
return invoke<LyricsDestination>("get_lyrics_default_destination");
}
/**
* Persist the app-wide default destination. Backend rejects unknown
* values; the caller should pass one of the three enum variants
* literally.
*/
export function setLyricsDefaultDestination(
destination: LyricsDestination,
): Promise<LyricsDestination> {
return invoke<LyricsDestination>("set_lyrics_default_destination", {
destination,
});
}
/**
* Format a millisecond timestamp as `<open>mm:ss.xx<close>`.
* Centisecond precision matches Musicolet / LRCLIB output. Used with
* `[` / `]` for LRC line stamps and `<` / `>` for Enhanced LRC inline
* word stamps β picking the delimiters up-front avoids string-replace
* round-trips on a known-good output.
*/
function formatTimestamp(timeMs: number, open: string, close: string): string {
const safe = Math.max(0, Math.floor(timeMs));
const minutes = Math.floor(safe / 60_000);
const seconds = Math.floor((safe % 60_000) / 1000);
const centis = Math.floor((safe % 1000) / 10);
const mm = minutes.toString().padStart(2, "0");
const ss = seconds.toString().padStart(2, "0");
const cc = centis.toString().padStart(2, "0");
return `${open}${mm}:${ss}.${cc}${close}`;
}
/**
* Format a millisecond timestamp as the LRC `[mm:ss.xx]` tag.
* Centisecond precision matches Musicolet / LRCLIB output.
*/
export function formatLrcTimestamp(timeMs: number): string {
return formatTimestamp(timeMs, "[", "]");
}
/**
* Serialize an array of `{ timeMs, text }` rows back into LRC text.
* Lines without a captured timestamp (timeMs < 0) are emitted with
* the placeholder `[--:--.--]` so the user can revisit them.
*/
export function serializeLrc(
rows: Array<{ timeMs: number; text: string }>,
): string {
return rows
.map((row) => {
const stamp =
row.timeMs < 0 ? "[--:--.--]" : formatLrcTimestamp(row.timeMs);
return `${stamp}${row.text}`;
})
.join("\n");
}
export interface LyricsPrefetchProgress {
processed: number;
total: number;
hits: number;
misses: number;
failed: number;
current_title: string | null;
}
export interface LyricsPrefetchSummary {
processed: number;
hits: number;
misses: number;
failed: number;
cancelled: boolean;
}
/**
* Walk every uncached track in the active profile and try to populate
* its lyric (embedded β LRCLIB, throttled at ~2 req/s). Emits
* `lyrics:prefetch-progress` events the UI can render as a progress
* bar. Resolves with a summary once the run finishes (or is cancelled).
*/
export function prefetchLibraryLyrics(): Promise<LyricsPrefetchSummary> {
return invoke<LyricsPrefetchSummary>("prefetch_library_lyrics");
}
/** Flip the prefetch cancel flag. Returns `true` if one was running. */
export function cancelLyricsPrefetch(): Promise<boolean> {
return invoke<boolean>("cancel_lyrics_prefetch");
}
// ββ Lyrics parsers (LRC + Enhanced LRC + TTML) ββββββββββββββββββββββ
/**
* One karaoke word within a synchronized line. `endMs` is the
* timestamp at which the next word becomes active β for the last word
* of a line it falls back to the next line's `timeMs` (or +β on the
* very last line).
*/
export interface LyricsWord {
timeMs: number;
endMs: number;
text: string;
}
/**
* Unified line type returned by every parser. Components that don't
* care about word-level timing can ignore `words`; the karaoke view
* uses it when present to drive the per-word highlight animation.
*
* Kept structurally compatible with the legacy `LrcLine` shape so
* existing call sites (`findActiveLineIndex`, panel scroll, etc.)
* keep working without per-call casts.
*/
export interface LyricsLine {
timeMs: number;
/** End of this line in ms. -1 if unknown (e.g. last line). */
endMs: number;
/** Plain text β for word-timed lines, this is the joined word text. */
text: string;
/** Per-word timestamps when the source format provides them. */
words?: LyricsWord[];
}
/** Backwards-compatible alias used across the panel + fullscreen views. */
export type LrcLine = LyricsLine;
const LRC_LINE_STAMP_RE = /\[(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?\]/g;
const LRC_WORD_STAMP_RE = /<(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?>/g;
/** `mm:ss(.xx|:xx)?` β ms. Pads fractions to 3 digits then truncates. */
function lrcStampToMs(
minutes: string,
seconds: string,
fraction?: string,
): number {
const m = Number(minutes);
const s = Number(seconds);
const fracMs = Number((fraction ?? "0").padEnd(3, "0").slice(0, 3));
return m * 60_000 + s * 1000 + fracMs;
}
/**
* Parse a plain LRC string (line-level timestamps only) into a sorted
* list of `LyricsLine`. Lines without a timestamp are dropped; a
* single text line carrying multiple timestamps yields multiple
* entries. Returns an empty array when no stamps are found β the
* caller should fall back to plain rendering.
*/
export function parseLrc(content: string): LyricsLine[] {
const out: LyricsLine[] = [];
for (const raw of content.split(/\r?\n/)) {
LRC_LINE_STAMP_RE.lastIndex = 0;
const stamps: number[] = [];
let match: RegExpExecArray | null;
while ((match = LRC_LINE_STAMP_RE.exec(raw)) !== null) {
stamps.push(lrcStampToMs(match[1], match[2], match[3]));
}
if (stamps.length === 0) continue;
const text = raw.replace(LRC_LINE_STAMP_RE, "").trim();
for (const timeMs of stamps) {
out.push({ timeMs, endMs: -1, text });
}
}
out.sort((a, b) => a.timeMs - b.timeMs);
return fillEndTimestamps(out);
}
/**
* Parse Enhanced LRC (`[mm:ss.xx]La <mm:ss.xx>nuit <mm:ss.xx>tombe`).
* Each line keeps its line-level `timeMs` and gets a `words[]` array
* with one entry per `<mm:ss.xx>word` token. A line with stamps but
* no inline word stamps gracefully degrades to the plain LRC layout
* (no `words` field).
*/
export function parseEnhancedLrc(content: string): LyricsLine[] {
const lines: LyricsLine[] = [];
for (const raw of content.split(/\r?\n/)) {
LRC_LINE_STAMP_RE.lastIndex = 0;
const lineStamps: number[] = [];
let m: RegExpExecArray | null;
while ((m = LRC_LINE_STAMP_RE.exec(raw)) !== null) {
lineStamps.push(lrcStampToMs(m[1], m[2], m[3]));
}
if (lineStamps.length === 0) continue;
const body = raw.replace(LRC_LINE_STAMP_RE, "");
LRC_WORD_STAMP_RE.lastIndex = 0;
const wordStamps: Array<{ at: number; timeMs: number }> = [];
let wm: RegExpExecArray | null;
while ((wm = LRC_WORD_STAMP_RE.exec(body)) !== null) {
wordStamps.push({
at: wm.index,
timeMs: lrcStampToMs(wm[1], wm[2], wm[3]),
});
}
if (wordStamps.length === 0) {
// Plain LRC line β keep the text as-is.
const text = body.trim();
for (const timeMs of lineStamps) {
lines.push({ timeMs, endMs: -1, text });
}
continue;
}
// Slice the body between consecutive word stamps to recover the
// word text. The slice from `wordStamps[i]` end to the next stamp
// start is the displayed word.
const built: LyricsWord[] = [];
// Any text before the first inline word stamp is sung at the
// line's own timestamp β common when a tool emits
// `[mm:ss]First <mm:ss>second`. Treat it as a virtual leading
// word; its timeMs is rewritten per-duplicate-line in the loop
// below so that `[00:01][00:30]Hello <00:31>world` doesn't make
// every clone inherit the same first-word time.
const prefix = body.slice(0, wordStamps[0].at);
const hasPrefix = prefix.length > 0 && prefix.trim().length > 0;
if (hasPrefix) {
built.push({
timeMs: -1, // placeholder, set per-line below
endMs: wordStamps[0].timeMs,
text: prefix,
});
}
for (let i = 0; i < wordStamps.length; i += 1) {
const start =
wordStamps[i].at + matchedStampLength(body, wordStamps[i].at);
const end =
i + 1 < wordStamps.length ? wordStamps[i + 1].at : body.length;
built.push({
timeMs: wordStamps[i].timeMs,
endMs: i + 1 < wordStamps.length ? wordStamps[i + 1].timeMs : -1,
text: body.slice(start, end),
});
}
// Drop trailing empty segments without timing (artefact of a
// trailing space after the last stamp).
const words = built.filter((w) => w.text.length > 0 || w.timeMs >= 0);
const text = words
.map((w) => w.text)
.join("")
.trim();
// Deep-clone the words array per line entry so `fillEndTimestamps`
// can mutate each independently. For prefix-bearing lines, the
// virtual first word inherits the current line stamp instead of a
// shared placeholder.
for (const timeMs of lineStamps) {
const clonedWords = words.map((w, idx) => ({
...w,
timeMs: hasPrefix && idx === 0 ? timeMs : w.timeMs,
}));
lines.push({ timeMs, endMs: -1, text, words: clonedWords });
}
}
lines.sort((a, b) => a.timeMs - b.timeMs);
return fillEndTimestamps(lines);
}
/** Length of the `<mm:ss(.xx)?>` token starting at `at` in `body`. */
function matchedStampLength(body: string, at: number): number {
const close = body.indexOf(">", at);
return close < 0 ? 0 : close - at + 1;
}
/**
* Parse Apple-Music-style TTML. Walks `<p>` for lines and `<span>` for
* words. `begin`/`end` accept `HH:MM:SS.mmm`, `MM:SS.mmm`, plain
* seconds (`12.5s`), or a bare number of seconds.
*
* Char-level spans (TTML lets `<span>` nest inside `<span>`) are
* collapsed into the outer word β we don't animate character-by-char
* in v1.
*
* Returns an empty array if the document has no parseable lines.
*/
export function parseTtml(content: string): LyricsLine[] {
if (typeof window === "undefined" || typeof DOMParser === "undefined") {
return [];
}
const doc = new DOMParser().parseFromString(content, "application/xml");
if (doc.querySelector("parsererror")) return [];
const out: LyricsLine[] = [];
const paragraphs = doc.getElementsByTagName("p");
for (let i = 0; i < paragraphs.length; i += 1) {
const p = paragraphs[i];
const lineBegin = parseTtmlTime(p.getAttribute("begin"));
if (lineBegin < 0) continue;
const lineEnd = parseTtmlTime(p.getAttribute("end"));
// Direct child <span>s are the words. Nested spans are folded into
// their parent's text so char-level timing collapses cleanly.
const wordEls: Element[] = [];
for (const child of Array.from(p.children)) {
if (child.tagName.toLowerCase() === "span") wordEls.push(child);
}
let words: LyricsWord[] | undefined;
let text: string;
if (wordEls.length > 0) {
words = [];
for (let w = 0; w < wordEls.length; w += 1) {
const el = wordEls[w];
const wBegin = parseTtmlTime(el.getAttribute("begin"));
const wEnd = parseTtmlTime(el.getAttribute("end"));
if (wBegin < 0) continue;
// Re-attach the trailing whitespace that TTML strips so words
// render with their natural spacing.
const raw = (el.textContent ?? "").replace(/\s+/g, " ");
const trailing = el.nextSibling?.nodeType === Node.TEXT_NODE ? " " : "";
words.push({
timeMs: wBegin,
endMs: wEnd >= 0 ? wEnd : -1,
text: raw + trailing,
});
}
if (words.length === 0) words = undefined;
text = (words ?? [])
.map((w) => w.text)
.join("")
.trim();
} else {
text = (p.textContent ?? "").replace(/\s+/g, " ").trim();
}
if (!text && (!words || words.length === 0)) continue;
out.push({
timeMs: lineBegin,
endMs: lineEnd >= 0 ? lineEnd : -1,
text,
words,
});
}
out.sort((a, b) => a.timeMs - b.timeMs);
return fillEndTimestamps(out);
}
/**
* Parse a TTML `begin`/`end` clock value into milliseconds. Accepts:
* - `HH:MM:SS.mmm`
* - `MM:SS.mmm` / `MM:SS`
* - `123.5s` (seconds, decimal allowed)
* - `1500ms`
* - bare seconds (`"5"` β 5000 ms)
* Returns -1 for null / empty / unparseable input.
*/
function parseTtmlTime(value: string | null): number {
if (value == null) return -1;
const s = value.trim();
if (!s) return -1;
if (s.endsWith("ms")) {
const n = Number(s.slice(0, -2));
return Number.isFinite(n) ? Math.round(n) : -1;
}
if (s.endsWith("s")) {
const n = Number(s.slice(0, -1));
return Number.isFinite(n) ? Math.round(n * 1000) : -1;
}
if (s.includes(":")) {
const parts = s.split(":");
if (parts.length === 2) {
const [mm, ss] = parts;
const m = Number(mm);
const sec = Number(ss);
if (Number.isFinite(m) && Number.isFinite(sec)) {
return Math.round(m * 60_000 + sec * 1000);
}
return -1;
}
if (parts.length === 3) {
const [hh, mm, ss] = parts;
const h = Number(hh);
const m = Number(mm);
const sec = Number(ss);
if (Number.isFinite(h) && Number.isFinite(m) && Number.isFinite(sec)) {
return Math.round(h * 3_600_000 + m * 60_000 + sec * 1000);
}
return -1;
}
return -1;
}
const n = Number(s);
return Number.isFinite(n) ? Math.round(n * 1000) : -1;
}
/**
* Fill each line's `endMs` with the next line's `timeMs` (and the last
* word of each line gets the line's `endMs`). Pure helper used by every
* parser so the karaoke view can interpolate without special-casing the
* last entry.
*/
function fillEndTimestamps(lines: LyricsLine[]): LyricsLine[] {
for (let i = 0; i < lines.length; i += 1) {
if (lines[i].endMs < 0) {
lines[i].endMs = i + 1 < lines.length ? lines[i + 1].timeMs : -1;
}
const words = lines[i].words;
if (words && words.length > 0) {
for (let w = 0; w < words.length; w += 1) {
if (words[w].endMs < 0) {
words[w].endMs =
w + 1 < words.length ? words[w + 1].timeMs : lines[i].endMs;
}
}
}
}
return lines;
}
/**
* Dispatcher consumed by every UI component. Picks the right parser
* for `format`. Plain text returns a single line at t=0 with no
* `words`. Unknown / empty content returns an empty array.
*/
export function parseLyrics(
content: string,
format: LyricsFormat,
): LyricsLine[] {
if (!content.trim()) return [];
switch (format) {
case "lrc":
return parseLrc(content);
case "enhanced_lrc":
return parseEnhancedLrc(content);
case "ttml":
return parseTtml(content);
case "plain":
default:
return [];
}
}
/**
* Serialize a list of word-stamped lines back to Enhanced LRC text.
* Lines without `words` fall back to a plain `[mm:ss.xx]` entry.
* Used by the editor when the user saves a word-timed track β TTML
* round-trip isn't part of v1, so we always export to Enhanced LRC.
*
* Words with `timeMs < 0` (not yet captured) are emitted **without**
* an inline stamp β their text is folded into the previous word so a
* half-finished line doesn't ship phantom `<00:00.00>word` stamps
* that would mis-sync on the next load. The user can re-open the
* editor and finish stamping later.
*/
export function serializeEnhancedLrc(lines: LyricsLine[]): string {
return lines
.map((line) => {
const stamp =
line.timeMs < 0 ? "[--:--.--]" : formatLrcTimestamp(line.timeMs);
if (!line.words || line.words.length === 0) {
return `${stamp}${line.text}`;
}
const parts: string[] = [];
for (const w of line.words) {
if (w.timeMs >= 0) {
parts.push(`${formatTimestamp(w.timeMs, "<", ">")}${w.text}`);
} else {
// Uncaptured β append the text to the previous segment so
// it survives the round-trip without acquiring a fake
// zero-second stamp.
if (parts.length > 0) {
parts[parts.length - 1] += w.text;
} else {
parts.push(w.text);
}
}
}
return `${stamp}${parts.join("")}`;
})
.join("\n");
}
/**
* Find the index of the line that should currently be highlighted
* given a playback position. Uses a simple linear-scan from the hint
* (the previous index) β synchronized lyrics rarely jump backwards
* mid-track so this is O(1) amortized.
*
* Returns `-1` when the position is before the first line.
*/
export function findActiveLineIndex(
lines: LyricsLine[],
positionMs: number,
hint = 0,
): number {
if (lines.length === 0 || positionMs < lines[0].timeMs) return -1;
// Walk forward from the hint until the next line's timestamp is in
// the future. Cap at lines.length - 1.
let i = Math.max(0, Math.min(hint, lines.length - 1));
// Walk backwards if the user seeked.
while (i > 0 && lines[i].timeMs > positionMs) i--;
while (i + 1 < lines.length && lines[i + 1].timeMs <= positionMs) i++;
return i;
}
/**
* Find the index of the active word within a line's `words` array
* given a playback position. Returns `-1` when the position is before
* the first word (so the line is highlighted but no word yet).
*/
export function findActiveWordIndex(
words: LyricsWord[],
positionMs: number,
hint = 0,
): number {
if (words.length === 0 || positionMs < words[0].timeMs) return -1;
let i = Math.max(0, Math.min(hint, words.length - 1));
while (i > 0 && words[i].timeMs > positionMs) i--;
while (i + 1 < words.length && words[i + 1].timeMs <= positionMs) i++;
return i;
}