<?phpnamespace App\Cast;/** * A Google Cast device driven in pure PHP (CASTV2), never blocking: a TLS connection to its port 8009 (opened, then * the handshake stepped each frame; the device's certificate is its own, self-signed: not checked, the LAN only), * CastMessage frames (CastV2), CONNECT to the platform receiver, a PING every 5 s (and PONG to its PINGs), LAUNCH of * an application (the Default Media Receiver CC1AD845, or WinZik's own receiver: an App ID), CONNECT to the * application's transport, then: * - with the Default Media Receiver it is a CastTarget: media LOAD of the song's URL (title, artist, album, cover, the * lyrics as a WebVTT text track), PLAY / PAUSE / SEEK / STOP, MEDIA_STATUS (position, state), the device's volume; * - with WinZik's receiver, TvTarget sends its messages on `urn:x-cast:net.jumphp.winzik` (send(), onMessage). * Commands given before the application is ready wait for it. Errors in French. */final class CastClient implements CastTarget{ private const PING_EVERY = 5.0; private const SILENCE = 20.0; private const STATUS_EVERY = 2.0; private const CONNECT_TIMEOUT = 8.0; /** @var resource|null */ private $socket = null; /** tcp | tls | open | ready | closed */ private string $phase = 'tcp'; private string $in = ''; private string $out = ''; private float $since; private float $heard; private float $pinged; private float $asked = 0.0; private int $request = 1; private string $transport = ''; private string $session = ''; private bool $launched = false; /** @var list<\Closure> what waits for the application */ private array $waiting = []; private string $error = ''; // the media (Default Media Receiver) private int $mediaSession = 0; private string $state = 'connecting'; private ?float $position = null; private float $positionAt = 0.0; private int $song = -1; private int $loading = -1; /** @var array<string, int> url => song id */ private array $songs = []; /** @var \Closure(array): void|null messages of WinZik's receiver (namespace WINZIK) */ public ?\Closure $onMessage = null; /** @var list<array{namespace: string, data: array}> tests / debugging: the last messages received */ public array $received = []; /** @param array<string, mixed> $ssl more stream context options (tests: a local fake device) */ public function __construct(private CastDevice $device, private string $appId = CastV2::DEFAULT_RECEIVER, array $ssl = []) { $this->since = $this->heard = $this->pinged = microtime(true); $context = stream_context_create(['ssl' => $ssl + ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, 'SNI_enabled' => false]]); $host = str_contains($device->host, ':') ? '[' . $device->host . ']' : $device->host; $socket = @stream_socket_client("tcp://$host:{$device->port}", $errno, $errstr, 0, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT, $context); if ($socket === false) { $this->fail('Connexion impossible à ' . $device->name . ' (' . ($errstr ?: 'réseau') . ')'); return; } stream_set_blocking($socket, false); $this->socket = $socket; } public function appId(): string { return $this->appId; } /** The application is running and connected: messages to it go out now. */ public function ready(): bool { return $this->phase === 'ready'; } public function closed(): bool { return $this->phase === 'closed'; } /** A message to the application (WinZik's receiver: namespace WINZIK), sent once it is ready. */ public function send(string $namespace, array $data): void { $this->whenReady(fn () => $this->write(CastV2::json($namespace, $data, $this->transport))); } // CastTarget (the Default Media Receiver) --------------------------------------------------------------------- public function load(array $song, float $at, bool $play): void { $this->loading = (int)$song['id']; $this->songs[(string)$song['url']] = (int)$song['id']; $this->state = 'loading'; $this->position = $at; $this->positionAt = microtime(true); $images = ($song['cover'] ?? '') !== '' ? [['url' => (string)$song['cover']]] : []; $media = [ 'contentId' => (string)$song['url'], 'contentUrl' => (string)$song['url'], 'contentType' => (string)($song['mime'] ?? 'audio/mpeg'), 'streamType' => 'BUFFERED', 'metadata' => array_filter([ 'metadataType' => 3, // MusicTrackMediaMetadata 'title' => (string)($song['title'] ?? 'WinZik'), 'artist' => (string)($song['artist'] ?? ''), 'albumName' => (string)($song['album'] ?? ''), 'images' => $images, ], fn ($v) => $v !== '' && $v !== []), ]; if ((float)($song['duration'] ?? 0) > 0) { $media['duration'] = round((float)$song['duration'], 2); } $load = ['type' => 'LOAD', 'media' => $media, 'autoplay' => $play, 'currentTime' => round($at, 2)]; if (($song['vtt'] ?? '') !== '') { // the lyrics as subtitles: the receiver may show them under the cover (a TV does for a film; for a song it // depends on the receiver: shown by some, ignored by others) $load['media']['tracks'] = [['trackId' => 1, 'type' => 'TEXT', 'subtype' => 'SUBTITLES', 'trackContentId' => (string)$song['vtt'], 'trackContentType' => 'text/vtt', 'name' => 'Paroles', 'language' => 'fr']]; $load['media']['textTrackStyle'] = ['fontScale' => 1.4, 'backgroundColor' => '#00000099', 'foregroundColor' => '#FFFFFFFF']; $load['activeTrackIds'] = [1]; } $this->whenReady(fn () => $this->media($load + ['sessionId' => $this->session])); } public function play(): void { $this->whenReady(fn () => $this->mediaSession > 0 ? $this->media(['type' => 'PLAY', 'mediaSessionId' => $this->mediaSession]) : null); } public function pause(): void { $this->whenReady(fn () => $this->mediaSession > 0 ? $this->media(['type' => 'PAUSE', 'mediaSessionId' => $this->mediaSession]) : null); } public function seek(float $seconds): void { $this->position = $seconds; $this->positionAt = microtime(true); $this->whenReady(fn () => $this->mediaSession > 0 ? $this->media(['type' => 'SEEK', 'mediaSessionId' => $this->mediaSession, 'currentTime' => round($seconds, 2)]) : null); } public function stop(): void { $this->whenReady(fn () => $this->mediaSession > 0 ? $this->media(['type' => 'STOP', 'mediaSessionId' => $this->mediaSession]) : null); } public function setVolume(int $volume): void { if ($this->phase === 'ready' || $this->phase === 'open') { $this->receiver(['type' => 'SET_VOLUME', 'volume' => ['level' => round(max(0, min(100, $volume)) / 100, 2)]]); } } public function status(): array { $p = $this->position; if ($p !== null && $this->state === 'playing') { $p += microtime(true) - $this->positionAt; } $state = match ($this->phase) { 'closed' => $this->state === 'lost' ? 'lost' : 'closed', 'ready' => $this->state, default => 'connecting', }; return ['state' => $state, 'position' => $p, 'song' => $this->song]; } public function error(): string { return $this->error; } /** Ends: WinZik's application stopped on the TV (it goes back to its home screen), the connection closed. */ public function close(): void { if ($this->socket !== null && in_array($this->phase, ['open', 'ready'], true)) { if ($this->launched && $this->session !== '') { $this->receiver(['type' => 'STOP', 'sessionId' => $this->session]); } if ($this->transport !== '') { $this->write(CastV2::json(CastV2::CONNECTION, ['type' => 'CLOSE'], $this->transport)); } $this->write(CastV2::json(CastV2::CONNECTION, ['type' => 'CLOSE'])); $this->flush(); } if ($this->socket !== null) { @fclose($this->socket); } $this->socket = null; $this->phase = 'closed'; } // the connection --------------------------------------------------------------------------------------------- public function poll(): void { if ($this->socket === null) { return; } $now = microtime(true); if ($this->phase === 'tcp') { $r = null; $w = [$this->socket]; $e = null; if (@stream_select($r, $w, $e, 0) === 1) { if (@stream_socket_get_name($this->socket, true) === false) { $this->fail($this->device->name . ' refuse la connexion (Cast éteint ?)'); return; } $this->phase = 'tls'; } elseif ($now - $this->since > self::CONNECT_TIMEOUT) { $this->fail($this->device->name . ' ne répond pas (éteint, ou sur un autre réseau ?)'); return; } } if ($this->phase === 'tls') { $ok = @stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($ok === false) { $this->fail('Connexion sécurisée impossible avec ' . $this->device->name); return; } if ($ok === 0) { if ($now - $this->since > self::CONNECT_TIMEOUT) { $this->fail($this->device->name . ' ne répond pas (connexion sécurisée)'); } return; } $this->phase = 'open'; $this->heard = $now; $this->write(CastV2::json(CastV2::CONNECTION, ['type' => 'CONNECT', 'userAgent' => 'WinZik', 'origin' => (object)[]])); $this->receiver(['type' => 'LAUNCH', 'appId' => $this->appId]); } $this->read(); if ($this->socket === null) { return; } if ($now - $this->pinged >= self::PING_EVERY) { $this->pinged = $now; $this->write(CastV2::json(CastV2::HEARTBEAT, ['type' => 'PING'])); } if ($now - $this->heard > self::SILENCE) { $this->state = 'lost'; $this->fail($this->device->name . ' ne répond plus (éteint, ou le Wi-Fi a coupé ?)'); return; } if ($this->phase === 'ready' && $this->mediaSession > 0 && $now - $this->asked >= self::STATUS_EVERY && $this->appId === CastV2::DEFAULT_RECEIVER) { $this->asked = $now; $this->media(['type' => 'GET_STATUS', 'mediaSessionId' => $this->mediaSession]); } $this->flush(); } private function read(): void { for ($n = 0; $n < 64; $n++) { $chunk = @fread($this->socket, 65536); if (!is_string($chunk) || $chunk === '') { break; } $this->in .= $chunk; $this->heard = microtime(true); } if (feof($this->socket) && $this->phase !== 'tcp' && $this->phase !== 'tls') { $this->fail($this->device->name . ' a fermé la connexion'); return; } try { $messages = CastV2::unframe($this->in); } catch (\RuntimeException) { $this->fail($this->device->name . ' n\'est pas un appareil Cast'); return; } foreach ($messages as $m) { $data = json_decode($m['payload'], true); if (is_array($data)) { $this->message($m['namespace'], $m['source'], $data); } if ($this->socket === null) { return; } } } /** @param array<string, mixed> $data */ private function message(string $namespace, string $source, array $data): void { $this->received[] = ['namespace' => $namespace, 'data' => $data]; if (count($this->received) > 50) { array_shift($this->received); } $type = (string)($data['type'] ?? ''); if ($namespace === CastV2::HEARTBEAT && $type === 'PING') { $this->write(CastV2::json(CastV2::HEARTBEAT, ['type' => 'PONG'], $source)); return; } if ($namespace === CastV2::CONNECTION && $type === 'CLOSE') { $this->fail($source === $this->transport && $this->transport !== '' ? 'La TV a arrêté WinZik' : $this->device->name . ' a fermé la connexion'); return; } if ($namespace === CastV2::RECEIVER) { $this->receiverMessage($type, $data); return; } if ($namespace === CastV2::MEDIA) { $this->mediaMessage($type, $data); return; } if ($namespace === CastV2::WINZIK && $this->onMessage !== null) { ($this->onMessage)($data); } } /** @param array<string, mixed> $data */ private function receiverMessage(string $type, array $data): void { if ($type === 'LAUNCH_ERROR' || $type === 'INVALID_REQUEST') { $reason = (string)($data['reason'] ?? ''); $this->fail($this->appId === CastV2::DEFAULT_RECEIVER ? 'La TV refuse de lancer le lecteur Cast' . ($reason !== '' ? " ($reason)" : '') : 'La TV refuse de lancer WinZik : vérifiez l\'App ID (' . $this->appId . ')' . ($reason !== '' ? " ($reason)" : '')); return; } if ($type !== 'RECEIVER_STATUS') { return; } $app = null; foreach ((array)($data['status']['applications'] ?? []) as $a) { if (is_array($a) && strtoupper((string)($a['appId'] ?? '')) === strtoupper($this->appId)) { $app = $a; } } if ($app === null) { if ($this->phase === 'ready') { $this->fail('Une autre application a pris la TV'); // someone cast something else } return; } if ($this->phase === 'open') { $this->transport = (string)($app['transportId'] ?? ''); $this->session = (string)($app['sessionId'] ?? ''); $this->launched = true; $this->write(CastV2::json(CastV2::CONNECTION, ['type' => 'CONNECT', 'userAgent' => 'WinZik', 'origin' => (object)[]], $this->transport)); $this->phase = 'ready'; $this->state = $this->loading >= 0 ? 'loading' : 'idle'; $waiting = $this->waiting; $this->waiting = []; foreach ($waiting as $w) { $w(); } } } /** @param array<string, mixed> $data */ private function mediaMessage(string $type, array $data): void { if ($type === 'LOAD_FAILED' || $type === 'LOAD_CANCELLED' || $type === 'INVALID_REQUEST') { $this->error = $type === 'LOAD_FAILED' ? 'La TV n\'arrive pas à lire ce morceau (réseau, pare-feu ou format)' : 'La TV a refusé la commande'; if ($type !== 'INVALID_REQUEST') { $this->state = 'idle'; $this->loading = -1; } return; } if ($type !== 'MEDIA_STATUS') { return; } $s = $data['status'][0] ?? null; if (!is_array($s)) { return; } $this->mediaSession = (int)($s['mediaSessionId'] ?? $this->mediaSession); $url = (string)($s['media']['contentId'] ?? ''); if ($url !== '' && isset($this->songs[$url])) { $this->song = $this->songs[$url]; } elseif ($this->loading >= 0 && in_array($s['playerState'] ?? '', ['PLAYING', 'PAUSED', 'BUFFERING'], true)) { $this->song = $this->loading; } if ($this->song === $this->loading && ($s['playerState'] ?? '') !== 'IDLE') { $this->loading = -1; } if (isset($s['currentTime'])) { $this->position = (float)$s['currentTime']; $this->positionAt = microtime(true); } $this->state = match ((string)($s['playerState'] ?? '')) { 'PLAYING' => 'playing', 'PAUSED' => 'paused', 'BUFFERING', 'LOADING' => 'loading', default => $this->loading >= 0 ? 'loading' : 'idle', }; if (($s['idleReason'] ?? '') === 'ERROR') { $this->error = 'La TV n\'arrive pas à lire ce morceau (réseau, pare-feu ou format)'; } } private function receiver(array $data): void { $this->write(CastV2::json(CastV2::RECEIVER, $data + ['requestId' => $this->request++])); } private function media(array $data): void { $this->write(CastV2::json(CastV2::MEDIA, $data + ['requestId' => $this->request++], $this->transport)); } private function whenReady(\Closure $do): void { if ($this->phase === 'ready') { $do(); } elseif ($this->phase !== 'closed') { $this->waiting[] = $do; } } private function write(string $bytes): void { $this->out .= $bytes; } private function flush(): void { for ($n = 0; $n < 16 && $this->out !== '' && $this->socket !== null; $n++) { $written = @fwrite($this->socket, $this->out); if ($written === false) { $this->fail($this->device->name . ' : connexion coupée'); return; } if ($written === 0) { return; } $this->out = (string)substr($this->out, $written); } } private function fail(string $message): void { $this->error = $message; if ($this->socket !== null) { @fclose($this->socket); } $this->socket = null; $this->phase = 'closed'; $this->waiting = []; }}