NL
apps/winzik / src / Media / VideoCache.php · commit 6576d6f
<?phpnamespace App\Media;/** * What the video player needs of a film (MP4, WebM, MKV), made by ffmpeg in the background into WinZik's cache: * its sound as a WAV (SDL_mixer plays it: the player's clock is the film's) and its pictures, 25 a second, 360 lines, * as JPEG files (made faster than they are shown: the film starts as soon as its sound is ready). The 4 last films stay. */class VideoCache{    public const FPS = 25;    private const KEEP = 4;    /** @var array<string, array{audio: ?Process, frames: ?Process, error: string}> */    private array $jobs = [];    /** @var array<string, int> dir => the last frame known to exist */    private array $last = [];    /** @param (\Closure(list<string>): Process)|null $runner */    public function __construct(private string $dir, private Tools $tools, private ?\Closure $runner = null)    {    }    public function folder(string $film): string    {        return $this->dir . '/' . md5($film);    }    /** The sound of a film to play, null while it is being made (or cannot be: error()). */    public function audio(string $film): ?string    {        $dir = $this->folder($film);        if (is_file("$dir/audio.ok") && is_file("$dir/audio.wav")) {            return "$dir/audio.wav";        }        if (is_file("$dir/audio.ok")) {            // a film prepared by WinZik 0.9.88 (its sound was an MP3): its sound is made again, its pictures stay            @unlink("$dir/audio.ok");            @unlink("$dir/audio.mp3");        }        if (!isset($this->jobs[$film])) {            $this->prepare($film);        }        return null;    }    public function error(string $film): string    {        return $this->jobs[$film]['error'] ?? '';    }    private function prepare(string $film): void    {        $ffmpeg = $this->tools->program('ffmpeg');        if ($ffmpeg === null) {            if ($this->tools->phone || in_array($this->tools->state['ffmpeg'], ['unsupported', 'error'], true)) {                // the phone app without its ffmpeg (JUMPHP_FFMPEG), or none on the computer: said, never waited for                $this->jobs[$film] = ['audio' => null, 'frames' => null, 'error' => $this->tools->ffmpegMissing()];            }            return;     // ffmpeg is on its way: the film waits (asked again each frame)        }        if (!is_file($film)) {            $this->jobs[$film] = ['audio' => null, 'frames' => null, 'error' => 'fichier introuvable'];            return;        }        $this->clean();        $dir = $this->folder($film);        @mkdir($dir, 0777, true);        @touch($dir);        $run = $this->runner ?? fn (array $cmd): Process => Process::start($cmd, $this->dir . '/logs');        $this->jobs[$film] = [            // the sound as WAV: no encoding, ready in a moment (the film starts with it); the visualizer reads it too            'audio' => $run([$ffmpeg, '-y', '-v', 'error', '-i', $film, '-vn', '-ac', '2', '-ar', '44100', '-c:a', 'pcm_s16le', "$dir/audio.wav"]),            'frames' => is_file("$dir/frames.ok") ? null                : $run([$ffmpeg, '-y', '-v', 'error', '-i', $film, '-an', '-vf', 'fps=' . self::FPS . ',scale=-2:360', '-q:v', '5', "$dir/%06d.jpg"]),            'error' => '',        ];    }    /** Each frame. */    public function poll(): void    {        foreach ($this->jobs as $film => &$job) {            $dir = $this->folder($film);            foreach (['audio', 'frames'] as $part) {                $p = $job[$part];                if ($p === null) {                    continue;                }                $p->poll();                if ($p->done()) {                    if ($p->ok()) {                        @touch("$dir/$part.ok");                    } elseif ($part === 'audio') {                        $job['error'] = 'ffmpeg : ' . ($p->error() ?: 'film illisible');                    }                    $p->cleanup();                    $job[$part] = null;                }            }        }        unset($job);    }    /** Quitting: the ffmpeg of every film ended now (a film half made is made again next time: no .ok); again: nothing. */    public function stop(): void    {        foreach ($this->jobs as $film => $job) {            foreach (['audio', 'frames'] as $part) {                if ($job[$part] !== null) {                    $job[$part]->stop();                    $job[$part]->cleanup();                }            }        }        $this->jobs = [];    }    /** True while the pictures of a film are still being made. */    public function making(string $film): bool    {        return ($this->jobs[$film]['frames'] ?? null) !== null;    }    /** The picture of a film at a moment (the nearest one made so far before it), null when none is. */    public function frame(string $film, float $seconds): ?string    {        $dir = $this->folder($film);        $index = max(1, (int)floor($seconds * self::FPS) + 1);        $file = sprintf('%s/%06d.jpg', $dir, $index);        if (is_file($file)) {            $this->last[$dir] = max($this->last[$dir] ?? 0, $index);            return $file;        }        $known = min($index, $this->last[$dir] ?? 0);        return $known > 0 ? sprintf('%s/%06d.jpg', $dir, $known) : null;    }    /** Only the last films stay in the cache (their pictures take room). */    private function clean(): void    {        $dirs = array_filter((array)glob($this->dir . '/*', GLOB_ONLYDIR), fn ($d) => basename((string)$d) !== 'logs');        usort($dirs, fn ($a, $b) => (int)filemtime((string)$b) <=> (int)filemtime((string)$a));        foreach (array_slice($dirs, self::KEEP - 1) as $old) {            Tools::remove((string)$old);        }    }}