PL
apps/winzik / src / Model / Lyrics.php · commit 6576d6f
<?phpnamespace App\Model;/** * Lyrics, the .LYR format of WinZik 2001, extended (0.10.x) in a way the older readers skip: * *   [LYR] *   [ 1.2625274 ] *   first line of the song *   [ 4.3006602 ] *   second line *   [LANGUE en] *   [TRADUCTION fr] *   1=première ligne de la chanson *   2=deuxième ligne * * A time in seconds between brackets, then the line sung from that time. The old player showed parole(posp) as soon * as the position passed temps(posp): the line shown at a time is the last one whose time has passed. * * Lyrics without times ("non synchronisées": found on the web, pasted) are written without any time row: * *   [LYR] *   [NON SYNCHRONISEES] *   first line *   (an empty row: a blank between two verses) *   second line * * Their lines get estimated times here (spread(): over the song's length, by their length), so whatever follows the * time (the lyrics bar, the karaoke) still moves; `$synced` false tells the screens to show them as a text to scroll. * * The rows after the lines ([LANGUE xx] = the language of the lyrics, [TRADUCTION xx] then "n=text": the translation * of line n, counted from 1 in the order of the file) are skipped by the readers before them: after a text row they * wait for a time row. */final class Lyrics{    public const NONE = 'Aucune Parole disponible';    public const UNSYNCED = '[NON SYNCHRONISEES]';    /** false: lines without times of their own (their times are estimated: spread()) */    public bool $synced = true;    /** @var array<int, string> the translation of each line (index of $lines => text), in $translationLang */    public array $translations = [];    /** the language of the translations ('fr'...), '' when none */    public string $translationLang = '';    /** the language of the lyrics themselves when known ('en'...), '' = not known */    public string $language = '';    /** @param list<array{0: float, 1: string}> $lines time (s), text */    public function __construct(public array $lines = [], bool $synced = true)    {        $this->synced = $synced;        if (!$synced) {            $this->spread(0.0);        }    }    public static function parse(string $content): ?self    {        $rows = Text::lines($content);        if ($rows === [] || strtoupper(trim(Text::unquote($rows[0]))) !== '[LYR]') {            return null;        }        $lines = [];        $time = null;        $synced = true;        $translations = [];        $lang = $source = '';        $inTranslation = false;        foreach (array_slice($rows, 1) as $row) {            $row = Text::unquote($row);            $trimmed = trim($row);            if (strtoupper($trimmed) === self::UNSYNCED && $lines === []) {                $synced = false;                continue;            }            if (preg_match('/^\[LANGUE\s+([a-z]{2,3}(?:-[a-z]{2,4})?)\]$/i', $trimmed, $m)) {                $source = strtolower($m[1]);                continue;            }            if (preg_match('/^\[TRADUCTION\s+([a-z]{2,3}(?:-[a-z]{2,4})?)\]$/i', $trimmed, $m)) {                $lang = strtolower($m[1]);                $inTranslation = true;                continue;            }            if ($inTranslation) {                if (preg_match('/^\s*(\d+)\s*=(.*)$/u', $row, $m) && (int)$m[1] >= 1) {                    $translations[(int)$m[1] - 1] = trim($m[2]);                }                continue;            }            if ($synced) {                if (preg_match('/^\s*\[\s*(-?[0-9]+(?:[.,][0-9]*)?)\s*\]\s*$/', $row, $m)) {                    $time = (float)str_replace(',', '.', $m[1]);                    continue;                }                if ($time !== null) {                    $lines[] = [$time, rtrim($row), count($lines)];                    $time = null;                }            } else {                $lines[] = [0.0, rtrim($row), count($lines)];            }        }        if (!$synced) {            // no blank rows at the start or the end            while ($lines !== [] && trim($lines[0][1]) === '') {                array_shift($lines);                $translations = self::shiftKeys($translations);            }            while ($lines !== [] && trim($lines[count($lines) - 1][1]) === '') {                array_pop($lines);            }        }        // sorted by time (a file written by hand may not be): the translations follow their lines        usort($lines, fn (array $a, array $b) => $a[0] <=> $b[0] ?: $a[2] <=> $b[2]);        $out = new self(array_map(fn (array $l) => [$l[0], $l[1]], $lines), $synced);        foreach ($lines as $i => $l) {            $index = $synced ? $l[2] : $i;            if (isset($translations[$index]) && $translations[$index] !== '') {                $out->translations[$i] = $translations[$index];            }        }        $out->translationLang = $out->translations !== [] ? $lang : '';        $out->language = $source;        return $out;    }    /** @param array<int, string> $t @return array<int, string> one line less at the top */    private static function shiftKeys(array $t): array    {        $out = [];        foreach ($t as $k => $v) {            if ($k > 0) {                $out[$k - 1] = $v;            }        }        return $out;    }    public static function load(string $file): ?self    {        $content = is_file($file) ? @file_get_contents($file) : false;        return $content === false ? null : self::parse($content);    }    /**     * Lyrics from a text: a .LYR, an LRC (times: synchronised), else plain lines (not synchronised). null when empty.     */    public static function fromText(string $text): ?self    {        $parsed = self::parse($text);        if ($parsed !== null) {            return $parsed->isEmpty() ? null : $parsed;        }        $lrc = \App\Media\Lrclib::fromLrc($text);        if ($lrc !== null) {            return $lrc;        }        $rows = array_map('rtrim', Text::lines($text));        while ($rows !== [] && trim($rows[0]) === '') {            array_shift($rows);        }        if ($rows === []) {            return null;        }        // two blank rows or more: one (a blank between two verses)        $lines = [];        foreach ($rows as $row) {            if (trim($row) === '' && $lines !== [] && trim($lines[count($lines) - 1][1]) === '') {                continue;            }            $lines[] = [0.0, trim($row) === '' ? '' : $row];        }        return new self($lines, false);    }    public function isEmpty(): bool    {        return $this->lines === [];    }    /**     * Lines without times: each one an estimated moment, spread over the song by their length (an intro of 6 % before     * the first, the last one by 92 %; a blank between verses counts a little). Without the length: 4 s a line.     */    public function spread(float $duration): void    {        if ($this->synced || $this->lines === []) {            return;        }        if ($duration <= 0) {            foreach ($this->lines as $i => $l) {                $this->lines[$i][0] = $i * 4.0;            }            return;        }        $weights = array_map(fn (array $l) => trim($l[1]) === '' ? 0.5 : 1 + 0.03 * mb_strlen(Karaoke::plain($l[1])), $this->lines);        $total = max(0.001, array_sum($weights));        $t = $duration * 0.06;        $span = $duration * 0.86;        foreach ($this->lines as $i => $l) {            $this->lines[$i][0] = round($t, 2);            $t += $span * $weights[$i] / $total;        }    }    /** The index of the line sung at that time, -1 before the first one (an estimate for lyrics not synchronised). */    public function indexAt(float $seconds): int    {        $found = -1;        foreach ($this->lines as $i => [$time]) {            if ($time > $seconds) {                break;            }            $found = $i;        }        return $found;    }    /** The line sung at that time ('' before the first one). */    public function lineAt(float $seconds): string    {        $i = $this->indexAt($seconds);        return $i < 0 ? '' : Karaoke::plain($this->lines[$i][1]);       // without the moments of its syllables    }    /** @return list<string> the lines as shown (without the moments of their syllables) */    public function texts(): array    {        return array_map(fn (array $l) => Karaoke::plain((string)$l[1]), $this->lines);    }    /** The translation of a line ('' when none). */    public function translation(int $index): string    {        return $this->translations[$index] ?? '';    }    /** Every line that has words has its translation (in $lang when given). */    public function hasTranslation(?string $lang = null): bool    {        if ($this->translations === [] || ($lang !== null && $lang !== $this->translationLang)) {            return false;        }        foreach ($this->texts() as $i => $text) {            if (trim($text) !== '' && trim($this->translations[$i] ?? '') === '') {                return false;            }        }        return true;    }    /** @param array<int, string> $translations index => text */    public function setTranslations(array $translations, string $lang): void    {        $this->translations = [];        foreach ($translations as $i => $t) {            $t = trim((string)preg_replace('/[\r\n]+/', ' ', (string)$t));            if (isset($this->lines[$i]) && $t !== '') {                $this->translations[(int)$i] = $t;            }        }        $this->translationLang = $this->translations !== [] ? strtolower($lang) : '';    }    /** The translations of other lyrics of the same song, given to the lines with the same words (an edit keeps them). */    public function keepTranslationsOf(?self $old): void    {        if ($old === null || $old->translations === []) {            return;        }        $known = [];        foreach ($old->texts() as $i => $text) {            if (isset($old->translations[$i])) {                $known[self::key($text)] ??= $old->translations[$i];            }        }        foreach ($this->texts() as $i => $text) {            if (!isset($this->translations[$i]) && isset($known[self::key($text)])) {                $this->translations[$i] = $known[self::key($text)];            }        }        if ($this->translations !== []) {            ksort($this->translations);            $this->translationLang = $old->translationLang;        }        if ($this->language === '') {            $this->language = $old->language;        }    }    private static function key(string $text): string    {        return mb_strtolower(trim((string)preg_replace('/\s+/u', ' ', $text)));    }    /** The words only, a line per row (what is translated, searched, shown as a text). */    public function plainText(): string    {        return implode("\n", $this->texts());    }    public function toLyr(): string    {        $out = "[LYR]\r\n";        if (!$this->synced) {            $out .= self::UNSYNCED . "\r\n";            foreach ($this->lines as [, $text]) {                $out .= $text . "\r\n";            }        } else {            foreach ($this->lines as [$time, $text]) {                $out .= '[ ' . rtrim(rtrim(sprintf('%.7F', $time), '0'), '.') . " ]\r\n" . $text . "\r\n";            }        }        if ($this->language !== '') {            $out .= '[LANGUE ' . $this->language . "]\r\n";        }        if ($this->translations !== [] && $this->translationLang !== '') {            $out .= '[TRADUCTION ' . $this->translationLang . "]\r\n";            ksort($this->translations);            foreach ($this->translations as $i => $t) {                $out .= ($i + 1) . '=' . $t . "\r\n";            }        }        return $out;    }}