ES
apps/winzik / src / Cast / Cast.php · commit 6576d6f
<?phpnamespace App\Cast;use App\Audio\Player;use App\Core\WinZik;/** * Casting to the TV (AGENTS.md "Cast"): the screens of the home network (Google Cast, DLNA), and one cast at a time, * in one of two modes: * - `stream`: the TV plays the music (DLNA AVTransport, or Google's Default Media Receiver); WinZik is the remote, *   its karaoke follows the TV's position; * - `interface`: the TV shows WinZik's TV screen (the song, the cover, the karaoke lyrics, what comes next) and plays *   it, WinZik being the remote: in a TV / console browser (openTvPage(): an address to type, a QR code), or on a *   Google Cast device with WinZik's receiver (an App ID: setAppId()); without an App ID a Cast device gets the *   music with the lyrics as subtitles; a DLNA TV cannot show a page (streaming then); * - `vlc` (openVlcStream()): an address that never changes to open in VLC (a TV's, a box's): ffmpeg makes from what *   WinZik plays a web radio (MP3), or a film with the cover and the karaoke (MPEG-TS, a computer's ffmpeg). * Desktop and phone app (sockets); not in the browser (supported() is false). */final class Cast{    private Discovery $discovery;    private LanHttp $http;    private ?CastSession $session = null;    private ?CastDevice $device = null;    /** the last notice, in French */    public string $message = '';    public bool $failed = false;    /** Google Cast App ID of WinZik's receiver ('' none: the Default Media Receiver) */    private string $appId = '';    /** @var array<string, mixed>|null the device of the last cast (listed before a search finds it again) */    private ?array $last = null;    /** the secret of the VLC address (kept: the address saved in VLC works again next time) */    private string $vlcCode = '';    /** @var list<string>|null tests: the addresses of this computer (null: its own) */    public ?array $addresses = null;    /** the media server of the network (VLC's "Réseau local" finds WinZik), null while off */    private ?MediaServer $media = null;    /** its UPnP identity (kept: the players remember it) */    private string $mediaUuid = '';    public function __construct(private WinZik $wz, private string $file, private ?TvServer $server = null, ?LanHttp $http = null)    {        $this->http = $http ?? new LanHttp();        $this->discovery = new Discovery($this->http);        $this->server ??= new TvServer();        $saved = is_file($file) ? json_decode((string)file_get_contents($file), true) : null;        if (is_array($saved)) {            $this->appId = is_string($saved['appId'] ?? null) ? self::cleanAppId($saved['appId']) : '';            $this->last = is_array($saved['last'] ?? null) ? $saved['last'] : null;            $this->mediaUuid = is_string($saved['media'] ?? null) && preg_match('/^[0-9a-f-]{36}$/', $saved['media']) ? $saved['media'] : '';            $this->vlcCode = is_string($saved['vlc'] ?? null) && preg_match('/^[a-z2-9]{10}$/', $saved['vlc']) ? $saved['vlc'] : '';            if ($this->last !== null && isset($this->last['id'], $this->last['kind'], $this->last['host'])) {                $l = $this->last;                $this->discovery->remember(new CastDevice((string)$l['kind'], (string)$l['id'], (string)($l['name'] ?? 'TV'), (string)($l['model'] ?? ''),                    (string)$l['host'], (int)($l['port'] ?? 8009), (string)($l['avTransport'] ?? ''), (string)($l['rendering'] ?? '')));            }        }    }    public static function supported(): bool    {        return TvServer::supported();    }    public function discovery(): Discovery    {        return $this->discovery;    }    public function server(): TvServer    {        return $this->server;    }    // the screens ---------------------------------------------------------------------------------------------------    /** Looks for the screens of the network for a few seconds (devices() grows meanwhile). */    public function search(float $seconds = 6.0): void    {        if (!$this->discovery->search($seconds)) {            $this->say($this->discovery->error, true);        }    }    public function searching(): bool    {        return $this->discovery->searching();    }    /** @return list<CastDevice> */    public function devices(): array    {        return $this->discovery->devices();    }    public function appId(): string    {        return $this->appId;    }    /** WinZik's Cast receiver ('' = none: Google's Default Media Receiver). Saved. */    public function setAppId(string $appId): void    {        $this->appId = self::cleanAppId($appId);        $this->save();    }    /** An App ID is 8 hexadecimal characters (upper case), anything else is none. */    public static function cleanAppId(string $appId): string    {        $appId = strtoupper(trim($appId));        return preg_match('/^[0-9A-F]{8}$/', $appId) ? $appId : '';    }    // a cast -------------------------------------------------------------------------------------------------------    /**     * Casts to a device found. $mode: 'stream' | 'interface'. false (and `message` says why) when it cannot start.     */    public function connect(string $deviceId, string $mode = 'stream'): bool    {        $device = $this->discovery->device($deviceId);        if ($device === null) {            return $this->say('Cet appareil n\'est plus là : relancez la recherche', true);        }        $this->disconnect(false);        $server = $this->server;        if (!$server->open()) {            return $this->say('Impossible d\'ouvrir le serveur de WinZik pour la TV (pare-feu ?)', true);        }        $server->useHostFor($device->host);        $mode = $mode === 'interface' ? 'interface' : 'stream';        if ($device->kind === CastDevice::DLNA) {            $target = new DlnaTarget($device, $this->http);            $how = 'dlna';            $note = $mode === 'interface' ? 'Une TV DLNA ne peut pas afficher l\'écran WinZik : la musique y est diffusée, les paroles restent ici' : '';            $mode = 'stream';        } elseif ($mode === 'interface' && $this->appId !== '') {            $target = new TvTarget(new CastClient($device, $this->appId));            $how = 'cast-app';            $note = '';        } else {            $target = new CastClient($device, CastV2::DEFAULT_RECEIVER);            $how = 'cast-media';            $note = $mode === 'interface' ? 'Sans App ID WinZik : le lecteur Cast de Google joue la musique, les paroles partent en sous-titres (selon la TV). L\'écran WinZik complet : son adresse dans le navigateur de la TV, ou un App ID.' : '';        }        $this->start(new CastSession($this->wz, $target, $server, $mode, $how), $device);        $this->last = $device->toArray() + ['avTransport' => $device->avTransport, 'rendering' => $device->rendering];        $this->save();        return $this->say($note !== '' ? $note : 'Connexion à ' . $device->name . '…', false);    }    /**     * Mode interface in any browser of the network (a smart TV's, a console's, a tablet's): WinZik's TV page, its     * address to type there (tvUrl()) or its QR code (qrPng()).     */    public function openTvPage(): bool    {        $this->disconnect(false);        if (!$this->server->open()) {            return $this->say('Impossible d\'ouvrir le serveur de WinZik pour la TV (pare-feu ?)', true);        }        $tv = new TvTarget();        $this->server->onState = fn (array $q): array => $tv->stateFor($q);        $this->server->onCommand = fn (string $do, array $q) => $tv->command($do, $q);        $this->start(new CastSession($this->wz, $tv, $this->server, 'interface', 'browser'), null);        return $this->say('Ouvrez ' . $this->server->tvUrl() . ' dans le navigateur de la TV', false);    }    /**     * The music for VLC: an address (vlcUrl(), the same each time) to open in VLC on the TV ("Flux réseau" /     * "Ouvrir un flux réseau"); $video: the cover and the karaoke as a film (an ffmpeg with an H.264 encoder and     * libass), else the sound only (MP3, any ffmpeg: the phone's too).     */    public function openVlcStream(bool $video = false): bool    {        $this->disconnect(false);        $ffmpeg = $this->wz->tools?->program('ffmpeg');        if ($ffmpeg === null) {            return $this->say($this->wz->tools?->ffmpegMissing() ?: 'ffmpeg manque : impossible de faire le flux pour VLC', true);        }        if ($video && !VlcTarget::canVideo($ffmpeg)) {            return $this->say('Le ffmpeg de cet appareil ne sait pas faire la vidéo karaoké (encodeur H.264, libass) : prenez le flux audio', true);        }        if ($this->vlcCode === '') {            $letters = 'abcdefghjkmnpqrstuvwxyz23456789';            foreach (str_split(random_bytes(10)) as $byte) {                $this->vlcCode .= $letters[ord($byte) % strlen($letters)];            }            $this->save();        }        $live = new LiveServer($this->vlcCode, $video ? 'video/mp2t' : 'audio/mpeg', $video ? 'ts' : 'mp3');        if (!$live->open()) {            return $this->say('Impossible d\'ouvrir le flux pour VLC (pare-feu ?)', true);        }        $live->anyAddress = $this->addresses !== null;        $target = new VlcTarget($ffmpeg, dirname($this->file) . '/tmp/vlc', $live, $video);        $this->tune($target);        $this->start(new CastSession($this->wz, $target, $this->server, 'stream', $video ? 'vlc-video' : 'vlc'), null);        return $this->say('Dans VLC sur la TV, ouvrez le flux réseau ' . $this->vlcUrl(), false);    }    /** The address to open in VLC ('' when no VLC stream is open); $host: the address the player reaches us at. */    public function vlcUrl(?string $host = null): string    {        $target = $this->session?->target;        if (!$target instanceof VlcTarget) {            return '';        }        $host ??= ($this->addresses ?? \App\Cloud\LanShare::localAddresses())[0] ?? '127.0.0.1';        return 'http://' . (str_contains($host, ':') ? "[$host]" : $host) . ':' . $target->live->port() . $target->live->path();    }    // the media server ------------------------------------------------------------------------------------------------    /**     * WinZik in VLC's "Réseau local" (UPnP / DLNA media server): on or off (option `mediaServer`, saved). false + message     * when it cannot listen.     */    public function setMediaServer(bool $on): bool    {        $this->wz->options['mediaServer'] = $on;        if (!$on) {            $this->media?->stop();            $this->media = null;            return true;        }        if ($this->media?->running()) {            return true;        }        if ($this->mediaUuid === '') {            $h = bin2hex(random_bytes(16));            $this->mediaUuid = sprintf('%s-%s-4%s-a%s-%s', substr($h, 0, 8), substr($h, 8, 4), substr($h, 13, 3), substr($h, 17, 3), substr($h, 20, 12));            $this->save();        }        $this->media = new MediaServer($this->wz, $this, $this->mediaUuid, self::mediaName());        $this->media->addresses = $this->addresses;        if ($this->addresses !== null) {            // tests: no announcement on the real network, no port 1900            $this->media->announceTo = '127.0.0.1:9';            $this->media->listen1900 = false;        }        if (!$this->media->start()) {            $this->media = null;            return $this->say('Impossible d\'ouvrir le serveur multimédia (pare-feu ?)', true);        }        return true;    }    public function mediaServer(): ?MediaServer    {        return $this->media;    }    /** The name VLC shows (nothing personal: not the computer's name). */    public static function mediaName(): string    {        return 'WinZik (' . (\JumPHP\Kernel\Platform::isPhoneApp() ? 'téléphone' : 'PC') . ')';    }    private function start(CastSession $session, ?CastDevice $device): void    {        $this->session = $session;        $this->device = $device;        $this->wz->player->silent = true;        $this->wz->setVolume($this->wz->player->volume);    // heard on the TV only    }    /** Ends the cast: the TV stops (WinZik's application closed there), the music comes back here, paused. */    public function disconnect(bool $say = true): void    {        if ($this->session === null) {            return;        }        $this->session->close();        $this->session = null;        $this->device = null;        $this->server->close();        $this->server->onState = null;        $this->server->onCommand = null;        if ($this->wz->player->state === Player::PLAYING) {            $this->wz->pause();        }        $this->wz->player->silent = false;        $this->wz->setVolume($this->wz->player->volume);        if ($say) {            $this->say('Diffusion arrêtée', false);        }    }    public function active(): bool    {        return $this->session !== null;    }    public function session(): ?CastSession    {        return $this->session;    }    public function device(): ?CastDevice    {        return $this->device;    }    /** stream | interface ('' nothing cast) */    public function mode(): string    {        return $this->session->mode ?? '';    }    /** dlna | cast-media | cast-app | browser | vlc | vlc-video ('' nothing cast) */    public function how(): string    {        return $this->session->how ?? '';    }    /** off (nothing cast) | connecting | casting | lost (no answer) */    public function state(): string    {        if ($this->session === null) {            return 'off';        }        return match ($this->session->target->status()['state']) {            'connecting' => 'connecting',            'lost' => 'lost',            default => 'casting',        };    }    /** One line in French: where it is cast, how, or what is wrong. */    public function statusText(): string    {        if ($this->session === null) {            return $this->message !== '' ? $this->message : 'Rien n\'est diffusé';        }        $vlc = str_starts_with($this->how(), 'vlc');        $where = $this->device->name ?? ($vlc ? 'VLC' : 'le navigateur de la TV');        $how = match ($this->how()) {            'dlna' => 'streaming DLNA',            'cast-media' => $this->mode() === 'interface' ? 'Cast, paroles en sous-titres' : 'streaming Cast',            'cast-app' => 'écran WinZik (Cast)',            'vlc' => 'flux audio',            'vlc-video' => 'vidéo karaoké',            default => 'écran WinZik',        };        return match ($this->state()) {            'connecting' => match (true) {                $vlc => 'En attente de VLC : ouvrez le flux réseau ' . $this->vlcUrl(),                $this->how() === 'browser' => 'En attente de la TV : ouvrez ' . $this->server->tvUrl(),                default => 'Connexion à ' . $where . '…',            },            'lost' => ($this->session->target->error() ?: $where . ' ne répond plus') . ' (nouvel essai…)',            default => 'Diffusé sur ' . $where . ' (' . $how . ')',        };    }    /** The address to type on the TV: its page in a browser, or the VLC stream ('' when there is none). */    public function tvUrl(): string    {        return $this->how() === 'browser' ? $this->server->tvUrl() : $this->vlcUrl();    }    /** The QR code of the TV page as a PNG (var/cast/tv-qr.png); null without a TV page. */    public function qrPng(): ?string    {        $url = $this->tvUrl();        if ($url === '') {            return null;        }        $png = dirname($this->file) . '/cast/tv-qr-' . substr(md5($url), 0, 8) . '.png';        return is_file($png) || Qr::png($url, $png, 8) ? $png : null;    }    /** The stream's karaoke mark (option `karaoke`, as the lyrics bar's) and quality (option `castQuality`), followed live. */    private function tune(VlcTarget $target): void    {        $target->style = (string)($this->wz->options['karaoke'] ?? 'ball');        $quality = (string)($this->wz->options['castQuality'] ?? 'auto');        $target->quality = isset(VlcTarget::QUALITY_NAMES[$quality]) ? $quality : 'auto';    }    /** Auto | Haute | Moyenne | Basse: the video stream's quality (saved; the next piece of the stream takes it). */    public function setQuality(string $quality): void    {        $this->wz->options['castQuality'] = isset(VlcTarget::QUALITY_NAMES[$quality]) ? $quality : 'auto';        if ($this->session?->target instanceof VlcTarget) {            $this->tune($this->session->target);        }    }    public function quality(): string    {        $q = (string)($this->wz->options['castQuality'] ?? 'auto');        return isset(VlcTarget::QUALITY_NAMES[$q]) ? $q : 'auto';    }    public function tick(float $dt): void    {        $this->media?->poll();        $vlc = $this->session?->target;        if ($vlc instanceof VlcTarget) {            $this->tune($vlc);            if ($vlc->qualityNote !== '') {                $this->wz->notice($vlc->qualityNote, 6);                $vlc->qualityNote = '';            }        }        $this->discovery->poll();        if ($this->session === null) {            $this->http->poll();            return;        }        $this->session->tick($dt);        $state = $this->session->target->status()['state'];        if ($state === 'closed') {            // the TV ended it (its remote, another phone casting): the music comes back here, paused            $why = $this->session->target->error();            $this->disconnect(false);            $this->say($why !== '' ? $why : 'La TV a arrêté la diffusion', true);            $this->wz->notice($this->message, 6);        }    }    public function stop(): void    {        $this->media?->stop();        $this->media = null;        $this->disconnect(false);        $this->discovery->close();        $this->http->close();    }    private function say(string $message, bool $failed): bool    {        $this->message = $message;        $this->failed = $failed;        return !$failed;    }    private function save(): void    {        @mkdir(dirname($this->file), 0777, true);        WinZik::writeJsonFile($this->file, ['appId' => $this->appId, 'last' => $this->last, 'vlc' => $this->vlcCode, 'media' => $this->mediaUuid]);    }}