# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders): # A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package) # A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples # A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes # A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read # A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats) # A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout # A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames, # either direction), and the lag found # A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases # apply) and return its stdout bytes. Encoder fixtures use it to encode with our # encoder in the fixture step, then decode the output with the reference tool: # print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped). import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def load(): return sys.modules[__name__] def signal(kind, rate, ch, frames, seed=1): """kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS), music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test), loud (a full-scale sine near clipping).""" rng = random.Random(seed) out = [0.0] * (frames * ch) for c in range(ch): ph = 0.0 notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)] for i in range(frames): t = i / rate if kind == "sine": v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c) elif kind == "sweep": f0, f1 = 50.0, rate / 2.2 dur = frames / rate f = f0 * (f1 / f0) ** (t / dur) ph += 2 * math.pi * f / rate v = 0.6 * math.sin(ph + c) elif kind == "noise": v = (rng.random() * 2 - 1) * 0.25 elif kind == "music": v = 0.0 for k, (f, a) in enumerate(notes): seg = (i // max(1, rate // 4) + k) % 4 env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate)) if seg != 3: v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t)) v += (rng.random() * 2 - 1) * 0.01 elif kind == "silence": v = 0.0 elif kind == "square": v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4 elif kind == "loud": v = 0.98 * math.sin(2 * math.pi * 330 * t + c) else: raise ValueError(kind) out[i * ch + c] = v return out def quantize(samples, bits): s = 2 ** (bits - 1) return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples] def f32le(samples): a = array.array("f", samples) if sys.byteorder != "little": a.byteswap() return a.tobytes() def from_f32le(b): a = array.array("f") a.frombytes(b[: len(b) // 4 * 4]) if sys.byteorder != "little": a.byteswap() return a.tolist() def wav(samples, rate, ch, bits=16, float_=False): n = len(samples) // ch if float_: data = f32le(samples) fmt = struct.pack(" 64: # coarse cross-correlation on the first channel to find candidate lags, then refine cands = [] m = min(nref, 1 << 15) seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))] for lag in range(-max_lag, max_lag + 1): acc = 0.0 for i in range(0, len(seg), 7): j = skip + i + lag if 0 <= j < ntest: acc += seg[i] * test[j * ch] cands.append((acc, lag)) cands.sort(reverse=True) lags = sorted(set(l for _, l in cands[:3])) for lag in lags: sig = err = 0.0 for i in range(skip, nref): j = i + lag if j < 0 or j >= ntest: continue for c in range(ch): a = ref[i * ch + c] e = a - test[j * ch + c] sig += a * a err += e * e s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0) if s > best[0]: best = (s, lag) return best def luau_bin(): p = shutil.which("luau") if p: return p return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True, text=True).stdout.strip() def luau(ctx, code): d = os.path.join(ROOT, "tests", "gen") os.makedirs(d, exist_ok=True) fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d) try: with os.fdopen(fd, "w") as f: f.write(code) r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True) if r.returncode != 0: raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:]) out = r.stdout return out[:-1] if out.endswith(b"\n") else out finally: os.unlink(path)