75 lines
2.9 KiB
Python
75 lines
2.9 KiB
Python
"""Compare the firmware's detector with the unchanged browser AudioWorklet."""
|
|
from array import array
|
|
from pathlib import Path
|
|
import math
|
|
import random
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
REFERENCE = ROOT.parent / "django/frontend/src/scripts/burst-listener-worklet.js"
|
|
CPP = Path(__file__).with_name("detector_trace.cpp")
|
|
JS = Path(__file__).with_name("worklet_trace.cjs")
|
|
RATE = 16000
|
|
|
|
|
|
def samples(kind):
|
|
rng = random.Random(71)
|
|
length = RATE * 13
|
|
values = [0] * length
|
|
if kind in {"kitchen", "impulse", "repeated", "overlap"}:
|
|
for i in range(length):
|
|
values[i] = round(rng.uniform(-0.012, 0.012) * 32767)
|
|
def bang(at, duration=.05, amplitude=.8):
|
|
start = round(at * RATE)
|
|
for j in range(round(duration * RATE)):
|
|
if start + j < length:
|
|
values[start + j] = round(amplitude * 32767 * math.sin(j * .28))
|
|
if kind == "startup": bang(.2)
|
|
if kind == "kitchen":
|
|
for at in (2, 4, 7):
|
|
bang(at, .15, .12) # below the browser's peak gate
|
|
if kind == "impulse": bang(4)
|
|
if kind == "repeated":
|
|
bang(4)
|
|
bang(4.3)
|
|
bang(10)
|
|
if kind == "overlap":
|
|
bang(4, .2)
|
|
bang(4.1, .2, .5)
|
|
return values
|
|
|
|
|
|
class DetectorParity(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.directory = tempfile.TemporaryDirectory()
|
|
cls.exe = Path(cls.directory.name) / "detector_trace"
|
|
subprocess.run(["g++", "-std=c++17", "-O2", str(CPP), "-o", str(cls.exe)], check=True)
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.directory.cleanup()
|
|
|
|
def test_reference_traces(self):
|
|
for kind in ("silence", "startup", "kitchen", "impulse", "repeated", "overlap"):
|
|
with self.subTest(kind=kind):
|
|
path = Path(self.directory.name) / f"{kind}.pcm"
|
|
raw = array('h', samples(kind))
|
|
if sys.byteorder != 'little': raw.byteswap()
|
|
path.write_bytes(raw.tobytes())
|
|
firmware = subprocess.check_output([str(self.exe)], input=path.read_bytes(), text=False).decode().splitlines()
|
|
browser = subprocess.check_output(["node", str(JS), str(REFERENCE), str(path)], text=True).splitlines()
|
|
self.assertEqual(firmware[:-1], browser[:-1])
|
|
self.assertAlmostEqual(float(firmware[-1][2:]), float(browser[-1][2:]), delta=0.00002)
|
|
if kind in {"silence", "startup", "kitchen"}: self.assertFalse(firmware[:-1])
|
|
else:
|
|
self.assertEqual(sum(line.startswith("T ") for line in firmware), 2 if kind == "repeated" else 1)
|
|
self.assertEqual(sum(line.startswith("S ") for line in firmware), 2 if kind == "repeated" else 1)
|
|
self.assertEqual(sum(line.startswith("E ") for line in firmware), 2 if kind == "repeated" else 1)
|
|
|
|
|
|
if __name__ == "__main__": unittest.main()
|