JA
apps/winzik / src / Model / Karaoke.php · commit 6576d6f
<?phpnamespace App\Model;/** * The bouncing ball of the lyrics on the whole screen: the line sung now cut into syllables, each with the moment it * is sung. The synchronised lyrics give a moment per line only: the syllables share the line's time by their length * (the singing ends a little before the next line). An "enhanced" LRC line gives a moment per word (<mm:ss.xx>): * those are used as they are. */final class Karaoke{    private const VOWELS = 'aeiouyàâäéèêëîïôöùûüœæAEIOUYÀÂÄÉÈÊËÎÏÔÖÙÛÜŒÆ';    /** two consonants that begin a syllable together (ta-bleau, ma-tra-que, ri-che) */    private const ONSETS = ['bl', 'br', 'ch', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gn', 'gr', 'ph', 'pl', 'pr', 'qu', 'th', 'tr', 'vr'];    /**     * The syllables of a line, its spaces and signs kept with them: put back together they are the line.     * @return list<string>     */    public static function syllables(string $line): array    {        $out = [];        // words and what is between them (spaces, commas...): the separators go with the syllable before them        preg_match_all('/([\p{L}\'’-]+)([^\p{L}\'’-]*)/u', $line, $m, PREG_SET_ORDER);        $lead = preg_match('/^[^\p{L}\'’-]+/u', $line, $l) ? $l[0] : '';        foreach ($m as [, $word, $after]) {            $parts = self::cut($word);            $parts[0] = $lead . $parts[0];            $lead = '';            $parts[count($parts) - 1] .= $after;            array_push($out, ...$parts);        }        return $out === [] ? ($line === '' ? [] : [$line]) : $out;    }    /** @return list<string> one word in syllables (a vowel group each; the consonants between shared out) */    private static function cut(string $word): array    {        $chars = mb_str_split($word);        $n = count($chars);        $isVowel = fn (int $i) => $i < $n && mb_strpos(self::VOWELS, $chars[$i]) !== false;        // the vowel groups        $groups = [];        for ($i = 0; $i < $n; $i++) {            if ($isVowel($i) && ($i === 0 || !$isVowel($i - 1))) {                $end = $i;                while ($end + 1 < $n && $isVowel($end + 1)) {                    $end++;                }                $groups[] = [$i, $end];            }        }        // a final mute e (« porte », « tristes ») sung with the syllable before when the word has others        if (count($groups) > 1) {            [$s, $e] = $groups[count($groups) - 1];            $tail = mb_strtolower(implode('', array_slice($chars, $s)));            if ($s === $e && in_array($tail, ['e', 'es', 'ent'], true)) {                array_pop($groups);            }        }        if (count($groups) <= 1) {            return [$word];        }        $cuts = [];        for ($g = 0; $g < count($groups) - 1; $g++) {            $from = $groups[$g][1] + 1;          // the consonants between this group and the next            $to = $groups[$g + 1][0];            $count = $to - $from;            if ($count <= 1) {                $cuts[] = $from;                 // one consonant: it begins the next syllable (ma-ri)            } else {                $pair = mb_strtolower($chars[$to - 2] . $chars[$to - 1]);                $cuts[] = in_array($pair, self::ONSETS, true) ? $to - 2 : $to - 1;   // ta-bleau, por-te            }        }        $parts = [];        $start = 0;        foreach ($cuts as $cut) {            $parts[] = implode('', array_slice($chars, $start, $cut - $start));            $start = $cut;        }        $parts[] = implode('', array_slice($chars, $start));        return array_values(array_filter($parts, fn ($p) => $p !== ''));    }    /**     * The moments of the syllables of a line that starts at $start, the next one at $next: by their length, over 85 %     * of the time (10 s at most for a line), or the line's own moments per word (enhanced LRC).     * @return array{0: list<string>, 1: list<float>, 2: float} its syllables, their moments, when the last one ends     */    public static function timing(string $line, float $start, float $next): array    {        $words = self::enhanced($line);        if ($words !== null) {            $syllables = [];            $times = [];            foreach ($words as $k => [$at, $text]) {                $parts = self::syllables($text);                $until = $words[$k + 1][0] ?? min($next, $at + 2.0);                $share = self::share($parts, $at, $until);                array_push($syllables, ...$parts);                array_push($times, ...$share);            }            return [$syllables, $times, min($next, ($words[count($words) - 1][0] ?? $start) + 1.5)];        }        $syllables = self::syllables($line);        // sung at about 0.3 s a syllable (3 a second: a song), never past 92 % of the time to the next line: a line        // followed by a pause (a solo, a chorus without words) is not stretched over it, the ball was late there        $gap = max(0.3, $next - $start);        $end = $start + max(min(0.6, $gap * 0.92), min(count($syllables) * 0.3 + 0.25, $gap * 0.92, 10.0));        return [$syllables, self::share($syllables, $start, $end), $end];    }    /** @param list<string> $parts @return list<float> their moments between $from and $to, by their letters */    private static function share(array $parts, float $from, float $to): array    {        // a syllable is sung about as long as another (a little longer when it has more letters)        $weights = array_map(fn (string $p) => 1 + 0.1 * (int)preg_match_all('/\p{L}/u', $p), $parts);        $total = max(1, array_sum($weights));        $times = [];        $t = $from;        foreach ($weights as $w) {            $times[] = $t;            $t += ($to - $from) * $w / $total;        }        return $times;    }    /** @return list<array{0: float, 1: string}>|null the words of an enhanced LRC line (<mm:ss.xx>word), null when none */    public static function enhanced(string $line): ?array    {        if (!preg_match_all('/<(\d+):(\d+(?:\.\d+)?)>([^<]*)/u', $line, $m, PREG_SET_ORDER)) {            return null;        }        $out = [];        foreach ($m as [, $min, $sec, $text]) {            if ($text !== '') {                $out[] = [(int)$min * 60 + (float)$sec, $text];            }        }        return $out !== [] ? $out : null;    }    /** The line as shown: without the moments of an enhanced LRC line. */    public static function plain(string $line): string    {        return trim((string)preg_replace('/<\d+:\d+(?:\.\d+)?>/', '', $line));    }}