Files
rosetta/tools/fixtures/flac.py
T

287 lines
12 KiB
Python

# FLAC fixtures (tools/fixtures.py): audio/flac. Ported from flac-luau tools/gen_fixtures.py.
# tests/gen/flac_cases.luau streams from the reference encoder (flac 0-8, 4-32 bits, 1-6 channels, odd rates and
# block sizes, LPC order 32, wasted bits, Rice2, Ogg FLAC, tags + a picture), ffmpeg's
# encoder (every stereo mode), a spliced variable-block stream, an ID3v2 tag in front;
# each with the zlib CRC-32 of `flac -d`'s samples (i32 LE, interleaved)
import base64, math, os, random, struct, tempfile, zlib
CTX = None
TMP = None
CASES = []
def signal(secs, rate, ch, bits, kind="music", seed=1, wasted=0):
"""Interleaved ints in the signed `bits` range."""
rnd = random.Random(seed)
n = int(secs * rate)
top = (1 << (bits - 1)) - 1
out = []
notes = [(rnd.uniform(80, 900), rnd.uniform(0, n), rnd.uniform(0.2, 0.6) * rate) for _ in range(int(secs * 6) + 2)]
for i in range(n):
t = i / rate
for c in range(ch):
if kind == "silence":
v = 0.0
elif kind == "noise":
v = rnd.uniform(-0.9, 0.9)
elif kind == "smooth": # slow polynomial-like curves (high fixed orders)
v = 0.8 * math.sin(2 * math.pi * (1000 + 300 * c) * t)
elif kind == "loudnoise": # full scale tone + strong noise: large Rice parameters at 32 bits
v = 0.6 * math.sin(2 * math.pi * 440 * t) + 0.08 * (rnd.random() - 0.5)
elif kind == "square": # constant runs
v = 0.5 if (i // 300) % 2 else -0.25
else:
v = 0.0
for f, st, dur in notes:
if st <= i < st + dur:
e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 200)
v += 0.2 * e * (math.sin(2 * math.pi * f * (1 + 0.003 * c) * t) +
0.4 * math.sin(4 * math.pi * f * t + c) + 0.15 * math.sin(6 * math.pi * f * t))
v += 0.002 * (rnd.random() - 0.5) + 0.05 * math.sin(2 * math.pi * 55 * t)
x = int(max(-1.0, min(1.0, v)) * top)
if wasted:
x = (x >> wasted) << wasted
out.append(x)
return out
def write_wav(path, ints, ch, rate, bits):
container = (bits + 7) // 8 * 8
data = bytearray()
for v in ints:
x = v << (container - bits)
if container == 8:
data.append((x + 128) & 255)
else:
data += x.to_bytes(container // 8, "little", signed=True)
guid = b"\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71"
fmt = struct.pack("<HHIIHHHHI16s", 0xFFFE, ch, rate, rate * ch * container // 8, ch * container // 8, container,
22, bits, 0, guid)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
def read_ref(flac_path, bits):
"""Reference ints from flac -d."""
if bits in (8, 16, 24, 32):
raw = flac_path + ".raw"
CTX.nix("flac", ["flac", "-s", "-f", "-d", "--force-raw-format", "--endian=little", "--sign=signed", flac_path, "-o", raw])
d = open(raw, "rb").read()
w = bits // 8
return [int.from_bytes(d[i:i + w], "little", signed=True) for i in range(0, len(d), w)]
wav = flac_path + ".wav"
CTX.nix("flac", ["flac", "-s", "-f", "-d", flac_path, "-o", wav])
d = open(wav, "rb").read()
container = struct.unpack_from("<H", d, 34)[0]
i = 12
while d[i:i + 4] != b"data":
i += 8 + struct.unpack_from("<I", d, i + 4)[0]
size = struct.unpack_from("<I", d, i + 4)[0]
d = d[i + 8:i + 8 + size]
w = container // 8
out = []
for j in range(0, len(d), w):
x = d[j] - 128 if w == 1 else int.from_bytes(d[j:j + w], "little", signed=True)
out.append(x >> (container - bits))
return out
def crc_ints(ints):
return zlib.crc32(b"".join(struct.pack("<i", v) for v in ints))
def emit(name, path, rate, ch, bits, note, ogg=False, tags=None, prefix=b""):
ref = read_ref(path, bits)
data = prefix + open(path, "rb").read()
c = {"name": name, "note": note, "data": data, "rate": rate, "channels": ch, "bps": bits, "frames": len(ref) // ch,
"crc": crc_ints(ref), "ogg": ogg}
if tags:
c["tags"] = tags
CASES.append(c)
def flac(name, secs, rate, ch, bits, args, kind="music", wasted=0, note=None, ogg=False, tags=None, seed=1):
wav = os.path.join(TMP, name + ".wav")
out = os.path.join(TMP, name + (".oga" if ogg else ".flac"))
write_wav(wav, signal(secs, rate, ch, bits, kind, seed, wasted), ch, rate, bits)
CTX.nix("flac", ["flac", "-s", "-f"] + args + [wav, "-o", out])
emit(name, out, rate, ch, bits, note or "flac " + " ".join(args), ogg=ogg, tags=tags)
return out
CRC8 = []
for i in range(256):
c = i
for _ in range(8):
c = ((c << 1) ^ 0x07) & 0xFF if c & 0x80 else (c << 1) & 0xFF
CRC8.append(c)
def crc8(d):
c = 0
for x in d:
c = CRC8[c ^ x]
return c
def crc16(d):
c = 0
for x in d:
c ^= x << 8
for _ in range(8):
c = ((c << 1) ^ 0x8005) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def utf8num(n):
if n < 0x80:
return bytes([n])
out = []
lim = 0x3F
while True:
out.append(0x80 | (n & 0x3F))
n >>= 6
lim >>= 1
if n <= lim:
break
k = len(out) + 1
first = ((0xFF00 >> k) & 0xFF) | n
return bytes([first]) + bytes(reversed(out))
def frames_of(data):
"""(offset, header_len, end) of each frame of a fixed-blocksize native stream (CRC-validated)."""
p = 4
while True:
h = data[p]
size = int.from_bytes(data[p + 1:p + 4], "big")
p += 4 + size
if h & 0x80:
break
syncs = []
for i in range(p, len(data) - 1):
if data[i] == 0xFF and data[i + 1] == 0xF8:
syncs.append(i)
frames, start = [], syncs[0]
k = 1
while start < len(data):
found = None
for e in syncs[k:] + [len(data)]:
if e > start and crc16(data[start:e - 2]) == int.from_bytes(data[e - 2:e], "big"):
found = e
break
frames.append((start, found))
k = syncs.index(found) + 1 if found in syncs else len(syncs)
start = found
return p, frames
def make_varblock():
"""Frames of two encodes (block 4096 and 1152) spliced every 36864 samples, headers rewritten as variable."""
ints = signal(2.0, 44100, 2, 16, "music", 4)
wav = os.path.join(TMP, "vb.wav")
write_wav(wav, ints, 2, 44100, 16)
enc = {}
for bs in (4096, 1152):
out = os.path.join(TMP, "vb%d.flac" % bs)
CTX.nix("flac", ["flac", "-s", "-f", "-5", "--no-seektable", "--no-padding", "-b", str(bs), wav, "-o", out])
enc[bs] = open(out, "rb").read()
first, fa = frames_of(enc[4096])
_, fb = frames_of(enc[1152])
out = bytearray(enc[4096][:first])
sample, use, maxf = 0, 4096, 0
total = len(ints) // 2
while sample < total:
frames = fa if use == 4096 else fb
fi = sample // use
for j in range(fi, min(fi + 36864 // use, len(frames))):
a, e = frames[j]
fr = enc[use][a:e]
# old header: 4 bytes, the coded frame number, optional fields; rebuild with the sample number
b0 = fr[4]
nl = 1 if b0 < 0x80 else (2 if b0 < 0xE0 else 3 if b0 < 0xF0 else 4 if b0 < 0xF8 else 5 if b0 < 0xFC else 6)
bscode = fr[2] >> 4
extra = {6: 1, 7: 2}.get(bscode, 0) + {12: 1, 13: 2, 14: 2}.get(fr[2] & 15, 0)
hlen = 4 + nl + extra
hdr = bytes([0xFF, 0xF9]) + fr[2:4] + utf8num(sample + (j - fi) * use) + fr[4 + nl:hlen]
body = hdr + bytes([crc8(hdr)]) + fr[hlen + 1:-2]
body += crc16(body).to_bytes(2, "big")
out += body
maxf = max(maxf, len(body))
sample = (fi + min(36864 // use, len(frames) - fi)) * use
use = 1152 if use == 4096 else 4096
# STREAMINFO: min block 1152, max 4096, frame sizes unknown
out[8:10] = (1152).to_bytes(2, "big")
out[10:12] = (4096).to_bytes(2, "big")
out[12:18] = bytes(6)
path = os.path.join(TMP, "varblock.flac")
open(path, "wb").write(bytes(out))
emit("varblock", path, 44100, 2, 16, "variable block size: 4096 / 1152 frames spliced, sample-number headers")
def ffmpeg(name, secs, rate, ch, bits, args, kind="music"):
wav = os.path.join(TMP, name + ".wav")
out = os.path.join(TMP, name + ".flac")
write_wav(wav, signal(secs, rate, ch, bits, kind, 5), ch, rate, bits)
CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + args + [out])
emit(name, out, rate, ch, bits, "ffmpeg " + " ".join(args))
def generate(ctx):
global CTX, TMP
CTX = ctx
TMP = tempfile.mkdtemp()
CASES.clear()
for lv in range(9):
flac("s16_l%d" % lv, 0.4, 44100, 2, 16, ["-%d" % lv])
flac("s16_long", 3.0, 44100, 2, 16, ["-5", "-S", "0.5s"], seed=2,
note="flac -5, 3 s, seek points every 0.5 s (bench + seek)")
png = os.path.join(TMP, "p.png")
open(png, "wb").write(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="))
flac("s16_noseek", 2.0, 44100, 2, 16, ["-6", "--no-seektable", "-T", "ARTIST=Some One", "-T", "TITLE=Test Tone",
"--picture", png], seed=3,
note="no seektable (bisection seek), tags, a picture", tags={"ARTIST": "Some One", "TITLE": "Test Tone"})
flac("u8_mono", 0.5, 22050, 1, 8, ["-5"])
flac("s24_96k", 0.3, 96000, 2, 24, ["-8"])
flac("s24_l0", 0.3, 48000, 2, 24, ["-0"])
flac("s32", 0.2, 48000, 2, 32, ["-5"])
flac("s32_l8", 0.2, 48000, 2, 32, ["-8"], kind="noise", note="flac -8, 32-bit noise (verbatim / escapes)")
flac("ch6", 0.3, 48000, 6, 16, ["-5"])
flac("ch3_24", 0.2, 44100, 3, 24, ["-7"])
flac("rate37000", 0.4, 37000, 1, 16, ["-5"])
flac("rate11025", 0.4, 11025, 2, 16, ["-3"])
flac("rate352800", 0.05, 352800, 2, 24, ["-5", "--lax"])
flac("rate100001", 0.1, 100001, 1, 16, ["-5", "--lax"], note="a rate only STREAMINFO can hold")
flac("rate7", 30.0, 7, 1, 16, ["-5", "--lax", "-b", "16"], note="7 Hz")
flac("bs17", 0.2, 44100, 1, 16, ["-5", "--lax", "-b", "17"])
flac("bs4609", 0.5, 44100, 2, 16, ["-8", "--lax", "-b", "4609"])
flac("bs65535", 1.6, 44100, 2, 16, ["-5", "--lax", "-b", "65535", "-r", "15"])
flac("lpc32", 0.3, 44100, 2, 16, ["--lax", "-b", "1001", "-l", "32", "-r", "0,8", "-e", "-p"],
note="LPC order 32, block 1001, exhaustive")
flac("bits12", 0.3, 44100, 2, 12, ["-5"])
flac("bits20", 0.3, 44100, 2, 20, ["-8"])
flac("bits4", 0.3, 8000, 1, 4, ["-5", "--lax"])
flac("wasted", 0.3, 44100, 2, 16, ["-5"], wasted=3, note="low 3 bits zero (wasted bits)")
flac("smooth", 0.3, 44100, 2, 24, ["-2"], kind="smooth", note="flac -2, 24-bit pure tones (fixed order 4)")
flac("s32_rice2", 0.2, 48000, 2, 32, ["-5"], kind="loudnoise", note="32-bit tone + noise (Rice2, k > 24)")
make_varblock()
flac("silence", 0.3, 44100, 2, 16, ["-5"], kind="silence")
flac("square", 0.3, 44100, 2, 16, ["-5"], kind="square")
flac("noise16", 0.3, 44100, 2, 16, ["-5"], kind="noise")
flac("ogg_s16", 1.0, 44100, 2, 16, ["-5", "--ogg"], ogg=True, note="Ogg FLAC")
for mode in ("left_side", "right_side", "mid_side", "indep"):
ffmpeg("ff_" + mode, 0.3, 44100, 2, 16, ["-c:a", "flac", "-ch_mode", mode])
ffmpeg("ff_l12", 0.4, 44100, 2, 16, ["-c:a", "flac", "-compression_level", "12"])
ffmpeg("ff_s24", 0.3, 48000, 2, 24, ["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24",
"-compression_level", "8"])
ffmpeg("ff_exact", 0.3, 44100, 2, 16, ["-c:a", "flac", "-exact_rice_parameters", "1", "-multi_dim_quant", "1",
"-lpc_type", "cholesky", "-lpc_passes", "2"])
# an ID3v2 tag in front of fLaC
src = os.path.join(TMP, "s16_l5.flac")
id3 = b"ID3\x04\x00\x00" + bytes([0, 0, 0, 20]) + b"TIT2\x00\x00\x00\x0a\x00\x00\x03hello id3"
emit("id3", src, 44100, 2, 16, "s16_l5 with an ID3v2 tag in front", prefix=id3)
ctx.emit("flac_cases", CASES)