Files
rosetta/tools/fixtures/_audio.py
T

195 lines
8.3 KiB
Python

# 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("<HHIIHH", 3, ch, rate, rate * ch * 4, ch * 4, 32)
else:
bps = bits // 8
s = 2 ** (bits - 1)
out = bytearray()
for v in samples:
q = max(-s, min(s - 1, int(math.floor(v * s + 0.5))))
if bits == 8:
out.append(q + 128)
else:
out += (q & ((1 << bits) - 1)).to_bytes(bps, "little")
data = bytes(out)
fmt = struct.pack("<HHIIHH", 1, ch, rate, rate * ch * bps, ch * bps, bits)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + data
if len(data) % 2:
body += b"\0"
return b"RIFF" + struct.pack("<I", len(body)) + body
def tool(ctx, packages, argv, data=None, ext="bin", outext=None):
"""run argv (a list; "{in}" / "{out}" are replaced by temp paths) under nix; returns stdout, or the {out} file"""
d = tempfile.mkdtemp(prefix="fmt-audio-")
try:
inp = os.path.join(d, "in." + ext)
out = os.path.join(d, "out." + (outext or "bin"))
if data is not None:
with open(inp, "wb") as f:
f.write(data)
args = [a.replace("{in}", inp).replace("{out}", out) for a in argv]
stdout = ctx.nix(packages, args)
if outext:
with open(out, "rb") as f:
return f.read()
return stdout
finally:
shutil.rmtree(d, ignore_errors=True)
def ffdecode(ctx, data, fmt=None, ext="bin", extra=None):
"""(rate, channels, floats) of any file ffmpeg reads"""
probe = tool(ctx, "ffmpeg", ["ffprobe", "-v", "error", "-show_entries", "stream=sample_rate,channels", "-of", "csv=p=0"]
+ (["-f", fmt] if fmt else []) + ["{in}"], data, ext).decode().strip().split("\n")[0].split(",")
rate, ch = int(probe[0]), int(probe[1])
raw = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error"] + (["-f", fmt] if fmt else []) + ["-i", "{in}"] + (extra or [])
+ ["-f", "f32le", "-acodec", "pcm_f32le", "-"], data, ext)
return rate, ch, from_f32le(raw)
def snr(ref, test, ch, max_lag=0, skip=0):
"""SNR (dB) of test vs ref over their common frames (after `skip` frames), best lag in [-max_lag, max_lag]
(test[i + lag] ~ ref[i]). Returns (snr, lag)."""
best = (-1e9, 0)
nref, ntest = len(ref) // ch, len(test) // ch
lags = range(-max_lag, max_lag + 1) if max_lag else [0]
if max_lag > 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)