<?phpnamespace App\Cast;use App\Cloud\Cloud;use App\Core\WinZik;use App\Model\Text;use JumPHP\Net\HttpRequest;use JumPHP\Net\HttpResponse;use JumPHP\Net\HttpServer;/** * WinZik as a media server of the home network (UPnP AV / DLNA MediaServer:1): VLC ("Réseau local" > "Universal * Plug'n'Play", on a TV: Parcourir > Réseau local), a TV, Kodi... list "WinZik (PC)" / "WinZik (téléphone)" by themselves: * * ▶ WinZik en direct what WinZik plays, song after song (the stream for VLC: Cast::openVlcStream(), started * ▶ WinZik en direct (vidéo) when a player opens it, WinZik playing if it was not; the video one: a computer's ffmpeg) * Playlist WinZik (n) the songs of the play list, each a file VLC plays itself (Range: it seeks) * * SSDP: NOTIFY ssdp:alive now and every NOTIFY_EVERY s (multicast 239.255.255.250:1900, sent from any socket: a player * that listens finds it even when the answers to its M-SEARCH cannot come, e.g. a phone that filters multicast), the * M-SEARCH heard on port 1900 (joined with SO_REUSEADDR: the computer's own SSDP service keeps working) answered by * unicast, ssdp:byebye at the end. HTTP (engine HttpServer on 47660+, private clients only): /dlna/desc.xml, the two * services' descriptions, their SOAP control (Browse, GetSearchCapabilities, GetSortCapabilities, GetSystemUpdateID, * GetProtocolInfo, GetCurrentConnectionIDs / Info), SUBSCRIBE answered (no events sent), /dlna/m/<id> the songs, * /dlna/i/<id> their covers, /dlna/live.mp3|ts the live stream (302 to the LiveServer). * The XML is written and read with strings and patterns (the phone's PHP has no XML extension). Never blocks. */final class MediaServer{ public const FIRST_PORT = 47660; public const NOTIFY_EVERY = 20.0; private const MAX_AGE = 1800; private const DEVICE = 'urn:schemas-upnp-org:device:MediaServer:1'; private const CD = 'urn:schemas-upnp-org:service:ContentDirectory:1'; private const CM = 'urn:schemas-upnp-org:service:ConnectionManager:1'; private const DLNA_FLAGS = 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000'; private ?HttpServer $http = null; /** @var \Socket|null port 1900 (M-SEARCH heard), null: announcements only */ private ?\Socket $ssdp = null; /** @var resource|null the socket the announcements leave from */ private $notifier = null; private float $nextNotify = 0.0; /** @var array<string, string> id => path of the songs listed (the last Browse) */ private array $songs = []; private int $updateId = 1; /** @var list<string>|null tests: this computer's addresses (null: its own) */ public ?array $addresses = null; /** tests: where the announcements go (null: 239.255.255.250:1900) */ public ?string $announceTo = null; /** tests: no port 1900 */ public bool $listen1900 = true; /** @var list<string> the requests seen (M-SEARCH from, Browse ids): tests and the status line */ public array $seen = []; public function __construct(private WinZik $wz, private Cast $cast, public readonly string $uuid, public readonly string $name) { } public static function supported(): bool { return HttpServer::isSupported(); } public function running(): bool { return $this->http !== null && $this->http->isListening(); } public function port(): int { return (int)$this->http?->port(); } public function start(): bool { if ($this->running()) { return true; } try { $this->http = new HttpServer(); $this->http->allow(fn (string $ip): bool => HttpServer::isPrivateAddress($ip)); $this->http->handle('/dlna/', fn (HttpRequest $r): ?HttpResponse => $this->serve($r)); $this->http->listen(self::FIRST_PORT); } catch (\Throwable) { $this->http = null; return false; } $n = @stream_socket_client('udp://' . ($this->announceTo ?? Ssdp::ADDRESS . ':' . Ssdp::PORT), $no, $err, 0); $this->notifier = $n === false ? null : $n; if ($this->listen1900) { $this->ssdp = self::listenSsdp(); } $this->nextNotify = 0.0; return true; } /** Port 1900, the SSDP group joined (sockets extension); null when it cannot (then announcements only). */ private static function listenSsdp(): ?\Socket { if (!function_exists('socket_create')) { return null; } $s = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($s === false) { return null; } @socket_set_option($s, SOL_SOCKET, SO_REUSEADDR, 1); if (defined('SO_REUSEPORT')) { @socket_set_option($s, SOL_SOCKET, SO_REUSEPORT, 1); } if (!@socket_bind($s, '0.0.0.0', Ssdp::PORT) || !@socket_set_option($s, IPPROTO_IP, MCAST_JOIN_GROUP, ['group' => Ssdp::ADDRESS, 'interface' => 0])) { socket_close($s); return null; } socket_set_nonblock($s); return $s; } public function stop(): void { if ($this->http === null) { return; } $this->announce('ssdp:byebye'); $this->http->close(); $this->http = null; if ($this->ssdp !== null) { socket_close($this->ssdp); $this->ssdp = null; } if (is_resource($this->notifier)) { fclose($this->notifier); } $this->notifier = null; } /** Each frame. */ public function poll(): void { if ($this->http === null) { return; } $this->http->poll(); $now = microtime(true); if ($now >= $this->nextNotify) { // three at once the first time (UDP can be lost), then one every NOTIFY_EVERY s $this->announce('ssdp:alive'); $this->nextNotify = $now + ($this->nextNotify === 0.0 ? 1.0 : self::NOTIFY_EVERY); } for ($n = 0; $this->ssdp !== null && $n < 16; $n++) { $from = ''; $port = 0; $got = @socket_recvfrom($this->ssdp, $packet, 2048, 0, $from, $port); if ($got === false || $got === 0) { break; } $this->heard((string)$packet, (string)$from, (int)$port); } } /** An M-SEARCH heard (port 1900, or the tests): answered when it asks for us. */ public function heard(string $packet, string $from, int $port, ?\Closure $send = null): void { if (!str_starts_with($packet, 'M-SEARCH') || !HttpServer::isPrivateAddress($from) && $this->addresses === null) { return; } $st = preg_match('/^ST:\s*(.+?)\s*$/mi', $packet, $m) ? $m[1] : ''; $types = $this->types(); $answers = match (true) { $st === 'ssdp:all' => $types, isset($types[$st]) => [$st => $types[$st]], default => [], }; if ($answers === []) { return; } $this->seen[] = "M-SEARCH $from $st"; $location = $this->location(TvServer::addressTowards($from)); foreach ($answers as $type => $usn) { $answer = "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=" . self::MAX_AGE . "\r\nDATE: " . gmdate('D, d M Y H:i:s') . " GMT\r\nEXT:\r\n" . "LOCATION: $location\r\nSERVER: " . $this->serverHeader() . "\r\nST: $type\r\nUSN: $usn\r\nContent-Length: 0\r\n\r\n"; if ($send !== null) { $send($answer); } elseif ($this->ssdp !== null) { @socket_sendto($this->ssdp, $answer, strlen($answer), 0, $from, $port); } } } /** @return array<string, string> NT / ST => USN */ private function types(): array { $u = 'uuid:' . $this->uuid; return ['upnp:rootdevice' => "$u::upnp:rootdevice", $u => $u, self::DEVICE => "$u::" . self::DEVICE, self::CD => "$u::" . self::CD, self::CM => "$u::" . self::CM]; } private function announce(string $nts): void { if (!is_resource($this->notifier)) { return; } $location = $this->location(null); foreach ($this->types() as $nt => $usn) { $packet = "NOTIFY * HTTP/1.1\r\nHOST: " . Ssdp::ADDRESS . ':' . Ssdp::PORT . "\r\n" . ($nts === 'ssdp:alive' ? 'CACHE-CONTROL: max-age=' . self::MAX_AGE . "\r\nLOCATION: $location\r\nSERVER: " . $this->serverHeader() . "\r\n" : '') . "NT: $nt\r\nNTS: $nts\r\nUSN: $usn\r\n\r\n"; @fwrite($this->notifier, $packet); } } private function serverHeader(): string { return PHP_OS_FAMILY . '/1.0 UPnP/1.0 WinZik/' . $this->wz->version(); } /** The description's address, on the address the asker reaches us at. */ public function location(?string $host): string { return $this->base($host) . '/dlna/desc.xml'; } private function base(?string $host): string { $host ??= ($this->addresses ?? \App\Cloud\LanShare::localAddresses())[0] ?? '127.0.0.1'; return 'http://' . (str_contains($host, ':') ? "[$host]" : $host) . ':' . $this->port(); } // HTTP ---------------------------------------------------------------------------------------------------------- private function serve(HttpRequest $r): ?HttpResponse { $here = $this->base($this->hostOf($r)); $path = substr($r->path, strlen('/dlna/')); if ($r->method === 'SUBSCRIBE' || $r->method === 'UNSUBSCRIBE') { return HttpResponse::text('', 200, 'text/plain', ['SID' => 'uuid:' . $this->uuid . '-ev', 'TIMEOUT' => 'Second-1800']); } return match (true) { $path === 'desc.xml' => self::xml($this->description()), $path === 'cd.xml' => self::xml(self::scpd('cd')), $path === 'cm.xml' => self::xml(self::scpd('cm')), $path === 'icon.png' && is_file($this->icon()) => HttpResponse::file($this->icon(), 'image/png'), $path === 'cd/control' && $r->method === 'POST' => $this->control('cd', $r, $here), $path === 'cm/control' && $r->method === 'POST' => $this->control('cm', $r, $here), (bool)preg_match('#^live\.(mp3|ts)$#', $path, $m) => $this->live($m[1] === 'ts', $r), (bool)preg_match('#^m/([0-9a-f]{16})(?:\.\w+)?$#', $path, $m) => $this->song($m[1]), (bool)preg_match('#^i/([0-9a-f]{16})$#', $path, $m) => $this->cover($m[1]), default => null, }; } private function hostOf(HttpRequest $r): ?string { $host = (string)$r->header('host', ''); $host = preg_match('/^\[([^\]]+)\]/', $host, $m) ? $m[1] : (string)preg_replace('/:\d+$/', '', $host); return filter_var($host, FILTER_VALIDATE_IP) ? $host : TvServer::addressTowards($r->remoteAddress); } private static function xml(string $text): HttpResponse { return HttpResponse::text($text, 200, 'text/xml; charset="utf-8"'); } private function icon(): string { return dirname(__DIR__, 2) . '/assets/icon.png'; } public function description(): string { $e = fn (string $s): string => htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8'); $icon = is_file($this->icon()) ? @getimagesize($this->icon()) : false; $service = fn (string $type, string $id, string $short): string => "<service><serviceType>$type</serviceType><serviceId>urn:upnp-org:serviceId:$id</serviceId>" . "<SCPDURL>/dlna/$short.xml</SCPDURL><controlURL>/dlna/$short/control</controlURL><eventSubURL>/dlna/$short/event</eventSubURL></service>"; return '<?xml version="1.0" encoding="utf-8"?>' . "\n" . '<root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:dlna="urn:schemas-dlna-org:device-1-0"><specVersion><major>1</major><minor>0</minor></specVersion>' . '<device><deviceType>' . self::DEVICE . '</deviceType><friendlyName>' . $e($this->name) . '</friendlyName>' . '<manufacturer>WinZik</manufacturer><manufacturerURL>https://jumphp.net/winzik</manufacturerURL>' . '<modelDescription>Le lecteur WinZik : sa playlist et ce qu\'il joue</modelDescription><modelName>WinZik</modelName>' . '<modelNumber>' . $e($this->wz->version()) . '</modelNumber><UDN>uuid:' . $this->uuid . '</UDN><dlna:X_DLNADOC>DMS-1.50</dlna:X_DLNADOC>' . ($icon !== false ? '<iconList><icon><mimetype>image/png</mimetype><width>' . $icon[0] . '</width><height>' . $icon[1] . '</height><depth>24</depth><url>/dlna/icon.png</url></icon></iconList>' : '') . '<serviceList>' . $service(self::CD, 'ContentDirectory', 'cd') . $service(self::CM, 'ConnectionManager', 'cm') . '</serviceList>' . '</device></root>'; } private static function scpd(string $which): string { $arg = fn (string $name, string $dir, string $var): string => "<argument><name>$name</name><direction>$dir</direction><relatedStateVariable>$var</relatedStateVariable></argument>"; $action = fn (string $name, string ...$args): string => "<action><name>$name</name><argumentList>" . implode('', $args) . '</argumentList></action>'; $var = fn (string $name, string $type, bool $events = false): string => '<stateVariable sendEvents="' . ($events ? 'yes' : 'no') . "\"><name>$name</name><dataType>$type</dataType></stateVariable>"; if ($which === 'cd') { $actions = $action('Browse', $arg('ObjectID', 'in', 'A_ARG_TYPE_ObjectID'), $arg('BrowseFlag', 'in', 'A_ARG_TYPE_BrowseFlag'), $arg('Filter', 'in', 'A_ARG_TYPE_Filter'), $arg('StartingIndex', 'in', 'A_ARG_TYPE_Index'), $arg('RequestedCount', 'in', 'A_ARG_TYPE_Count'), $arg('SortCriteria', 'in', 'A_ARG_TYPE_SortCriteria'), $arg('Result', 'out', 'A_ARG_TYPE_Result'), $arg('NumberReturned', 'out', 'A_ARG_TYPE_Count'), $arg('TotalMatches', 'out', 'A_ARG_TYPE_Count'), $arg('UpdateID', 'out', 'A_ARG_TYPE_UpdateID')) . $action('GetSearchCapabilities', $arg('SearchCaps', 'out', 'SearchCapabilities')) . $action('GetSortCapabilities', $arg('SortCaps', 'out', 'SortCapabilities')) . $action('GetSystemUpdateID', $arg('Id', 'out', 'SystemUpdateID')); $vars = $var('A_ARG_TYPE_ObjectID', 'string') . '<stateVariable sendEvents="no"><name>A_ARG_TYPE_BrowseFlag</name><dataType>string</dataType>' . '<allowedValueList><allowedValue>BrowseMetadata</allowedValue><allowedValue>BrowseDirectChildren</allowedValue></allowedValueList></stateVariable>' . $var('A_ARG_TYPE_Filter', 'string') . $var('A_ARG_TYPE_Index', 'ui4') . $var('A_ARG_TYPE_Count', 'ui4') . $var('A_ARG_TYPE_SortCriteria', 'string') . $var('A_ARG_TYPE_Result', 'string') . $var('A_ARG_TYPE_UpdateID', 'ui4') . $var('SearchCapabilities', 'string') . $var('SortCapabilities', 'string') . $var('SystemUpdateID', 'ui4', true); } else { $actions = $action('GetProtocolInfo', $arg('Source', 'out', 'SourceProtocolInfo'), $arg('Sink', 'out', 'SinkProtocolInfo')) . $action('GetCurrentConnectionIDs', $arg('ConnectionIDs', 'out', 'CurrentConnectionIDs')); $vars = $var('SourceProtocolInfo', 'string', true) . $var('SinkProtocolInfo', 'string', true) . $var('CurrentConnectionIDs', 'string', true); } return '<?xml version="1.0" encoding="utf-8"?>' . "\n" . '<scpd xmlns="urn:schemas-upnp-org:service-1-0"><specVersion><major>1</major><minor>0</minor></specVersion>' . "<actionList>$actions</actionList><serviceStateTable>$vars</serviceStateTable></scpd>"; } /** A SOAP action. */ private function control(string $service, HttpRequest $r, string $here): HttpResponse { $soap = (string)$r->header('soapaction', ''); $action = preg_match('/#(\w+)"?\s*$/', $soap, $m) ? $m[1] : (preg_match('/<(?:\w+:)?(\w+)\s+xmlns(?::\w+)?="urn:schemas-upnp-org:service/', $r->body, $m) ? $m[1] : ''); $arg = fn (string $name): string => preg_match('#<' . $name . '(?:\s[^>]*)?>(.*?)</' . $name . '>#s', $r->body, $m) ? html_entity_decode($m[1], ENT_XML1 | ENT_QUOTES, 'UTF-8') : ''; $type = $service === 'cd' ? self::CD : self::CM; $out = match ($service . ':' . $action) { 'cd:Browse' => $this->browse($arg('ObjectID'), $arg('BrowseFlag'), (int)$arg('StartingIndex'), (int)$arg('RequestedCount'), $here), 'cd:GetSearchCapabilities' => ['SearchCaps' => ''], 'cd:GetSortCapabilities' => ['SortCaps' => ''], 'cd:GetSystemUpdateID' => ['Id' => (string)$this->updateId], 'cm:GetProtocolInfo' => ['Source' => 'http-get:*:audio/mpeg:*,http-get:*:audio/ogg:*,http-get:*:audio/flac:*,http-get:*:audio/wav:*,http-get:*:video/mp4:*,http-get:*:video/mp2t:*', 'Sink' => ''], 'cm:GetCurrentConnectionIDs' => ['ConnectionIDs' => '0'], default => null, }; if ($out === null) { return HttpResponse::text('<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><s:Fault>' . '<faultcode>s:Client</faultcode><faultstring>UPnPError</faultstring><detail><UPnPError xmlns="urn:schemas-upnp-org:control-1-0"><errorCode>401</errorCode>' . '<errorDescription>Invalid Action</errorDescription></UPnPError></detail></s:Fault></s:Body></s:Envelope>', 500, 'text/xml; charset="utf-8"'); } $body = ''; foreach ($out as $k => $v) { $body .= "<$k>" . htmlspecialchars((string)$v, ENT_XML1, 'UTF-8') . "</$k>"; } return HttpResponse::text('<?xml version="1.0" encoding="utf-8"?>' . "\n" . '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body>' . "<u:{$action}Response xmlns:u=\"$type\">$body</u:{$action}Response></s:Body></s:Envelope>", 200, 'text/xml; charset="utf-8"', ['EXT' => '']); } // the content --------------------------------------------------------------------------------------------------- /** @return array{Result: string, NumberReturned: string, TotalMatches: string, UpdateID: string} */ public function browse(string $id, string $flag, int $start, int $count, string $here): array { $this->seen[] = "Browse $id $flag"; $songs = $this->playlistSongs(); $live = $this->liveItems($here); $root = ['id' => '0', 'parent' => '-1', 'title' => $this->name, 'count' => count($live) + 1]; $list = ['id' => 'pl', 'parent' => '0', 'title' => 'Playlist WinZik (' . count($songs) . ')', 'count' => count($songs)]; if ($flag === 'BrowseMetadata') { $one = match (true) { $id === '0' => self::container($root), $id === 'pl' => self::container($list), isset($live[$id]) => $live[$id], str_starts_with($id, 'pl/') && isset($songs[substr($id, 3)]) => $this->songItem(substr($id, 3), $songs[substr($id, 3)], $here), default => null, }; $children = $one === null ? [] : [$one]; $total = count($children); } else { $children = match ($id) { '0' => array_merge(array_values($live), [self::container($list)]), 'pl' => array_map(fn (string $sid, string $path): string => $this->songItem($sid, $path, $here), array_keys($songs), array_values($songs)), default => [], }; $total = count($children); $children = array_slice($children, max(0, $start), $count > 0 ? $count : null); } $didl = '<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" ' . 'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/">' . implode('', $children) . '</DIDL-Lite>'; return ['Result' => $didl, 'NumberReturned' => (string)count($children), 'TotalMatches' => (string)$total, 'UpdateID' => (string)$this->updateId]; } /** @return array<string, string> id => path: the songs of the play list that are files here */ private function playlistSongs(): array { $songs = []; foreach ($this->wz->playlist->items as $item) { if (Cloud::isPseudo($item)) { continue; } $path = $this->wz->path($item); if (is_file($path)) { $songs[substr(md5($path), 0, 16)] = $path; } } if (array_keys($songs) !== array_keys($this->songs)) { $this->updateId++; } return $this->songs = $songs + array_slice($this->songs, 0, 200, true); // a song just removed still plays } /** @return array<string, string> the live items (id => DIDL) */ private function liveItems(string $here): array { $tag = $this->wz->tag; $now = $this->wz->playlist->current() !== null ? trim(($tag->artist !== '' ? $tag->artist . ' - ' : '') . $tag->title) : ''; $items = ['live' => self::item('live', '0', '▶ WinZik en direct' . ($now !== '' ? ' : ' . $now : ''), 'object.item.audioItem.audioBroadcast', "$here/dlna/live.mp3", 'audio/mpeg', '', 0.0, 0, 'WinZik', '')]; $ffmpeg = $this->wz->tools?->program('ffmpeg'); if ($ffmpeg !== null && VlcTarget::canVideo($ffmpeg)) { $items['livevideo'] = self::item('livevideo', '0', '▶ WinZik en direct (vidéo karaoké)', 'object.item.videoItem.videoBroadcast', "$here/dlna/live.ts", 'video/mp2t', '', 0.0, 0, 'WinZik', ''); } return $items; } private function songItem(string $id, string $path, string $here): string { [$tag, $info] = $this->wz->describe($path); $ext = Text::extension($path); $mime = CastSession::mime($path); $video = str_starts_with($mime, 'video/'); $cover = ''; try { $cover = (string)$this->wz->covers()->picture($path, $tag); } catch (\Throwable) { } return self::item("pl/$id", 'pl', $tag->title !== '' ? $tag->title : Text::baseName($path), $video ? 'object.item.videoItem' : 'object.item.audioItem.musicTrack', "$here/dlna/m/$id.$ext", $mime, $cover !== '' ? "$here/dlna/i/$id" : '', $info->duration, (int)@filesize($path), $tag->artist, $tag->album); } /** @param array{id: string, parent: string, title: string, count: int} $c */ private static function container(array $c): string { return '<container id="' . self::attr($c['id']) . '" parentID="' . self::attr($c['parent']) . '" restricted="1" childCount="' . $c['count'] . '" searchable="0">' . '<dc:title>' . self::text($c['title']) . '</dc:title><upnp:class>object.container.storageFolder</upnp:class></container>'; } private static function item(string $id, string $parent, string $title, string $class, string $url, string $mime, string $cover, float $duration, int $size, string $artist, string $album): string { $pn = $mime === 'audio/mpeg' && !str_ends_with($url, 'live.mp3') ? 'DLNA.ORG_PN=MP3;' : ''; $flags = str_contains($url, '/live.') ? 'DLNA.ORG_OP=00;DLNA.ORG_FLAGS=01700000000000000000000000000000' : self::DLNA_FLAGS; $d = (int)round($duration * 1000); return '<item id="' . self::attr($id) . '" parentID="' . self::attr($parent) . '" restricted="1">' . '<dc:title>' . self::text($title) . '</dc:title><upnp:class>' . $class . '</upnp:class>' . ($artist !== '' ? '<dc:creator>' . self::text($artist) . '</dc:creator><upnp:artist>' . self::text($artist) . '</upnp:artist>' : '') . ($album !== '' ? '<upnp:album>' . self::text($album) . '</upnp:album>' : '') . ($cover !== '' ? '<upnp:albumArtURI dlna:profileID="JPEG_TN">' . self::text($cover) . '</upnp:albumArtURI>' : '') . '<res protocolInfo="http-get:*:' . $mime . ':' . $pn . $flags . '"' . ($size > 0 ? ' size="' . $size . '"' : '') . ($d > 0 ? sprintf(' duration="%d:%02d:%02d.%03d"', intdiv($d, 3600000), intdiv($d % 3600000, 60000), intdiv($d % 60000, 1000), $d % 1000) : '') . '>' . self::text($url) . '</res></item>'; } private static function text(string $s): string { return htmlspecialchars($s, ENT_XML1 | ENT_SUBSTITUTE, 'UTF-8'); } private static function attr(string $s): string { return htmlspecialchars($s, ENT_XML1 | ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } private function song(string $id): ?HttpResponse { $path = $this->songs[$id] ?? null; if ($path === null || !is_file($path)) { return null; } $mime = CastSession::mime($path); return HttpResponse::file($path, $mime, ['transferMode.dlna.org' => 'Streaming', 'contentFeatures.dlna.org' => ($mime === 'audio/mpeg' ? 'DLNA.ORG_PN=MP3;' : '') . self::DLNA_FLAGS]); } private function cover(string $id): ?HttpResponse { $path = $this->songs[$id] ?? null; if ($path === null) { return null; } [$tag] = $this->wz->describe($path); $cover = (string)$this->wz->covers()->picture($path, $tag); return $cover !== '' && is_file($cover) ? HttpResponse::file($cover, str_ends_with($cover, '.png') ? 'image/png' : 'image/jpeg') : null; } /** The live item opened: the stream for VLC starts (WinZik plays if it did not), the player goes there. */ private function live(bool $video, HttpRequest $r): HttpResponse { $how = $this->cast->how(); if ($how !== ($video ? 'vlc-video' : 'vlc') && !$this->cast->openVlcStream($video)) { return HttpResponse::text($this->cast->message . "\n", 503); } if ($r->method === 'GET' && $this->wz->player->state !== \App\Audio\Player::PLAYING && $this->wz->playlist->count() > 0) { $this->wz->play(); } return HttpResponse::text('', 302, 'text/plain', ['Location' => $this->cast->vlcUrl($this->hostOf($r))]); }}