ws-audio: merge ws/absorb (flac, bmp, zip)

This commit is contained in:
4DBug committed 2026-10-31 08:53:32 -05:00
commit 3dfe1e2cdd
125 files changed
+4625 -2

No files matched your search

+31 -1
View File
@@ -1,6 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time).
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone.
local Deflate = require("@formats/codecs/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
@@ -13,6 +14,10 @@ local Opus = require("@formats/audio/opus")
local OpusCelt = require("@tests/gen/opus_celt_st_128")
local OpusSilk = require("@tests/gen/opus_silk_wb_st")
local OpusHybrid = require("@tests/gen/opus_hybrid_st")
local Flac = require("@formats/audio/flac")
local FC = require("@tests/gen/flac_cases")
local Wav = require("@formats/audio/wav")
local Types = require("@formats/Types")
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
@@ -93,4 +98,29 @@ do
Vorbis.decode(Bytes.reader(b))
end)
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt))
for _, name in { "s16_long", "s24_96k" } do
for _, c in FC do
if c.name == name then
local b = buffer.fromstring(c.data)
local dec = assert(Flac.open(Bytes.reader(b)))
local secs = dec.duration
local dt = bench("flac decode " .. name, 5, dec.frames * dec.channels * 4, function()
Flac.decode(Bytes.reader(b))
end)
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt))
end
end
end
do
local a = Types.Audio.new(44100, 2, 44100 * 10)
for i = 0, 44100 * 20 - 1 do
buffer.writef32(a.samples, i * 4, math.sin(i * 0.01) * 0.5)
end
bench("wav encode s16 (10 s stereo)", 5, buffer.len(a.samples), function()
Wav.encode(a)
end)
local file = assert(Wav.encode(a))
bench("wav decode s16 (10 s stereo)", 5, buffer.len(a.samples), function()
Wav.decode(Bytes.reader(file))
end)
end
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png mp3 opus vorbis > /dev/null || exit 1
python3 -I tools/fixtures.py deflate png mp3 opus flac vorbis > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+134
View File
@@ -0,0 +1,134 @@
# BMP reference decodes with Pillow (run by tools/fixtures/bmp.py inside a nix python with pillow): reads a JSON request
# on stdin, writes JSON on stdout. Ported from bmp-luau tools/mkfixtures.py (its Pillow rules: see "expected").
# {"root": dir, "files": [rel...], "refs": {rel: png}, "encode": [{"name", "mode", "w", "h", "rgba" (hex), "palette"?}]}
# -> {"files": [{"name", "w", "h", "crc"} or {"name", "error"}], "encode": [{"name", "bmp" (hex)}]}
# Expected pixels: Pillow's RGBA, with these rules (Pillow differs from browsers there):
# - 32 bpp BI_RGB: the 4th byte is alpha (Pillow ignores it), unless every one is 0 (then opaque).
# - 32 bpp with an alpha mask whose values are all 0: opaque.
# - RLE: decoded by rle_reference below over Pillow's palette (Pillow's RLE decoder has bugs); skipped pixels are
# transparent black.
# - Files Pillow cannot read (unusual BITFIELDS in the suite's g/): the suite's own reference PNG.
import io, json, os, struct, sys, zlib
from PIL import Image, ImageFile
# truncated files (a bad bfSize / short pixel array, as in some skins): Pillow fills the missing rows with 0
ImageFile.LOAD_TRUNCATED_IMAGES = True
# RLE: Pillow's decoder mishandles odd RLE4 absolute runs, an end of line at x = 0 and an end of bitmap before the
# last row (as in the Winamp base skin), so the reference for RLE files is this spec decoder over Pillow's palette.
# Pixels the stream skips (delta, early end of line / bitmap) are transparent black, as in browsers.
# (Pillow's own RLE decode still has to load without failing, for the palette: pad its output with index 0)
from PIL import BmpImagePlugin
_set_as_raw = BmpImagePlugin.BmpRleDecoder.set_as_raw
def _padded(self, data, rawmode=None, extra=()):
need = self.state.xsize * self.state.ysize
return _set_as_raw(self, data + b"\0" * max(0, need - len(data)), rawmode, extra)
BmpImagePlugin.BmpRleDecoder.set_as_raw = _padded
def rle_reference(im, raw, w, h, rle4):
off = struct.unpack_from("<I", raw, 10)[0]
top = struct.unpack_from("<i", raw, 22)[0] < 0
if im.mode == "P":
p = im.getpalette() or []
pal = [tuple(p[i * 3:i * 3 + 3]) + (255,) for i in range(len(p) // 3)]
elif im.mode == "L":
pal = [(i, i, i, 255) for i in range(256)]
else:
pal = [(0, 0, 0, 255), (255, 255, 255, 255)]
pal += [(0, 0, 0, 255)] * (256 - len(pal))
out = bytearray(w * h * 4)
def put(x, y, i):
if x < w and y < h:
r = y if top else h - 1 - y
out[(r * w + x) * 4:(r * w + x) * 4 + 4] = bytes(pal[i])
p, x, y, n = off, 0, 0, len(raw)
while y < h and p + 1 < n:
c, v = raw[p], raw[p + 1]
p += 2
if c:
for k in range(c):
put(x + k, y, (v >> 4 if k % 2 == 0 else v & 15) if rle4 else v)
x += c
elif v == 0:
x, y = 0, y + 1
elif v == 1:
break
elif v == 2:
if p + 1 >= n:
break
x, y = x + raw[p], y + raw[p + 1]
p += 2
else:
nb = (v + 1) // 2 if rle4 else v
if p + nb > n:
break
for k in range(v):
b = raw[p + k // 2] if rle4 else raw[p + k]
put(x + k, y, (b >> 4 if k % 2 == 0 else b & 15) if rle4 else b)
x += v
p += nb + (nb & 1)
return bytes(out)
def expected(path, raw, root):
try:
im = Image.open(path)
im.load()
except Exception:
ref = REFS.get(os.path.relpath(path, root))
if not ref:
raise
ref = os.path.join(root, "ref", ref)
im = Image.open(ref)
im.load()
w, h = im.size
hs = struct.unpack_from("<I", raw, 14)[0]
comp = struct.unpack_from("<I", raw, 30)[0] if hs >= 40 else 0
if comp in (1, 2) and im.format == "BMP":
return w, h, rle_reference(im, raw, w, h, comp == 2), True
rgba = bytearray(im.convert("RGBA").tobytes())
if hs >= 40:
bpp, comp = struct.unpack_from("<HI", raw, 28)
if bpp == 32 and comp in (0, 3, 6):
alpha = None
if comp == 0:
off = struct.unpack_from("<I", raw, 10)[0]
top = struct.unpack_from("<i", raw, 22)[0] < 0
alpha = bytearray(w * h)
for y in range(h):
r = y if top else h - 1 - y
alpha[y * w:(y + 1) * w] = raw[off + r * w * 4 + 3: off + (r + 1) * w * 4: 4]
else:
alpha = rgba[3::4]
if not any(alpha):
alpha = b"\xff" * (w * h)
rgba[3::4] = alpha
return w, h, bytes(rgba), False
req = json.load(sys.stdin)
REFS = req.get("refs", {})
out = {"files": [], "encode": []}
for rel in req["files"]:
p = os.path.join(req["root"], rel)
raw = open(p, "rb").read()
try:
w, h, rgba, _ = expected(p, raw, req["root"])
out["files"].append({"name": rel, "w": w, "h": h, "crc": zlib.crc32(rgba)})
except Exception as e:
out["files"].append({"name": rel, "error": str(e)})
for e in req.get("encode", []):
rgba = bytes.fromhex(e["rgba"])
im = Image.frombytes("RGBA", (e["w"], e["h"]), rgba)
if e["mode"] == "RGB":
im = im.convert("RGB")
elif e["mode"] == "P":
pal = e["palette"] # [[r, g, b], ...] in first-appearance order
idx = {tuple(c): i for i, c in enumerate(pal)}
p = Image.new("P", im.size)
p.putpalette([v for c in pal for v in c])
p.putdata([idx[px[:3]] for px in im.getdata()])
im = p
b = io.BytesIO()
im.save(b, "BMP")
out["encode"].append({"name": e["name"], "bmp": b.getvalue().hex()})
json.dump(out, sys.stdout)
+69
View File
@@ -0,0 +1,69 @@
# BMP fixtures (tools/fixtures.py): image/bmp. Ported from bmp-luau tools/fixtures.sh + mkfixtures.py.
# tests/gen/bmp_suite.luau the BMP Suite 2.8 (tests/fixtures/bmpsuite: g/ must match, q/ and b/ must not throw;
# public domain, see licenses/) with Pillow's reference RGBA (tools/fixtures/_bmp_reference.py)
# tests/gen/bmp_enc.luau encoder references: images saved by Pillow as 24 bpp RGB, 8 bpp P (palette in first-appearance
# order) and 32 bpp RGBA (BI_RGB); our encoder must write the same bytes
# (bmp-luau also tested the Winamp skins of the Webamp demo; those are not redistributable and are not used here.)
import json, os, random
INPUTS = ["tests/fixtures/bmpsuite", "tools/fixtures/_bmp_reference.py"]
def image(rng, w, h, ncolours, alpha):
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)]
px = bytearray()
for y in range(h):
for x in range(w):
c = pal[(x * 7 + y * 13 + rng.randrange(3)) % ncolours] if ncolours else (rng.randrange(256), rng.randrange(256), rng.randrange(256))
px += bytes(c) + bytes([rng.randrange(256) if alpha else 255])
return bytes(px)
def first_appearance(rgba):
seen, pal = set(), []
for i in range(0, len(rgba), 4):
c = tuple(rgba[i:i + 3])
if c not in seen:
seen.add(c)
pal.append(list(c))
return pal
def generate(ctx):
root = os.path.join(ctx.root, "tests", "fixtures", "bmpsuite")
refs = {}
for line in open(os.path.join(root, "ref.txt")).read().split("\n"):
if line:
a, b = line.split()
refs[a] = b
files = [d + "/" + f for d in ("g", "q", "b") for f in sorted(os.listdir(os.path.join(root, d)))]
rng = random.Random(11)
enc = []
for name, w, h, ncol, alpha, mode in (("rgb-37x23", 37, 23, 0, False, "RGB"), ("rgb-1x1", 1, 1, 0, False, "RGB"),
("rgb-640x3", 640, 3, 0, False, "RGB"), ("pal-5-13x9", 13, 9, 5, False, "P"),
("pal-256-64x64", 64, 64, 256, False, "P"), ("pal-1-3x3", 3, 3, 1, False, "P"),
("pal-17-50x7", 50, 7, 17, False, "P"), ("rgba-21x11", 21, 11, 0, True, "RGBA"),
("rgba-pal-9x9", 9, 9, 4, True, "RGBA")):
rgba = image(rng, w, h, ncol, alpha)
if mode == "P":
pal = first_appearance(rgba)
assert len(pal) <= 256
enc.append({"name": name, "mode": mode, "w": w, "h": h, "rgba": rgba.hex(), **({"palette": pal} if mode == "P" else {})})
req = {"root": root, "files": files, "refs": refs, "encode": enc}
code = open(os.path.join(ctx.root, "tools", "fixtures", "_bmp_reference.py")).read()
res = json.loads(ctx.python(["pillow"], code, input=json.dumps(req).encode()))
suite = []
for f in res["files"]:
mode = "match" if f["name"].startswith("g/") else "nocrash"
if mode == "match" and "error" in f:
raise RuntimeError("pillow cannot read %s: %s" % (f["name"], f["error"]))
e = {"name": f["name"], "mode": mode, "data": ctx.read(os.path.join("tests", "fixtures", "bmpsuite", f["name"]))}
if "w" in f:
e.update(w=f["w"], h=f["h"], crc=f["crc"])
suite.append(e)
ctx.emit("bmp_suite", suite)
out = []
for e, r in zip(enc, res["encode"]):
out.append({"name": e["name"], "mode": e["mode"], "w": e["w"], "h": e["h"], "rgba": bytes.fromhex(e["rgba"]),
"bmp": bytes.fromhex(r["bmp"])})
ctx.emit("bmp_enc", out)
+286
View File
@@ -0,0 +1,286 @@
# 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)
+161
View File
@@ -0,0 +1,161 @@
# ZIP fixtures (tools/fixtures.py): containers/Zip + archive/zip. Ported from zip-luau tools/fixtures.py.
# tests/gen/zip_cases.luau generated archives with Python zipfile's view of every entry ({ name, size, crc, method }):
# stored and deflate entries, an archive comment holding a fake end record, data descriptors,
# force_zip64, a hand-built all-ZIP64 archive, 66000 entries (ZIP64 end record), a prefix
# stub, a wrong local extra length, unicode names, empty; plus every .wsz skin in $SKINS_DIR
# when it is set (the Webamp demo skins; not redistributable, so not committed). Archives
# over 1 MB are stored zlib-compressed (dataZ)
import io, os, random, struct, sys, zipfile, zlib
SKINS = os.environ.get("SKINS_DIR", "")
TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000))
class Unseekable(io.RawIOBase):
def __init__(self):
self.buf = bytearray()
def writable(self):
return True
def write(self, b):
self.buf += b
return len(b)
def mk(files, comment=b"", stream=False, force64=False):
out = Unseekable() if stream else io.BytesIO()
with zipfile.ZipFile(out, "w") as z:
for name, data, method in files:
zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42))
zi.compress_type = method
if force64:
with z.open(zi, "w", force_zip64=True) as f:
f.write(data)
else:
z.writestr(zi, data)
z.comment = comment
return bytes(out.buf if stream else out.getvalue())
def zip64_by_hand(files):
# every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator
local, cd = bytearray(), bytearray()
for name, data in files:
n = name.encode()
c = zlib.compressobj(9, zlib.DEFLATED, -15)
comp = c.compress(data) + c.flush()
crc = zlib.crc32(data)
off = len(local)
lx = struct.pack("<HHQQ", 1, 16, len(data), len(comp))
local += struct.pack("<IHHHHHIIIHH", 0x04034b50, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(lx)) + n + lx + comp
cx = struct.pack("<HHQQQ", 1, 24, len(data), len(comp), off)
cd += struct.pack("<IHHHHHHIIIHHHHHII", 0x02014b50, 45, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(cx), 0, 0, 0, 0, 0xFFFFFFFF) + n + cx
cdoff = len(local)
z64 = len(local) + len(cd)
rec = struct.pack("<IQHHIIQQQQ", 0x06064b50, 44, 45, 45, 0, 0, len(files), len(files), len(cd), cdoff)
loc = struct.pack("<IIQI", 0x07064b50, 0, z64, 1)
eocd = struct.pack("<IHHHHIIH", 0x06054b50, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0)
return bytes(local + cd + rec + loc + eocd)
def entries(data, limit=None):
z = zipfile.ZipFile(io.BytesIO(data))
return len(z.infolist()), [[i.filename, i.file_size, i.CRC, i.compress_type] for i in z.infolist()[:limit]]
def generate(ctx):
S, D = zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED
rng = random.Random(3)
TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000))
class Unseekable(io.RawIOBase):
def __init__(self):
self.buf = bytearray()
def writable(self):
return True
def write(self, b):
self.buf += b
return len(b)
def mk(files, comment=b"", stream=False, force64=False):
out = Unseekable() if stream else io.BytesIO()
with zipfile.ZipFile(out, "w") as z:
for name, data, method in files:
zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42))
zi.compress_type = method
if force64:
with z.open(zi, "w", force_zip64=True) as f:
f.write(data)
else:
z.writestr(zi, data)
z.comment = comment
return bytes(out.buf if stream else out.getvalue())
def zip64_by_hand(files):
# every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator
local, cd = bytearray(), bytearray()
for name, data in files:
n = name.encode()
c = zlib.compressobj(9, zlib.DEFLATED, -15)
comp = c.compress(data) + c.flush()
crc = zlib.crc32(data)
off = len(local)
lx = struct.pack("<HHQQ", 1, 16, len(data), len(comp))
local += struct.pack("<IHHHHHIIIHH", 0x04034b50, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(lx)) + n + lx + comp
cx = struct.pack("<HHQQQ", 1, 24, len(data), len(comp), off)
cd += struct.pack("<IHHHHHHIIIHHHHHII", 0x02014b50, 45, 45, 0, 8, 0, 0x21, crc, 0xFFFFFFFF, 0xFFFFFFFF, len(n), len(cx), 0, 0, 0, 0, 0xFFFFFFFF) + n + cx
cdoff = len(local)
z64 = len(local) + len(cd)
rec = struct.pack("<IQHHIIQQQQ", 0x06064b50, 44, 45, 45, 0, 0, len(files), len(files), len(cd), cdoff)
loc = struct.pack("<IIQI", 0x07064b50, 0, z64, 1)
eocd = struct.pack("<IHHHHIIH", 0x06054b50, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0)
return bytes(local + cd + rec + loc + eocd)
S, D = zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED
basic = [
("readme.txt", TEXT, D),
("Skin/Main.BMP", rng.randbytes(5000) + bytes(20000), D),
("Skin/stored.bin", rng.randbytes(3000), S),
("Skin/", b"", S),
("Skin/sub/deep.txt", b"deep", D),
("empty.txt", b"", D),
("__MACOSX/Skin/._Main.BMP", b"\0\5\x16\7junk", S),
("Skïn/ünicode.txt", "héllo".encode(), D),
]
archives = [] # (label, bytes, expect: list of (name, size, crc) or None for "parse with zipfile")
REF = {} # label -> the archive zipfile reads for the expected listing (when zipfile cannot read the real one)
def add(label, data, ref=None):
archives.append((label, data))
if ref is not None:
REF[label] = ref
add("basic", mk(basic))
# zipfile itself takes the fake end record in this comment (it searches for the last signature)
add("comment", mk(basic[:3], comment=b"a comment with a fake end record PK\x05\x06" + b"\0" * 18 + b" and more" * 100), mk(basic[:3]))
add("descriptors", mk(basic[:6], stream=True))
add("force_zip64", mk(basic[:6], force64=True))
add("zip64_by_hand", zip64_by_hand([("a.txt", TEXT), ("b/c.bin", rng.randbytes(4000)), ("z.txt", b"")]))
add("prefixed", b"MZ" + b"\x90" * 3000 + mk(basic[:3]))
add("empty", mk([]))
w = bytearray(mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)]))
struct.pack_into("<H", w, 28, 7) # first local header: wrong extra length (the central directory has 0)
add("wrong_local_extra", bytes(w), mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)]))
many = mk([("d/%05d.txt" % i, b"%d" % i, S) for i in range(66000)])
add("many", many)
skins = []
if os.path.isdir(SKINS):
for name in sorted(os.listdir(SKINS)):
if name.lower().endswith(".wsz"):
with open(os.path.join(SKINS, name), "rb") as f:
skins.append((name, f.read()))
out = {"archives": [], "skins": []}
for key, group in (("archives", archives), ("skins", skins)):
for label, data in group:
count, ents = entries(REF.get(label, data), 200 if label == "many" else None)
c = {"name": label, "count": count, "entries": ents}
if len(data) > 1000000:
c["dataZ"] = zlib.compress(data, 9) # big archives (66000 entries): zlib, inflated by the test
else:
c["data"] = data
out[key].append(c)
ctx.emit("zip_cases", out)