tmp = sys_get_temp_dir() . '/winzik-vlc-' . bin2hex(random_bytes(4)); @mkdir($this->tmp, 0777, true); } protected function tearDown(): void { exec('rm -rf ' . escapeshellarg($this->tmp)); } /** A player of the stream: a raw socket (as VLC), what came after the headers kept. */ private function listen(string $url, bool $icy = false) { $p = parse_url($url); $s = stream_socket_client('tcp://' . $p['host'] . ':' . $p['port'], $no, $err, 2); self::assertNotFalse($s, $err); fwrite($s, "GET {$p['path']} HTTP/1.1\r\nHost: {$p['host']}\r\nUser-Agent: VLC/3.0.21\r\n" . ($icy ? "Icy-MetaData: 1\r\n" : '') . "\r\n"); stream_set_blocking($s, false); return $s; } private function pump(WinZik $wz, $socket, string &$got, callable $done, float $seconds = 6.0): bool { $end = microtime(true) + $seconds; while (microtime(true) < $end) { $wz->tick(0.01); $chunk = @fread($socket, 65536); if (is_string($chunk)) { $got .= $chunk; } if ($done($got)) { return true; } usleep(10000); } return false; } private function winzik(?string $ffmpeg): array { $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; $wz->tools = Tools::forPhone("$this->tmp/bin", "$this->tmp/tmp", $ffmpeg); $server = new TvServer(); $server->addresses = ['127.0.0.1']; $cast = new Cast($wz, "$this->tmp/var/cast.json", $server); $cast->addresses = ['127.0.0.1']; $wz->useCast($cast); return [$wz, $cast]; } /** A fake ffmpeg: its arguments in calls.txt, then 4000 bytes "MP3!" a little at a time into its last argument. */ private function fakeFfmpeg(): string { $f = "$this->tmp/ffmpeg"; file_put_contents($f, "#!/bin/sh\nfor a; do out=\$a; done\ncase \"\$out\" in -*|long) exit 0;; esac\necho \"\$*\" >> " . escapeshellarg("$this->tmp/calls.txt") . "\n" . "i=0\nwhile [ \$i -lt 40 ]; do printf 'MP3!%.0s' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 >> \"\$out\"; i=\$((i+1)); sleep 0.05; done\n"); chmod($f, 0755); return $f; } public function testAnIcyBlockIsItsLengthInSixteensThenTheTitlePaddedWithZeros(): void { $block = LiveServer::meta("Daft Punk - One More Time"); self::assertSame(0, (strlen($block) - 1) % 16); self::assertSame((strlen($block) - 1) / 16, ord($block[0])); self::assertStringStartsWith("StreamTitle='Daft Punk - One More Time';", substr($block, 1)); self::assertStringContainsString('’', LiveServer::meta("L'été"), 'a quote would end the title'); } public function testThePlayersGetTheStreamWithTheTitleEveryMetaintBytesAndAWrongAddressNothing(): void { $live = new LiveServer('abcdefghjk'); $live->anyAddress = true; self::assertTrue($live->open(LiveServer::FIRST_PORT + 7)); $live->setTitle('Artiste - Titre'); $base = 'http://127.0.0.1:' . $live->port(); $icy = $this->listen($base . '/live/abcdefghjk.mp3', true); $plain = $this->listen($base . '/live/abcdefghjk.mp3'); $wrong = $this->listen($base . '/live/zzzzzzzzzz.mp3'); $got = ['', '', '']; $read = function () use (&$got, $icy, $plain, $wrong, $live): void { $live->poll(); foreach ([$icy, $plain, $wrong] as $i => $s) { $c = @fread($s, 65536); $got[$i] .= is_string($c) ? $c : ''; } }; for ($i = 0; $i < 50 && $live->listeners() < 2; $i++) { $read(); usleep(5000); } self::assertSame(2, $live->listeners()); $live->feed(str_repeat('a', LiveServer::METAINT + 100)); for ($i = 0; $i < 50; $i++) { $read(); usleep(5000); } [$head, $body] = explode("\r\n\r\n", $got[0], 2); self::assertStringContainsString('icy-metaint: ' . LiveServer::METAINT, $head); self::assertStringContainsString('Content-Type: audio/mpeg', $head); self::assertSame(str_repeat('a', LiveServer::METAINT) . LiveServer::meta('Artiste - Titre') . str_repeat('a', 100), $body); [$head, $body] = explode("\r\n\r\n", $got[1], 2); self::assertStringNotContainsString('icy-metaint', $head); self::assertSame(LiveServer::METAINT + 100, strlen($body)); self::assertStringStartsWith('HTTP/1.0 404', $got[2]); $live->close(); } public function testWinZikStreamsWhatItPlaysToVlcAndStartsFfmpegAgainAtEachSeekAndSong(): void { [$wz, $cast] = $this->winzik($this->fakeFfmpeg()); $wz->playIndex(0); self::assertTrue($cast->openVlcStream(), $cast->message); $url = $cast->tvUrl(); self::assertMatchesRegularExpression('#^http://127\.0\.0\.1:\d+/live/[a-z2-9]{10}\.mp3$#', $url); self::assertSame($url, $cast->vlcUrl()); self::assertSame('connecting', $cast->state()); self::assertStringContainsString($url, $cast->statusText()); self::assertTrue($wz->player->silent, 'the sound is on the TV'); $vlc = $this->listen($url, true); $got = ''; self::assertTrue($this->pump($wz, $vlc, $got, fn (string $got) => substr_count($got, 'MP3!') >= 100), 'the stream comes'); self::assertSame('casting', $cast->state()); self::assertStringContainsString('Diffusé sur VLC (flux audio)', $cast->statusText()); self::assertStringContainsString('icy-name: WinZik', $got); $calls = array_values(array_filter(file("$this->tmp/calls.txt", FILE_IGNORE_NEW_LINES), fn (string $c): bool => str_contains($c, ' -i '))); self::assertStringContainsString("-readrate 1 -ss 0.", $calls[0]); self::assertStringContainsString("-i $this->tmp/un.mp3", $calls[0]); self::assertStringContainsString('-f mp3', $calls[0]); // a seek here: ffmpeg again from there, the same stream goes on $wz->seek(30.0); self::assertTrue($this->pump($wz, $vlc, $got, fn () => count(file("$this->tmp/calls.txt")) >= 2)); self::assertStringContainsString('-ss 30.', file("$this->tmp/calls.txt")[1]); // the next song: ffmpeg on its file $wz->next(); self::assertTrue($this->pump($wz, $vlc, $got, fn () => str_contains((string)file_get_contents("$this->tmp/calls.txt"), "$this->tmp/deux.mp3"))); $before = strlen($got); self::assertTrue($this->pump($wz, $vlc, $got, fn (string $got) => strlen($got) > $before + 400), 'still flowing'); // pause: nothing more comes $wz->pause(); $this->pump($wz, $vlc, $got, fn () => false, 0.3); $paused = strlen($got); $this->pump($wz, $vlc, $got, fn () => false, 0.4); self::assertSame($paused, strlen($got)); $code = json_decode((string)file_get_contents("$this->tmp/var/cast.json"), true)['vlc']; $cast->disconnect(); self::assertSame('off', $cast->state()); self::assertFalse($wz->player->silent); fclose($vlc); // the same address next time (kept in VLC's favourites) self::assertTrue($cast->openVlcStream()); self::assertStringEndsWith("/live/$code.mp3", $cast->tvUrl()); $cast->disconnect(); $wz->useCast(null); } public function testWithoutFfmpegTheStreamSaysWhy(): void { [$wz, $cast] = $this->winzik(null); self::assertFalse($cast->openVlcStream()); self::assertTrue($cast->failed); self::assertStringContainsString('ffmpeg', $cast->message); $wz->useCast(null); } public function testTheKaraokeOfTheFilmSingsEachSyllableShowsTheTranslationAndTheLinesComing(): void { $lines = [ ['t' => 1.0, 'e' => 3.0, 'text' => 'Bonjour la vie', 'syl' => ['Bon', 'jour ', 'la ', 'vie'], 'at' => [1.5, 2.0, 2.4, 2.6], 'tr' => 'Hello life'], ['t' => 4.0, 'e' => 6.0, 'text' => 'Au revoir', 'syl' => ['Au ', 're', 'voir'], 'at' => [4.0, 4.5, 5.0], 'tr' => ''], ]; foreach (['Trois', 'Quatre', 'Cinq', 'Six', 'Sept', 'Huit'] as $k => $word) { $lines[] = ['t' => 7.0 + 2 * $k, 'e' => 8.0 + 2 * $k, 'text' => $word, 'syl' => [$word], 'at' => [7.0 + 2 * $k], 'tr' => '']; } $song = ['title' => 'Chanson {test}', 'artist' => 'Moi', 'duration' => 60.0, 'lyricsData' => ['synced' => true, 'lines' => $lines]]; $fonts = __DIR__ . '/../assets/fonts'; $ass = VlcTarget::ass($song, 0.0, true, 'ball', $fonts); self::assertStringContainsString('Chanson (test)', $ass, 'braces would be ASS tags'); self::assertStringContainsString('Dialogue: 2,0:00:01.00,0:00:04.00,Sing,,0,0,0,,{\pos(830,205)}{\k50}{\kf50}Bon{\kf40}jour {\kf20}la {\kf40}vie', $ass); self::assertMatchesRegularExpression('/Dialogue: 1,0:00:01\.00,0:00:04\.00,Tr,,0,0,0,,\{\\\\pos\(830,\d+\)\}Hello life/', $ass); // the lines coming: VlcTarget::AHEAD of them under the line sung, fading preg_match_all('/^Dialogue: 1,0:00:01\.00,0:00:04\.00,Next,.*\\\\alpha&H([0-9A-F]{2})&\}(.*)$/m', $ass, $next); self::assertSame(['Au revoir', 'Trois', 'Quatre', 'Cinq', 'Six'], $next[2]); self::assertSame($next[1], array_values(array_unique($next[1])), 'each one fainter'); // the ball lands on each syllable at its moment: waiting on « Bon » from the line's start, then bounces self::assertMatchesRegularExpression('/Dialogue: 3,0:00:01\.00,0:00:01\.50,Mark,.*\\\\move\(/', $ass); self::assertSame(1 + 3 * 4 + 1, preg_match_all('/^Dialogue: 3,0:00:0[1-3]\.\d\d,0:00:0[1-4]\.\d\d,Mark/m', $ass)); foreach (['star', 'note', 'bar'] as $style) { self::assertStringContainsString(',Mark,', VlcTarget::ass($song, 0.0, true, $style, $fonts), $style); } self::assertStringNotContainsString(',Mark,', VlcTarget::ass($song, 0.0, true, 'off', $fonts)); self::assertStringNotContainsString(',Mark,', VlcTarget::ass($song, 0.0, true), 'no font to measure: no mark'); // a piece from 4.5 s: the first line is no longer sung (only shown dim above), the second starts at once $later = VlcTarget::ass($song, 4.5, false, 'ball', $fonts); self::assertStringNotContainsString(',Sing,,0,0,0,,{\pos(830,205)}{\k50}{\kf50}Bon', $later); self::assertStringContainsString('Dialogue: 2,0:00:00.00,0:00:02.50,Sing', $later); self::assertStringContainsString('\alpha&H70&}Bonjour la vie', $later, 'the line before, dim'); } public function testTheFontMetricsMeasureWhatLibassDraws(): void { $lato = \App\Cast\FontMetrics::of(__DIR__ . '/../assets/fonts/ui-bold.ttf'); self::assertNotNull($lato); $w = $lato->width('Bonjour la vie', 50.0); self::assertGreaterThan(250, $w); self::assertLessThan(400, $w); self::assertEqualsWithDelta($lato->width('Bon', 50.0) + $lato->width('jour', 50.0), $lato->width('Bonjour', 50.0), 0.01); self::assertEqualsWithDelta(2 * $lato->width('vie', 25.0), $lato->width('vie', 50.0), 0.01); self::assertNull(\App\Cast\FontMetrics::of('/nonexistent.ttf')); } public function testTheAutomaticQualityGoesDownWhenFfmpegCannotKeepUp(): void { $live = new LiveServer('abcdefghjk'); $t = new VlcTarget('ffmpeg', "$this->tmp/vlc", $live, true); self::assertSame('haute', $t->level()); $t->quality = 'basse'; self::assertSame('basse', $t->level()); $t->quality = 'auto'; (new \ReflectionProperty($t, 'song'))->setValue($t, ['path' => "$this->tmp/un.mp3", 'duration' => 30.0]); $cmd = implode(' ', $t->videoCommand("$this->tmp/un.mp3", 1)); self::assertStringContainsString('color=c=0x0d1020:s=1280x720:r=25', $cmd); self::assertStringContainsString('-progress live-progress.txt', $cmd); (new \ReflectionProperty($t, 'autoLevel'))->setValue($t, 'moyenne'); $cmd = implode(' ', $t->videoCommand("$this->tmp/un.mp3", 2)); self::assertStringContainsString('s=960x540', $cmd); self::assertStringContainsString('-b:v 1500k', $cmd); } public function testWithTheRealFfmpegVlcGetsMp3AndTheFilmIsH264WithAac(): void { $ffmpeg = Tools::onPath('ffmpeg'); $ffprobe = Tools::onPath('ffprobe'); if ($ffmpeg === null || $ffprobe === null) { self::markTestSkipped('ffmpeg absent'); } foreach ([false, true] as $video) { if ($video && !VlcTarget::canVideo($ffmpeg)) { continue; } [$wz, $cast] = $this->winzik($ffmpeg); $wz->playIndex(0); self::assertTrue($cast->openVlcStream($video), $cast->message); $vlc = $this->listen($cast->tvUrl()); $got = ''; self::assertTrue($this->pump($wz, $vlc, $got, fn (string $got) => strlen($got) > ($video ? 200000 : 40000), 10.0), 'bytes: ' . strlen($got)); $file = "$this->tmp/got." . ($video ? 'ts' : 'mp3'); file_put_contents($file, explode("\r\n\r\n", $got, 2)[1]); exec(escapeshellarg($ffprobe) . ' -v error -show_entries stream=codec_name -of csv=p=0 ' . escapeshellarg($file), $codecs); self::assertSame($video ? ['h264', 'aac'] : ['mp3'], array_values(array_unique(array_map('trim', $codecs)))); $codecs = []; $cast->disconnect(); fclose($vlc); $wz->useCast(null); } } /** HTTP to WinZik's media server, answered while WinZik ticks. @param array $headers */ private function http(WinZik $wz, string $method, string $url, string $body = '', array $headers = []): ?array { $http = new \App\Cast\LanHttp(); $res = false; $http->request($method, $url, $body, $headers, 3.0, function (?array $r) use (&$res): void { $res = $r; }); $end = microtime(true) + 4; while ($res === false && microtime(true) < $end) { $wz->tick(0.01); $http->poll(); usleep(5000); } return $res ?: null; } private function browse(WinZik $wz, string $control, string $id, string $flag = 'BrowseDirectChildren'): array { $soap = '' . "$id$flag*00" . ''; $r = $this->http($wz, 'POST', $control, $soap, ['Content-Type' => 'text/xml; charset="utf-8"', 'SOAPACTION' => '"urn:schemas-upnp-org:service:ContentDirectory:1#Browse"']); self::assertSame(200, $r['status'], (string)($r['body'] ?? '')); preg_match('#(.*)#s', $r['body'], $m); preg_match('#(\d+)#', $r['body'], $t); return [html_entity_decode($m[1], ENT_XML1 | ENT_QUOTES, 'UTF-8'), (int)$t[1]]; } public function testVlcFindsWinZikOnTheNetworkBrowsesItsPlaylistAndItsLiveStream(): void { [$wz, $cast] = $this->winzik($this->fakeFfmpeg()); self::assertTrue($cast->setMediaServer(true), $cast->message); $media = $cast->mediaServer(); self::assertNotNull($media); // VLC's M-SEARCH for media servers: the answer says where the description is $answers = []; $media->heard("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: urn:schemas-upnp-org:device:MediaServer:1\r\n\r\n", '127.0.0.1', 50000, function (string $a) use (&$answers): void { $answers[] = $a; }); self::assertCount(1, $answers); self::assertMatchesRegularExpression('#LOCATION: (http://127\.0\.0\.1:\d+/dlna/desc\.xml)#', $answers[0]); self::assertStringContainsString("USN: uuid:$media->uuid::urn:schemas-upnp-org:device:MediaServer:1", $answers[0]); $media->heard("M-SEARCH * HTTP/1.1\r\nST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n\r\n", '127.0.0.1', 50000, function (string $a) use (&$answers): void { $answers[] = $a; }); self::assertCount(1, $answers, 'not a renderer'); preg_match('#LOCATION: (\S+)#', $answers[0], $m); $desc = $this->http($wz, 'GET', $m[1]); self::assertSame(200, $desc['status']); self::assertStringContainsString('urn:schemas-upnp-org:device:MediaServer:1', $desc['body']); self::assertStringContainsString('WinZik (PC)', $desc['body']); self::assertStringContainsString('/dlna/cd/control', $desc['body']); $base = preg_replace('#/dlna/desc\.xml$#', '', $m[1]); self::assertStringContainsString('Browse', $this->http($wz, 'GET', "$base/dlna/cd.xml")['body']); // the root: the live stream and the play list [$root, $total] = $this->browse($wz, "$base/dlna/cd/control", '0'); self::assertSame(2, $total); self::assertStringContainsString('▶ WinZik en direct', $root); self::assertStringContainsString("$base/dlna/live.mp3", $root); self::assertStringContainsString('browse($wz, "$base/dlna/cd/control", 'pl'); self::assertSame(2, $total); self::assertSame(2, preg_match_all('#]*>(http://[^<]+\.mp3)#', $list, $res)); self::assertStringContainsString('object.item.audioItem.musicTrack', $list); // VLC plays a song of the list itself (and seeks: Range) $song = $this->http($wz, 'GET', $res[1][0], '', ['Range' => 'bytes=0-99']); self::assertSame([206, 100], [$song['status'], strlen($song['body'])]); [$meta] = $this->browse($wz, "$base/dlna/cd/control", 'pl', 'BrowseMetadata'); self::assertStringContainsString('state()); $live = $this->http($wz, 'GET', "$base/dlna/live.mp3"); self::assertSame(302, $live['status']); self::assertMatchesRegularExpression('#^http://127\.0\.0\.1:\d+/live/[a-z2-9]{10}\.mp3$#', $live['headers']['location']); self::assertSame('vlc', $cast->how()); self::assertSame(\App\Audio\Player::PLAYING, $wz->player->state); $vlc = $this->listen($live['headers']['location']); $got = ''; self::assertTrue($this->pump($wz, $vlc, $got, fn (string $got) => substr_count($got, 'MP3!') >= 50)); fclose($vlc); // off: gone from the network self::assertTrue($cast->setMediaServer(false)); self::assertNull($cast->mediaServer()); self::assertFalse($wz->options['mediaServer']); self::assertNull($this->http($wz, 'GET', $m[1])); $wz->useCast(null); } public function testThePhoneMakesTheFilmWithItsOwnHardwareEncoderAndWinZiksFont(): void { $live = new LiveServer('abcdefghjk'); $t = new VlcTarget('ffmpeg', "$this->tmp/vlc", $live, true); $t->forceEncoder = 'h264_mediacodec'; $song = ['path' => "$this->tmp/un.mp3", 'title' => 'T', 'artist' => 'A', 'duration' => 30.0]; (new \ReflectionProperty($t, 'song'))->setValue($t, $song); $cmd = implode(' ', $t->videoCommand("$this->tmp/un.mp3", 3)); self::assertStringContainsString('-c:v h264_mediacodec -ndk_codec 1', $cmd); self::assertStringContainsString('subtitles=filename=live-3.ass:fontsdir=fonts,format=nv12[v]', $cmd); self::assertStringNotContainsString('libx264', $cmd); self::assertFileExists("$this->tmp/vlc/fonts/ui.ttf", 'Lato for libass (no fontconfig on a phone)'); self::assertStringContainsString('Style: Sing,Lato,', (string)file_get_contents("$this->tmp/vlc/live-3.ass")); $t->forceEncoder = 'libx264'; self::assertStringContainsString('format=yuv420p[v]', implode(' ', $t->videoCommand("$this->tmp/un.mp3", 4))); } }