Files

335 lines
15 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, hints=None):
"""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]). hints: lags tried first; the search runs only when none gives 10 dB. Returns (snr, lag)."""
if hints:
got = max(snr(ref, test, ch, 0, skip, None) if h == 0 else _snr_at(ref, test, ch, h, skip) for h in hints)
if got[0] >= 10:
return got
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 _snr_at(ref, test, ch, lag, skip):
sig = err = 0.0
nref, ntest = len(ref) // ch, len(test) // ch
for i in range(skip, nref):
j = i + lag
if 0 <= j < ntest:
for c in range(ch):
a = ref[i * ch + c]
e = a - test[j * ch + c]
sig += a * a
err += e * e
return (200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0), lag)
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)
def emit_signal(ctx, name, samples, rate, ch):
"""emit tests/gen/<name>.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)"""
ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)})
def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"):
"""encode the emitted signal module `sigmod` with require("@rosetta/<module>").encode(audio, opts) in Luau; returns
the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/audio/Pcm.audioDecoder) instead of the Audio."""
code = """
local S = require("@tests/gen/%s")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local M = require("@rosetta/%s")
local a = Types.Audio.new(S.rate, S.channels, S.frames)
buffer.writestring(a.samples, 0, S.data)
local src: any = a
if "%s" == "decoder" then src = Pcm.audioDecoder(a) end
local out, err = M.encode(src, %s)
if not out then error("encode failed: " .. tostring(err)) end
print(buffer.tostring(out))
""" % (sigmod, module, source, opts_lua)
return luau(ctx, code)
def max_diff(a, b):
if len(a) != len(b):
return float("inf")
return max((abs(x - y) for x, y in zip(a, b)), default=0.0)
def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000):
"""The fixtures of an uncompressed container (aiff, au, voc):
made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of
the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the
reference (f32le)
encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared
against the f32 input (max abs difference, which the test bounds by the format's quantization step)
Emits <fmt>_cases (files + references), <fmt>_sig / <fmt>_sig1 (the inputs, stereo / mono) and <fmt>_enc."""
stereo = signal("music", sig_rate, 2, sig_frames, seed=3)
mono = signal("sweep", sig_rate, 1, sig_frames, seed=4)
emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2)
emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1)
inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16),
"{in_float}": wav(stereo, sig_rate, 2, float_=True)}
cases = []
for name, packages, argv in made:
d = tempfile.mkdtemp(prefix="fmt-audio-")
try:
paths = {}
for key, data in inputs.items():
paths[key] = os.path.join(d, key.strip("{}") + ".wav")
with open(paths[key], "wb") as f:
f.write(data)
out = os.path.join(d, "out." + fmt)
args = []
for a in argv:
for key, p in paths.items():
a = a.replace(key, p)
args.append(a.replace("{out}", out))
ctx.nix(packages, args)
with open(out, "rb") as f:
data = f.read()
finally:
shutil.rmtree(d, ignore_errors=True)
rate, ch, ref = ffdecode(ctx, data, ext=fmt)
cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)})
ctx.emit(fmt + "_cases", cases)
results = []
for name, opts_lua, ch in encodes:
sig = stereo if ch == 2 else mono
out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua)
streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder")
rate, dch, dec = ffdecode(ctx, out, ext=fmt)
errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt)
results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch),
"maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"),
"bytes": len(out), "sameStreamed": out == streamed, "data": out})
ctx.emit(fmt + "_enc", results)
def encode_luau_many(ctx, module, jobs, sigmod):
"""jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } }
-> [bytes]: one Luau run encodes them all (length-prefixed on stdout)"""
body = ['job("%s", %s)' % (name, opts) for name, opts in jobs]
code = """
local Types = require("@rosetta/Types")
local M = require("@rosetta/%s")
local S = require("@tests/gen/%s")
local outs = {}
local function job(name, opts)
local s = S[name]
local a = Types.Audio.new(s.rate, s.channels, s.frames)
buffer.writestring(a.samples, 0, s.data)
local out, err = M.encode(a, opts)
if not out then error("encode failed: " .. tostring(err)) end
local n = buffer.len(out)
table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out))
end
%s
print(table.concat(outs))
""" % (module, sigmod, "\n".join(body))
raw = luau(ctx, code)
res, p = [], 0
while p < len(raw):
n = int(raw[p:p + 12])
res.append(raw[p + 12:p + 12 + n])
p += 12 + n
return res
def shell_many(ctx, packages, files, script):
"""write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout"""
d = tempfile.mkdtemp(prefix="fmt-audio-")
try:
for name, data in files.items():
with open(os.path.join(d, name), "wb") as f:
f.write(data)
return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)])
finally:
shutil.rmtree(d, ignore_errors=True)