TR
apps/winzik / src / Media / Process.php · commit 6576d6f
<?phpnamespace App\Media;/** * A program running in the background (yt-dlp, ffmpeg, tar): its output goes to files, read as they grow, so nothing * ever waits (pipes block on Windows, files do not). poll() each frame; done() when it ended. */class Process{    /** @var resource|null */    private $proc = null;    private int $code = -1;    private int $read = 0;    private string $partial = '';    /** @var list<string> the lines of its output so far */    public array $lines = [];    /** @param list<string> $command */    public function __construct(public readonly array $command, private string $out, private string $err)    {    }    /** @var list<string> lines given at once by finished() */    private array $given = [];    /**     * A program that already ended with this output (tests: yt-dlp / ffmpeg without the network); $effect runs when it     * is read, as the real one would have written its files. @param list<string> $command @param list<string> $output     */    public static function finished(array $command, array $output, int $code = 0, ?\Closure $effect = null): self    {        $p = new self($command, '', '');        $p->given = $output;        $p->code = $code;        $p->effect = $effect;        return $p;    }    private ?\Closure $effect = null;    /** @param list<string> $command */    public static function start(array $command, string $logDir): self    {        @mkdir($logDir, 0777, true);        $id = bin2hex(random_bytes(4));        $p = new self($command, "$logDir/$id.out", "$logDir/$id.err");        $p->run();        return $p;    }    protected function run(): void    {        $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';        $proc = @proc_open($this->command, [0 => ['file', $null, 'r'], 1 => ['file', $this->out, 'w'], 2 => ['file', $this->err, 'w']], $pipes,            null, null, ['bypass_shell' => true, 'suppress_errors' => true]);        if (!is_resource($proc)) {            $this->code = 127;            $this->lines[] = 'impossible de lancer ' . $this->command[0];            return;        }        $this->proc = $proc;    }    /** Reads what it wrote since the last call. @return list<string> the new whole lines */    public function poll(): array    {        if ($this->out === '') {            if ($this->effect !== null) {                ($this->effect)();                $this->effect = null;            }            [$new, $this->given] = [$this->given, []];            array_push($this->lines, ...$new);            return $new;        }        $new = [];        // its state first, then what it wrote: once it has ended, everything it wrote is in the file (read in the other        // order, the end of a long answer written meanwhile was lost: a search "never answered")        $ended = false;        if ($this->proc !== null) {            $status = proc_get_status($this->proc);            if (!$status['running']) {                $this->code = (int)$status['exitcode'];                proc_close($this->proc);                $this->proc = null;                $ended = true;            }        }        clearstatcache(false, $this->out);        $size = @filesize($this->out);        if ($size !== false && $size > $this->read && ($f = @fopen($this->out, 'rb'))) {            fseek($f, $this->read);            $chunk = (string)fread($f, $size - $this->read);            fclose($f);            $this->read += strlen($chunk);            $parts = preg_split('/\r\n|\r|\n/', $this->partial . $chunk) ?: [];            $this->partial = (string)array_pop($parts);            foreach ($parts as $line) {                if ($line !== '') {                    $new[] = $this->lines[] = $line;                }            }        }        if ($ended && $this->partial !== '') {            $new[] = $this->lines[] = $this->partial;            $this->partial = '';        }        return $new;    }    public function done(): bool    {        return $this->proc === null;    }    public function ok(): bool    {        return $this->done() && $this->code === 0;    }    public function output(): string    {        return implode("\n", $this->lines);    }    /** The end of its error output (why it failed). */    public function error(): string    {        if ($this->err === '') {            return $this->code === 0 ? '' : 'erreur ' . $this->code;        }        $text = trim((string)@file_get_contents($this->err));        $lines = array_values(array_filter(explode("\n", $text), fn ($l) => str_contains($l, 'ERROR') || str_contains($l, 'rror')));        return mb_substr((string)(end($lines) ?: explode("\n", $text)[0]), 0, 200);    }    /** its process id (0: ended or never started) */    public function pid(): int    {        return $this->proc !== null ? proc_get_status($this->proc)['pid'] : 0;    }    public function kill(): void    {        if ($this->proc !== null) {            @proc_terminate($this->proc);        }    }    /**     * Ends it now and for good (quitting WinZik: no ffmpeg / whisper left running alone): asked to end, then killed if it     * is still there a moment later, and reaped (no zombie). Its files stay (cleanup()). Nothing when already ended.     */    public function stop(float $grace = 0.5): void    {        if ($this->proc === null) {            return;        }        @proc_terminate($this->proc);        $until = microtime(true) + $grace;        while (($status = proc_get_status($this->proc))['running'] && microtime(true) < $until) {            usleep(10_000);        }        if ($status['running']) {            @proc_terminate($this->proc, 9);            $until = microtime(true) + 1.0;            while (proc_get_status($this->proc)['running'] && microtime(true) < $until) {                usleep(10_000);            }        }        $code = proc_get_status($this->proc)['exitcode'];        @proc_close($this->proc);        $this->proc = null;        $this->code = $code >= 0 ? (int)$code : 143;    }    public function cleanup(): void    {        @unlink($this->out);        @unlink($this->err);    }}