polled while waiting */ private array $pollers = []; protected function setUp(): void { $this->tmp = sys_get_temp_dir() . '/winzik-cast-' . bin2hex(random_bytes(4)); @mkdir($this->tmp, 0777, true); $this->pollers = []; } protected function tearDown(): void { exec('rm -rf ' . escapeshellarg($this->tmp)); } /** Polls everything until $done says yes (or $seconds pass). */ private function until(callable $done, float $seconds = 5.0): bool { $end = microtime(true) + $seconds; while (microtime(true) < $end) { foreach ($this->pollers as $p) { $p(); } if ($done()) { return true; } usleep(10000); } return false; } // the wire -------------------------------------------------------------------------------------------------- public function testACastMessageGoesThereAndBackWhateverTheSizeOfItsPayload(): void { foreach ([0, 1, 127, 128, 300, 9000] as $n) { $payload = json_encode(['type' => 'LOAD', 'x' => str_repeat('é', $n)]); $frame = CastV2::frame(CastV2::encode(['source' => 'sender-0', 'destination' => 'web-3', 'namespace' => CastV2::MEDIA, 'payload' => (string)$payload])); self::assertSame(strlen($frame) - 4, unpack('N', $frame)[1]); // the frames come in pieces, several at once $buffer = substr($frame, 0, 3); self::assertSame([], CastV2::unframe($buffer)); $buffer .= substr($frame, 3) . $frame; $out = CastV2::unframe($buffer); self::assertCount(2, $out); self::assertSame('', $buffer); self::assertSame(['sender-0', 'web-3', CastV2::MEDIA, $payload, null, 0], [$out[0]['source'], $out[0]['destination'], $out[0]['namespace'], $out[0]['payload'], $out[0]['binary'], $out[0]['version']]); } $bin = CastV2::decode(CastV2::encode(['namespace' => 'urn:x-cast:com.google.cast.tp.deviceauth', 'binary' => "\x00\x01\xff"])); self::assertSame("\x00\x01\xff", $bin['binary']); // the bytes of a known message: CONNECT as Chromium writes it $connect = CastV2::encode(['namespace' => CastV2::CONNECTION, 'payload' => '{"type":"CONNECT"}']); self::assertSame('0800120873656e6465722d301a0a72656365697665722d30', bin2hex(substr($connect, 0, 24))); // a frame announced bigger than 64 KB is not a Cast device $bad = pack('N', 70000) . 'xx'; $this->expectException(\RuntimeException::class); CastV2::unframe($bad); } public function testTheAnswersOfACastDeviceToTheMdnsQuestionGiveItsNameModelAndAddress(): void { $q = Mdns::query(); self::assertSame("\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x0b_googlecast\x04_tcp\x05local\x00\x00\x0c\x80\x01", $q); $packet = Mdns::answer('Chromecast-Ultra-0a1b', 'Salon', 'Chromecast Ultra', '0a1b2c', '192.168.1.42'); self::assertSame([['id' => '0a1b2c', 'name' => 'Salon', 'model' => 'Chromecast Ultra', 'host' => '192.168.1.42', 'port' => 8009]], Mdns::castDevices($packet, '192.168.1.42')); // as a real device answers: names compressed (pointers), the TXT and SRV in the additional records, no A record // as a Freebox Player answers: names compressed (pointers), TXT, SRV and A in the additional records $hex = '0000840000000001000000030b5f676f6f676c6563617374045f746370056c6f63616c00000c000100000078001a1746726565626f782d506c617965' . '722d504f502d33666437c00cc02e0010800100001194007b1369643d336664376164346364353937363365370763643d4630304403726d3d0576653d' . '3035156d643d46726565626f7820506c6179657220504f501269633d2f73657475702f69636f6e2e706e670b666e3d53616c6f6e2054560963613d32' . '30303730390473743d300762733d46413846046e663d310372733dc02e00218001000000780011000000001f49083366643761643463c01dc0e10001' . '8001000000780004c0a80103'; self::assertSame([['id' => '3fd7ad4cd59763e7', 'name' => 'Salon TV', 'model' => 'Freebox Player POP', 'host' => '192.168.1.3', 'port' => 8009]], Mdns::castDevices((string)hex2bin($hex), '192.168.1.99')); // garbage, a question, a loop of pointers: nothing, no error self::assertSame([], Mdns::castDevices('xx')); self::assertSame([], Mdns::castDevices($q)); self::assertSame([], Mdns::castDevices("\x00\x00\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00\xc0\x0c")); } public function testAnSsdpAnswerAndATvDescriptionGiveItsNameAndItsControlAddresses(): void { $answer = "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=1800\r\nDATE: Thu, 20 Nov 2026 10:00:00 GMT\r\nEXT:\r\n" . "LOCATION: http://192.168.1.20:9197/dmr\r\nSERVER: SHP, UPnP/1.0, Samsung UPnP SDK/1.0\r\n" . "ST: urn:schemas-upnp-org:device:MediaRenderer:1\r\nUSN: uuid:0a1b::urn:schemas-upnp-org:device:MediaRenderer:1\r\n\r\n"; self::assertSame('http://192.168.1.20:9197/dmr', Ssdp::parse($answer)['location'] ?? null); self::assertNull(Ssdp::parse("NOTIFY * HTTP/1.1\r\nNTS: ssdp:byebye\r\nLOCATION: http://x/\r\nNT: upnp:rootdevice\r\n\r\n")); self::assertNull(Ssdp::parse("HTTP/1.1 200 OK\r\nLOCATION: http://192.168.1.1/igd.xml\r\nST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n\r\n")); self::assertStringContainsString("ST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n", Ssdp::search()); $xml = '[TV] Salon & cuisine' . 'Samsung ElectronicsUE55uuid:0a1b' . 'urn:schemas-upnp-org:service:ConnectionManager:1/cm' . 'urn:schemas-upnp-org:service:AVTransport:1upnp/control/AVTransport1' . 'urn:schemas-upnp-org:service:RenderingControl:1/upnp/control/RenderingControl1' . ''; $d = Ssdp::description($xml, 'http://192.168.1.20:9197/dmr'); self::assertSame(['[TV] Salon & cuisine', 'UE55', 'Samsung Electronics', 'uuid:0a1b', 'http://192.168.1.20:9197/upnp/control/AVTransport1', 'http://192.168.1.20:9197/upnp/control/RenderingControl1'], array_values((array)$d)); self::assertNull(Ssdp::description('Box', 'http://192.168.1.1/')); self::assertSame('http://h:1/a/b/c', Ssdp::absolute('http://h:1/a/b/desc.xml', 'c')); } public function testTheQrCodeOfTheTvPageIsTheOneOpenCvReadBack(): void { // checked once with OpenCV's QRCodeDetector (versions 1 to 6); kept here as it was read back $m = Qr::matrix('http://192.168.1.60:47620/tv/k7m2p9xq'); self::assertCount(29, $m); self::assertSame('65a7f8429e4f1aa1419a086a89f5e3a8', md5(implode("\n", array_map(fn ($r) => implode('', array_map(fn ($b) => $b ? '#' : '.', $r)), $m)))); self::assertTrue(Qr::png('http://10.0.0.2:47620/tv/abcd2345', "$this->tmp/qr.png", 4)); self::assertSame([(29 + 8) * 4, (29 + 8) * 4], array_slice((array)getimagesize("$this->tmp/qr.png"), 0, 2)); $this->expectException(\InvalidArgumentException::class); Qr::matrix(str_repeat('x', 200)); } public function testTheReceiverPageToHostIsTheTvPageWithTheCastTransport(): void { self::assertSame(TvPage::html('cast'), (string)file_get_contents(TvPage::receiverFile()), 'site/cast/receiver.html is made from assets/cast/tv.html: php tools/cast-receiver.php'); self::assertStringContainsString('cast_receiver_framework.js', TvPage::html('cast')); self::assertStringNotContainsString('gstatic', TvPage::html('http')); } // discovery against fakes on 127.0.0.1 ------------------------------------------------------------------------- public function testTheSearchFindsTheDlnaTvAndTheChromecastOfTheNetwork(): void { $tv = new FakeRenderer(); FakeCastDevice::certificate("$this->tmp/cert.pem"); $cc = new FakeCastDevice("$this->tmp/cert.pem"); $d = new Discovery(new LanHttp()); $d->targets = ['ssdp' => '127.0.0.1:' . $tv->udpPort, 'mdns' => '127.0.0.1:' . $cc->udpPort]; $this->pollers = [fn () => $tv->poll(), fn () => $cc->poll(), fn () => $d->poll()]; self::assertTrue($d->search(3.0)); self::assertTrue($this->until(fn () => count($d->devices()) === 2, 3.0)); [$a, $b] = $d->devices(); self::assertSame([CastDevice::CAST, 'Salon', 'Chromecast', '127.0.0.1', $cc->port], [$a->kind, $a->name, $a->model, $a->host, $a->port]); self::assertSame([CastDevice::DLNA, 'Téléviseur du salon', 'Fake TV 2026'], [$b->kind, $b->name, $b->model]); self::assertSame("http://127.0.0.1:{$tv->port}/ctrl/avt", $b->avTransport); self::assertSame("http://127.0.0.1:{$tv->port}/ctrl/rc", $b->rendering); self::assertTrue($this->until(fn () => !$d->searching(), 4.0)); // switched off: the next search forgets it $tv->close(); $this->pollers = [fn () => $cc->poll(), fn () => $d->poll()]; $d->search(3.0); self::assertTrue($this->until(fn () => !$d->searching(), 5.0)); self::assertSame(['Salon'], array_map(fn (CastDevice $x) => $x->name, $d->devices())); $cc->close(); } // DLNA --------------------------------------------------------------------------------------------------------- private function renderer(FakeRenderer $tv): CastDevice { return new CastDevice(CastDevice::DLNA, 'dlna:uuid:fake-tv-0001', $tv->name, 'Fake TV 2026', '127.0.0.1', $tv->port, "http://127.0.0.1:{$tv->port}/ctrl/avt", "http://127.0.0.1:{$tv->port}/ctrl/rc"); } public function testADlnaTvIsToldTheSongWithItsMetadataThenPlaysPausesSeeksAndSaysWhereItIs(): void { $tv = new FakeRenderer(); $http = new LanHttp(); $t = new DlnaTarget($this->renderer($tv), $http); $this->pollers = [fn () => $tv->poll(), fn () => $t->poll()]; $song = ['id' => 1, 'url' => 'http://127.0.0.1:9/c/x/m/1.mp3', 'mime' => 'audio/mpeg', 'title' => 'Ça plane pour moi', 'artist' => 'Plastic & co', 'album' => 'Album', 'cover' => 'http://127.0.0.1:9/c/x/i/1', 'duration' => 180.0]; $t->load($song, 0.0, true); self::assertTrue($this->until(fn () => $t->status()['state'] === 'playing')); self::assertSame(['Stop', 'SetAVTransportURI', 'Play'], array_slice($tv->names(), 0, 3)); self::assertSame($song['url'], $tv->uri); self::assertStringContainsString('Ça plane pour moi', $tv->metadata); self::assertStringContainsString('Plastic & co', $tv->metadata); self::assertStringContainsString('http://127.0.0.1:9/c/x/i/1', $tv->metadata); self::assertStringContainsString('protocolInfo="http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;', $tv->metadata); self::assertStringContainsString('object.item.audioItem.musicTrack', $tv->metadata); self::assertSame(1, $t->status()['song']); $t->seek(75.4); self::assertTrue($this->until(fn () => in_array('Seek', $tv->names(), true))); self::assertSame(['InstanceID' => '0', 'Unit' => 'REL_TIME', 'Target' => '0:01:15'], $tv->actions[array_search('Seek', $tv->names(), true)]['args']); self::assertTrue($this->until(fn () => abs((float)$t->status()['position'] - 76) < 1.5, 3.0), 'the position comes from GetPositionInfo'); $t->pause(); self::assertTrue($this->until(fn () => $t->status()['state'] === 'paused', 3.0)); $t->setVolume(35); self::assertTrue($this->until(fn () => $tv->volume === 35)); // the TV refuses a song: said in French $tv->refuse = 714; $t->load(['id' => 2, 'url' => 'http://127.0.0.1:9/c/x/m/2.mkv', 'mime' => 'video/x-matroska', 'title' => 'Film'], 0.0, true); self::assertTrue($this->until(fn () => $t->error() !== '')); self::assertSame('La TV refuse ce morceau : La TV refuse : Illegal MIME-Type (714)', $t->error()); // switched off: lost after three questions without answer $tv->close(); $this->pollers = [fn () => $t->poll()]; self::assertTrue($this->until(fn () => $t->status()['state'] === 'lost', 6.0)); self::assertStringContainsString('ne répond plus', $t->error()); $t->close(); } // Google Cast over TLS ----------------------------------------------------------------------------------------- public function testAChromecastIsDrivenOverTlsWithTheDefaultMediaReceiver(): void { FakeCastDevice::certificate("$this->tmp/cert.pem"); $cc = new FakeCastDevice("$this->tmp/cert.pem"); $c = new CastClient(new CastDevice(CastDevice::CAST, 'cast:fake01', 'Salon', 'Chromecast', '127.0.0.1', $cc->port)); $this->pollers = [fn () => $cc->poll(), fn () => $c->poll()]; $song = ['id' => 4, 'url' => 'http://127.0.0.1:9/c/x/m/4.mp3', 'mime' => 'audio/mpeg', 'title' => 'Titre', 'artist' => 'Artiste', 'album' => '', 'cover' => 'http://127.0.0.1:9/c/x/i/4', 'duration' => 200.0, 'vtt' => 'http://127.0.0.1:9/c/x/v/4.vtt']; $c->load($song, 12.0, true); // waits for the receiver self::assertTrue($this->until(fn () => $c->status()['state'] === 'playing'), 'TLS handshake, CONNECT, LAUNCH, CONNECT to the app, LOAD'); self::assertSame(['CONNECT', 'CONNECT'], $cc->types(CastV2::CONNECTION)); self::assertSame(FakeCastDevice::TRANSPORT, array_values(array_filter($cc->messages, fn ($m) => $m['namespace'] === CastV2::CONNECTION))[1]['destination']); self::assertSame(['type' => 'LAUNCH', 'appId' => 'CC1AD845'], array_intersect_key((array)$cc->last('LAUNCH'), ['type' => 1, 'appId' => 1])); $load = (array)$cc->last('LOAD'); self::assertSame([$song['url'], 'audio/mpeg', 'BUFFERED', 3, 'Titre', 'Artiste', [['url' => $song['cover']]], 12, true, [1]], [$load['media']['contentId'], $load['media']['contentType'], $load['media']['streamType'], $load['media']['metadata']['metadataType'], $load['media']['metadata']['title'], $load['media']['metadata']['artist'], $load['media']['metadata']['images'], $load['currentTime'], $load['autoplay'], $load['activeTrackIds']]); self::assertSame('text/vtt', $load['media']['tracks'][0]['trackContentType']); self::assertSame(4, $c->status()['song']); $c->pause(); self::assertTrue($this->until(fn () => $c->status()['state'] === 'paused')); $c->seek(60.0); self::assertTrue($this->until(fn () => $cc->last('SEEK') !== null && abs((float)$c->status()['position'] - 60) < 0.5)); $c->setVolume(30); self::assertTrue($this->until(fn () => abs($cc->level - 0.3) < 0.001)); // the device pings: answered $cc->say(CastV2::HEARTBEAT, ['type' => 'PING']); self::assertTrue($this->until(fn () => in_array('PONG', $cc->types(CastV2::HEARTBEAT), true))); // the TV's own remote plays again: WinZik hears it $cc->playerState = 'PLAYING'; $cc->mediaStatus(); self::assertTrue($this->until(fn () => $c->status()['state'] === 'playing')); // the end: the application stopped on the TV, the connection closed $c->close(); self::assertTrue($this->until(fn () => in_array('STOP', $cc->types(CastV2::RECEIVER), true))); self::assertSame('', $cc->running); $cc->close(); } public function testAnUnknownAppIdIsRefusedInFrenchAndAStoppedApplicationEndsTheCast(): void { FakeCastDevice::certificate("$this->tmp/cert.pem"); $cc = new FakeCastDevice("$this->tmp/cert.pem"); $device = new CastDevice(CastDevice::CAST, 'cast:fake01', 'Salon', 'Chromecast', '127.0.0.1', $cc->port); $c = new CastClient($device, '0BADBEEF'); $this->pollers = [fn () => $cc->poll(), fn () => $c->poll()]; self::assertTrue($this->until(fn () => $c->closed())); self::assertSame('La TV refuse de lancer WinZik : vérifiez l\'App ID (0BADBEEF) (NOT_FOUND)', $c->error()); $cc->close(); // WinZik's receiver: its STATE out, the page's REPORT back; then someone stops it from the TV $cc = new FakeCastDevice("$this->tmp/cert.pem"); $device->port = $cc->port; $tv = new TvTarget(new CastClient($device, 'A1B2C3D4')); $this->pollers = [fn () => $cc->poll(), fn () => $tv->poll()]; $tv->load(['id' => 3, 'url' => 'http://127.0.0.1:9/m/3.mp3', 'title' => 'Chanson', 'lyricsData' => ['lines' => [['t' => 1.0, 'text' => 'la la']]]], 5.0, true); self::assertTrue($this->until(fn () => $tv->status()['state'] === 'playing')); $state = (array)$cc->last('STATE'); self::assertSame('Chanson', $state['state']['song']['title']); self::assertSame('la la', $state['state']['song']['lyricsData']['lines'][0]['text'], 'the lyrics go in the Cast message'); self::assertSame(3, $tv->status()['song']); $cc->say(CastV2::WINZIK, ['type' => 'COMMAND', 'do' => 'next'], FakeCastDevice::TRANSPORT); self::assertTrue($this->until(fn () => ($k = $tv->takeCommands()) !== [] && $k[0]['do'] === 'next')); $cc->say(CastV2::CONNECTION, ['type' => 'CLOSE'], FakeCastDevice::TRANSPORT); self::assertTrue($this->until(fn () => $tv->status()['state'] === 'closed')); self::assertSame('La TV a arrêté WinZik', $tv->error()); $cc->close(); } // WinZik casting --------------------------------------------------------------------------------------------- /** WinZik with two songs (copies of the demo) and lyrics on the first one. */ private function winzik(): WinZik { $wz = new WinZik(); $wz->playlist->clear(); foreach (['un', 'deux'] as $name) { copy(__DIR__ . '/../assets/music/winzik.mp3', "$this->tmp/$name.mp3"); $wz->playlist->add("$this->tmp/$name.mp3"); } file_put_contents("$this->tmp/un.lyr", "[LYR]\r\n[ 0.5 ]\r\nBonjour la vie\r\n[ 3 ]\r\nAu revoir\r\n"); $wz->playlist->shuffle = false; return $wz; } private function cast(WinZik $wz): Cast { $server = new TvServer(); $server->addresses = ['127.0.0.1']; $cast = new Cast($wz, "$this->tmp/var/cast.json", $server); $wz->useCast($cast); return $cast; } public function testWinZikStreamsToADlnaTvAndStaysItsRemoteWithTheKaraokeInTime(): void { $tv = new FakeRenderer(); $wz = $this->winzik(); $cast = $this->cast($wz); $cast->discovery()->remember($this->renderer($tv)); $this->pollers = [fn () => $tv->poll(), fn () => $wz->tick(0.01)]; $wz->playIndex(0); self::assertTrue($cast->connect('dlna:uuid:fake-tv-0001', 'interface')); self::assertSame('stream', $cast->mode(), 'a DLNA TV shows no page'); self::assertStringContainsString('Une TV DLNA ne peut pas afficher', $cast->message); self::assertTrue($wz->player->silent); self::assertTrue($this->until(fn () => $tv->state === 'PLAYING' && $tv->fetched !== null)); // the TV got the song from WinZik's server (Range: it can seek), with its title self::assertMatchesRegularExpression('#^http://127\.0\.0\.1:\d+/c/[0-9a-f]{32}/m/1\.mp3$#', $tv->uri); self::assertSame(206, $tv->fetched['status']); self::assertSame(65536, $tv->fetched['length']); self::assertSame('Streaming', $tv->fetched['headers']['transfermode.dlna.org'] ?? null); self::assertStringContainsString('', $tv->metadata); self::assertSame('casting', $cast->state()); self::assertStringContainsString('Diffusé sur Téléviseur du salon (streaming DLNA)', $cast->statusText()); // WinZik's buttons drive the TV $wz->pause(); self::assertTrue($this->until(fn () => $tv->state === 'PAUSED_PLAYBACK')); $wz->seek(20.0); self::assertTrue($this->until(fn () => abs($tv->position - 20) < 1)); $wz->play(); self::assertTrue($this->until(fn () => $tv->state === 'PLAYING')); $wz->next(); self::assertTrue($this->until(fn () => str_ends_with($tv->uri, '/m/2.mp3') && $tv->state === 'PLAYING')); // the TV's own remote: WinZik follows its pause, then its position (the karaoke here stays in time with the TV) $this->until(fn () => false, CastSession::GRACE + 0.2); $tv->pauseHere(); self::assertTrue($this->until(fn () => $wz->player->state === Player::PAUSED, 3.0)); $tv->playHere(42.0); self::assertTrue($this->until(fn () => $wz->player->state === Player::PLAYING && abs($wz->player->position - 42) < 1.5, 4.0)); // the end: the TV stops, WinZik's sound comes back, paused $cast->disconnect(); self::assertTrue($this->until(fn () => $tv->state === 'STOPPED')); self::assertFalse($wz->player->silent); self::assertSame(Player::PAUSED, $wz->player->state); self::assertSame('off', $cast->state()); self::assertSame('dlna:uuid:fake-tv-0001', json_decode((string)file_get_contents("$this->tmp/var/cast.json"), true)['last']['id']); $tv->close(); $wz->useCast(null); } public function testTheTvPageInABrowserFollowsWinZikShowsTheLyricsAndItsRemoteChangesTheSong(): void { $wz = $this->winzik(); $cast = $this->cast($wz); $wz->playIndex(0); $wz->lyrics = new Lyrics([[0.5, 'Bonjour la vie'], [3.0, 'Au revoir']]); self::assertTrue($cast->openTvPage()); self::assertSame('connecting', $cast->state()); $url = $cast->tvUrl(); self::assertMatchesRegularExpression('#^http://127\.0\.0\.1:\d+/tv/[a-z2-9]{8}$#', $url); self::assertStringContainsString($url, $cast->statusText()); self::assertFileExists((string)$cast->qrPng()); $http = new LanHttp(); $this->pollers = [fn () => $wz->tick(0.01), fn () => $http->poll()]; $get = function (string $u, array $headers = []) use ($http): ?array { $res = false; $http->request('GET', $u, '', $headers, 3.0, function (?array $r) use (&$res): void { $res = $r; }); $this->until(function () use (&$res): bool { return $res !== false; }); return $res ?: null; }; // the page: the token inside, the HTTP transport $page = $get($url); self::assertSame(200, $page['status']); preg_match("#const BASE = '(/c/[0-9a-f]{32})'#", $page['body'], $m); self::assertNotEmpty($m); $base = preg_replace('#/tv/.*$#', '', $url) . $m[1]; self::assertSame(404, $get(preg_replace('#/tv/\w+$#', '/tv/aaaaaaaa', $url))['status'], 'a wrong code shows nothing'); self::assertSame(404, $get(str_replace($m[1], '/c/' . str_repeat('0', 32), $base) . '/s')['status']); // the state: the song, playing, its lyrics with syllables $state = json_decode($get("$base/s?song=-1&pos=0&st=idle")['body'], true); [$tag] = $wz->describe("$this->tmp/un.mp3"); self::assertSame([$tag->title, $tag->artist, true, 1], [$state['song']['title'], $state['song']['artist'], $state['playing'], $state['song']['id']]); $song = $get($state['song']['url'], ['Range' => 'bytes=100-199']); self::assertSame([206, 100, 'bytes 100-199/' . filesize("$this->tmp/un.mp3")], [$song['status'], strlen($song['body']), $song['headers']['content-range']]); $lyrics = json_decode($get($state['song']['lyrics'])['body'], true); self::assertSame('Bonjour la vie', $lyrics['lines'][0]['text']); self::assertSame(['Bon', 'jour ', 'la ', 'vie'], $lyrics['lines'][0]['syl']); self::assertCount(4, $lyrics['lines'][0]['at']); self::assertSame([['title' => $tag->title, 'artist' => $tag->artist]], $state['next'], 'the song after (a copy of the same demo)'); // the page plays: casting; WinZik paused here: the page is told $get("$base/s?song=1&pos=1.0&st=playing"); self::assertSame('casting', $cast->state()); $wz->pause(); $wz->tick(0.01); self::assertFalse(json_decode($get("$base/s?song=1&pos=1.2&st=playing")['body'], true)['playing']); $wz->play(); $wz->tick(0.01); // a seek here: the page's seek counter moves $before = json_decode($get("$base/s?song=1&pos=1.3&st=playing")['body'], true)['posSeq']; $wz->seek(30.0); $wz->tick(0.01); $after = json_decode($get("$base/s?song=1&pos=30&st=playing")['body'], true); self::assertSame($before + 1, $after['posSeq']); self::assertEqualsWithDelta(30.0, $after['position'], 0.5); // OK / ▶ on the TV's remote: the next song, here and there self::assertSame(200, $get("$base/k?do=next")['status']); self::assertTrue($this->until(fn () => $wz->playlist->active === 1)); self::assertSame(2, json_decode($get("$base/s?song=1&pos=31&st=playing")['body'], true)['song']['id']); $cast->disconnect(); self::assertNull($get("$base/s"), 'closed with the cast'); $wz->useCast(null); } public function testWinZikCastsToAChromecastWithItsLyricsAsSubtitlesWhenThereIsNoAppId(): void { FakeCastDevice::certificate("$this->tmp/cert.pem"); $cc = new FakeCastDevice("$this->tmp/cert.pem"); $wz = $this->winzik(); $cast = $this->cast($wz); $cast->discovery()->remember(new CastDevice(CastDevice::CAST, 'cast:fake01', 'Salon', 'Chromecast', '127.0.0.1', $cc->port)); $this->pollers = [fn () => $cc->poll(), fn () => $wz->tick(0.01)]; $wz->playIndex(0); $wz->lyrics = new Lyrics([[0.5, 'Bonjour la vie'], [3.0, 'Au revoir']]); self::assertTrue($cast->connect('cast:fake01', 'interface')); self::assertSame('cast-media', $cast->how()); self::assertTrue($this->until(fn () => $cc->playerState === 'PLAYING')); $vtt = (array)$cc->last('LOAD'); $vttUrl = (string)$vtt['media']['tracks'][0]['trackContentId']; $http = new LanHttp(); $body = null; $http->request('GET', $vttUrl, '', [], 3.0, function (?array $r, string $why) use (&$body): void { $body = $r ?? ['status' => 0, 'headers' => [], 'body' => $why]; }); $this->pollers[] = fn () => $http->poll(); self::assertTrue($this->until(function () use (&$body): bool { return $body !== null; })); self::assertSame("WEBVTT\n\n00:00:00.500 --> 00:00:03.000\nBonjour la vie\n\n00:00:03.000 --> 00:00:09.000\nAu revoir\n\n", $body['body']); self::assertSame('*', $body['headers']['access-control-allow-origin']); // with an App ID: WinZik's own receiver $cast->setAppId('a1b2c3d4'); self::assertSame('A1B2C3D4', $cast->appId()); self::assertTrue($cast->connect('cast:fake01', 'interface')); self::assertSame('cast-app', $cast->how()); self::assertTrue($this->until(fn () => $cc->last('STATE') !== null && $cast->state() === 'casting')); self::assertSame('Diffusé sur Salon (écran WinZik (Cast))', $cast->statusText()); // stopped from the TV: the cast ends by itself, the sound comes back here, paused $cc->say(CastV2::CONNECTION, ['type' => 'CLOSE'], FakeCastDevice::TRANSPORT); self::assertTrue($this->until(fn () => !$cast->active())); self::assertSame('La TV a arrêté WinZik', $cast->message); self::assertFalse($wz->player->silent); $cc->close(); $wz->useCast(null); } }