KO
apps/winzik / tests / SpectrumTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Media\Spectrum;use App\Media\Wav;use PHPUnit\Framework\TestCase;/** The visualizer's FFT and bars: a pure sine lands in its bin, silence leaves the bars down. */final class SpectrumTest extends TestCase{    /** @var list<string> */    private array $files = [];    protected function tearDown(): void    {        foreach ($this->files as $file) {            @unlink($file);        }    }    /** @param array<int, float> $re @param array<int, float> $im */    private static function fft(array &$re, array &$im): void    {        $fft = new \ReflectionMethod(Spectrum::class, 'fft');        $fft->invokeArgs(null, [&$re, &$im]);    }    /** A 16-bit WAV of a sine (or silence: $hz 0). */    private function wav(float $hz, int $rate = 44100, float $seconds = 1.0, float $amplitude = 0.8, int $channels = 2): string    {        $data = '';        for ($i = 0, $n = (int)($seconds * $rate); $i < $n; $i++) {            $v = (int)round($amplitude * 32767 * sin(2 * M_PI * $hz * $i / $rate));            $data .= str_repeat(pack('v', $v & 0xFFFF), $channels);        }        $file = sys_get_temp_dir() . '/wz-spectrum-' . bin2hex(random_bytes(4)) . '.wav';        $fmt = pack('vvVVvv', 1, $channels, $rate, $rate * 2 * $channels, 2 * $channels, 16);        file_put_contents($file, 'RIFF' . pack('V', 36 + strlen($data)) . 'WAVE' . 'fmt ' . pack('V', 16) . $fmt . 'data' . pack('V', strlen($data)) . $data);        $this->files[] = $file;        return $file;    }    public function testAPureSineLandsInItsBinAtEverySize(): void    {        for ($n = 64; $n <= 2048; $n *= 2) {            foreach ([1, 3, $n / 8, $n / 2 - 1] as $bin) {                $re = [];                for ($i = 0; $i < $n; $i++) {                    $re[] = sin(2 * M_PI * $bin * $i / $n);                }                $im = array_fill(0, $n, 0.0);                self::fft($re, $im);                $power = [];                for ($k = 0; $k <= $n / 2; $k++) {                    $power[$k] = $re[$k] ** 2 + $im[$k] ** 2;                }                self::assertSame($bin, array_search(max($power), $power, true), "n=$n bin=$bin");                self::assertEqualsWithDelta($n / 2, sqrt($power[$bin]), 1e-6 * $n, "n=$n bin=$bin: its full amplitude");                self::assertLessThan(1e-12 * $n * $n, array_sum($power) - $power[$bin], "n=$n bin=$bin: nothing elsewhere");            }        }    }    public function testTheFftAgreesWithTheSlowFourierTransform(): void    {        mt_srand(7);        foreach ([64, 256] as $n) {            $x = [];            for ($i = 0; $i < $n; $i++) {                $x[] = mt_rand(-1000, 1000) / 1000;            }            $re = $x;            $im = array_fill(0, $n, 0.0);            self::fft($re, $im);            foreach ([0, 1, 5, $n / 4, $n / 2, $n - 1] as $k) {                $sr = $si = 0.0;                foreach ($x as $i => $v) {                    $sr += $v * cos(-2 * M_PI * $k * $i / $n);                    $si += $v * sin(-2 * M_PI * $k * $i / $n);                }                self::assertEqualsWithDelta($sr, $re[$k], 1e-9, "n=$n k=$k re");                self::assertEqualsWithDelta($si, $im[$k], 1e-9, "n=$n k=$k im");            }        }    }    public function testSilenceAndNoSongLeaveTheBarsDown(): void    {        $spectrum = new Spectrum();        $silent = Wav::open($this->wav(0));        self::assertNotNull($silent);        for ($i = 0; $i < 30; $i++) {            $spectrum->update(1 / 60, $silent, $i / 60, true);        }        self::assertSame(0.0, max($spectrum->bars));        self::assertSame(0.0, max($spectrum->peaks));        self::assertSame(0.0, $spectrum->beat);        self::assertSame(array_fill(0, 64, 0.0), $spectrum->wave, 'floats, as said');        $spectrum->update(1 / 60, null, 0, true);        self::assertCount(Spectrum::BANDS, $spectrum->bars);        self::assertLessThanOrEqual(Spectrum::HISTORY, count($spectrum->history));    }    public function testASineLightsTheBarOfItsFrequencyThenTheBarsFallWhenItStops(): void    {        $bandOf = function (float $hz): int {            $spectrum = new Spectrum();            $wav = Wav::open($this->wav($hz));            self::assertNotNull($wav);            $spectrum->update(1 / 60, $wav, 0.3, true);            $bars = $spectrum->bars;            // the bars are lifted a little with the band (b * 0.006): compare without it            foreach ($bars as $b => $v) {                $bars[$b] = $v - $b * 0.006;            }            self::assertGreaterThan(0.5, max($spectrum->bars), "$hz Hz");            return (int)array_search(max($bars), $bars, true);        };        $low = $bandOf(100);        $mid = $bandOf(1000);        $high = $bandOf(8000);        self::assertLessThan($mid, $low);        self::assertLessThan($high, $mid);        self::assertSame(Spectrum::BANDS - 1, $bandOf(15000), 'near 16 kHz: the last bar');        $spectrum = new Spectrum();        $wav = Wav::open($this->wav(1000));        $spectrum->update(1 / 60, $wav, 0.2, true);        $top = max($spectrum->bars);        $spectrum->update(0.25, $wav, 0.45, false);        self::assertLessThan($top, max($spectrum->bars), 'paused: they fall');        self::assertEqualsWithDelta($top, max($spectrum->peaks), 1e-9, 'the peak held a moment');        for ($i = 0; $i < 10; $i++) {            $spectrum->update(0.25, $wav, 0.45, false);        }        self::assertSame(0.0, max($spectrum->bars));        self::assertSame(0.0, max($spectrum->peaks));    }    public function testOddRatesAndTheEndOfTheSongGiveNoError(): void    {        $errors = [];        set_error_handler(function (int $no, string $message) use (&$errors): bool {            $errors[] = $message;            return true;        });        try {            foreach ([8000, 11025, 22050, 48000, 96000] as $rate) {                $spectrum = new Spectrum();                $wav = Wav::open($this->wav(440, $rate, 0.5, 0.5, 1));                self::assertNotNull($wav);                foreach ([0.0, 0.25, 0.49, 0.5, 3.0, -1.0] as $at) {                    $spectrum->update(1 / 60, $wav, $at, true);                }                foreach ($spectrum->bars as $v) {                    self::assertGreaterThanOrEqual(0.0, $v);                    self::assertLessThanOrEqual(1.0, $v);                }            }            // a broken header: a rate of 0            $file = $this->wav(440, 8000, 0.5);            $bytes = (string)file_get_contents($file);            file_put_contents($file, substr($bytes, 0, 24) . pack('V', 0) . substr($bytes, 28));            $wav = Wav::open($file);            if ($wav !== null) {                (new Spectrum())->update(1 / 60, $wav, 0.1, true);            }            // no channel            file_put_contents($file, substr($bytes, 0, 22) . pack('v', 0) . substr($bytes, 24));            $wav = Wav::open($file);            if ($wav !== null) {                (new Spectrum())->update(1 / 60, $wav, 0.1, true);            }        } finally {            restore_error_handler();        }        self::assertSame([], $errors);    }    public function testABeatOfTheBassLightsTheLamp(): void    {        // 40 frames of a quiet bass, then a loud one        $quiet = Wav::open($this->wav(80, 44100, 1.0, 0.02));        $loud = Wav::open($this->wav(80, 44100, 1.0, 0.9));        self::assertNotNull($quiet);        self::assertNotNull($loud);        $spectrum = new Spectrum();        $spectrum->newSong();        for ($i = 0; $i < 40; $i++) {            $spectrum->update(1 / 60, $quiet, 0.1 + $i / 100, true);        }        self::assertSame(0.0, $spectrum->beat, 'the same level all along: no beat');        $spectrum->update(1 / 60, $loud, 0.5, true);        self::assertSame(1.0, $spectrum->beat);        $spectrum->update(0.1, $loud, 0.6, true);        self::assertLessThan(1.0, $spectrum->beat, 'not sooner than 0.28 s after the last one, and fading');    }}