TR
apps/winzik / src / Media / YouTubeNativeJob.php · commit 6576d6f
<?phpnamespace App\Media;/** * One download of the queue without yt-dlp: the video found (an address, an id, or "ytsearch1:artiste titre" of a * Spotify / Deezer import: the first video of that search), its streams asked to InnerTube, downloaded by ranges * (RangedDownload) into WinZik's temporary folder, then ffmpeg makes the MP3 (title, artist, comment tags, as yt-dlp's * --embed-metadata) or the MP4 (the video and its sound copied as they are) in the music / video folder. * * state: resolve | download | convert | done | error; progress 0..1 of the download; file once done. */final class YouTubeNativeJob{    public string $state = 'resolve';    public float $progress = 0.0;    public string $error = '';    public string $file = '';    public string $title = '';    /** @var list<RangedDownload> */    private array $downloads = [];    /** @var list<string> the streams downloaded (ffmpeg's inputs) */    private array $inputs = [];    private ?Process $convert = null;    /** @var array{id: string, title: string, author: string, duration: int, description: string, streams: list<array<string, mixed>>}|null */    private ?array $video = null;    private bool $stopped = false;    /**     * @param \Closure(list<string>): Process $runner how ffmpeg is started     * @param (\Closure(string, string, int): RangedDownload)|null $download how a stream is downloaded (url, target, size)     */    public function __construct(private YouTubeInnerTube $api, public readonly string $url, public readonly string $format, private string $dir,        private string $tmpDir, private string $ffmpeg, private \Closure $runner, private ?\Closure $download = null)    {        $this->download ??= fn (string $url, string $target, int $size): RangedDownload => new RangedDownload($url, $target, $size);        $this->resolve();    }    /** Can this address be taken without yt-dlp? (YouTube, an id, or a "ytsearch1:" search) */    public static function handles(string $url): bool    {        return YouTubeInnerTube::videoId($url) !== null || preg_match('/^ytsearch\d*:\S/', $url) === 1;    }    private function resolve(): void    {        $id = YouTubeInnerTube::videoId($this->url);        if ($id !== null) {            $this->ask($id);            return;        }        if (!preg_match('/^ytsearch\d*:(.+)$/s', $this->url, $m)) {            $this->fail('sans yt-dlp, seules les adresses YouTube se téléchargent');            return;        }        $this->api->search(trim($m[1]), 1, 1)->then(function (mixed $found) use ($m): void {            $first = is_array($found) ? ($found[0] ?? null) : null;            if (!is_array($first)) {                $this->fail('rien trouvé sur YouTube pour « ' . trim($m[1]) . ' »');                return;            }            $this->ask((string)$first['id']);        }, fn (\Throwable $e) => $this->fail($e->getMessage()));    }    private function ask(string $id): void    {        if ($this->stopped) {            return;        }        $this->api->video($id)->then(function (mixed $video): void {            if ($this->stopped || !is_array($video)) {                return;            }            $this->video = $video;            $this->title = (string)$video['title'];            $streams = YouTubeInnerTube::pick($video['streams'], $this->format);            if ($streams === []) {                $this->fail($this->format === 'mp4' ? 'aucune image ni aucun son à télécharger pour cette vidéo' : 'aucun son à télécharger pour cette vidéo');                return;            }            @mkdir($this->tmpDir, 0777, true);            $key = substr(md5($this->url . '|' . $this->format . '|' . microtime(true)), 0, 10);            foreach ($streams as $i => $s) {                $target = $this->tmpDir . "/$key-$i.stream";                $this->inputs[] = $target;                $this->downloads[] = ($this->download)((string)$s['url'], $target, (int)$s['size']);            }            $this->state = 'download';        }, fn (\Throwable $e) => $this->fail($e->getMessage()));    }    /** Each frame. @return bool true once it ended (done or error) */    public function poll(): bool    {        if ($this->state === 'download') {            $all = true;            $got = $size = 0.0;            foreach ($this->downloads as $d) {                $all = $d->poll() && $all;                if ($d->error !== '') {                    $this->fail('téléchargement : ' . $d->error);                    return true;                }                // each stream weighs its size (unknown: as much as the others)                $weight = $d->size > 0 ? $d->size : 1.0;                $got += $d->progress * $weight;                $size += $weight;            }            $this->progress = $size > 0 ? min(0.999, $got / $size) : 0.0;            if ($all) {                $this->progress = 1.0;                $this->startConvert();            }        }        if ($this->state === 'convert' && $this->convert !== null) {            $this->convert->poll();            if ($this->convert->done()) {                $ok = $this->convert->ok() && is_file($this->file);                $why = $this->convert->error();                $this->convert->cleanup();                $this->convert = null;                $this->removeInputs();                if ($ok) {                    $this->state = 'done';                } else {                    @unlink($this->file);                    $this->fail('ffmpeg : ' . ($why ?: 'conversion impossible'));                }            }        }        return $this->state === 'done' || $this->state === 'error';    }    private function startConvert(): void    {        $video = (array)$this->video;        @mkdir($this->dir, 0777, true);        $this->file = $this->dir . '/' . self::fileName((string)($video['title'] ?? 'YouTube')) . '.' . $this->format;        $tags = ['title' => (string)($video['title'] ?? ''), 'artist' => (string)($video['author'] ?? ''), 'comment' => (string)($video['description'] ?? '')];        $this->convert = ($this->runner)(self::command($this->ffmpeg, $this->inputs, $this->format, $this->file, $tags));        $this->state = 'convert';    }    /**     * ffmpeg's command: MP3 (VBR best quality, as yt-dlp's --audio-quality 0, tags ID3v2) or MP4 (copied as it is: video     * of the first input, sound of the last). One core only: the phone and the computer keep playing.     * @param list<string> $inputs @param array{title: string, artist: string, comment: string} $tags @return list<string>     */    public static function command(string $ffmpeg, array $inputs, string $format, string $out, array $tags): array    {        $command = [$ffmpeg, '-y', '-v', 'error', '-nostdin'];        foreach ($inputs as $input) {            array_push($command, '-i', $input);        }        if ($format === 'mp4') {            $last = count($inputs) - 1;            array_push($command, '-map', '0:v:0', '-map', $last . ':a:0', '-c', 'copy', '-movflags', '+faststart');        } else {            array_push($command, '-map', '0:a:0', '-vn', '-c:a', 'libmp3lame', '-q:a', '0', '-id3v2_version', '3');        }        array_push($command, '-map_metadata', '-1', '-threads', '1');        foreach ($tags as $name => $value) {            $value = trim(str_replace("\0", '', $value));            if ($value !== '') {                array_push($command, '-metadata', $name . '=' . mb_substr($value, 0, 2000));            }        }        $command[] = $out;        return $command;    }    /** A title as a file name (as yt-dlp's "%(title).120B"): no / \ : * ? " < > |, no control characters, 120 bytes at most. */    public static function fileName(string $title): string    {        $name = (string)preg_replace('/[\x00-\x1f\x7f]/u', '', $title);        $name = strtr($name, ['/' => '⧸', '\\' => '⧹', ':' => ':', '*' => '*', '?' => '?', '"' => '"', '<' => '<', '>' => '>', '|' => '|']);        $name = trim($name, " .\t");        while (strlen($name) > 120) {            $name = mb_substr($name, 0, mb_strlen($name) - 1);        }        $name = rtrim($name, ' .');        return $name !== '' ? $name : 'YouTube';    }    /** Stopped for good (removed from the queue, WinZik quitting): downloads and ffmpeg ended, temporary files removed. */    public function stop(): void    {        $this->stopped = true;        foreach ($this->downloads as $d) {            $d->cancel();        }        if ($this->convert !== null) {            $this->convert->stop();            $this->convert->cleanup();            $this->convert = null;            @unlink($this->file);        }        $this->removeInputs();        if ($this->state !== 'done') {            $this->state = 'error';            $this->error = $this->error ?: 'arrêté';        }    }    private function removeInputs(): void    {        foreach ($this->inputs as $input) {            @unlink($input);        }    }    private function fail(string $why): void    {        if ($this->state === 'done' || $this->state === 'error') {            return;        }        $this->state = 'error';        $this->error = $why;        foreach ($this->downloads as $d) {            $d->cancel();        }        $this->removeInputs();    }}