NL
apps/winzik / src / Media / Wav.php · commit 6576d6f
<?phpnamespace App\Media;/** A 16-bit PCM WAV file read at any moment: the samples of a window of time, mixed to mono, -1..1. */final class Wav{    public int $rate = 44100;    public int $channels = 2;    private int $dataStart = 44;    private int $dataSize = 0;    /** @var resource|null */    private $f = null;    public static function open(string $file): ?self    {        $f = @fopen($file, 'rb');        if ($f === false) {            return null;        }        $head = (string)fread($f, 12);        if (strlen($head) < 12 || substr($head, 0, 4) !== 'RIFF' || substr($head, 8, 4) !== 'WAVE') {            fclose($f);            return null;        }        $w = new self();        $bits = 0;        $format = 0;        while (!feof($f)) {            $chunk = (string)fread($f, 8);            if (strlen($chunk) < 8) {                break;            }            ['id' => $id, 'size' => $size] = (array)unpack('a4id/Vsize', $chunk);            if ($id === 'fmt ') {                $fmt = (string)fread($f, (int)$size);                ['format' => $format, 'channels' => $w->channels, 'rate' => $w->rate] = (array)unpack('vformat/vchannels/Vrate', $fmt);                $bits = (int)(unpack('v', substr($fmt, 14, 2))[1] ?? 0);            } elseif ($id === 'data') {                $w->dataStart = (int)ftell($f);                // ffmpeg writing to a file it cannot rewind puts 0 or -1 here: the rest of the file is the data                $w->dataSize = (int)$size > 0 && (int)$size < 0x7FFFFFFF ? (int)$size : PHP_INT_MAX;                break;            } else {                fseek($f, (int)$size + ((int)$size & 1), SEEK_CUR);            }        }        if ($format !== 1 || $bits !== 16 || $w->dataSize === 0 || $w->channels < 1 || $w->rate < 1) {            fclose($f);            return null;        }        $w->f = $f;        $w->path = $file;        return $w;    }    private string $path = '';    /** Its length in seconds (a WAV still being written: what is there now). */    public function duration(): float    {        $size = $this->dataSize < PHP_INT_MAX ? $this->dataSize : max(0, (int)@filesize($this->path) - $this->dataStart);        return $size / max(1, $this->rate * 2 * $this->channels);    }    /** @return list<float> $count mono samples from $seconds on (fewer near the end, none past it) */    public function samples(float $seconds, int $count): array    {        if ($this->f === null) {            return [];        }        $frame = 2 * $this->channels;        $offset = (int)floor(max(0.0, $seconds) * $this->rate) * $frame;        if ($offset >= $this->dataSize) {            return [];        }        fseek($this->f, $this->dataStart + $offset);        $bytes = (string)fread($this->f, $count * $frame);        $all = $bytes === '' ? [] : array_values((array)unpack('s*', $bytes));        $out = [];        $ch = $this->channels;        for ($i = 0, $n = intdiv(count($all), $ch); $i < $n; $i++) {            $sum = 0;            for ($c = 0; $c < $ch; $c++) {                $sum += $all[$i * $ch + $c];            }            $out[] = $sum / ($ch * 32768);        }        return $out;    }    public function __destruct()    {        if ($this->f !== null) {            fclose($this->f);        }    }}