EN
apps/winzik / src / Cast / CastSession.php · commit 6576d6f
<?phpnamespace App\Cast;use App\Audio\Player;use App\Core\WinZik;use App\Model\Karaoke;use App\Model\Lyrics;use App\Model\Text;/** * One cast: WinZik's player keeps running, silent (Player::$silent), and stays the one the interfaces show and * drive; each frame this compares it with the frame before and tells the TV what changed (a new song: its URL on * TvServer; play, pause, stop, a seek, the volume), then follows the TV: its position (WinZik's clock is set back on * it when they drift apart: the karaoke on the phone / PC stays in time with the TV), a pause or a play done with the * TV's remote, the keys of WinZik's TV page (next, previous...). The end of a song comes from WinZik's own clock * (kept on the TV's): the next song goes to the TV as any new song. */final class CastSession{    /** seconds after a command sent during which the TV's answers are not taken as its own changes */    public const GRACE = 3.0;    /** seconds of difference between the TV and WinZik's clock before WinZik's is set on the TV's */    public const DRIFT = 1.5;    private string $file = '';    private int $song = 0;    private string $lastState = Player::STOPPED;    private float $lastPos = 0.0;    private int $lastVolume;    private float $commandAt;    private string $lastError = '';    public function __construct(        private WinZik $wz,        public readonly CastTarget $target,        private TvServer $server,        /** stream | interface */        public readonly string $mode,        /** dlna | cast-media | cast-app | browser */        public readonly string $how,    ) {        $this->lastVolume = $wz->player->volume;        $this->commandAt = microtime(true);    }    public function songId(): int    {        return $this->song;    }    public function tick(float $dt): void    {        $this->server->poll();        $this->target->poll();        $p = $this->wz->player;        $now = microtime(true);        $file = (string)$p->file;        if ($file !== '' && $file !== $this->file) {            $this->file = $file;            $this->song++;            $this->target->load($this->song($file), $p->position, $p->state === Player::PLAYING);            $this->commandAt = $now;        } elseif ($file === $this->file && $file !== '') {            if ($p->state !== $this->lastState) {                match ($p->state) {                    Player::PLAYING => $this->target->play(),                    Player::PAUSED => $this->target->pause(),                    default => $this->target->stop(),                };                $this->commandAt = $now;            } elseif ($p->state === Player::PLAYING ? abs($p->position - ($this->lastPos + $dt)) > self::DRIFT : abs($p->position - $this->lastPos) > 0.25) {                $this->target->seek($p->position);       // the position bar, the keys, a tap on a line of the karaoke                $this->commandAt = $now;            }        }        if ($p->volume !== $this->lastVolume) {            $this->target->setVolume($p->volume);        }        $this->follow($now);        if ($this->target instanceof TvTarget) {            $this->remoteKeys($this->target);            $this->target->next = $this->upcoming();            $this->target->karaoke = (string)($this->wz->options['karaoke'] ?? 'ball');        }        $error = $this->target->error();        if ($error !== '' && $error !== $this->lastError) {            $this->wz->notice($error, 6);        }        $this->lastError = $error;        $this->lastState = $p->state;        $this->lastPos = $p->position;        $this->lastVolume = $p->volume;    }    /** The TV's own changes: WinZik follows them (not while an order of ours is on its way). */    private function follow(float $now): void    {        $st = $this->target->status();        $p = $this->wz->player;        if ($now - $this->commandAt < self::GRACE || $st['song'] !== $this->song || (string)$p->file !== $this->file) {            return;        }        if ($st['state'] === 'playing' && $p->state === Player::PLAYING && $st['position'] !== null            && abs($st['position'] - $p->position) > self::DRIFT) {            $p->seek($st['position']);        } elseif ($st['state'] === 'paused' && $p->state === Player::PLAYING) {            $this->wz->pause();          // paused with the TV's remote        } elseif ($st['state'] === 'playing' && $p->state === Player::PAUSED) {            $this->wz->play();        }    }    private function remoteKeys(TvTarget $tv): void    {        foreach ($tv->takeCommands() as $c) {            match ($c['do']) {                'toggle' => $this->wz->togglePause(),                'play' => $this->wz->play(),                'pause' => $this->wz->pause(),                'next' => $this->wz->next(),                'prev' => $this->wz->player->position > 3 ? $this->wz->seek(0) : $this->wz->previous(),                'seek' => $this->wz->seek(max(0.0, (float)$c['t'])),                default => null,            };        }    }    /** @return list<array{title: string, artist: string}> the two songs after this one (not with Hasard: unknown) */    private function upcoming(): array    {        $pl = $this->wz->playlist;        if ($pl->shuffle) {            return [];        }        $out = [];        for ($i = $pl->active + 1; $i < $pl->count() && count($out) < 2; $i++) {            $item = $pl->items[$i];            if (\App\Cloud\Cloud::isPseudo($item)) {                continue;            }            [$tag] = $this->wz->describe($item);            $out[] = ['title' => $tag->title !== '' ? $tag->title : Text::baseName($item), 'artist' => $tag->artist];        }        return $out;    }    /**     * The song as the TV gets it: on TvServer (its file, cover, lyrics), its addresses and what to show.     * @return array<string, mixed>     */    private function song(string $path): array    {        $wz = $this->wz;        $tag = $wz->tag;        $cover = '';        try {            $cover = (string)$wz->covers()->picture((string)$wz->playlist->current(), $tag);        } catch (\Throwable) {            $cover = '';        }        $duration = $wz->player->duration();        $lyrics = $wz->lyrics;        $data = $lyrics !== null && !$lyrics->isEmpty() ? self::lyricsData($lyrics, $duration) : null;        $this->server->addSong($this->song, [            'path' => $path,            'mime' => self::mime($path),            'cover' => $cover,            'vtt' => $data !== null && $this->mode === 'interface' ? self::vtt($data) : '',            'lyrics' => $data !== null ? (string)json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : '',        ]);        $urls = $this->server->urls($this->song);        return [            'id' => $this->song,            'path' => $path,            'coverPath' => $cover,            'url' => $urls['url'],            'mime' => self::mime($path),            'title' => $tag->title !== '' ? $tag->title : Text::baseName($path),            'artist' => $tag->artist,            'album' => $tag->album,            'cover' => $urls['cover'],            'duration' => $duration,            'vtt' => $urls['vtt'],            'lyrics' => $urls['lyrics'],            'lyricsData' => $data,        ];    }    public static function mime(string $path): string    {        return match (strtolower(pathinfo($path, PATHINFO_EXTENSION))) {            'ogg' => 'audio/ogg',            'flac' => 'audio/flac',            'wav' => 'audio/wav',            'mp4' => 'video/mp4',            'webm' => 'video/webm',            'mkv' => 'video/x-matroska',            'mid', 'midi' => 'audio/midi',            default => 'audio/mpeg',        };    }    /**     * The lyrics for the TV page: each line, when it starts / ends, its syllables and their moments (Karaoke, as the     * phone's karaoke), its translation when the lyrics have one (Lyrics::$translations); `synced` false: times only     * estimated (lyrics without times): the TV shows the lines without the syllable sweep.     * @return array{lines: list<array{t: float, e: float, text: string, syl: list<string>, at: list<float>, tr: string}>, synced: bool, lang: string}     */    public static function lyricsData(Lyrics $lyrics, float $duration): array    {        $out = [];        $lines = $lyrics->lines;        $translations = $lyrics->translations;        foreach ($lines as $i => [$time, $text]) {            $next = $lines[$i + 1][0] ?? ($duration > $time ? $duration : $time + 6.0);            $plain = Karaoke::plain($text);            [$syllables, $times, $end] = Karaoke::timing($text, (float)$time, (float)$next);            $out[] = ['t' => round((float)$time, 2), 'e' => round((float)$end, 2), 'text' => $plain, 'syl' => $syllables,                'at' => array_map(fn (float $t) => round($t, 2), $times), 'tr' => is_string($translations[$i] ?? null) ? $translations[$i] : ''];        }        return ['lines' => $out, 'synced' => $lyrics->synced, 'lang' => $lyrics->translationLang];    }    /** The lyrics as WebVTT subtitles (each line until the next one, 6 s at most). @param array{lines: list<array<string, mixed>>} $data */    public static function vtt(array $data): string    {        $out = "WEBVTT\n\n";        $lines = $data['lines'];        foreach ($lines as $i => $l) {            if (trim((string)$l['text']) === '') {                continue;            }            $start = (float)$l['t'];            $end = min((float)($lines[$i + 1]['t'] ?? $start + 6.0), $start + 6.0);            $out .= self::vttTime($start) . ' --> ' . self::vttTime(max($start + 0.5, $end)) . "\n"                . str_replace(["\r", "\n", '-->'], ['', ' ', '→'], (string)$l['text'])                . ((string)($l['tr'] ?? '') !== '' ? "\n" . str_replace(["\r", "\n", '-->'], ['', ' ', '→'], (string)$l['tr']) : '') . "\n\n";        }        return $out;    }    private static function vttTime(float $s): string    {        $ms = (int)round($s * 1000);        return sprintf('%02d:%02d:%02d.%03d', intdiv($ms, 3600000), intdiv($ms % 3600000, 60000), intdiv($ms % 60000, 1000), $ms % 1000);    }    public function close(): void    {        $this->target->close();    }}