ws-m4a: merge ws/absorb (audio/opus, containers/Ogg, ...) for the CELT encoder; m4a fixtures load their helper by path (tools/fixtures/ on sys.path shadowed the xml package)
This commit is contained in:
commit
29a95ce24f
215 files changed
+24209
-61
No files matched your search
+90
-1
@@ -1,11 +1,23 @@
|
||||
-- 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) and tools/fixtures/png.py (1024 x 768 images).
|
||||
-- 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/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")
|
||||
local Png = require("@formats/image/png")
|
||||
local B = require("@tests/gen/deflate_bench")
|
||||
local PB = require("@tests/gen/png_bench")
|
||||
local Mp3 = require("@formats/audio/mp3")
|
||||
local MC = require("@tests/gen/mp3_cases")
|
||||
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"
|
||||
|
||||
@@ -18,6 +30,7 @@ local function bench(label: string, n: number, bytes: number, f: () -> ())
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6))
|
||||
return dt
|
||||
end
|
||||
|
||||
local z = buffer.fromstring(B.zlib)
|
||||
@@ -56,6 +69,82 @@ do
|
||||
Png.encode(img)
|
||||
end)
|
||||
end
|
||||
for _, name in { "l3_cbr128_js", "l3_vbr_v2_48k", "l2_192_st" } do
|
||||
for _, c in MC do
|
||||
if c.name == name then
|
||||
local b = buffer.fromstring(c.data)
|
||||
local dec = assert(Mp3.open(Bytes.reader(b)))
|
||||
local secs = dec.duration
|
||||
local dt = bench("mp3 decode " .. name, 5, dec.frames * dec.channels * 4, function()
|
||||
local d = assert(Mp3.open(Bytes.reader(b)))
|
||||
d:readAll()
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt))
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", OpusHybrid } } do
|
||||
local b = buffer.fromstring(c[2].data)
|
||||
bench("opus decode " .. c[1] .. " (3 s st)", 3, #c[2].ref, function()
|
||||
Opus.decode(Bytes.reader(b))
|
||||
end)
|
||||
end
|
||||
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
|
||||
do
|
||||
local Json = require("@formats/codecs/Json")
|
||||
local JB = require("@tests/gen/json_bench")
|
||||
local v = assert(Json.decode(JB.text))
|
||||
assert(Json.encode(v) == JB.compact, "json bench mismatch")
|
||||
bench("json decode (indented)", 5, #JB.text, function()
|
||||
Json.decode(JB.text)
|
||||
end)
|
||||
bench("json decode (compact)", 5, #JB.compact, function()
|
||||
Json.decode(JB.compact)
|
||||
end)
|
||||
bench("json encode (compact, sorted)", 5, #JB.compact, function()
|
||||
Json.encode(v)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local XB = require("@tests/gen/xml_bench")
|
||||
local doc = assert(Xml.decode(XB.text))
|
||||
bench("xml decode (DOM)", 5, #XB.text, function()
|
||||
Xml.decode(XB.text)
|
||||
end)
|
||||
bench("xml events", 5, #XB.text, function()
|
||||
for _ in Xml.events(XB.text) do
|
||||
end
|
||||
end)
|
||||
bench("xml encode", 5, #XB.text, function()
|
||||
Xml.encode(doc)
|
||||
end)
|
||||
end
|
||||
|
||||
-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT
|
||||
do
|
||||
|
||||
+1
-1
@@ -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 m4a > /dev/null || exit 1
|
||||
python3 -I tools/fixtures.py deflate png mp3 opus flac json xml m4a > /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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,99 @@
|
||||
# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...):
|
||||
# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash)
|
||||
# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys,
|
||||
# numbers as %.17g, so Python's parse and ours compare exactly.
|
||||
import os, subprocess, datetime
|
||||
|
||||
|
||||
def fetch(url, sha256):
|
||||
expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256)
|
||||
out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True)
|
||||
return out.stdout.decode()
|
||||
|
||||
|
||||
def _b(s):
|
||||
if isinstance(s, str):
|
||||
return s.encode("utf-8", "surrogatepass")
|
||||
return bytes(s)
|
||||
|
||||
|
||||
def canon(v):
|
||||
"""null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>;
|
||||
bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>"""
|
||||
out = bytearray()
|
||||
_canon(v, out)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def num(x):
|
||||
x = float(x)
|
||||
if x != x:
|
||||
return b"#nan"
|
||||
if x in (float("inf"), float("-inf")):
|
||||
return b"#inf" if x > 0 else b"#-inf"
|
||||
if x == int(x) and abs(x) < 2 ** 53:
|
||||
return b"#%d" % int(x)
|
||||
return b"#" + ("%.17g" % x).encode()
|
||||
|
||||
|
||||
def _canon(v, out):
|
||||
if v is None:
|
||||
out += b"n"
|
||||
elif v is True:
|
||||
out += b"t"
|
||||
elif v is False:
|
||||
out += b"f"
|
||||
elif isinstance(v, (int, float)):
|
||||
out += num(v)
|
||||
elif isinstance(v, str):
|
||||
b = _b(v)
|
||||
out += b"s%d:" % len(b) + b
|
||||
elif isinstance(v, (bytes, bytearray)):
|
||||
out += b"b%d:" % len(v) + bytes(v)
|
||||
elif isinstance(v, (list, tuple)):
|
||||
out += b"["
|
||||
for x in v:
|
||||
_canon(x, out)
|
||||
out += b","
|
||||
out += b"]"
|
||||
elif isinstance(v, dict):
|
||||
items = []
|
||||
for k, x in v.items():
|
||||
kb = bytearray()
|
||||
_canon(k, kb)
|
||||
items.append((bytes(kb), x))
|
||||
items.sort(key=lambda p: p[0])
|
||||
out += b"{"
|
||||
for kb, x in items:
|
||||
out += kb + b"="
|
||||
_canon(x, out)
|
||||
out += b","
|
||||
out += b"}"
|
||||
elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)):
|
||||
out += b"d" + date_text(v).encode()
|
||||
else:
|
||||
raise TypeError("canon: %r" % type(v))
|
||||
|
||||
|
||||
def date_text(v):
|
||||
"""RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00"""
|
||||
def frac(us):
|
||||
return ("." + ("%06d" % us).rstrip("0")) if us else ""
|
||||
|
||||
def tz(t):
|
||||
off = t.utcoffset()
|
||||
if off is None:
|
||||
return ""
|
||||
m = int(off.total_seconds()) // 60
|
||||
if m == 0:
|
||||
return "Z"
|
||||
sign = "-" if m < 0 else "+"
|
||||
m = abs(m)
|
||||
return "%s%02d:%02d" % (sign, m // 60, m % 60)
|
||||
|
||||
if isinstance(v, datetime.datetime):
|
||||
return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second,
|
||||
frac(v.microsecond), tz(v))
|
||||
if isinstance(v, datetime.date):
|
||||
return "%04d-%02d-%02d" % (v.year, v.month, v.day)
|
||||
return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond))
|
||||
@@ -0,0 +1,220 @@
|
||||
# APNG fixtures (tools/fixtures.py).
|
||||
# tests/gen/apng_cases.luau animated PNGs with the reference composited canvases (CRC-32 of each full rgba8 frame)
|
||||
# - made by ffmpeg's apng encoder (sub-rectangles, dispose / blend chosen by ffmpeg, -plays)
|
||||
# - written here by hand: every dispose op (none / background / previous) and blend op (source / over) on
|
||||
# sub-rectangles with partial alpha, a hidden default image (IDAT not part of the animation), palette + tRNS,
|
||||
# grey, RGB, a first frame with dispose previous, split fdATs
|
||||
# The reference canvases come from ffmpeg (`-f apng -i x -f rawvideo -pix_fmt rgba`); a small compositor here
|
||||
# (the same integer blend as ffmpeg's pngdec.c) must agree with ffmpeg, so a broken reference is caught too.
|
||||
# Files ffmpeg cannot represent (the hidden default image) use the compositor here alone.
|
||||
import os, random, struct, subprocess, tempfile, zlib
|
||||
|
||||
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
|
||||
|
||||
CH = {0: 1, 2: 3, 3: 1, 6: 4}
|
||||
|
||||
|
||||
def raw_rows(px, w, h, ct, rng):
|
||||
"""px: list of h rows of w sample tuples -> filtered (random filter per row) scanlines"""
|
||||
ch = CH[ct]
|
||||
out = bytearray()
|
||||
prev = None
|
||||
for y in range(h):
|
||||
row = bytes(s for p in px[y] for s in p)
|
||||
ft = rng.randrange(5)
|
||||
out.append(ft)
|
||||
for i, x in enumerate(row):
|
||||
a = row[i - ch] if i >= ch else 0
|
||||
b = prev[i] if prev else 0
|
||||
c = prev[i - ch] if prev and i >= ch else 0
|
||||
if ft == 4:
|
||||
p = a + b - c
|
||||
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
||||
pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
|
||||
else:
|
||||
pred = (0, a, b, (a + b) // 2)[ft]
|
||||
out.append((x - pred) & 255)
|
||||
prev = row
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def to_rgba(ct, s, plte=None, trns=None):
|
||||
if ct == 6:
|
||||
return tuple(s)
|
||||
if ct == 2:
|
||||
return (s[0], s[1], s[2], 255)
|
||||
if ct == 0:
|
||||
return (s[0], s[0], s[0], 255)
|
||||
c = plte[s[0]]
|
||||
a = trns[s[0]] if trns and s[0] < len(trns) else 255
|
||||
return (c[0], c[1], c[2], a)
|
||||
|
||||
|
||||
def apng(w, h, ct, frames, plays=0, default=None, plte=None, trns=None, rng=None, split=1):
|
||||
"""frames: list of dict(x, y, w, h, px, num, den, dispose, blend); default: px of a hidden default image"""
|
||||
rng = rng or random.Random(1)
|
||||
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, ct, 0, 0, 0))
|
||||
out += chunk(b"acTL", struct.pack(">II", len(frames), plays))
|
||||
if plte:
|
||||
out += chunk(b"PLTE", b"".join(bytes(c) for c in plte))
|
||||
if trns:
|
||||
out += chunk(b"tRNS", bytes(trns))
|
||||
seq = 0
|
||||
if default is not None:
|
||||
out += chunk(b"IDAT", zlib.compress(raw_rows(default, w, h, ct, rng)))
|
||||
for i, f in enumerate(frames):
|
||||
out += chunk(b"fcTL", struct.pack(">IIIIIHHBB", seq, f["w"], f["h"], f["x"], f["y"], f["num"], f["den"], f["dispose"], f["blend"]))
|
||||
seq += 1
|
||||
z = zlib.compress(raw_rows(f["px"], f["w"], f["h"], ct, rng))
|
||||
step = max(1, -(-len(z) // split))
|
||||
for k in range(0, len(z), step):
|
||||
if i == 0 and default is None:
|
||||
out += chunk(b"IDAT", z[k:k + step])
|
||||
else:
|
||||
out += chunk(b"fdAT", struct.pack(">I", seq) + z[k:k + step])
|
||||
seq += 1
|
||||
return out + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def div255(x):
|
||||
return ((x + 128) * 257) >> 16
|
||||
|
||||
|
||||
def composite(w, h, ct, frames, plte=None, trns=None):
|
||||
"""full rgba8 canvases (bytes), blending like ffmpeg's pngdec.c (APNG spec semantics)"""
|
||||
canvas = [(0, 0, 0, 0)] * (w * h)
|
||||
outs = []
|
||||
for i, f in enumerate(frames):
|
||||
dispose, blend = f["dispose"], f["blend"]
|
||||
if i == 0:
|
||||
blend = 0
|
||||
if dispose == 2:
|
||||
dispose = 1
|
||||
saved = list(canvas)
|
||||
for yy in range(f["h"]):
|
||||
for xx in range(f["w"]):
|
||||
src = to_rgba(ct, f["px"][yy][xx], plte, trns)
|
||||
k = (f["y"] + yy) * w + f["x"] + xx
|
||||
if blend == 0 or src[3] == 255:
|
||||
canvas[k] = src
|
||||
elif src[3] == 0:
|
||||
pass
|
||||
else:
|
||||
fa, bg = src[3], canvas[k]
|
||||
ba = bg[3]
|
||||
oa = fa + div255((255 - fa) * ba)
|
||||
if ba == 255:
|
||||
canvas[k] = tuple(div255(fa * src[c] + (255 - fa) * bg[c]) for c in range(3)) + (oa,)
|
||||
else:
|
||||
canvas[k] = tuple((255 * fa * src[c] + (255 - fa) * ba * bg[c]) // (255 * oa) for c in range(3)) + (oa,)
|
||||
outs.append(b"".join(bytes(p) for p in canvas))
|
||||
if dispose == 1:
|
||||
for yy in range(f["h"]):
|
||||
for xx in range(f["w"]):
|
||||
canvas[(f["y"] + yy) * w + f["x"] + xx] = (0, 0, 0, 0)
|
||||
elif dispose == 2:
|
||||
canvas = saved
|
||||
return outs
|
||||
|
||||
|
||||
def ffmpeg_frames(ctx, data, w, h):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = os.path.join(tmp, "in.png")
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
raw = subprocess.run(["ffmpeg", "-v", "error", "-f", "apng", "-i", p, "-f", "rawvideo", "-pix_fmt", "rgba", "-fps_mode", "passthrough", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
n = w * h * 4
|
||||
return [raw[i:i + n] for i in range(0, len(raw), n)]
|
||||
|
||||
|
||||
def sprite(rng, w, h, ct, alpha=True, ncolors=None):
|
||||
px = []
|
||||
for y in range(h):
|
||||
row = []
|
||||
for x in range(w):
|
||||
if ct == 3:
|
||||
row.append((rng.randrange(ncolors),))
|
||||
elif ct == 0:
|
||||
row.append(((x * 17 + y * 5 + rng.randrange(8)) & 255,))
|
||||
elif ct == 2:
|
||||
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255))
|
||||
else:
|
||||
a = rng.choice((0, 255, 255, rng.randrange(256))) if alpha else 255
|
||||
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255, a))
|
||||
px.append(row)
|
||||
return px
|
||||
|
||||
|
||||
def frame(rng, ct, x, y, w, h, dispose, blend, num=1, den=10, **kw):
|
||||
return {"x": x, "y": y, "w": w, "h": h, "px": sprite(rng, w, h, ct, **kw), "num": num, "den": den, "dispose": dispose, "blend": blend}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(77)
|
||||
cases = []
|
||||
|
||||
def add(name, data, w, h, frames_meta, refs, default_crc=None, plays=0, ffmpeg=True, opaque=False):
|
||||
c = {"name": name, "data": data, "width": w, "height": h, "plays": plays,
|
||||
"frames": [{"x": f["x"], "y": f["y"], "w": f["w"], "h": f["h"], "num": f["num"], "den": f["den"], "dispose": f["dispose"], "blend": f["blend"]} for f in frames_meta],
|
||||
"crcs": [zlib.crc32(r) for r in refs], "ffmpeg": ffmpeg, "opaque": opaque}
|
||||
if default_crc is not None:
|
||||
c["defaultCrc"] = default_crc
|
||||
cases.append(c)
|
||||
|
||||
def hand(name, w, h, ct, frames, plays=0, plte=None, trns=None, split=1):
|
||||
data = apng(w, h, ct, frames, plays=plays, plte=plte, trns=trns, rng=rng, split=split)
|
||||
mine = composite(w, h, ct, frames, plte, trns)
|
||||
ref = ffmpeg_frames(ctx, data, w, h)
|
||||
if ct in (0, 2): # ffmpeg decodes to an opaque pixel format: disposed pixels come out opaque black
|
||||
mine = [bytes(v if i % 4 != 3 else 255 for i, v in enumerate(m)) for m in mine]
|
||||
if ref != mine:
|
||||
for fi, (a, b) in enumerate(zip(ref, mine)):
|
||||
if a != b:
|
||||
k = next(j for j in range(len(a)) if a[j] != b[j])
|
||||
print("apng fixture mismatch:", name, fi, k // 4 % w, k // 4 // w, a[k - k % 4:k - k % 4 + 4], b[k - k % 4:k - k % 4 + 4], frames[fi]["dispose"], frames[fi]["blend"], frames[fi - 1]["dispose"] if fi else None, sum(1 for j in range(0, len(a), 4) if a[j:j + 4] != b[j:j + 4]))
|
||||
raise RuntimeError("apng fixture %s: ffmpeg and the reference compositor disagree (%d vs %d frames)" % (name, len(ref), len(mine)))
|
||||
add(name, data, w, h, frames, ref, plays=plays, opaque=ct in (0, 2))
|
||||
|
||||
# every dispose x blend on sub-rectangles over a semi-transparent background
|
||||
W, H = 20, 16
|
||||
fr = [frame(rng, 6, 0, 0, W, H, 0, 0)]
|
||||
for d in (0, 1, 2):
|
||||
for b in (0, 1):
|
||||
fr.append(frame(rng, 6, rng.randrange(8), rng.randrange(6), 1 + rng.randrange(12), 1 + rng.randrange(10), d, b, num=rng.randrange(1, 200), den=rng.choice((0, 100, 1000))))
|
||||
fr.append(frame(rng, 6, 3, 2, 9, 7, 2, 1))
|
||||
fr.append(frame(rng, 6, 0, 0, W, H, 0, 1))
|
||||
hand("rgba-dispose-blend", W, H, 6, fr, plays=3, split=2)
|
||||
# first frame dispose previous (= background), then over
|
||||
hand("first-previous", 12, 9, 6, [frame(rng, 6, 0, 0, 12, 9, 2, 1), frame(rng, 6, 2, 2, 5, 4, 0, 1), frame(rng, 6, 0, 0, 3, 3, 1, 0)])
|
||||
# palette + tRNS, over
|
||||
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(40)]
|
||||
trns = [rng.choice((0, 128, 255, rng.randrange(256))) for _ in range(30)]
|
||||
hand("palette-trns", 17, 13, 3, [frame(rng, 3, 0, 0, 17, 13, 1, 0, ncolors=40)] + [frame(rng, 3, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(12), 1 + rng.randrange(8), rng.randrange(3), rng.randrange(2), ncolors=40) for _ in range(5)], plte=pal, trns=trns)
|
||||
# grey and RGB (no alpha: over = source)
|
||||
hand("gray", 15, 11, 0, [frame(rng, 0, 0, 0, 15, 11, 0, 0)] + [frame(rng, 0, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)], plays=1)
|
||||
hand("rgb", 15, 11, 2, [frame(rng, 2, 0, 0, 15, 11, 1, 0)] + [frame(rng, 2, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)])
|
||||
# a single-frame APNG
|
||||
hand("one-frame", 7, 5, 6, [frame(rng, 6, 0, 0, 7, 5, 0, 0)])
|
||||
|
||||
# hidden default image (not part of the animation): ffmpeg's demuxer cannot express it, so the compositor here
|
||||
dpx = sprite(rng, 10, 8, 6)
|
||||
fr = [frame(rng, 6, 0, 0, 10, 8, 0, 0), frame(rng, 6, 2, 1, 4, 5, 1, 1), frame(rng, 6, 5, 3, 5, 5, 0, 1)]
|
||||
data = apng(10, 8, 6, fr, default=dpx, rng=rng)
|
||||
add("hidden-default", data, 10, 8, fr, composite(10, 8, 6, fr), default_crc=zlib.crc32(b"".join(bytes(p) for row in dpx for p in row)), ffmpeg=False)
|
||||
|
||||
# ffmpeg's own encoder (it picks sub-rectangles, dispose and blend ops)
|
||||
for name, src, pix, plays in (
|
||||
("ffmpeg-testsrc", "testsrc=size=40x30:rate=10", "rgb24", 0),
|
||||
("ffmpeg-rgba", "testsrc2=size=36x28:rate=8,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(mod(X+T*40,20),10),255,90)'", "rgba", 2),
|
||||
):
|
||||
data = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-frames:v", "7", "-pix_fmt", pix, "-plays", str(plays), "-f", "apng", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
w, h = struct.unpack(">II", data[16:24])
|
||||
ref = ffmpeg_frames(ctx, data, w, h)
|
||||
cases.append({"name": name, "data": data, "width": w, "height": h, "plays": plays, "crcs": [zlib.crc32(r) for r in ref], "ffmpeg": True, "opaque": pix == "rgb24"})
|
||||
|
||||
ctx.emit("apng_cases", cases)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,91 @@
|
||||
# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix)
|
||||
# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several
|
||||
# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly.
|
||||
# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } }
|
||||
# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } }
|
||||
# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys)
|
||||
import importlib.util, json, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
|
||||
C = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(C)
|
||||
|
||||
SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz"
|
||||
SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k"
|
||||
|
||||
|
||||
def rand_value(rng, depth=0):
|
||||
v = _rand_value(rng, depth)
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return int(v) # Python writes 1.0, we write 1: keep integral numbers ints
|
||||
return v
|
||||
|
||||
|
||||
def _rand_value(rng, depth=0):
|
||||
r = rng.random()
|
||||
if depth > 4 or r < 0.45:
|
||||
k = rng.randrange(9)
|
||||
if k == 0:
|
||||
return None
|
||||
if k == 1:
|
||||
return rng.random() < 0.5
|
||||
if k == 2:
|
||||
return rng.randrange(-10 ** 15, 10 ** 15)
|
||||
if k == 3:
|
||||
return rng.randrange(-1000, 1000)
|
||||
if k == 4:
|
||||
return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8))
|
||||
if k == 5:
|
||||
return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14)
|
||||
return rand_str(rng)
|
||||
if r < 0.72:
|
||||
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))]
|
||||
d = {}
|
||||
for _ in range(rng.randrange(0, 7)):
|
||||
d[rand_str(rng)] = rand_value(rng, depth + 1)
|
||||
return d
|
||||
|
||||
|
||||
ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
"
|
||||
|
||||
|
||||
def rand_str(rng):
|
||||
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12)))
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
root = C.fetch(SUITE_URL, SUITE_SHA)
|
||||
d = os.path.join(root, "test_parsing")
|
||||
cases = []
|
||||
for name in sorted(os.listdir(d)):
|
||||
if not name.endswith(".json"):
|
||||
continue
|
||||
data = open(os.path.join(d, name), "rb").read()
|
||||
c = {"name": name, "expect": name[0], "data": data}
|
||||
try:
|
||||
v = json.loads(data.decode("utf-8", "surrogatepass"))
|
||||
c["canon"] = C.canon(v)
|
||||
except Exception:
|
||||
pass
|
||||
cases.append(c)
|
||||
ctx.emit("json_suite", cases)
|
||||
|
||||
rng = ctx.rng(7)
|
||||
corpus = []
|
||||
for _ in range(300):
|
||||
v = rand_value(rng)
|
||||
corpus.append({
|
||||
"canon": C.canon(v),
|
||||
"compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False),
|
||||
"ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False),
|
||||
"pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False),
|
||||
"ascii": json.dumps(v, separators=(",", ":"), sort_keys=True),
|
||||
})
|
||||
ctx.emit("json_corpus", corpus)
|
||||
|
||||
big = [rand_value(rng) for _ in range(3000)]
|
||||
text = json.dumps(big, ensure_ascii=False, indent=1)
|
||||
while len(text) < 1_000_000:
|
||||
big = big + big
|
||||
text = json.dumps(big, ensure_ascii=False, indent=1)
|
||||
ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)})
|
||||
@@ -8,10 +8,13 @@
|
||||
# tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau)
|
||||
# checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames,
|
||||
# tags (ffprobe's view), mp4box (MP4Box -info exit status 0) }
|
||||
import json, math, os, shutil, struct, subprocess, sys, tempfile, zlib
|
||||
import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _m4a_signal import signal, pack, wav # noqa: E402
|
||||
# the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
_spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py"))
|
||||
_sig = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_sig)
|
||||
signal, pack, wav = _sig.signal, _sig.pack, _sig.wav
|
||||
|
||||
INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff",
|
||||
"tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau",
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# MP3 fixtures (tools/fixtures.py). Ported from mp3-luau tools/make_fixtures.sh + make_refs.py.
|
||||
# tests/gen/mp3_cases.luau the committed streams in tests/fixtures/mp3/ (made by ffmpeg's libmp3lame / mp2 encoders
|
||||
# from a synthetic test signal: tones, a chirp, noise, clicks) with their minimp3 reference
|
||||
# decodes (*.ref, from the minimp3 C harness: see the format below), plus streams lame
|
||||
# encodes here; each with ffmpeg's decode of three windows and its length.
|
||||
# .ref layout (little-endian): "MP3REF1\0", u32 hz, channels, frames, window frames W, window count N, then
|
||||
# N x (u32 start frame, W x channels f32), then u32 block size B, u32 block count, f64 sum of squares per block.
|
||||
import math, os, random, struct, tempfile
|
||||
|
||||
INPUTS = ["tests/fixtures/mp3"]
|
||||
DIR = os.path.join("tests", "fixtures", "mp3")
|
||||
|
||||
|
||||
def ffmpeg_windows(ctx, data, ch, starts, W):
|
||||
with tempfile.TemporaryDirectory() as tmp: # a file, not a pipe: ffmpeg applies the LAME gapless info only when it can seek
|
||||
path = os.path.join(tmp, "in.mp3")
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
out = ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(ch), "pipe:1"])
|
||||
frames = len(out) // (4 * ch)
|
||||
wins = []
|
||||
for s in starts:
|
||||
s = max(0, min(frames - W, s))
|
||||
wins.append({"start": s, "pcm": out[s * ch * 4:(s + W) * ch * 4]})
|
||||
return frames, wins
|
||||
|
||||
|
||||
def ref_windows(ref):
|
||||
hz, ch, frames, W, N = struct.unpack_from("<5I", ref, 8)
|
||||
p, starts = 28, []
|
||||
for _ in range(N):
|
||||
starts.append(struct.unpack_from("<I", ref, p)[0])
|
||||
p += 4 + W * ch * 4
|
||||
return ch, W, starts
|
||||
|
||||
|
||||
def wav(rate, ch, secs, seed):
|
||||
rnd = random.Random(seed)
|
||||
fr = bytearray()
|
||||
for i in range(int(secs * rate)):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
v = 0.25 * math.sin(2 * math.pi * (330 * (c + 1) + 200 * t) * t) + 0.04 * (rnd.random() - 0.5)
|
||||
if (i // 2000) % 7 == 3:
|
||||
v += 0.3 * math.sin(2 * math.pi * 4000 * t) * (1 - (i % 2000) / 2000)
|
||||
fr += struct.pack("<h", int(max(-1, min(1, v)) * 32767))
|
||||
hdr = b"RIFF" + struct.pack("<I", 36 + len(fr)) + b"WAVEfmt " + struct.pack("<IHHIIHH", 16, 1, ch, rate, rate * ch * 2, ch * 2, 16)
|
||||
return hdr + b"data" + struct.pack("<I", len(fr)) + bytes(fr)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for fn in sorted(os.listdir(os.path.join(ctx.root, DIR))):
|
||||
if not fn.endswith((".mp3", ".mp2")):
|
||||
continue
|
||||
name = fn[:-4]
|
||||
data = ctx.read(os.path.join(DIR, fn))
|
||||
ref = ctx.read(os.path.join(DIR, name + ".ref"))
|
||||
ch, W, starts = ref_windows(ref)
|
||||
frames, wins = ffmpeg_windows(ctx, data, ch, starts, W)
|
||||
cases.append({"name": name, "data": data, "ref": ref, "ffFrames": frames, "ff": wins})
|
||||
# streams the lame CLI writes here (no minimp3 reference: ffmpeg only)
|
||||
for name, rate, ch, args in (("lame_v5_st", 44100, 2, ["-V", "5"]), ("lame_cbr64_mono_22k", 22050, 1, ["-b", "64", "-m", "m"]),
|
||||
("lame_abr96_48k", 48000, 2, ["--abr", "96"])):
|
||||
src = wav(rate, ch, 1.2, len(name))
|
||||
with tempfile.TemporaryDirectory() as tmp: # a file: lame writes the LAME (gapless) tag only when it can seek
|
||||
path = os.path.join(tmp, "out.mp3")
|
||||
ctx.nix("lame", ["lame", "--quiet", "--resample", str(rate / 1000)] + args + ["-", path], input=src)
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
W = 1152
|
||||
frames, wins = ffmpeg_windows(ctx, data, ch, [0, 20000, 10 ** 9], W)
|
||||
cases.append({"name": name, "data": data, "ffFrames": frames, "ff": wins, "channels": ch, "rate": rate,
|
||||
"srcFrames": int(1.2 * rate)})
|
||||
ctx.emit("mp3_cases", cases)
|
||||
@@ -0,0 +1,209 @@
|
||||
# Ogg fixtures (tools/fixtures.py): containers/Ogg. Ported from ogg-luau tools/gen_fixtures.py.
|
||||
# tests/gen/ogg_cases.luau real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files
|
||||
# (lacing edge cases, junk, a corrupt page copy, a lost page), each with the packet list
|
||||
# from the small independent parser below: { size, crc32, granule, bos, eos }
|
||||
import math, os, random, struct, tempfile, wave, zlib
|
||||
|
||||
# --- CRC + writer -----------------------------------------------------------------------------------------
|
||||
def _crc_table():
|
||||
t = []
|
||||
for i in range(256):
|
||||
r = i << 24
|
||||
for _ in range(8):
|
||||
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
|
||||
r &= 0xFFFFFFFF
|
||||
t.append(r)
|
||||
return t
|
||||
|
||||
|
||||
CRC = _crc_table()
|
||||
|
||||
|
||||
def ogg_crc(data):
|
||||
c = 0
|
||||
for x in data:
|
||||
c = ((c << 8) & 0xFFFFFFFF) ^ CRC[(c >> 24) ^ x]
|
||||
return c
|
||||
|
||||
|
||||
def page(serial, seq, granule, flags, segs, data):
|
||||
h = struct.pack("<4sBBqIIIB", b"OggS", 0, flags, granule, serial, seq, 0, len(segs)) + bytes(segs)
|
||||
p = bytearray(h + data)
|
||||
struct.pack_into("<I", p, 22, ogg_crc(p))
|
||||
return bytes(p)
|
||||
|
||||
|
||||
def mux_stream(serial, packets, max_segs=255, granule_of=None):
|
||||
"""Pages for one stream; packets = list of (bytes, granule). Pages break after max_segs lacing values."""
|
||||
pages = []
|
||||
segs, data, seq, cont, gran = [], b"", 0, False, -1
|
||||
first = True
|
||||
|
||||
def flush(eos=False, next_cont=False):
|
||||
nonlocal segs, data, seq, cont, gran, first
|
||||
flags = (1 if cont else 0) | (2 if first else 0) | (4 if eos else 0)
|
||||
pages.append(page(serial, seq, gran, flags, segs, data))
|
||||
seq += 1
|
||||
first = False
|
||||
segs, data, gran = [], b"", -1
|
||||
cont = next_cont
|
||||
|
||||
for i, (pkt, g) in enumerate(packets):
|
||||
n = len(pkt)
|
||||
lac = [255] * (n // 255) + [n % 255]
|
||||
pos = 0
|
||||
for j, l in enumerate(lac):
|
||||
if len(segs) == max_segs:
|
||||
flush(next_cont=j > 0)
|
||||
segs.append(l)
|
||||
data += pkt[pos:pos + l]
|
||||
pos += l
|
||||
gran = g
|
||||
if i == 0 or (i % 7 == 3): # bos page holds only the first packet; break pages now and then
|
||||
flush()
|
||||
flush(eos=True)
|
||||
return pages
|
||||
|
||||
|
||||
# --- reference parser ---------------------------------------------------------------------------------------
|
||||
def parse(data):
|
||||
"""{serial: [ (bytes, granule, bos, eos) ]} with resync + CRC check, like the library."""
|
||||
out, partial, order, seqs = {}, {}, [], {}
|
||||
pos = 0
|
||||
while True:
|
||||
i = data.find(b"OggS", pos)
|
||||
if i < 0 or i + 27 > len(data):
|
||||
break
|
||||
nseg = data[i + 26]
|
||||
segs = data[i + 27:i + 27 + nseg]
|
||||
total = 27 + nseg + sum(segs)
|
||||
if len(segs) < nseg or i + total > len(data):
|
||||
pos = i + 1
|
||||
continue
|
||||
p = bytearray(data[i:i + total])
|
||||
crc = struct.unpack_from("<I", p, 22)[0]
|
||||
p[22:26] = b"\0\0\0\0"
|
||||
if ogg_crc(p) != crc:
|
||||
pos = i + 1
|
||||
continue
|
||||
flags, gran, serial = p[5], struct.unpack_from("<q", p, 6)[0], struct.unpack_from("<I", p, 14)[0]
|
||||
if serial not in out:
|
||||
out[serial] = []
|
||||
order.append(serial)
|
||||
partial[serial] = None
|
||||
seq = struct.unpack_from("<I", p, 18)[0]
|
||||
if serial in seqs and seq != seqs[serial] + 1:
|
||||
partial[serial] = None
|
||||
seqs[serial] = seq
|
||||
body = 27 + nseg
|
||||
last_complete = max([k for k, l in enumerate(segs) if l < 255], default=-1)
|
||||
cur = partial[serial] if (flags & 1) else None
|
||||
if not (flags & 1):
|
||||
cur = None
|
||||
skip = (flags & 1) and partial[serial] is None
|
||||
first_on_page = True
|
||||
for k, l in enumerate(segs):
|
||||
chunk = bytes(p[body:body + l])
|
||||
body += l
|
||||
if skip:
|
||||
if l < 255:
|
||||
skip = False
|
||||
first_on_page = False
|
||||
continue
|
||||
cur = (cur or b"") + chunk
|
||||
if l < 255:
|
||||
last = k == last_complete
|
||||
out[serial].append((cur, gran if last else -1, bool(flags & 2) and first_on_page,
|
||||
bool(flags & 4) and last))
|
||||
first_on_page = False
|
||||
cur = None
|
||||
partial[serial] = cur
|
||||
pos = i + total
|
||||
return order, out
|
||||
|
||||
|
||||
def codec(pkt):
|
||||
if pkt.startswith(b"OpusHead"):
|
||||
return "opus"
|
||||
if pkt[:5] == b"\x7fFLAC":
|
||||
return "flac"
|
||||
if pkt[:7] == b"\x01vorbis":
|
||||
return "vorbis"
|
||||
return "unknown"
|
||||
|
||||
|
||||
|
||||
def case(name, data, note):
|
||||
order, streams = parse(data)
|
||||
ss = []
|
||||
for s in order:
|
||||
pk = streams[s]
|
||||
gs = [g for _, g, _, _ in pk if g != -1]
|
||||
ss.append({"serial": s, "codec": codec(pk[0][0]), "lastGranule": gs[-1] if gs else -1,
|
||||
"packets": [[len(b), zlib.crc32(b), g, bos, eos] for b, g, bos, eos in pk]})
|
||||
return {"name": name, "note": note, "data": data, "streams": ss}
|
||||
|
||||
|
||||
def tone_wav(path, secs, rate=48000, ch=2):
|
||||
rnd = random.Random(1)
|
||||
with wave.open(path, "wb") as w:
|
||||
w.setnchannels(ch)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(rate)
|
||||
fr = bytearray()
|
||||
for i in range(int(secs * rate)):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
v = 0.3 * math.sin(2 * math.pi * (220 * (c + 1) + 40 * math.sin(t)) * t) + 0.05 * (rnd.random() - 0.5)
|
||||
fr += struct.pack("<h", int(v * 32767))
|
||||
w.writeframes(bytes(fr))
|
||||
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp()
|
||||
cases = []
|
||||
wav = os.path.join(tmp, "a.wav")
|
||||
tone_wav(wav, 12)
|
||||
opus = os.path.join(tmp, "a.opus")
|
||||
ctx.nix("opus-tools", ["opusenc", "--quiet", "--bitrate", "48", wav, opus])
|
||||
cases.append(case("opus_stereo", open(opus, "rb").read(), "opusenc 48 kb/s, 12 s stereo"))
|
||||
wav2 = os.path.join(tmp, "b.wav")
|
||||
tone_wav(wav2, 1.5, 44100, 1)
|
||||
oflac = os.path.join(tmp, "b.oga")
|
||||
ctx.nix("flac", ["flac", "-s", "--ogg", "-5", "-o", oflac, wav2])
|
||||
cases.append(case("flac_ogg", open(oflac, "rb").read(), "flac --ogg -5, 1.5 s mono"))
|
||||
vorb = os.path.join(tmp, "c.ogg")
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav2, "-ac", "2", "-c:a", "vorbis", "-strict", "-2", vorb])
|
||||
cases.append(case("vorbis_ffmpeg", open(vorb, "rb").read(), "ffmpeg native vorbis, 1.5 s stereo"))
|
||||
|
||||
# two interleaved streams, lacing edge cases, junk, a corrupt page, a dropped page
|
||||
rnd = random.Random(7)
|
||||
sizes = [0, 1, 254, 255, 256, 509, 510, 511, 765, 4000, 70000, 0, 0, 3, 65025, 255 * 255 + 1]
|
||||
a = [(b"OpusHead" + bytes(11), 0)] + [(bytes(rnd.randrange(256) for _ in range(n)), 100 * (i + 1))
|
||||
for i, n in enumerate(sizes)]
|
||||
b = [(b"\x7fFLAC" + bytes(40), 0)] + [(bytes(rnd.randrange(256) for _ in range(rnd.randrange(1, 900))), 50 * (i + 1))
|
||||
for i in range(60)]
|
||||
pa = mux_stream(0x1234ABCD, a, max_segs=255)
|
||||
pb = mux_stream(7, b, max_segs=17)
|
||||
out = pa[:1] + pb[:1] # bos pages first
|
||||
ra, rb = pa[1:], pb[1:]
|
||||
while ra or rb:
|
||||
if rb and (not ra or rnd.random() < 0.5):
|
||||
out.append(rb.pop(0))
|
||||
else:
|
||||
out.append(ra.pop(0))
|
||||
blob = bytearray()
|
||||
for k, pg in enumerate(out):
|
||||
if k == 5:
|
||||
blob += b"junkOggSjunk" + bytes(40)
|
||||
if k == 9: # a corrupt copy before the real page
|
||||
bad = bytearray(pg)
|
||||
bad[len(bad) // 2] ^= 0xFF
|
||||
blob += bad
|
||||
blob += pg
|
||||
blob += b"OggS\0trailing-truncated"
|
||||
cases.append(case("mux_edge", bytes(blob), "2 streams, lacing edges, junk, a corrupt page copy, truncated tail"))
|
||||
lost = [pg for pg in out if not (struct.unpack_from("<I", pg, 14)[0] == 7 and struct.unpack_from("<I", pg, 18)[0] == 5)]
|
||||
cases.append(case("mux_lost", b"".join(lost), "mux_edge without page 5 of serial 7"))
|
||||
ctx.emit("ogg_cases", cases)
|
||||
@@ -0,0 +1,66 @@
|
||||
# Opus fixtures (tools/fixtures.py): audio/opus. Ported from opus-luau tools/fixtures.sh.
|
||||
# tests/gen/opus_<name>.luau { name, data = the .opus file, ref = opusdec --float output (f32 LE interleaved) }
|
||||
# Sources: 48 kHz signals synthesised by ffmpeg (aevalsrc: tones, vibrato, chirps, noise bursts, clicks, a speech-like
|
||||
# harmonic source with moving formants), encoded by opusenc (CELT-only frame sizes / bitrates, forced SILK NB / MB /
|
||||
# WB, hybrid SWB / FB, a 5.1 mapping-family-1 stream, a long tagged file) and ffmpeg libopus (CBR, voip, lowdelay).
|
||||
import os, tempfile
|
||||
|
||||
MUSIC = ("0.25*sin(2*PI*(220+30*sin(2*PI*5*t))*t)+0.15*sin(2*PI*(100*t+700*t*t))+0.3*exp(-25*mod(t,0.375))*(random(0)-0.5)"
|
||||
"+0.4*lt(mod(t,0.5),0.0006)")
|
||||
MUSIC2 = ("0.2*sin(2*PI*330*t)+0.1*sin(2*PI*1320*t)*lt(mod(t,0.25),0.125)+0.25*exp(-40*mod(t+0.1,0.375))*(random(1)-0.5)"
|
||||
"+0.12*sin(2*PI*(3000-2500*t/3)*t)")
|
||||
F0 = "(120+40*sin(2*PI*0.7*t))"
|
||||
FM = "(600+300*sin(2*PI*1.3*t))"
|
||||
SPEECH = ("(0.5+0.5*sin(2*PI*2.1*t))*(sin(2*PI*{f0}*t)*0.3+sin(2*PI*2*{f0}*t)*0.25+sin(2*PI*3*{f0}*t)*0.2*exp(-abs(3*{f0}-{fm})/400)"
|
||||
"+sin(2*PI*5*{f0}*t)*0.15*exp(-abs(5*{f0}-{fm}*2)/400)+sin(2*PI*8*{f0}*t)*0.08+0.02*(random(2)-0.5))").format(f0=F0, fm=FM)
|
||||
SOURCES = {
|
||||
"music": (MUSIC + "|" + MUSIC2, 3),
|
||||
"mono": (MUSIC + "+0.5*" + SPEECH, 3),
|
||||
"speech": (SPEECH, 3),
|
||||
"speechst": (SPEECH + "|0.7*" + SPEECH + "+0.1*sin(2*PI*440*t)", 3),
|
||||
"mixst": (MUSIC + "+" + SPEECH + "|" + MUSIC2 + "+0.6*" + SPEECH, 3),
|
||||
"surround": (MUSIC + "|" + MUSIC2 + "|" + SPEECH + "|0.3*sin(2*PI*55*t)|0.5*" + MUSIC2 + "|0.5*" + MUSIC, 2),
|
||||
"long": (MUSIC + "+0.3*" + SPEECH + "|" + MUSIC2 + "+0.3*" + SPEECH, 12),
|
||||
}
|
||||
# name, source, encoder ("enc" = opusenc, "ff" = ffmpeg libopus), arguments
|
||||
CASES = [
|
||||
("celt_st_128", "music", "enc", ["--music", "--bitrate", "128"]),
|
||||
("celt_st_32", "music", "enc", ["--music", "--bitrate", "32"]),
|
||||
("celt_st_64", "mixst", "enc", ["--music", "--bitrate", "64"]),
|
||||
("celt_st_256", "music", "enc", ["--music", "--bitrate", "256"]),
|
||||
("celt_mono_64", "mono", "enc", ["--music", "--bitrate", "64"]),
|
||||
("celt_fs2_5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "2.5"]),
|
||||
("celt_fs5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "5"]),
|
||||
("celt_fs10", "mixst", "enc", ["--music", "--bitrate", "96", "--framesize", "10"]),
|
||||
("celt_fs40", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "40"]),
|
||||
("celt_fs60", "mixst", "enc", ["--music", "--bitrate", "160", "--framesize", "60"]),
|
||||
("silk_nb", "speech", "enc", ["--speech", "--bitrate", "8", "--max-delay", "0"]),
|
||||
("silk_mb", "speech", "enc", ["--speech", "--bitrate", "12", "--set-ctl-int", "4008=1102"]),
|
||||
("silk_wb", "speech", "enc", ["--speech", "--bitrate", "20", "--framesize", "40", "--set-ctl-int", "4008=1103"]),
|
||||
("silk_wb_st", "speechst", "enc", ["--speech", "--bitrate", "28", "--framesize", "60", "--set-ctl-int", "4008=1103"]),
|
||||
("silk_nb_st", "speechst", "enc", ["--speech", "--bitrate", "12", "--framesize", "10", "--set-ctl-int", "4008=1101"]),
|
||||
("hybrid_swb", "speech", "enc", ["--speech", "--bitrate", "24"]),
|
||||
("hybrid_fb", "speech", "enc", ["--speech", "--bitrate", "36", "--framesize", "10"]),
|
||||
("hybrid_st", "speechst", "enc", ["--speech", "--bitrate", "40"]),
|
||||
("mix_st_24", "mixst", "enc", ["--bitrate", "24"]),
|
||||
("surround51", "surround", "enc", ["--bitrate", "192"]),
|
||||
("long_128", "long", "enc", ["--bitrate", "128", "--comment", "TITLE=Long Test", "--artist", "opus-luau"]),
|
||||
("ff_cbr", "mixst", "ff", ["-b:a", "96k", "-vbr", "off"]),
|
||||
("ff_voip", "speechst", "ff", ["-b:a", "32k", "-application", "voip"]),
|
||||
("ff_lowdelay", "music", "ff", ["-b:a", "128k", "-application", "lowdelay", "-frame_duration", "5"]),
|
||||
]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp()
|
||||
for name, (expr, secs) in SOURCES.items():
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='%s':s=48000:d=%d" % (expr, secs),
|
||||
"-c:a", "pcm_s16le", os.path.join(tmp, name + ".wav")])
|
||||
for name, src, enc, args in CASES:
|
||||
wav, opus, ref = (os.path.join(tmp, x) for x in (src + ".wav", name + ".opus", name + ".f32"))
|
||||
if enc == "enc":
|
||||
ctx.nix("opus-tools", ["opusenc", "--quiet"] + args + [wav, opus])
|
||||
else:
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-i", wav, "-c:a", "libopus"] + args + [opus])
|
||||
ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", opus, ref])
|
||||
ctx.emit("opus_" + name, {"name": name, "data": open(opus, "rb").read(), "ref": open(ref, "rb").read()})
|
||||
@@ -0,0 +1,66 @@
|
||||
# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text.
|
||||
# tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986)
|
||||
# tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD)
|
||||
# tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via
|
||||
# xml.etree.ElementTree) with the entries they hold: { url, title?, duration? }
|
||||
import random, urllib.parse, xml.etree.ElementTree as ET
|
||||
|
||||
BASES = ["http://a/b/c/d;p?q", "https://host.example/lists/m.m3u8", "http://h/x/", "https://cdn.example/a/b/c/list.pls",
|
||||
"http://a"]
|
||||
SEGS = ["g", "h", "..", ".", "music", "a b", "x.mp3", "s;p", "%41", "ü"]
|
||||
|
||||
|
||||
def ref(rng):
|
||||
parts = [rng.choice(SEGS) for _ in range(rng.randrange(1, 5))]
|
||||
r = "/".join(parts)
|
||||
k = rng.randrange(6)
|
||||
if k == 0:
|
||||
r = "/" + r
|
||||
elif k == 1:
|
||||
r = "./" + r
|
||||
if rng.random() < 0.2:
|
||||
r += "?y=" + rng.choice(SEGS)
|
||||
if rng.random() < 0.15:
|
||||
r += "#" + rng.choice(["s", "f/../x"])
|
||||
return r
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(8)
|
||||
cases = []
|
||||
for _ in range(400):
|
||||
base = rng.choice(BASES)
|
||||
r = ref(rng)
|
||||
if " " in r or "ü" in r or (base == "http://a" and r.startswith(".")):
|
||||
continue # raw spaces / UTF-8 are encoded first by the playlist code; urljoin keeps a leading "." here
|
||||
cases.append([r, base, urllib.parse.urljoin(base, r)])
|
||||
ctx.emit("playlist_url", cases)
|
||||
ctx.emit("playlist_cp1252", [[b, bytes([b]).decode("cp1252", errors="replace")] for b in range(0x80, 0x100)])
|
||||
|
||||
out = []
|
||||
for n in range(12):
|
||||
ents = []
|
||||
for i in range(rng.randrange(1, 9)):
|
||||
e = {"url": "http://media.example/%d/track%d.mp3" % (n, i)}
|
||||
if rng.random() < 0.8:
|
||||
e["title"] = rng.choice(["Song %d" % i, "Björk – Jóga", "A, B & C", "x <y> \"z\""])
|
||||
if rng.random() < 0.7:
|
||||
e["duration"] = rng.randrange(1, 600)
|
||||
ents.append(e)
|
||||
m3u = "#EXTM3U\n" + "".join(("#EXTINF:%d,%s\n" % (e.get("duration", -1), e.get("title", "")) if ("title" in e or "duration" in e) else "") + e["url"] + "\n" for e in ents)
|
||||
pls = "[playlist]\n" + "".join("File%d=%s\n" % (i + 1, e["url"]) + ("Title%d=%s\n" % (i + 1, e["title"]) if "title" in e else "") + ("Length%d=%d\n" % (i + 1, e.get("duration", -1))) for i, e in enumerate(ents)) + "NumberOfEntries=%d\nVersion=2\n" % len(ents)
|
||||
root = ET.Element("playlist", {"version": "1", "xmlns": "http://xspf.org/ns/0/"})
|
||||
ET.SubElement(root, "title").text = "List %d" % n
|
||||
tl = ET.SubElement(root, "trackList")
|
||||
for e in ents:
|
||||
t = ET.SubElement(tl, "track")
|
||||
ET.SubElement(t, "location").text = e["url"]
|
||||
if "title" in e:
|
||||
ET.SubElement(t, "title").text = e["title"]
|
||||
if "duration" in e:
|
||||
ET.SubElement(t, "duration").text = str(e["duration"] * 1000)
|
||||
xspf = ET.tostring(root, encoding="UTF-8", xml_declaration=True)
|
||||
expect = [{k: v for k, v in e.items()} for e in ents]
|
||||
# M3U loses a title when there is no EXTINF text; PLS keeps only what it wrote
|
||||
out.append({"name": "list%d" % n, "m3u": m3u, "pls": pls, "xspf": xspf, "title": "List %d" % n, "entries": expect})
|
||||
ctx.emit("playlist_cases", out)
|
||||
@@ -0,0 +1,199 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,174 @@
|
||||
# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs,
|
||||
# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the
|
||||
# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus
|
||||
# random mutations) with expat's verdict.
|
||||
# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same)
|
||||
# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it
|
||||
# tests/gen/xml_bench.luau { text } (~1 MB)
|
||||
import xml.etree.ElementTree as ET
|
||||
from xml.parsers import expat
|
||||
|
||||
NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")]
|
||||
TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"]
|
||||
TXT = "ab <>&\"' é中\U0001f600\t\n ]]"
|
||||
|
||||
|
||||
def s(x):
|
||||
x = x or ""
|
||||
b = x.encode("utf-8", "surrogatepass")
|
||||
return b"%d:" % len(b) + b
|
||||
|
||||
|
||||
def canon(e):
|
||||
out = b"(" + s(e.tag)
|
||||
for k in sorted(e.attrib):
|
||||
out += b"|" + s(k) + b"=" + s(e.attrib[k])
|
||||
out += b"|t" + s(e.text)
|
||||
for c in e:
|
||||
out += canon(c)
|
||||
return out + b")t" + s(e.tail)
|
||||
|
||||
|
||||
def esc_text(t):
|
||||
return t.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
|
||||
def esc_attr(t, q):
|
||||
t = t.replace("&", "&").replace("<", "<")
|
||||
return t.replace(q, """ if q == '"' else "'")
|
||||
|
||||
|
||||
def rand_text(rng):
|
||||
return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10)))
|
||||
|
||||
|
||||
def gen_elem(rng, depth, declared):
|
||||
prefix = rng.choice([p for p in declared])
|
||||
local = rng.choice(TAGS)
|
||||
name = (prefix + ":" + local) if prefix else local
|
||||
attrs = []
|
||||
newdecl = set(declared)
|
||||
if depth > 0 and rng.random() < 0.15:
|
||||
p, uri = rng.choice(NS[1:])
|
||||
attrs.append(("xmlns:" + p, uri))
|
||||
newdecl.add(p)
|
||||
if rng.random() < 0.1:
|
||||
attrs.append(("xmlns", "urn:default%d" % rng.randrange(3)))
|
||||
used = set(a for a, _ in attrs)
|
||||
for _ in range(rng.randrange(0, 4)):
|
||||
an = rng.choice(["id", "k", "v-1", "é", "x.y"])
|
||||
if rng.random() < 0.2 and len(newdecl) > 1:
|
||||
an = rng.choice([p for p in newdecl if p]) + ":" + an
|
||||
if an in used:
|
||||
continue
|
||||
used.add(an)
|
||||
attrs.append((an, rand_text(rng)))
|
||||
parts = ["<" + name]
|
||||
for k, v in attrs:
|
||||
q = rng.choice("\"'")
|
||||
parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q))
|
||||
if depth > 4 or rng.random() < 0.15:
|
||||
parts.append(rng.choice(["/>", " />"]))
|
||||
return "".join(parts)
|
||||
parts.append(">")
|
||||
for _ in range(rng.randrange(0, 5)):
|
||||
r = rng.random()
|
||||
if r < 0.35:
|
||||
parts.append(esc_text(rand_text(rng)))
|
||||
elif r < 0.45:
|
||||
parts.append("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>")
|
||||
elif r < 0.5:
|
||||
parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->")
|
||||
elif r < 0.53:
|
||||
parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>")
|
||||
elif r < 0.58:
|
||||
parts.append(rng.choice(["&ent;", "é", "😀", "&", "<", " "]))
|
||||
else:
|
||||
parts.append(gen_elem(rng, depth + 1, newdecl))
|
||||
parts.append("</%s>" % name)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def gen_doc(rng):
|
||||
head = ""
|
||||
if rng.random() < 0.5:
|
||||
head += '<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38; text <">\n <!-- a comment -->\n]>\n'
|
||||
if rng.random() < 0.3:
|
||||
head += "<!-- prolog comment -->\n"
|
||||
declared = {""}
|
||||
body = gen_elem(rng, 0, declared)
|
||||
# the root must declare every prefix it may use: declare all at the root
|
||||
root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:])
|
||||
i = body.index(">") if not body.startswith("<") else 0
|
||||
name_end = 1
|
||||
while body[name_end] not in " />":
|
||||
name_end += 1
|
||||
body = body[:name_end] + " " + root_decl + body[name_end:]
|
||||
return head + body + ("\n" if rng.random() < 0.5 else "")
|
||||
|
||||
|
||||
def expat_ok(data):
|
||||
p = expat.ParserCreate()
|
||||
try:
|
||||
p.Parse(data, True)
|
||||
return True
|
||||
except Exception: # ExpatError, or LookupError for an unknown encoding name
|
||||
return False
|
||||
|
||||
|
||||
WF = [
|
||||
"<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>",
|
||||
"<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>�</a>", "<a>�</a>", "<a>�</a>", "<a>& </a>",
|
||||
"<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>",
|
||||
"<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>",
|
||||
"<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>",
|
||||
"<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='<A'/>",
|
||||
"<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >",
|
||||
"<a>é\U0001f600</a>", "<a>&<>"'</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>",
|
||||
"<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ",
|
||||
]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(11)
|
||||
docs = []
|
||||
for k in range(250):
|
||||
text = gen_doc(rng)
|
||||
root = ET.fromstring(text.encode("utf-8"))
|
||||
docs.append({"data": text.encode("utf-8"), "canon": canon(root)})
|
||||
# other encodings: UTF-16 (BOM, both byte orders) and Latin-1
|
||||
for k in range(10):
|
||||
text = gen_doc(rng)
|
||||
body = text.split("?>", 1)[1] if text.startswith("<?xml") else text
|
||||
c = canon(ET.fromstring(text.encode("utf-8")))
|
||||
docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c})
|
||||
docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c})
|
||||
for k in range(10):
|
||||
text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ 中</r>"
|
||||
data = text.encode("latin-1")
|
||||
docs.append({"data": data, "canon": canon(ET.fromstring(data))})
|
||||
ctx.emit("xml_docs", docs)
|
||||
|
||||
wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF]
|
||||
# mutations of valid documents: delete / duplicate / replace one markup character
|
||||
for k in range(400):
|
||||
text = gen_doc(rng).encode("utf-8")
|
||||
b = bytearray(text)
|
||||
for _ in range(rng.randrange(1, 3)):
|
||||
pos = rng.randrange(len(b))
|
||||
op = rng.randrange(3)
|
||||
ch = rng.choice(b"<>/&;='\"![]-? ")
|
||||
if op == 0:
|
||||
del b[pos]
|
||||
elif op == 1:
|
||||
b.insert(pos, ch)
|
||||
else:
|
||||
b[pos] = ch
|
||||
wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))})
|
||||
ctx.emit("xml_wf", wf)
|
||||
|
||||
parts = []
|
||||
while sum(map(len, parts)) < 1_000_000:
|
||||
parts.append(gen_elem(rng, 1, {""}))
|
||||
ctx.emit("xml_bench", {"text": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"})
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user