EN
apps/winzik / tests / AudioInfoTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Model\AudioInfo;use PHPUnit\Framework\TestCase;/** The length and bit rate of generated WAV / MP3 / OGG headers, and of broken files. */final class AudioInfoTest extends TestCase{    /** @var list<string> */    private array $files = [];    protected function tearDown(): void    {        foreach ($this->files as $file) {            @unlink($file);        }    }    private function file(string $bytes, string $ext = 'mp3'): string    {        $file = sys_get_temp_dir() . '/wz-info-' . bin2hex(random_bytes(4)) . '.' . $ext;        file_put_contents($file, $bytes);        $this->files[] = $file;        return $file;    }    /** A 16-bit PCM WAV; $dataSize: what its header says (null: the real size). */    private static function wav(int $rate, int $channels, float $seconds, ?int $dataSize = null, string $extra = ''): string    {        $data = str_repeat("\0", (int)round($seconds * $rate) * 2 * $channels);        $fmt = pack('vvVVvv', 1, $channels, $rate, $rate * 2 * $channels, 2 * $channels, 16);        $body = 'WAVE' . 'fmt ' . pack('V', 16) . $fmt . $extra . 'data' . pack('V', $dataSize ?? strlen($data)) . $data;        return 'RIFF' . pack('V', strlen($body)) . $body;    }    /** MPEG-1 layer III frames, 128 kbps, 44.1 kHz, stereo (417 bytes each). */    private static function frames(int $count): string    {        return str_repeat("\xFF\xFB\x90\x00" . str_repeat("\x55", 413), $count);    }    private static function id3v2(int $bodySize): string    {        $n = $bodySize;        return 'ID3' . "\x03\0\0" . chr(($n >> 21) & 0x7F) . chr(($n >> 14) & 0x7F) . chr(($n >> 7) & 0x7F) . chr($n & 0x7F)            . 'TIT2' . pack('N', 6) . "\0\0" . "\x00Titre" . str_repeat("\0", $bodySize - 16);    }    public function testTheLengthOfAWavComesFromItsDataChunk(): void    {        $info = AudioInfo::of($this->file(self::wav(44100, 2, 2.5), 'wav'));        self::assertEqualsWithDelta(2.5, $info->duration, 0.001);        self::assertSame(1411, $info->kbps);        self::assertSame([44100, 2], [$info->sampleRate, $info->channels]);        $mono = AudioInfo::of($this->file(self::wav(8000, 1, 3.0, null, 'LIST' . pack('V', 5) . 'INFOx' . "\0"), 'wav'));        self::assertEqualsWithDelta(3.0, $mono->duration, 0.001, 'a chunk before the data (odd size, padded) skipped');        self::assertSame([8000, 1, 128], [$mono->sampleRate, $mono->channels, $mono->kbps]);    }    public function testAWavCutShortOrStreamedCountsTheBytesThereAre(): void    {        $whole = self::wav(22050, 1, 4.0);        self::assertEqualsWithDelta(2.0, AudioInfo::of($this->file(substr($whole, 0, 44 + 22050 * 2 * 2), 'wav'))->duration, 0.001, 'cut in the middle');        // ffmpeg writing to a pipe: 0 or 0xFFFFFFFF as the size of the data        self::assertEqualsWithDelta(4.0, AudioInfo::of($this->file(self::wav(22050, 1, 4.0, 0xFFFFFFFF), 'wav'))->duration, 0.001);        self::assertEqualsWithDelta(4.0, AudioInfo::of($this->file(self::wav(22050, 1, 4.0, 0), 'wav'))->duration, 0.001);    }    public function testAConstantBitRateMp3IsMeasuredByItsSize(): void    {        $frames = self::frames(1000);        $info = AudioInfo::of($this->file($frames));        self::assertSame(128, $info->kbps);        self::assertSame([44100, 2], [$info->sampleRate, $info->channels]);        self::assertEqualsWithDelta(strlen($frames) * 8 / 128000, $info->duration, 0.001);        // an ID3v2 tag at its start and an ID3v1 at its end do not count        $tagged = AudioInfo::of($this->file(self::id3v2(2000) . $frames . 'TAG' . str_repeat("\0", 125)));        self::assertEqualsWithDelta($info->duration, $tagged->duration, 0.001);    }    public function testAVariableBitRateMp3IsMeasuredByItsXingOrVbriHeader(): void    {        // the Xing header after the side info (36 bytes into the first frame): 3000 frames of 1152 samples        $first = "\xFF\xFB\x90\x00" . str_repeat("\0", 32) . 'Xing' . pack('N', 1) . pack('N', 3000);        $first .= str_repeat("\0", 417 - strlen($first));        $info = AudioInfo::of($this->file($first . self::frames(50)));        self::assertEqualsWithDelta(3000 * 1152 / 44100, $info->duration, 0.001);        $info = AudioInfo::of($this->file(str_replace('Xing', 'Info', $first) . self::frames(50)));        self::assertEqualsWithDelta(3000 * 1152 / 44100, $info->duration, 0.001, 'Info: the same, CBR by LAME');        $vbri = "\xFF\xFB\x90\x00" . str_repeat("\0", 32) . 'VBRI' . pack('n', 1) . pack('n', 0) . pack('n', 0) . pack('N', 100000) . pack('N', 1000);        $vbri .= str_repeat("\0", 417 - strlen($vbri));        self::assertEqualsWithDelta(1000 * 1152 / 44100, AudioInfo::of($this->file($vbri . self::frames(5)))->duration, 0.001);        // MPEG-2 layer III (22.05 kHz, 576 samples a frame), mono        $mpeg2 = "\xFF\xF3\x80\xC0" . str_repeat("\0", 13) . 'Xing' . pack('N', 1) . pack('N', 500);        $info = AudioInfo::of($this->file($mpeg2 . str_repeat("\0", 300)));        self::assertEqualsWithDelta(500 * 576 / 22050, $info->duration, 0.001);        self::assertSame([22050, 1], [$info->sampleRate, $info->channels]);    }    public function testAnMp3WithABigCoverInItsTagStillHasItsLength(): void    {        // yt-dlp --embed-thumbnail: a picture of 200 KB in the ID3v2 tag, before the sound        $frames = self::frames(2000);        $info = AudioInfo::of($this->file(self::id3v2(200_000) . $frames));        self::assertSame(128, $info->kbps);        self::assertEqualsWithDelta(strlen($frames) * 8 / 128000, $info->duration, 0.001);    }    public function testAnOggVorbisIsMeasuredByItsLastPage(): void    {        $page = fn (int $granule, string $data): string => 'OggS' . "\0\0" . pack('V', $granule) . pack('V', 0) . str_repeat("\0", 13) . $data;        $head = $page(0, "\x01vorbis" . pack('V', 0) . chr(2) . pack('V', 48000) . str_repeat("\0", 20));        $info = AudioInfo::of($this->file($head . str_repeat("\x11", 5000) . $page(48000 * 7, 'end'), 'ogg'));        self::assertEqualsWithDelta(7.0, $info->duration, 0.001);        self::assertSame([48000, 2], [$info->sampleRate, $info->channels]);    }    public function testBrokenFilesHaveNoLengthAndNoError(): void    {        $samples = [            self::wav(44100, 2, 0.5) => 'wav',            self::frames(30) => 'mp3',            self::id3v2(500) . self::frames(30) => 'mp3',            "\xFF\xFB\x90\x00" . str_repeat("\0", 32) . 'Xing' . pack('N', 1) . pack('N', 3000) => 'mp3',            'OggS' . "\0\0" . str_repeat("\0", 20) . "\x01vorbis" . str_repeat("\0", 30) => 'ogg',            "\0\0\0\x20ftypM4A " . str_repeat("\0", 20) . 'moov' . "\0\0\0\x6Cmvhd" . "\0" . str_repeat("\0", 11) . pack('N', 1000) . pack('N', 5000) => 'm4a',        ];        $errors = [];        set_error_handler(function (int $no, string $message) use (&$errors): bool {            $errors[] = $message;            return true;        });        try {            foreach ($samples as $bytes => $ext) {                for ($len = 0; $len <= strlen((string)$bytes); $len += max(1, intdiv(strlen((string)$bytes), 97))) {                    $info = AudioInfo::of($this->file(substr((string)$bytes, 0, $len), $ext));                    self::assertGreaterThanOrEqual(0.0, $info->duration, "$ext cut at $len");                    self::assertFalse(is_nan($info->duration) || is_infinite($info->duration), "$ext cut at $len");                }            }            self::assertSame(0.0, AudioInfo::of($this->file(random_bytes(3000), 'wav'))->duration);            self::assertSame(0.0, AudioInfo::of($this->file('RIFF' . pack('V', 4) . 'WAVE' . 'fmt ' . pack('V', 16) . str_repeat("\0", 16) . 'data' . pack('V', 100) . str_repeat("\0", 100), 'wav'))->duration, 'a byte rate of 0');            self::assertSame(0.0, AudioInfo::of(sys_get_temp_dir() . '/wz-info-missing.mp3')->duration);            self::assertSame(0.0, AudioInfo::of(sys_get_temp_dir())->duration);        } finally {            restore_error_handler();        }        self::assertSame([], $errors, 'no warning');    }}