// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2): src/utils/lyrics/estimatedLineTiming.ts, // the line-synced path of parserCore.ts (parseLRC, attachInterludes), chorusDetector.ts and // findLatestActiveLineIndex from appPlaybackHelpers.ts. // // The site's lyrics are line-synced (one stamp a line). Folia spreads each line's time over its words, ends a line // early when a long gap follows, and fills gaps with an interlude line of six dots. // // Changed from Folia: the input is the site's parsed stamps rather than LRC text, and a stamp with no words ends // the line before it (Folia skips such stamps and lets the line run to the next one with words). import type { Line, Word } from '../types'; import { splitGraphemes } from './graphemes'; import { buildLineRenderHints } from './renderHints'; export const INTERLUDE_FULL_TEXT = '......'; export const isInterludeLine = (line: Pick): boolean => line.fullText === INTERLUDE_FULL_TEXT; /** Spreads a line-synced lyric over evenly weighted tokens: one per CJK character, one per spaced word otherwise. */ export const buildTimedWords = (text: string, startTime: number, endTime: number): Word[] => { const duration = Math.max(endTime - startTime, 0.1); const rawTokens = text.split(/\s+/).filter(token => token); const words: Word[] = []; const tokens: Array<{ text: string; weight: number }> = []; let totalWeight = 0; for (const token of rawTokens) { if (/[一-龥぀-ヿ가-힯]/.test(token)) { // By grapheme, not UTF-16 unit: an emoji or a CJK Extension B character stays one token. splitGraphemes(token).forEach(char => { const isPunctuation = /[,。!?、:;"')]/.test(char); const weight = isPunctuation ? 0 : 1; tokens.push({ text: char, weight }); totalWeight += weight; }); } else { const weight = 1 + (token.length * 0.15); tokens.push({ text: token, weight }); totalWeight += weight; } } if (totalWeight === 0) totalWeight = 1; const activeDuration = duration * 0.9; const timePerWeight = activeDuration / totalWeight; let currentWordStart = startTime; tokens.forEach(token => { const wordDuration = token.weight * timePerWeight; const finalDuration = Math.max(wordDuration, 0.05); words.push({ text: token.text, startTime: currentWordStart, endTime: currentWordStart + finalDuration }); if (token.weight > 0) currentWordStart += wordDuration; else currentWordStart += 0.05; }); if (words.length > 0) { const lastWord = words[words.length - 1]; if (lastWord.endTime > endTime) { const scale = (endTime - startTime) / (lastWord.endTime - startTime); words.forEach(word => { word.startTime = startTime + ((word.startTime - startTime) * scale); word.endTime = startTime + ((word.endTime - startTime) * scale); }); } } return words; }; /** * End time of a line-synced line: the next stamp, but a line followed by a long gap ends after a reading-time * estimate so its sweep keeps a natural pace and the gap becomes an interlude. */ export const estimateLrcLineEndTime = (text: string, startTime: number, nextStartTime: number | undefined): number => { let duration = nextStartTime !== undefined ? nextStartTime - startTime : 5; const estimatedReadingTime = text.length * 0.5; if (duration > estimatedReadingTime + 2 && duration > 5) { duration = Math.min(duration, estimatedReadingTime + 2); } return startTime + duration; }; const createInterlude = (start: number, end: number): Line => { const wordDuration = (end - start) / 6; const words: Word[] = []; for (let index = 0; index < 6; index += 1) { words.push({ text: '.', startTime: start + (index * wordDuration), endTime: start + ((index + 1) * wordDuration) }); } return { startTime: start, endTime: end, fullText: INTERLUDE_FULL_TEXT, words }; }; export const attachInterludes = (lines: Line[]): Line[] => { const finalLines: Line[] = []; if (lines.length > 0 && lines[0].startTime > 3) { finalLines.push(createInterlude(0.5, lines[0].startTime - 0.5)); } for (let index = 0; index < lines.length; index += 1) { const current = lines[index]; finalLines.push(current); const next = lines[index + 1]; if (next) { const gap = next.startTime - current.endTime; if (gap > 3) finalLines.push(createInterlude(current.endTime + 0.05, next.startTime - 0.05)); } } return finalLines; }; /** The texts sung most often, when anything repeats: Folia takes those lines for the chorus. */ export const detectChorusTexts = (texts: string[]): Set => { const counts = new Map(); for (const raw of texts) { const text = raw.trim(); if (!text || text === INTERLUDE_FULL_TEXT || text.length < 2) continue; counts.set(text, (counts.get(text) ?? 0) + 1); } let maxCount = 0; counts.forEach(count => { if (count > maxCount) maxCount = count; }); const chorus = new Set(); if (maxCount <= 1) return chorus; counts.forEach((count, text) => { if (count === maxCount) chorus.add(text); }); return chorus; }; /** * The site's stamps (seconds and words, earliest first; a stamp without words only ends the line before it) as * Folia lines: timed words, interludes in the gaps, chorus marks and render hints. */ export const buildLinesFromStamps = (stamps: ReadonlyArray<{ time: number; text: string }>): Line[] => { const sung = stamps.map((stamp, index) => ({ ...stamp, index })).filter(stamp => stamp.text.trim().length > 0); const chorus = detectChorusTexts(sung.map(stamp => stamp.text)); const lines: Line[] = sung.map(stamp => { const text = stamp.text.trim(); const next = stamps[stamp.index + 1]; const endTime = estimateLrcLineEndTime(text, stamp.time, next?.time); return { words: buildTimedWords(text, stamp.time, endTime), startTime: stamp.time, endTime, fullText: text, ...(chorus.has(text) ? { isChorus: true } : {}), }; }); return attachInterludes(lines).map(line => ({ ...line, renderHints: buildLineRenderHints(line) })); }; /** The line on screen at `time`: the latest one that has started and whose render window is still open. */ export const findLatestActiveLineIndex = (lines: Line[], time: number): number => { for (let index = lines.length - 1; index >= 0; index -= 1) { const line = lines[index]; if (!line || time < line.startTime) continue; if (time <= (line.renderHints?.renderEndTime ?? line.endTime)) return index; } return -1; };