.mp3 (audio) /live/.ts (video, MPEG-TS) any other path: 404 * * A player that asks for it (Icy-MetaData: 1, VLC does) gets the title in the stream too (ICY / SHOUTcast metadata * every METAINT bytes): VLC shows "Artiste - Titre". A new player gets the last moments first (prebuffer: it starts * at once); a player that does not keep up (its queue over MAX_QUEUE) is dropped. Never waits. */ final class LiveServer { public const FIRST_PORT = 47650; public const METAINT = 16000; private const MAX_QUEUE = 8 * 1024 * 1024; private const PREBUFFER = 96 * 1024; /** @var resource|null */ private $socket = null; private int $port = 0; /** @var array */ private array $clients = []; private int $nextId = 0; /** the last bytes sent (a new player starts with them) */ private string $recent = ''; /** what VLC shows as the title */ private string $title = ''; /** tests: any client address */ public bool $anyAddress = false; public function __construct(public string $code, public string $mime = 'audio/mpeg', public string $ext = 'mp3') { } /** Listens on the first free port from $port (the same one each time when it is free: VLC's history keeps it). */ public function open(int $port = self::FIRST_PORT): bool { if ($this->socket !== null) { return true; } if (!function_exists('stream_socket_server')) { return false; } for ($p = $port; $p < $port + 20; $p++) { $s = @stream_socket_server("tcp://0.0.0.0:$p", $no, $err); if ($s !== false) { stream_set_blocking($s, false); $this->socket = $s; $this->port = $p; return true; } } return false; } public function isOpen(): bool { return $this->socket !== null; } public function port(): int { return $this->port; } public function path(): string { return '/live/' . $this->code . '.' . $this->ext; } /** The players listening now. */ public function listeners(): int { return count(array_filter($this->clients, fn (array $c): bool => $c['live'])); } /** The title shown by the players (sent with the next metadata block). */ public function setTitle(string $title): void { $this->title = $title; } /** A new stream starts (another format, a new ffmpeg): what a new player would get first is forgotten. */ public function restart(string $mime, string $ext): void { $this->recent = ''; if ($mime !== $this->mime || $ext !== $this->ext) { $this->mime = $mime; $this->ext = $ext; foreach (array_keys($this->clients) as $id) { $this->drop($id); // its player asks again with the new address } } } /** What ffmpeg made: to every player. */ public function feed(string $bytes): void { if ($bytes === '') { return; } // a new player gets the last moments: ~4 s of sound, ~2 s of film (a key picture in them: VLC starts at once) $this->recent = substr($this->recent . $bytes, -($this->ext === 'ts' ? 768 * 1024 : self::PREBUFFER)); if ($this->ext === 'ts') { $this->recent = substr($this->recent, strlen($this->recent) % 188); // whole MPEG-TS packets } foreach ($this->clients as $id => $c) { if ($c['live']) { $this->queue($id, $bytes); } } } /** Each frame: new players, their requests, what to write. */ public function poll(): void { if ($this->socket === null) { return; } for ($n = 0; $n < 8 && ($client = @stream_socket_accept($this->socket, 0, $peer)) !== false; $n++) { stream_set_blocking($client, false); $ip = (string)preg_replace('/:\d+$/', '', trim((string)$peer)); $ip = trim($ip, '[]'); if (!$this->anyAddress && !HttpServer::isPrivateAddress($ip)) { @fwrite($client, "HTTP/1.0 403 Forbidden\r\nContent-Length: 0\r\n\r\n"); @fclose($client); continue; } $this->clients[$this->nextId++] = ['socket' => $client, 'ip' => $ip, 'in' => '', 'out' => '', 'live' => false, 'icy' => false, 'untilMeta' => self::METAINT, 'since' => microtime(true)]; } foreach (array_keys($this->clients) as $id) { $this->step($id); } } private function step(int $id): void { $c = &$this->clients[$id]; if (!$c['live']) { $chunk = @fread($c['socket'], 8192); if (is_string($chunk) && $chunk !== '') { $c['in'] .= $chunk; } elseif (feof($c['socket']) || microtime(true) - $c['since'] > 10 || strlen($c['in']) > 16384) { unset($c); $this->drop($id); return; } $end = strpos($c['in'], "\r\n\r\n"); if ($end === false) { return; } unset($c); $this->answer($id, substr($this->clients[$id]['in'], 0, $end)); if (!isset($this->clients[$id])) { return; } $c = &$this->clients[$id]; } else { @fread($c['socket'], 8192); // nothing more is expected: read away } if ($c['out'] !== '') { $written = @fwrite($c['socket'], $c['out']); if ($written === false || ($written === 0 && feof($c['socket']))) { unset($c); $this->drop($id); return; } $c['out'] = (string)substr($c['out'], $written); } if (!$c['live'] && $c['out'] === '') { unset($c); $this->drop($id); // a refusal written: closed } } private function answer(int $id, string $head): void { $lines = explode("\r\n", $head); $method = ''; $path = ''; if (preg_match('#^(GET|HEAD) (\S+) HTTP/\d\.\d$#', (string)$lines[0], $m)) { [$method, $path] = [$m[1], (string)strtok($m[2], '?')]; } $icy = false; foreach ($lines as $line) { if (preg_match('/^icy-metadata:\s*1/i', $line)) { $icy = true; } } if ($method === '' || !hash_equals($this->path(), $path)) { $this->clients[$id]['out'] = "HTTP/1.0 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 10\r\nConnection: close\r\n\r\nNot found\n"; return; } $headers = "HTTP/1.0 200 OK\r\nContent-Type: {$this->mime}\r\nCache-Control: no-cache, no-store\r\nPragma: no-cache\r\n" . "Connection: close\r\nicy-name: WinZik\r\nicy-description: WinZik sur la TV\r\nicy-pub: 0\r\n" . ($icy && $this->ext === 'mp3' ? 'icy-metaint: ' . self::METAINT . "\r\n" : '') . "\r\n"; $c = &$this->clients[$id]; $c['out'] = $headers; if ($method === 'HEAD') { return; // closed once the headers are written } $c['live'] = true; $c['icy'] = $icy && $this->ext === 'mp3'; $c['in'] = ''; unset($c); $this->queue($id, $this->recent); } /** $bytes for one player, with the metadata blocks where they go. */ private function queue(int $id, string $bytes): void { $c = &$this->clients[$id]; if (!$c['icy']) { $c['out'] .= $bytes; } else { while ($bytes !== '') { $part = substr($bytes, 0, $c['untilMeta']); $bytes = (string)substr($bytes, strlen($part)); $c['out'] .= $part; $c['untilMeta'] -= strlen($part); if ($c['untilMeta'] === 0) { $c['out'] .= self::meta($this->title); $c['untilMeta'] = self::METAINT; } } } if (strlen($c['out']) > self::MAX_QUEUE) { unset($c); $this->drop($id); // it does not keep up (or is gone without a word) } } /** An ICY metadata block: its length / 16 in one byte, then StreamTitle='…'; padded with zeros. */ public static function meta(string $title): string { $title = str_replace(["'", "\r", "\n", "\0"], ['’', ' ', ' ', ''], $title); $text = "StreamTitle='" . mb_strcut($title, 0, 200) . "';"; $blocks = (int)ceil(strlen($text) / 16); return chr($blocks) . str_pad($text, $blocks * 16, "\0"); } private function drop(int $id): void { if (isset($this->clients[$id])) { @fclose($this->clients[$id]['socket']); unset($this->clients[$id]); } } public function close(): void { foreach (array_keys($this->clients) as $id) { $this->drop($id); } if ($this->socket !== null) { @fclose($this->socket); } $this->socket = null; $this->recent = ''; } }