Files
rosetta/tools/fixtures/flac_enc.py
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

90 lines
5.0 KiB
Python

# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py
# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the
# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level
# sweep is compared in size with `flac -<level>` (libFLAC 1.5, --no-padding --no-seektable).
# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data }
# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs
import hashlib, importlib.util, os
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
A = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(A)
INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/audio/Pcm", "src/Formats/core/Md5.luau"]
def pcm_bytes(samples, bits):
s = 2 ** (bits - 1)
nb = (bits + 7) // 8
out = bytearray()
for v in samples:
q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5))))
out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little")
return bytes(out)
def generate(ctx):
sigs = {}
def sig(kind, ch, frames, rate=44100):
name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate)
if name not in sigs:
samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded
sigs[name] = (samples, rate, ch)
return name
cases = [] # (name, sigmod, bits, opts_lua, ref_level)
for level in range(9):
cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level))
cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level))
cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level))
for kind in ("sine", "silence", "loud", "square"):
for ch in (1, 2):
for bits in (8, 16, 24):
cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None))
for level in (0, 5, 8):
for n in (1, 15, 100, 1153, 4097):
cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None))
for bs in (192, 576, 1000, 4608, 16):
cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None))
cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None))
cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None))
cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None))
cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None))
cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None))
ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs")
files = {"c%03d.flac" % i: o for i, o in enumerate(outs)}
script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done'
report = A.shell_many(ctx, "flac", files, script).decode(errors="replace")
rows = {}
for line in report.strip().split("\n"):
f, rc, md5, msg = line.split("|", 3)
rows[f] = (int(rc), md5.strip(), msg.strip())
# libFLAC reference sizes for the level sweep
refs = {}
wavs = {}
for i, c in enumerate(cases):
if c[4] is not None:
samples, rate, ch = sigs[c[1]]
wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2])
wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode()
script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed '
'--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done')
for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"):
f, size = line.split()
refs[int(f[1:4])] = int(size)
emitted = []
for i, (name, sigmod, bits, opts, lvl) in enumerate(cases):
samples, rate, ch = sigs[sigmod]
rc, md5, msg = rows["c%03d.flac" % i]
want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest()
e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch,
"flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]),
"data": outs[i]}
if i in refs:
e["refSize"] = refs[i]
emitted.append(e)
ctx.emit("flac_enc", emitted)