JA
apps/winzik / src / Model / AudioInfo.php · commit 6576d6f
<?phpnamespace App\Model;/** * The length (seconds) and bit rate (kbps) of an audio file, read from its headers: SDL_mixer plays the files but * does not say how long they are, and the old player showed both (Form1.Label14 = the kbps, the position bar needs * the duration). MP3 (CBR, and VBR through its Xing / Info / VBRI header), WAV, OGG (Vorbis / Opus). * No 64-bit integer: the browser's PHP is 32-bit (unpack('V') pairs make the big numbers floats). */final class AudioInfo{    private const BITRATES = [        // [version 1][layer] then [version 2 / 2.5][layer], kbps for the index 0..15        '1-1' => [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0],        '1-2' => [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0],        '1-3' => [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0],        '2-1' => [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0],        '2-2' => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0],        '2-3' => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0],    ];    private const RATES = ['1' => [44100, 48000, 32000], '2' => [22050, 24000, 16000], '2.5' => [11025, 12000, 8000]];    public function __construct(public float $duration = 0.0, public int $kbps = 0, public int $sampleRate = 0, public int $channels = 0)    {    }    public static function of(string $file): self    {        $size = is_file($file) ? (float)@filesize($file) : 0.0;        if ($size <= 0) {            return new self();        }        $f = @fopen($file, 'rb');        if ($f === false) {            return new self();        }        $head = (string)fread($f, 65536);        $tail = '';        if ($size > 65536) {            fseek($f, (int)max(0, $size - 65536));            $tail = (string)fread($f, 65536);        } else {            $tail = $head;        }        // MP3: the sound starts after the ID3v2 tag, which can be far bigger than what was read (a cover of 200 KB)        $start = 0;        $audio = $head;        if (str_starts_with($head, 'ID3') && strlen($head) >= 10) {            $b = array_map('ord', str_split(substr($head, 6, 4)));            $start = 10 + (($b[0] & 0x7F) << 21 | ($b[1] & 0x7F) << 14 | ($b[2] & 0x7F) << 7 | ($b[3] & 0x7F))                + ((ord($head[5]) & 0x10) !== 0 ? 10 : 0);      // a footer            $audio = '';            if ($start < $size && fseek($f, $start) === 0) {                $audio = (string)fread($f, 65536);            }        }        fclose($f);        try {            $info = match (true) {                str_starts_with($head, 'RIFF') && substr($head, 8, 4) === 'WAVE' => self::wav($head, $size),                str_starts_with($head, 'OggS') => self::ogg($head, $tail, $size),                substr($head, 4, 4) === 'ftyp' => self::mp4($head, $tail),                default => Text::extension($file) === 'mp3' || str_starts_with($head, 'ID3') ? self::mp3($audio, $start, $tail, $size) : new self(),            };        } catch (\Throwable) {            $info = new self();        }        return $info;    }    /** 32 bits at $at ('N' big endian, 'V' little endian), 0 when the file ends before; a float past 2^31 (32-bit PHP). */    private static function u32(string $s, int $at, string $format = 'N'): float    {        if ($at < 0 || $at + 4 > strlen($s)) {            return 0.0;        }        $n = (float)unpack($format, substr($s, $at, 4))[1];        return $n < 0 ? $n + 4294967296.0 : $n;    }    /** MP4 / M4A: the length of its "mvhd" box (at the start of the file, or at its end). */    private static function mp4(string $head, string $tail): self    {        foreach ([$head, $tail] as $part) {            $at = strpos($part, 'mvhd');            if ($at === false || strlen($part) < $at + 36) {                continue;            }            $version = ord($part[$at + 4]);            if ($version === 1) {                $scale = self::u32($part, $at + 4 + 20);                $length = self::u32($part, $at + 4 + 24) * 4294967296.0 + self::u32($part, $at + 4 + 28);            } else {                $scale = self::u32($part, $at + 4 + 12);                $length = self::u32($part, $at + 4 + 16);            }            if ($scale > 0) {                return new self($length / $scale);            }        }        return new self();    }    private static function wav(string $head, float $size): self    {        $pos = 12;        $byteRate = 0;        $rate = $channels = $bits = 0;        while ($pos + 8 <= strlen($head)) {            $id = substr($head, $pos, 4);            $len = self::u32($head, $pos + 4, 'V');            if ($id === 'fmt ') {                if ($pos + 8 + 16 > strlen($head)) {                    break;                }                $fmt = unpack('vformat/vchannels/Vrate/VbyteRate/vblock/vbits', substr($head, $pos + 8, 16));                [$channels, $rate, $byteRate, $bits] = [$fmt['channels'], $fmt['rate'], $fmt['byteRate'], $fmt['bits']];            } elseif ($id === 'data') {                // ffmpeg writing to a pipe puts 0 (or 0xFFFFFFFF) there: the rest of the file is the data                $rest = max(0.0, $size - $pos - 8);                $data = $len > 0 ? min($len, $rest) : $rest;                return new self($byteRate > 0 ? $data / $byteRate : 0.0, (int)round($byteRate * 8 / 1000), $rate, $channels);            }            $pos += 8 + (int)min($len, 1 << 30) + ((int)$len & 1);        }        return new self();    }    private static function ogg(string $head, string $tail, float $size): self    {        $rate = 0;        $channels = 0;        if (($v = strpos($head, "\x01vorbis")) !== false && $v + 16 <= strlen($head)) {            $channels = ord($head[$v + 11]);            $rate = (int)self::u32($head, $v + 12, 'V');        } elseif (($o = strpos($head, 'OpusHead')) !== false && $o + 10 <= strlen($head)) {            $channels = ord($head[$o + 9]);            $rate = 48000;        }        // the last page's granule position = the number of samples        $last = strrpos($tail, 'OggS');        if ($last === false || $rate <= 0 || $last + 14 > strlen($tail)) {            return new self(0.0, 0, $rate, $channels);        }        $samples = self::u32($tail, $last + 6, 'V') + self::u32($tail, $last + 10, 'V') * 4294967296.0;        $duration = $samples / $rate;        return new self($duration, $duration > 0 ? (int)round($size * 8 / $duration / 1000) : 0, $rate, $channels);    }    /** @param string $head the file from $start on (after its ID3v2 tag) */    private static function mp3(string $head, int $start, string $tail, float $size): self    {        $audioBytes = $size - $start - (substr($tail, -128, 3) === 'TAG' ? 128 : 0);        for ($p = 0, $n = strlen($head) - 4; $p < $n; $p++) {            if (ord($head[$p]) !== 0xFF || (ord($head[$p + 1]) & 0xE0) !== 0xE0) {                continue;            }            $h = self::frame(substr($head, $p, 4));            if ($h === null) {                continue;            }            [$version, $layer, $kbps, $rate, $channels, $samples] = $h;            // a VBR header in the first frame: Xing / Info (after the side info) or VBRI (32 bytes after the header)            foreach (['Xing', 'Info'] as $tag) {                $x = strpos(substr($head, $p, 200), $tag);                if ($x !== false) {                    $flags = (int)self::u32($head, $p + $x + 4);                    if ($flags & 1) {                        $frames = self::u32($head, $p + $x + 8);                        $duration = $frames * $samples / $rate;                        return new self($duration, $duration > 0 ? (int)round($audioBytes * 8 / $duration / 1000) : $kbps, $rate, $channels);                    }                }            }            if (substr($head, $p + 36, 4) === 'VBRI') {                $frames = self::u32($head, $p + 36 + 14);                $duration = $frames * $samples / $rate;                return new self($duration, $duration > 0 ? (int)round($audioBytes * 8 / $duration / 1000) : $kbps, $rate, $channels);            }            return new self($kbps > 0 ? max(0.0, $audioBytes - $p) * 8 / ($kbps * 1000) : 0.0, $kbps, $rate, $channels);        }        return new self();    }    /** @return array{0: string, 1: int, 2: int, 3: int, 4: int, 5: int}|null version, layer, kbps, rate, channels, samples per frame */    private static function frame(string $bytes): ?array    {        if (strlen($bytes) < 4) {            return null;        }        [$b1, $b2, $b3] = [ord($bytes[1]), ord($bytes[2]), ord($bytes[3])];        $version = match (($b1 >> 3) & 3) { 0 => '2.5', 2 => '2', 3 => '1', default => null };        $layer = match (($b1 >> 1) & 3) { 1 => 3, 2 => 2, 3 => 1, default => 0 };        $bitrateIndex = $b2 >> 4;        $rateIndex = ($b2 >> 2) & 3;        if ($version === null || $layer === 0 || $bitrateIndex === 0 || $bitrateIndex === 15 || $rateIndex === 3) {            return null;        }        $kbps = self::BITRATES[($version === '1' ? '1' : '2') . '-' . $layer][$bitrateIndex];        $rate = self::RATES[$version][$rateIndex];        $samples = $layer === 1 ? 384 : ($layer === 3 && $version !== '1' ? 576 : 1152);        $channels = ($b3 >> 6) === 3 ? 1 : 2;        return [$version, $layer, $kbps, $rate, $channels, $samples];    }}