Files

200 lines
9.3 KiB
Python

# WAV fixtures (tools/fixtures.py): audio/wav. Ported from wav-luau tools/mkfixtures.py.
# tests/gen/wav_cases.luau a short synthetic stereo signal in every supported format and container (ffmpeg / sox),
# plus hand-patched variants (data size 0 / 0xFFFFFFFF, truncation, odd chunks with and
# without the pad byte, tags after the data), with ffmpeg's (or sox's) f32le decode
# tests/gen/wav_enc.luau encoder references: random samples at each depth, written by ffmpeg with -bitexact
# (PCM u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64); our encoder must
# produce the same bytes
import os, random, struct, tempfile
CTX = None
def build_cases():
work = tempfile.mkdtemp()
RATE, DUR = 16000, 0.2
SRC = "aevalsrc=0.6*sin(2*PI*440*t)+0.25*sin(2*PI*3100*t*t*10)|0.5*sin(2*PI*660*t)+0.2*(random(1)*2-1):s=%d:d=%g" % (RATE, DUR)
def run(*args):
CTX.nix(["ffmpeg", "sox"], list(args))
def path(n):
return os.path.join(work, n)
def ffenc(name, *args, ac=2):
run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", str(ac), *args, path(name))
return path(name)
def ref(p):
return CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", p, "-f", "f32le", "-c:a", "pcm_f32le", "-"])
def soxref(p):
# ffmpeg cannot read every RIFX file: sox decodes those (through its 32-bit integer pipeline)
return CTX.nix("sox", ["sox", p, "-t", "raw", "-e", "floating-point", "-b", "32", "-L", "-"])
def chunks(d):
be = d[:4] == b"RIFX"
p, out = 12, []
while p + 8 <= len(d):
cid = d[p:p + 4]
size = struct.unpack_from(">I" if be else "<I", d, p + 4)[0]
out.append((cid, p, size))
if size == 0xFFFFFFFF:
break
p += 8 + size + (size & 1)
return out
def find(d, cid):
for c, p, s in chunks(d):
if c == cid:
return p, s
raise KeyError(cid)
entries = []
def add(name, data, refdata, channels, fmt, container="RIFF", tags=None):
frames = len(refdata) // (4 * channels)
# ADPCM: ffmpeg decodes the padding of the last block too; the fact chunk holds the true length
if b"fact" in data[:200]:
fp, _ = find(data, b"fact")
frames = min(frames, struct.unpack_from("<I", data, fp + 8)[0])
entries.append(dict(name=name, file=data, ref=refdata, channels=channels, rate=RATE, frames=frames,
format=fmt, container=container, tags=tags))
def plain(name, fmt, *args, ac=2, tags=None):
p = ffenc(name + ".wav", *args, ac=ac)
d = open(p, "rb").read()
add(name, d, ref(p), ac, fmt, tags=tags)
return p, d
# formats
plain("u8", "pcm", "-c:a", "pcm_u8")
p16, d16 = plain("s16", "pcm", "-c:a", "pcm_s16le")
plain("s16_mono_tags", "pcm", "-c:a", "pcm_s16le", "-metadata", "title=Hello Title", "-metadata", "artist=Some Artist",
"-metadata", "album=An Album", "-metadata", "genre=Test", ac=1,
tags={"title": "Hello Title", "artist": "Some Artist", "album": "An Album", "genre": "Test"})
plain("s24_ext", "pcm", "-c:a", "pcm_s24le")
plain("s32_ext", "pcm", "-c:a", "pcm_s32le")
plain("f32", "float", "-c:a", "pcm_f32le")
plain("f64", "float", "-c:a", "pcm_f64le")
plain("alaw", "alaw", "-c:a", "pcm_alaw")
plain("mulaw_mono", "mulaw", "-c:a", "pcm_mulaw", ac=1)
plain("ima", "ima_adpcm", "-c:a", "adpcm_ima_wav")
plain("ima_mono", "ima_adpcm", "-c:a", "adpcm_ima_wav", ac=1)
plain("ms", "ms_adpcm", "-c:a", "adpcm_ms")
plain("ms_mono", "ms_adpcm", "-c:a", "adpcm_ms", ac=1)
plain("s16_6ch_ext", "pcm", "-c:a", "pcm_s16le", ac=6)
# containers
p = ffenc("rf64.wav", "-c:a", "pcm_s16le", "-rf64", "always")
add("rf64", open(p, "rb").read(), ref(p), 2, "pcm", container="RF64")
for name, args in (("rifx_s16", ["-b", "16"]), ("rifx_s24", ["-b", "24"]), ("rifx_f32", ["-e", "floating-point", "-b", "32"])):
p = path(name + ".wav")
run("sox", path("s24_ext.wav"), "-B", *args, p)
add(name, open(p, "rb").read(), soxref(p), 2, "float" if "f32" in name else "pcm", container="RIFX")
# streamed output: data size 0xFFFFFFFF
p = path("pipe.wav")
with open(p, "wb") as f:
f.write(CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-f", "lavfi", "-i", SRC, "-c:a", "pcm_s16le", "-f", "wav", "pipe:1"]))
d = open(p, "rb").read()
assert find(d, b"data")[1] == 0xFFFFFFFF
add("streamed_ffffffff", d, ref(p16), 2, "pcm")
# data size 0
r16 = ref(p16)
dp, _ = find(d16, b"data")
d = bytearray(d16)
struct.pack_into("<I", d, dp + 4, 0)
add("datasize_0", bytes(d), r16, 2, "pcm")
# truncated mid-frame: 1000 whole frames + 3 bytes
add("truncated_s16", d16[:dp + 8 + 1000 * 4 + 3], r16[:1000 * 2 * 4], 2, "pcm")
# truncated IMA ADPCM: one whole block, then a partial block with its headers + 3 whole groups + 5 bytes
pima = path("ima.wav")
dima = open(pima, "rb").read()
fp, _ = find(dima, b"fmt ")
ba = struct.unpack_from("<H", dima, fp + 8 + 12)[0]
spb = (ba - 8) * 2 // 2 + 1
dp, _ = find(dima, b"data")
cut = dp + 8 + ba + 8 + 3 * 8 + 5
frames = spb + 1 + 3 * 8
rima = ref(pima)
assert len(rima) >= frames * 8
add("truncated_ima", dima[:cut], rima[:frames * 2 * 4], 2, "ima_adpcm")
# odd-sized chunks before the data, padded and unpadded
fp, fs = find(d16, b"fmt ")
head, rest = d16[:fp + 8 + fs], d16[fp + 8 + fs:]
def riff(body):
return b"RIFF" + struct.pack("<I", len(body) + 4) + b"WAVE" + body
odd_padded = riff(head[12:] + b"junk" + struct.pack("<I", 3) + b"abc\0" + rest)
add("odd_chunk_padded", odd_padded, r16, 2, "pcm")
odd_unpadded = riff(head[12:] + b"abcd" + struct.pack("<I", 5) + b"12345" + rest)
add("odd_chunk_unpadded", odd_unpadded, r16, 2, "pcm")
# 8-bit mono, odd frame count (odd data size, pad byte), LIST/INFO after the data
p = path("u8odd.wav")
run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", "1", "-af", "atrim=end_sample=3199",
"-c:a", "pcm_u8", "-map_metadata", "-1", "-fflags", "+bitexact", p)
d = open(p, "rb").read()
dp, ds = find(d, b"data")
assert ds % 2 == 1, ds
info = b"INFO" + b"INAM" + struct.pack("<I", 5) + b"Odd!\0\0" + b"IART" + struct.pack("<I", 4) + b"Me\0\0"
body = d[12:dp + 8 + ds] + b"\0" + b"LIST" + struct.pack("<I", len(info)) + info
add("u8_odd_list_after", riff(body), ref(p), 1, "pcm", tags={"title": "Odd!", "artist": "Me"})
return entries
def raw_samples(rng, kind, n):
"""n random samples as (raw little-endian bytes, the same values as f32 little-endian)"""
raw, f32 = bytearray(), bytearray()
for i in range(n):
if kind == "u8":
v = rng.randrange(256); raw.append(v); x = (v - 128) / 128
elif kind == "s16":
v = rng.randrange(-32768, 32768); raw += struct.pack("<h", v); x = v / 32768
elif kind == "s24":
v = rng.randrange(-8388608, 8388608); raw += struct.pack("<i", v)[:3]; x = v / 8388608
elif kind == "s32":
v = rng.randrange(-8388608, 8388608) * 256; raw += struct.pack("<i", v); x = v / 2147483648
else:
x = struct.unpack("<f", struct.pack("<f", rng.uniform(-1, 1)))[0]; raw += struct.pack("<f", x)
f32 += struct.pack("<f", x)
if kind in ("s16", "s24", "s32", "u8"):
# the extremes too
pass
return bytes(raw), bytes(f32)
FF = {"u8": ("u8", "pcm_u8"), "s16": ("s16le", "pcm_s16le"), "s24": ("s24le", "pcm_s24le"), "s32": ("s32le", "pcm_s32le"),
"f32": ("f32le", "pcm_f32le")}
def generate(ctx):
global CTX
CTX = ctx
ctx.emit("wav_cases", [{k: v for k, v in e.items() if v is not None} for e in build_cases()])
rng = random.Random(3)
tmp = tempfile.mkdtemp()
enc = []
for kind, ch, rate, frames, extra in (("s16", 2, 44100, 1001, []), ("s24", 2, 44100, 777, []), ("s32", 2, 44100, 500, []),
("f32", 2, 44100, 640, []), ("u8", 1, 8000, 999, []), ("s16", 6, 48000, 300, []),
("f32", 6, 8000, 120, []), ("s16", 1, 96000, 256, []), ("s16", 3, 8000, 50, []),
("s16", 4, 8000, 50, []), ("s16", 5, 8000, 50, []), ("s16", 7, 8000, 50, []),
("s16", 8, 8000, 50, []), ("s24", 1, 22050, 333, []),
("s16", 2, 44100, 441, ["-rf64", "always"]), ("f32", 1, 44100, 100, ["-rf64", "always"])):
raw, f32 = raw_samples(rng, kind, frames * ch)
src = os.path.join(tmp, "in.raw")
open(src, "wb").write(raw)
out = os.path.join(tmp, "out.wav")
fmt, codec = FF[kind]
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-f", fmt, "-ar", str(rate), "-ac", str(ch), "-i", src,
"-c:a", codec] + extra + ["-fflags", "+bitexact", "-flags:a", "+bitexact", "-map_metadata", "-1", out])
enc.append({"name": "%s-%dch-%d%s" % (kind, ch, rate, "-rf64" if extra else ""), "kind": kind, "channels": ch,
"rate": rate, "frames": frames, "rf64": bool(extra), "samples": f32, "file": open(out, "rb").read()})
ctx.emit("wav_enc", enc)