EN
apps/winzik / src / Cast / DlnaTarget.php · commit 6576d6f
<?phpnamespace App\Cast;/** * A DLNA / UPnP media renderer plays the song (a smart TV, a box, a sound bar): SOAP actions of AVTransport * (SetAVTransportURI with DIDL-Lite metadata: title, artist, album, cover; Play, Pause, Stop, Seek; GetTransportInfo * and GetPositionInfo every second) and RenderingControl (SetVolume). One action at a time (many renderers do not * like two at once), in order; a renderer that stops answering is `lost` after three tries. A DLNA TV cannot show a * web page: streaming only. */final class DlnaTarget implements CastTarget{    private const POLL = 1.0;    private const TIMEOUT = 5.0;    /** @var list<array{service: string, url: string, action: string, args: array<string, string>, then: ?\Closure, soft: bool}> */    private array $queue = [];    private bool $busy = false;    private string $state = 'connecting';    private ?float $position = null;    private float $positionAt = 0.0;    private int $song = -1;    private int $loading = -1;    private float $lastPoll = 0.0;    private int $failures = 0;    private string $error = '';    private bool $closed = false;    public function __construct(private CastDevice $device, private LanHttp $http)    {        // a first question: is it there?        $this->queue('AVTransport', 'GetTransportInfo', [], function (?array $out): void {            if ($out !== null && $this->state === 'connecting') {                $this->state = 'idle';            }        });    }    public function load(array $song, float $at, bool $play): void    {        $this->queue = [];      // what was waiting was for the song before        $this->loading = (int)$song['id'];        $this->state = 'loading';        $this->position = $at;        $this->positionAt = microtime(true);        $this->queue('AVTransport', 'Stop', [], null, true);        $this->queue('AVTransport', 'SetAVTransportURI', ['CurrentURI' => (string)$song['url'], 'CurrentURIMetaData' => self::didl($song)],            function (?array $out) use ($song): void {                if ($out === null) {                    $this->error = 'La TV refuse ce morceau' . ($this->error !== '' ? ' : ' . $this->error : '');                    $this->loading = -1;                    $this->state = 'idle';                    return;                }                $this->song = (int)$song['id'];            });        if ($play) {            $this->queue('AVTransport', 'Play', ['Speed' => '1']);        }        if ($at > 1.0) {            $this->queue('AVTransport', 'Seek', ['Unit' => 'REL_TIME', 'Target' => self::clock($at)], null, true);        }    }    public function play(): void    {        $this->queue('AVTransport', 'Play', ['Speed' => '1']);    }    public function pause(): void    {        $this->queue('AVTransport', 'Pause', []);    }    public function seek(float $seconds): void    {        $this->position = $seconds;        $this->positionAt = microtime(true);        $this->queue('AVTransport', 'Seek', ['Unit' => 'REL_TIME', 'Target' => self::clock($seconds)]);    }    public function stop(): void    {        $this->queue('AVTransport', 'Stop', [], null, true);    }    public function setVolume(int $volume): void    {        if ($this->device->rendering === '') {            return;        }        // only the last volume asked matters        $this->queue = array_values(array_filter($this->queue, fn (array $q) => $q['action'] !== 'SetVolume'));        $this->queue('RenderingControl', 'SetVolume', ['Channel' => 'Master', 'DesiredVolume' => (string)max(0, min(100, $volume))], null, true);    }    public function poll(): void    {        $this->http->poll();        if ($this->closed) {            return;        }        $now = microtime(true);        if (!$this->busy && $this->queue === [] && $now - $this->lastPoll >= self::POLL && $this->state !== 'lost') {            $this->lastPoll = $now;            $this->queue('AVTransport', 'GetTransportInfo', [], function (?array $out): void {                if ($out === null) {                    return;                }                $was = $this->state;                $this->state = match (strtoupper($out['CurrentTransportState'] ?? '')) {                    'PLAYING' => 'playing',                    'PAUSED_PLAYBACK', 'PAUSED_RECORDING' => 'paused',                    'TRANSITIONING' => 'loading',                    default => $this->loading >= 0 && $this->song !== $this->loading ? 'loading' : 'idle',                };                if ($this->state === 'playing' && $this->song === $this->loading) {                    $this->loading = -1;                }                if ($was === 'playing' && $this->state !== 'playing') {                    $this->position = $this->interpolated();                    $this->positionAt = microtime(true);                }            }, true);            $this->queue('AVTransport', 'GetPositionInfo', [], function (?array $out): void {                if ($out !== null && isset($out['RelTime']) && ($t = self::seconds($out['RelTime'])) !== null) {                    $this->position = $t;                    $this->positionAt = microtime(true);                }            }, true);        }        $this->next();    }    public function status(): array    {        return ['state' => $this->state, 'position' => $this->position === null ? null : $this->interpolated(), 'song' => $this->song];    }    private function interpolated(): float    {        $p = (float)$this->position;        return $this->state === 'playing' ? $p + (microtime(true) - $this->positionAt) : $p;    }    public function error(): string    {        return $this->error;    }    public function close(): void    {        if (!$this->closed) {            $this->queue = [];            $this->queue('AVTransport', 'Stop', [], null, true);            $this->next();        }        $this->closed = true;    }    /** @param array<string, string> $args */    private function queue(string $service, string $action, array $args, ?\Closure $then = null, bool $soft = false): void    {        $url = $service === 'AVTransport' ? $this->device->avTransport : $this->device->rendering;        if ($url === '') {            return;        }        $this->queue[] = ['service' => $service, 'url' => $url, 'action' => $action, 'args' => $args, 'then' => $then, 'soft' => $soft];    }    private function next(): void    {        if ($this->busy || $this->queue === []) {            return;        }        $q = array_shift($this->queue);        $this->busy = true;        $urn = $q['service'] === 'AVTransport' ? Ssdp::AV_TRANSPORT : Ssdp::RENDERING;        $this->http->request('POST', $q['url'], self::envelope($urn, $q['action'], $q['args']), [            'Content-Type' => 'text/xml; charset="utf-8"',            'SOAPACTION' => '"' . $urn . '#' . $q['action'] . '"',            'User-Agent' => 'WinZik/1.0 UPnP/1.1 DLNADOC/1.50',        ], self::TIMEOUT, function (?array $r, string $why) use ($q): void {            $this->busy = false;            $out = null;            if ($r === null) {                $this->failures++;                if ($this->failures >= 3) {                    $this->state = 'lost';                    $this->error = 'La TV ne répond plus (éteinte, ou sur un autre réseau ?)';                }                if (!$q['soft']) {                    $this->error = 'La TV ne répond pas (' . $why . ')';                }            } else {                $this->failures = 0;                if ($this->state === 'lost') {                    $this->state = 'idle';                }                if ($r['status'] === 200) {                    $out = self::values($r['body']);                } elseif (!$q['soft']) {                    $this->error = self::fault($r['body'], $r['status']);                }            }            if ($q['then'] !== null) {                ($q['then'])($out);            }            if (!$this->closed) {                $this->next();            }        });    }    /** @param array<string, string> $args */    public static function envelope(string $urn, string $action, array $args): string    {        $body = '<InstanceID>0</InstanceID>';        foreach ($args as $name => $value) {            $body .= "<$name>" . htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8') . "</$name>";        }        return '<?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 xmlns:u=\"$urn\">$body</u:$action></s:Body></s:Envelope>";    }    /** @return array<string, string> the out arguments of an answer (<RelTime>0:01:02</RelTime>...) */    public static function values(string $xml): array    {        $out = [];        if (preg_match('#<(?:\w+:)?Body[^>]*>\s*<(?:\w+:)?\w+Response[^>]*>(.*?)</(?:\w+:)?\w+Response>#s', $xml, $m)) {            preg_match_all('#<(\w+)>(.*?)</\1>|<(\w+)\s*/>#s', $m[1], $all, PREG_SET_ORDER);            foreach ($all as $a) {                if (($a[1] ?? '') !== '') {                    $out[$a[1]] = html_entity_decode($a[2], ENT_QUOTES | ENT_XML1, 'UTF-8');                } elseif (($a[3] ?? '') !== '') {                    $out[$a[3]] = '';                }            }        }        return $out;    }    /** A SOAP fault in French: "La TV refuse : Transition not available (701)". */    public static function fault(string $xml, int $status): string    {        $code = preg_match('#<errorCode>(\d+)</errorCode>#', $xml, $m) ? $m[1] : '';        $text = preg_match('#<errorDescription>(.*?)</errorDescription>#s', $xml, $d) ? trim(html_entity_decode($d[1])) : '';        if ($code === '' && $text === '') {            return 'La TV refuse (erreur HTTP ' . $status . ')';        }        return 'La TV refuse : ' . ($text !== '' ? $text : 'erreur') . ($code !== '' ? " ($code)" : '');    }    /**     * The DIDL-Lite of a song (its title, artist, album, cover, the resource with its DLNA protocol info).     * @param array<string, mixed> $song     */    public static function didl(array $song): string    {        $e = fn (mixed $s) => htmlspecialchars((string)$s, ENT_XML1 | ENT_QUOTES, 'UTF-8');        $mime = (string)($song['mime'] ?? 'audio/mpeg');        $pn = $mime === 'audio/mpeg' ? 'DLNA.ORG_PN=MP3;' : '';        $video = str_starts_with($mime, 'video/');        $duration = (float)($song['duration'] ?? 0) > 0 ? ' duration="' . self::clock((float)$song['duration']) . '.000"' : '';        return '<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/">'            . '<item id="winzik-' . (int)($song['id'] ?? 0) . '" parentID="0" restricted="1">'            . '<dc:title>' . $e($song['title'] ?? 'WinZik') . '</dc:title>'            . (($song['artist'] ?? '') !== '' ? '<upnp:artist>' . $e($song['artist']) . '</upnp:artist><dc:creator>' . $e($song['artist']) . '</dc:creator>' : '')            . (($song['album'] ?? '') !== '' ? '<upnp:album>' . $e($song['album']) . '</upnp:album>' : '')            . (($song['cover'] ?? '') !== '' ? '<upnp:albumArtURI>' . $e($song['cover']) . '</upnp:albumArtURI>' : '')            . '<upnp:class>object.item.' . ($video ? 'videoItem' : 'audioItem.musicTrack') . '</upnp:class>'            . '<res protocolInfo="http-get:*:' . $e($mime) . ':' . $pn . 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000"' . $duration . '>'            . $e($song['url'] ?? '') . '</res></item></DIDL-Lite>';    }    /** 75.4 -> "0:01:15" */    public static function clock(float $seconds): string    {        $s = (int)max(0, round($seconds));        return sprintf('%d:%02d:%02d', intdiv($s, 3600), intdiv($s % 3600, 60), $s % 60);    }    /** "0:01:15.300" -> 75.3; "NOT_IMPLEMENTED" -> null */    public static function seconds(string $clock): ?float    {        if (!preg_match('/^(\d+):(\d{1,2}):(\d{1,2}(?:\.\d+)?)$/', trim($clock), $m)) {            return null;        }        return (int)$m[1] * 3600 + (int)$m[2] * 60 + (float)$m[3];    }}