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 $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 $t @return array 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 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 $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; } }