PL
apps/winzik / src / Media / SoundCache.php · commit 6576d6f
<?phpnamespace App\Media;/** * The sound of a song as WAV, made by ffmpeg in the background (WinZik's cache): what the visualizer reads (the true * samples at the player's position), and the song through the equalizer (ffmpeg's equalizer filter, one per band, * and the preamp), which the player then plays instead, from where it is. SDL_mixer gives no hook on its sound * (no Mix_RegisterEffect in the binding): the sound is made before it is played. */final class SoundCache{    private const KEEP = 6;    /** @var array<string, Process> target file => ffmpeg making it */    private array $jobs = [];    /** @var array<string, string> target file => why it failed */    private array $failed = [];    /** @param (\Closure(list<string>): Process)|null $runner */    public function __construct(private string $dir, private Tools $tools, private ?\Closure $runner = null)    {    }    /** The song as it is (WAV): null while it is being made. */    public function plain(string $song): ?string    {        if (strtolower(pathinfo($song, PATHINFO_EXTENSION)) === 'wav' && Wav::open($song) !== null) {            return $song;        }        return $this->make($song, $this->dir . '/' . md5('plain|' . $song) . '.wav', []);    }    /**     * The song through the equalizer: null while it is being made. @param list<float> $bands dB of the 10 bands     */    public function equalized(string $song, array $bands, float $preamp): ?string    {        $key = md5('eq|' . $song . '|' . implode(',', $bands) . '|' . $preamp);        $filters = [];        foreach ([60, 170, 310, 600, 1000, 3000, 6000, 12000, 14000, 16000] as $i => $hz) {            if (abs($bands[$i] ?? 0.0) >= 0.1) {                $filters[] = sprintf('equalizer=f=%d:t=o:w=1:g=%.1f', $hz, $bands[$i]);            }        }        if ($filters === [] && abs($preamp) < 0.1) {            return null;        }        if (abs($preamp) >= 0.1) {            $filters[] = sprintf('volume=%.1fdB', $preamp);        }        $filters[] = 'alimiter=limit=0.98';     // no clipping when the bands go up        return $this->make($song, $this->dir . "/$key.wav", ['-af', implode(',', $filters)]);    }    public function busy(): bool    {        return $this->jobs !== [];    }    /** @param list<string> $filters */    private function make(string $song, string $target, array $filters): ?string    {        if (is_file("$target.ok")) {            return $target;        }        if (isset($this->jobs[$target]) || isset($this->failed[$target])) {            return null;        }        $ffmpeg = $this->tools->program('ffmpeg');        if ($ffmpeg === null || !is_file($song)) {            return null;        }        @mkdir($this->dir, 0777, true);        $this->clean();        $run = $this->runner ?? fn (array $cmd): Process => Process::start($cmd, $this->dir . '/logs');        $this->jobs[$target] = $run(array_merge([$ffmpeg, '-y', '-v', 'error', '-i', $song, '-vn'], $filters,            ['-ac', '2', '-ar', '44100', '-c:a', 'pcm_s16le', $target]));        return null;    }    /** Each frame. */    public function poll(): void    {        foreach ($this->jobs as $target => $p) {            $p->poll();            if ($p->done()) {                if ($p->ok() && is_file($target)) {                    @touch("$target.ok");                } else {                    $this->failed[$target] = $p->error();                    @unlink($target);                }                $p->cleanup();                unset($this->jobs[$target]);            }        }    }    /** Quitting: every ffmpeg ended now, its half written file removed (no .ok: made again next time); again: nothing. */    public function stop(): void    {        foreach ($this->jobs as $target => $p) {            $p->stop();            $p->cleanup();            @unlink($target);        }        $this->jobs = [];    }    private function clean(): void    {        $files = (array)glob($this->dir . '/*.wav');        if (count($files) < self::KEEP) {            return;        }        usort($files, fn ($a, $b) => (int)filemtime((string)$b) <=> (int)filemtime((string)$a));        foreach (array_slice($files, self::KEEP) as $old) {            @unlink((string)$old);            @unlink($old . '.ok');        }    }}