TR
apps/winzik / src / Cast / VlcTarget.php · commit 6576d6f
<?phpnamespace App\Cast;/** * WinZik as a web radio for VLC (on a TV, a box, a computer): one address that never changes, opened once in VLC * ("Flux réseau"), where the song WinZik plays goes on and on, song after song (LiveServer). ffmpeg makes it at the * pace of the music (-re) from where WinZik is: each new song, seek or play starts a new ffmpeg at that moment, its * output (a file, read as it grows: nothing waits, Windows too) goes on in the same stream. * * - audio: MP3 192 kb/s (no tag, no Xing header: the pieces follow each other as one stream), the title in the ICY *   metadata (VLC shows "Artiste - Titre"). The phone's ffmpeg does it too. * - video (an ffmpeg with libass and an H.264 encoder: a computer's libx264, the phone app's h264_mediacodec = the *   phone's own hardware encoder): MPEG-TS 1280 x 720, the cover and the karaoke drawn by ffmpeg *   (subtitles filter, an ASS file with \kf syllables: yellow as they are sung, the translation in blue, the next *   line in grey); its timestamps go on from piece to piece (-output_ts_offset) so VLC sees one film. * * WinZik's player keeps the clock (silent, like any cast): VLC plays a few seconds behind it (its own buffer). VLC is * never told anything back (no position, no pause of its own): pausing here stops the stream, VLC waits. */final class VlcTarget implements CastTarget{    public const WIDTH = 1280;    public const HEIGHT = 720;    /** @var array<string, mixed>|null */    private ?array $song = null;    private bool $playing = false;    private float $position = 0.0;    private float $startedAt = 0.0;    /** @var resource|null the ffmpeg running */    private $proc = null;    /** @var list<resource> ffmpegs asked to stop, reaped once they are gone */    private array $dying = [];    private string $out = '';    private int $read = 0;    private int $run = 0;    /** seconds of video sent so far (the next piece's timestamps start there) */    private float $streamed = 0.0;    private string $error = '';    private bool $closed = false;    public function __construct(        private string $ffmpeg,        private string $tmpDir,        public readonly LiveServer $live,        public readonly bool $video = false,    ) {        @mkdir($tmpDir, 0777, true);        foreach (glob($tmpDir . '/live-*') ?: [] as $old) {            @unlink($old);        }    }    /** Whether this ffmpeg can make the video (H.264, the subtitles filter, MPEG-TS). */    public static function canVideo(string $ffmpeg): bool    {        return self::videoEncoder($ffmpeg) !== null;    }    /** The H.264 encoder of this ffmpeg for the film (libx264, else the phone's h264_mediacodec), null: no film. Asked once. */    public static function videoEncoder(string $ffmpeg): ?string    {        static $known = [];        if (array_key_exists($ffmpeg, $known)) {            return $known[$ffmpeg];        }        $ask = fn (string $what): string => self::ask($ffmpeg, [$what]);        $encoders = $ask('-encoders');        $encoder = match (true) {            preg_match('/\blibx264\b/', $encoders) === 1 => 'libx264',            preg_match('/\bh264_mediacodec\b/', $encoders) === 1 => 'h264_mediacodec',            default => null,        };        return $known[$ffmpeg] = $encoder !== null && preg_match('/\ssubtitles\s/', $ask('-filters')) === 1            && preg_match('/\smpegts\s/', $ask('-muxers')) === 1 ? $encoder : null;    }    public function load(array $song, float $at, bool $play): void    {        $this->song = $song;        $this->position = max(0.0, $at);        $this->playing = $play;        $artist = (string)($song['artist'] ?? '');        $this->live->setTitle(($artist !== '' ? $artist . ' - ' : '') . (string)($song['title'] ?? ''));        $play ? $this->start() : $this->halt();    }    public function play(): void    {        if (!$this->playing) {            $this->playing = true;            $this->start();        }    }    public function pause(): void    {        if ($this->playing) {            $this->position = $this->position();            $this->playing = false;            $this->halt();        }    }    public function seek(float $seconds): void    {        $this->position = max(0.0, $seconds);        if ($this->playing) {            $this->start();        }    }    public function stop(): void    {        $this->playing = false;        $this->position = 0.0;        $this->halt();    }    /** The TV's own volume (VLC's): WinZik's stays as it is. */    public function setVolume(int $volume): void    {    }    /** Where the song is now (seconds). */    public function position(): float    {        return $this->playing && $this->proc !== null ? $this->position + (microtime(true) - $this->startedAt) : $this->position;    }    public function poll(): void    {        $this->live->poll();        $this->pump();        $this->watchSpeed();        foreach ($this->dying as $i => $p) {            if (!proc_get_status($p)['running']) {                proc_close($p);                unset($this->dying[$i]);            }        }        if ($this->proc !== null && !proc_get_status($this->proc)['running']) {            $this->pump();      // its last bytes            $code = proc_get_status($this->proc)['exitcode'];            $this->ended();            if ($code > 0 && $this->read === 0) {                $this->error = ($this->video && $this->encoder() === 'h264_mediacodec' ? 'La vidéo ne marche pas sur ce téléphone (son encodeur vidéo) : prenez le flux audio'                    : 'ffmpeg n\'a pas pu lire ce morceau') . $this->why();            }        }    }    /** What ffmpeg wrote since the last frame: to the players. */    private function pump(): void    {        if ($this->out === '') {            return;        }        clearstatcache(false, $this->out);        $size = (int)@filesize($this->out);        if ($size <= $this->read || !($f = @fopen($this->out, 'rb'))) {            return;        }        fseek($f, $this->read);        $length = $size - $this->read;        if ($this->video) {            $length -= $length % 188;       // whole MPEG-TS packets only        }        $bytes = $length > 0 ? (string)fread($f, min($length, 4 * 1024 * 1024)) : '';        fclose($f);        $this->read += strlen($bytes);        $this->live->feed($bytes);    }    public function status(): array    {        $state = match (true) {            $this->closed => 'closed',            $this->live->listeners() === 0 => 'connecting',            $this->playing => 'playing',            default => 'paused',        };        return ['state' => $state, 'position' => null, 'song' => (int)($this->song['id'] ?? -1)];    }    public function error(): string    {        return $this->error;    }    public function close(): void    {        $this->halt();        foreach ($this->dying as $p) {            @proc_terminate($p, 9);            @proc_close($p);        }        $this->dying = [];        $this->live->close();        $this->closed = true;        foreach (glob($this->tmpDir . '/live-*') ?: [] as $old) {            @unlink($old);        }    }    // ffmpeg --------------------------------------------------------------------------------------------------------    /** A new ffmpeg from the position (the one before stopped). */    private function start(): void    {        $this->halt();        $path = (string)($this->song['path'] ?? '');        if ($path === '' || !is_file($path)) {            return;        }        $this->error = '';        $n = ++$this->run;        $this->out = sprintf('%s/live-%d.%s', $this->tmpDir, $n, $this->video ? 'ts' : 'mp3');        $this->read = 0;        @unlink($this->out);        $command = $this->video ? $this->videoCommand($path, $n) : $this->audioCommand($path);        $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';        $proc = @proc_open($command, [0 => ['file', $null, 'r'], 1 => ['file', $null, 'w'], 2 => ['file', $this->tmpDir . '/live-err.txt', 'w']],            $pipes, $this->tmpDir, null, ['bypass_shell' => true, 'suppress_errors' => true]);        if (!is_resource($proc)) {            $this->error = 'ffmpeg ne démarre pas';            $this->out = '';            return;        }        $this->proc = $proc;        $this->startedAt = microtime(true);        @unlink($this->tmpDir . '/live-progress.txt');        $this->slow = 0;    }    /** @return list<string> */    public function audioCommand(string $path): array    {        return [$this->ffmpeg, '-hide_banner', '-nostdin', '-loglevel', 'error', ...$this->pace(), '-ss', self::seconds($this->position), '-i', $path,            '-map', '0:a:0', '-vn', '-c:a', 'libmp3lame', '-b:a', '192k', '-ar', '44100', '-ac', '2',            '-write_xing', '0', '-id3v2_version', '0', '-f', 'mp3', '-y', $this->out];    }    /**     * At the pace of the music: -re, or (an ffmpeg that has them) 2 s at once first (VLC gets a buffer at once: no     * stutter when a frame of WinZik is late) and a catch up after a slow moment instead of staying behind.     * @return list<string>     */    private function pace(): array    {        $o = self::options($this->ffmpeg);        return array_merge(['-readrate', '1'], $o['burst'] ? ['-readrate_initial_burst', '2'] : [], $o['catchup'] ? ['-readrate_catchup', '1.5'] : []);    }    /** @return array{burst: bool, catchup: bool} what this ffmpeg's options allow (asked once) */    private static function options(string $ffmpeg): array    {        static $known = [];        if (!isset($known[$ffmpeg])) {            $help = self::ask($ffmpeg, ['-h', 'long']);            $known[$ffmpeg] = ['burst' => str_contains($help, 'readrate_initial_burst'), 'catchup' => str_contains($help, 'readrate_catchup')];        }        return $known[$ffmpeg];    }    /** @param list<string> $args */    private static function ask(string $ffmpeg, array $args): string    {        $p = @proc_open([$ffmpeg, '-hide_banner', ...$args], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, null, ['bypass_shell' => true]);        if (!is_resource($p)) {            return '';        }        $text = (string)stream_get_contents($pipes[1]);        fclose($pipes[1]);        fclose($pipes[2]);        proc_close($p);        return $text;    }    /** @return list<string> the cover and the karaoke (an ASS file next to it) over a dark picture, H.264 + AAC in MPEG-TS */    public function videoCommand(string $path, int $n): array    {        $cover = (string)($this->song['coverPath'] ?? '');        $hasCover = $cover !== '' && is_file($cover);        $ass = "live-$n.ass";       // ffmpeg runs in tmpDir: plain names (no drive letter nor backslash to escape)        $fonts = $this->fonts();        file_put_contents($this->tmpDir . '/' . $ass, self::ass($this->song ?? [], $this->position, $hasCover, $this->style, $fonts ? $this->tmpDir . '/fonts' : null));        [$w, $h, $fps, $rate] = self::QUALITIES[$this->level()];        $k = $w / self::WIDTH;        $side = (int)(2 * round(self::COVER * $k / 2));        // the cover through NV12: the phone's ffmpeg (no asm) turns RGB(A) into planar YUV wrongly (a garbled cover), into NV12 right        $graph = sprintf('color=c=0x0d1020:s=%dx%d:r=%d[bg];', $w, $h, $fps)            . ($hasCover ? sprintf('[1:v]scale=%d:%d:force_original_aspect_ratio=decrease,format=nv12,format=yuv420p[c];[bg][c]overlay=x=%d-w/2:y=%d[b];[b]',                $side, $side, (int)round(self::COVER_X * $k), (int)round(self::COVER_Y * $k)) : '[bg]')            . "subtitles=filename=$ass" . ($fonts ? ':fontsdir=fonts' : '') . ',format=' . ($this->encoder() === 'h264_mediacodec' ? 'nv12' : 'yuv420p') . '[v]';        $duration = (float)($this->song['duration'] ?? 0);        $left = $duration > $this->position ? $duration - $this->position : 0.0;        $gop = (string)(2 * $fps);        return array_merge(            [$this->ffmpeg, '-hide_banner', '-nostdin', '-loglevel', 'error', ...$this->pace(), '-ss', self::seconds($this->position), '-i', $path],            $hasCover ? ['-loop', '1', '-framerate', (string)$fps, '-i', $cover] : [],            ['-filter_complex', $graph, '-map', '[v]', '-map', '0:a:0',                ...($this->encoder() === 'h264_mediacodec'                    ? ['-c:v', 'h264_mediacodec', '-ndk_codec', '1', '-g', $gop, '-b:v', $rate]                    : ['-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency', '-g', $gop, '-b:v', $rate, '-maxrate', $rate, '-bufsize', $rate]),                '-c:a', 'aac', '-b:a', '160k', '-ar', '44100', '-ac', '2'],            $left > 0 ? ['-t', self::seconds($left)] : ['-shortest'],            ['-progress', 'live-progress.txt', '-stats_period', '1',                '-output_ts_offset', self::seconds($this->streamed), '-muxdelay', '0', '-f', 'mpegts', '-y', $this->out],        );    }    // quality ---------------------------------------------------------------------------------------------------------    /** width, height, pictures a second, bitrate */    public const QUALITIES = [        'haute' => [1280, 720, 25, '2500k'],        'moyenne' => [960, 540, 25, '1500k'],        'basse' => [640, 360, 20, '800k'],    ];    public const QUALITY_NAMES = ['auto' => 'Automatique', 'haute' => 'Haute (720p)', 'moyenne' => 'Moyenne (540p)', 'basse' => 'Basse (360p)'];    /** the karaoke's mark over the syllable sung (LyricsBar::KARAOKE: ball, star, note, bar, off) */    public string $style = 'ball';    /** auto | haute | moyenne | basse */    public string $quality = 'auto';    /** automatic: the level now (it goes down when ffmpeg cannot keep up) */    private string $autoLevel = 'haute';    private int $slow = 0;    private float $progressAt = 0.0;    /** what the automatic quality did last ('' nothing), for the interfaces */    public string $qualityNote = '';    /** The level of the film made now. */    public function level(): string    {        return isset(self::QUALITIES[$this->quality]) ? $this->quality : $this->autoLevel;    }    /**     * Automatic quality: ffmpeg's speed (its -progress file, each second) under 0.95 four seconds in a row (it cannot     * make the film as fast as the music: VLC stutters) = a lower level at once, from where it is.     */    private function watchSpeed(): void    {        $now = microtime(true);        if (!$this->video || $this->quality !== 'auto' || $this->proc === null || $now - $this->progressAt < 1.0 || $now - $this->startedAt < 4.0) {            return;        }        $this->progressAt = $now;        $text = (string)@file_get_contents($this->tmpDir . '/live-progress.txt');        if (!preg_match_all('/^speed=\s*([\d.]+)x/m', $text, $m)) {            return;        }        $speed = (float)end($m[1]);        $this->slow = $speed < 0.95 ? $this->slow + 1 : 0;        $levels = array_keys(self::QUALITIES);        $i = array_search($this->autoLevel, $levels, true);        if ($this->slow >= 4 && $i !== false && isset($levels[$i + 1])) {            $this->autoLevel = $levels[$i + 1];            $this->slow = 0;            $this->qualityNote = 'Qualité baissée en ' . strtolower(self::QUALITY_NAMES[$this->autoLevel]) . ' : cet appareil ne suivait pas';            $this->position = $this->position();            $this->start();        }    }    /** tests: the encoder to write in the command (null: this ffmpeg's) */    public ?string $forceEncoder = null;    private function encoder(): string    {        return $this->forceEncoder ?? self::videoEncoder($this->ffmpeg) ?? 'libx264';    }    /** WinZik's own font (Lato) in tmpDir/fonts, for libass (no fontconfig on the phone): false when it is missing. */    private function fonts(): bool    {        $from = dirname(__DIR__, 2) . '/assets/fonts';        $to = $this->tmpDir . '/fonts';        @mkdir($to, 0777, true);        foreach (['ui.ttf', 'ui-bold.ttf'] as $font) {            if (!is_file("$to/$font") && (!is_file("$from/$font") || !@copy("$from/$font", "$to/$font"))) {                return false;            }        }        return true;    }    /** The ffmpeg running is stopped (asked to end, reaped later: never waited for). */    private function halt(): void    {        if ($this->proc !== null) {            @proc_terminate($this->proc);            $this->dying[] = $this->proc;            $this->ended();        }    }    private function ended(): void    {        if ($this->proc !== null && !in_array($this->proc, $this->dying, true)) {            proc_close($this->proc);        }        if ($this->proc !== null) {            $ran = microtime(true) - $this->startedAt;            $this->streamed += max(0.0, $ran) + 0.1;    // the next piece starts just after (never before) this one        }        $this->proc = null;        if ($this->out !== '') {            @unlink($this->out);            @unlink(preg_replace('/\.(ts|mp3)$/', '.ass', $this->out));        }        $this->out = '';        $this->read = 0;    }    private function why(): string    {        $text = trim((string)@file_get_contents($this->tmpDir . '/live-err.txt'));        $last = $text !== '' ? trim((string)strrchr("\n" . $text, "\n")) : '';        return $last !== '' ? ' (' . mb_substr($last, 0, 160) . ')' : '';    }    private static function seconds(float $s): string    {        return number_format(max(0.0, $s), 3, '.', '');    }    // the karaoke as ASS subtitles ------------------------------------------------------------------------------------    /** the screen (ASS coordinates, 1280 x 720 whatever the film's size: libass scales) */    private const COVER = 340;    private const COVER_X = 250;    private const COVER_Y = 110;    private const LYRICS_X = 830;    private const LYRICS_W = 760;    private const SING_Y = 205;    private const SING_SIZE = 50;    /** the lines coming after the one sung, shown under it (smaller, fading) */    public const AHEAD = 5;    /**     * The song's screen as ASS, in two columns: on the left the cover (overlaid by ffmpeg), the title and the artist;     * on the right the line sung before (dim), the line sung now syllable by syllable (\kf: white to yellow) with the     * karaoke's mark over the syllable sung ($style: ball, star, note, bar or off, as LyricsBar's), its translation in     * blue, then the AHEAD lines coming. Times shifted by $from (the piece starts there). $fonts: the folder of Lato,     * to measure the syllables (the mark lands on each); without it no mark.     * @param array<string, mixed> $song     */    public static function ass(array $song, float $from, bool $cover, string $style = 'ball', ?string $fonts = null): string    {        $w = self::WIDTH;        $h = self::HEIGHT;        $lx = self::LYRICS_X;        $right = $w - $lx - (int)(self::LYRICS_W / 2);        $left = $lx - (int)(self::LYRICS_W / 2);        $style = isset(\App\Gui\LyricsBar::KARAOKE[$style]) ? $style : 'ball';        $out = "[Script Info]\nScriptType: v4.00+\nPlayResX: $w\nPlayResY: $h\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n"            . "[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"            . "Style: Title,Lato,36,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,2,0,8,40,860,0,1\n"            . "Style: Artist,Lato,28,&H00C8C8C8,&H00C8C8C8,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,8,40,860,0,1\n"            . "Style: Sing,Lato," . self::SING_SIZE . ",&H004AD8FF,&H00FFFFFF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,3,0,8,$left,$right,0,1\n"            . "Style: Tr,Lato,30,&H00FFA86F,&H00FFA86F,&H00000000,&H00000000,0,1,0,0,100,100,0,0,1,2,0,8,$left,$right,0,1\n"            . "Style: Next,Lato,32,&H00A0A0A0,&H00A0A0A0,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,8,$left,$right,0,1\n"            . "Style: Mark,Lato,20,&H004AD8FF,&H004AD8FF,&H00202020,&H00000000,0,0,0,0,100,100,0,0,1,1,0,7,0,0,0,1\n\n"            . "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n";        $duration = max(1.0, (float)($song['duration'] ?? 0) - $from);        $end = self::assTime(max($duration, 3600.0));        $title = self::assText((string)($song['title'] ?? ''));        $artist = self::assText((string)($song['artist'] ?? ''));        $ty = $cover ? self::COVER_Y + self::COVER + 26 : 300;        $out .= "Dialogue: 0,0:00:00.00,$end,Title,,0,0,0,,{\\pos(" . self::COVER_X . ",$ty)}$title\n";        if ($artist !== '') {            $out .= "Dialogue: 0,0:00:00.00,$end,Artist,,0,0,0,,{\\pos(" . self::COVER_X . ',' . ($ty + 48) . ")}$artist\n";        }        $data = $song['lyricsData'] ?? null;        $lines = array_values(array_filter(is_array($data) && is_array($data['lines'] ?? null) ? $data['lines'] : [],            fn ($l): bool => is_array($l) && trim((string)($l['text'] ?? '')) !== ''));        $synced = is_array($data) && ($data['synced'] ?? true);        $bold = $fonts !== null ? FontMetrics::of("$fonts/ui-bold.ttf") : null;        $sy = self::SING_Y;        foreach ($lines as $i => $l) {            $text = trim((string)$l['text']);            $start = (float)$l['t'];            $stop = max((float)($lines[$i + 1]['t'] ?? ((float)($l['e'] ?? $start) + 2.0)), (float)($l['e'] ?? $start));            if ($stop - $from <= 0) {                continue;       // already sung before this piece            }            $a = self::assTime(max(0.0, $start - $from));            $b = self::assTime(max(0.1, $stop - $from));            $syl = array_map('strval', is_array($l['syl'] ?? null) ? $l['syl'] : []);            $at = array_map('floatval', is_array($l['at'] ?? null) ? $l['at'] : []);            $karaokeLine = $synced && $syl !== [] && count($syl) === count($at);            // the line sung, made smaller when wider than the column (never wrapped: the mark must land on its syllables)            $size = (float)self::SING_SIZE;            $width = $bold?->width($karaokeLine ? implode('', $syl) : $text, $size) ?? 0.0;            if ($width > self::LYRICS_W) {                $size = floor($size * self::LYRICS_W / $width);                $width = $bold?->width($karaokeLine ? implode('', $syl) : $text, $size) ?? 0.0;            }            $fs = $size < self::SING_SIZE ? "\\fs$size" : '';            if ($karaokeLine) {                $lead = (int)round(max(0.0, $at[0] - $start) * 100);                $karaoke = $lead > 0 ? "{\\k$lead}" : '';                foreach ($syl as $k => $s) {                    $next = (float)($at[$k + 1] ?? ($l['e'] ?? $at[$k]));                    $karaoke .= '{\\kf' . max(1, (int)round(($next - $at[$k]) * 100)) . '}' . self::assText($s);                }            } else {                $karaoke = '{\\1c&HFFFFFF&}' . self::assText($text);            }            $out .= "Dialogue: 2,$a,$b,Sing,,0,0,0,,{\\pos($lx,$sy)$fs}$karaoke\n";            if ($karaokeLine && $bold !== null && $style !== 'off') {                $out .= self::mark($style, $syl, $at, (float)($l['e'] ?? $stop), $start, $stop, $from, $bold, $size, $lx - $width / 2);            }            if ($i > 0) {                $out .= "Dialogue: 1,$a,$b,Next,,0,0,0,,{\\pos($lx," . ($sy - 62) . ')\\fs28\\alpha&H70&}' . self::assText(trim((string)$lines[$i - 1]['text'])) . "\n";            }            $tr = trim((string)($l['tr'] ?? ''));            $y = $sy + (int)round($size * 1.25);            if ($tr !== '') {                $out .= "Dialogue: 1,$a,$b,Tr,,0,0,0,,{\\pos($lx,$y)}" . self::assText($tr) . "\n";                $y += 48;            }            $y += 14;            for ($j = 1; $j <= self::AHEAD && isset($lines[$i + $j]); $j++) {                $alpha = sprintf('%02X', min(0xC0, 0x10 + 0x24 * ($j - 1)));                $out .= "Dialogue: 1,$a,$b,Next,,0,0,0,,{\\pos($lx,$y)\\alpha&H$alpha&}" . self::assText(trim((string)$lines[$i + $j]['text'])) . "\n";                $y += 46;                if ($y > $h - 40) {                    break;                }            }        }        return $out;    }    /**     * The karaoke's mark over the line sung: from syllable to syllable, landing on each at the moment it is sung (a     * bounce in four straight pieces for the ball, the star and the note; the bar slides under the syllable), waiting     * on the first before it, on the last after it.     * @param list<string> $syl @param list<float> $at     */    private static function mark(string $style, array $syl, array $at, float $lineEnd, float $start, float $stop, float $from,        FontMetrics $font, float $size, float $x0): string    {        $centres = [];        $widths = [];        $x = $x0;        foreach ($syl as $s) {            $w = $font->width($s, $size);            $trim = $font->width(rtrim($s), $size);            $centres[] = $x + $trim / 2;            $widths[] = $trim;            $x += $w;        }        $y = self::SING_Y - 12;         // over the letters        $shape = match ($style) {            'star' => 'm 0 -11 l 3 -3 l 11 -3 l 5 2 l 7 10 l 0 5 l -7 10 l -5 2 l -11 -3 l -3 -3',            'note' => 'm -9 6 b -9 2 -5 1 -2 1 b 1 1 3 3 3 6 b 3 9 0 11 -3 11 b -7 11 -9 9 -9 6 m 1 6 l 3 6 l 3 -13 l 1 -13 m 3 -13 b 8 -10 11 -6 9 0 b 8 -4 6 -6 3 -8',            default => 'm 0 -8 b 4 -8 8 -4 8 0 b 8 4 4 8 0 8 b -4 8 -8 4 -8 0 b -8 -4 -4 -8 0 -8',        };        $out = '';        $put = function (float $t1, float $t2, string $tags) use (&$out, $from): void {            if ($t2 - $from <= 0 || $t2 <= $t1) {                return;            }            $out .= 'Dialogue: 3,' . self::assTime(max(0.0, $t1 - $from)) . ',' . self::assTime(max(0.01, $t2 - $from)) . ",Mark,,0,0,0,,{$tags}\n";        };        $n = count($syl);        if ($style === 'bar') {            $put($start, $at[0], sprintf('{\\an7\\pos(%.1f,%d)\\p1}m 0 0 l %.1f 0 l %.1f 5 l 0 5', $centres[0] - $widths[0] / 2, self::SING_Y + (int)($size * 1.15), $widths[0], $widths[0]));            for ($k = 0; $k < $n; $k++) {                $t2 = $k + 1 < $n ? $at[$k + 1] : $stop;                $put($at[$k], $t2, sprintf('{\\an7\\pos(%.1f,%d)\\p1}m 0 0 l %.1f 0 l %.1f 5 l 0 5', $centres[$k] - $widths[$k] / 2, self::SING_Y + (int)($size * 1.15), $widths[$k], $widths[$k]));            }            return $out;        }        $draw = fn (float $xa, float $ya, float $xb, float $yb, int $ms): string => sprintf('{\\an5\\move(%.1f,%.1f,%.1f,%.1f,0,%d)\\p1}%s', $xa, $ya, $xb, $yb, $ms, $shape);        $put($start, $at[0], $draw($centres[0], $y, $centres[0], $y, 0));       // waiting on the first syllable        for ($k = 0; $k < $n; $k++) {            if ($k + 1 >= $n) {                $put($at[$k], min($stop, max($lineEnd, $at[$k] + 0.3)), $draw($centres[$k], $y, $centres[$k], $y, 0));                break;            }            $t1 = $at[$k];            $d = max(0.05, $at[$k + 1] - $t1);            $hop = min(34.0, 12.0 + 14.0 * $d);     // a longer syllable, a higher bounce            for ($q = 0; $q < 4; $q++) {                $f1 = $q / 4;                $f2 = ($q + 1) / 4;                $xa = $centres[$k] + ($centres[$k + 1] - $centres[$k]) * $f1;                $xb = $centres[$k] + ($centres[$k + 1] - $centres[$k]) * $f2;                $ya = $y - $hop * 4 * $f1 * (1 - $f1);                $yb = $y - $hop * 4 * $f2 * (1 - $f2);                $put($t1 + $d * $f1, $t1 + $d * $f2, $draw($xa, $ya, $xb, $yb, (int)round($d * 250)));            }        }        return $out;    }    private static function assText(string $text): string    {        return str_replace(['\\', '{', '}', "\r", "\n"], ['/', '(', ')', '', ' '], $text);    }    private static function assTime(float $s): string    {        $cs = (int)round($s * 100);        return sprintf('%d:%02d:%02d.%02d', intdiv($cs, 360000), intdiv($cs % 360000, 6000), intdiv($cs % 6000, 100), $cs % 100);    }}