formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)
This commit is contained in:
commit
cdcb5b0b77
226 files changed
+8409
No files matched your search
@@ -0,0 +1,55 @@
|
||||
# Reference decodes of the PngSuite (run once, the output is committed; from png-luau tools/png_reference.py):
|
||||
# nix shell --impure --expr 'with import <nixpkgs> {}; python3.withPackages (p: [p.pypng p.pillow])' \
|
||||
# -c python3 -I tools/fixtures/_png_reference.py
|
||||
# Writes tests/fixtures/pngsuite_ref.txt: "<file> <width> <height> <crc32 of RGBA8 pixels>" per image, or
|
||||
# "<file> corrupt" for the suite's deliberately broken x* files. Pixels come from pypng (pure Python, exact at every bit depth) as RGBA,
|
||||
# scaled to 8 bits the way png-luau does: 16-bit samples keep the high byte, 1/2/4-bit samples are scaled by
|
||||
# 255 / (2^depth - 1). Pillow cross-checks every image without 16-bit samples.
|
||||
import os, sys, zlib
|
||||
import png
|
||||
from PIL import Image
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SUITE = os.path.join(ROOT, "tests", "fixtures", "pngsuite")
|
||||
|
||||
def rgba8(path):
|
||||
r = png.Reader(filename=path)
|
||||
w, h, rows, info = r.asRGBA()
|
||||
bd = info["bitdepth"]
|
||||
out = bytearray()
|
||||
for row in rows:
|
||||
if bd == 16:
|
||||
out += bytes(v >> 8 for v in row)
|
||||
elif bd == 8:
|
||||
out += bytes(row)
|
||||
else:
|
||||
m = (1 << bd) - 1
|
||||
out += bytes(v * 255 // m for v in row)
|
||||
return w, h, bytes(out), bd
|
||||
|
||||
lines, agree, checked = [], 0, 0
|
||||
for name in sorted(os.listdir(SUITE)):
|
||||
if not name.endswith(".png"):
|
||||
continue
|
||||
path = os.path.join(SUITE, name)
|
||||
if name.startswith("x"):
|
||||
lines.append("%s corrupt" % name) # the suite's deliberately corrupt files (x*: bad signature, CRC, ...)
|
||||
continue
|
||||
try:
|
||||
w, h, px, bd = rgba8(path)
|
||||
except Exception as e:
|
||||
lines.append("%s error" % name)
|
||||
continue
|
||||
lines.append("%s %d %d %08x" % (name, w, h, zlib.crc32(px)))
|
||||
with open(path, "rb") as f:
|
||||
raw = f.read()
|
||||
if bd != 16 and b"sBIT" not in raw:
|
||||
checked += 1
|
||||
im = Image.open(path).convert("RGBA")
|
||||
if im.tobytes() == px:
|
||||
agree += 1
|
||||
else:
|
||||
print("pillow disagrees:", name, file=sys.stderr)
|
||||
with open(os.path.join(ROOT, "tests", "fixtures", "pngsuite_ref.txt"), "w") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
print("%d images, %d rejected; pillow agrees on %d of %d checked" % (len(lines), sum(l.endswith(" error") for l in lines), agree, checked))
|
||||
@@ -0,0 +1,124 @@
|
||||
# Deflate fixtures (tools/fixtures.py): deterministic corpora compressed with Python's zlib at every level and
|
||||
# strategy, raw / zlib / gzip framing, small windows, flushes, gzip headers and multi-member gzip; plus a 6 MB bench
|
||||
# corpus. Ported from deflate-luau tools/fixtures.py. Reads Webamp skins (zips of BMPs) from $SKINS_DIR as data only,
|
||||
# if present (the corpus is smaller without them; the tests do not depend on it).
|
||||
# tests/gen/deflate.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data } } }
|
||||
# tests/gen/deflate_bench.luau { size, crc, zlib, gzip }
|
||||
import gzip, os, random, zipfile, zlib
|
||||
|
||||
SKINS = os.environ.get("SKINS_DIR", "/tmp/wa-ref/webamp/packages/webamp-demo/skins")
|
||||
|
||||
|
||||
def text_corpus(limit):
|
||||
# Python's own stdlib sources: real text, deterministic for a given Python
|
||||
base = os.path.dirname(os.__file__)
|
||||
out = bytearray()
|
||||
for name in sorted(os.listdir(base)):
|
||||
if name.endswith(".py"):
|
||||
with open(os.path.join(base, name), "rb") as f:
|
||||
out += f.read()
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return bytes(out[:limit])
|
||||
|
||||
|
||||
def skin_bmps(limit):
|
||||
out = bytearray()
|
||||
if os.path.isdir(SKINS):
|
||||
for name in sorted(os.listdir(SKINS)):
|
||||
if name.lower().endswith(".wsz"):
|
||||
with zipfile.ZipFile(os.path.join(SKINS, name)) as z:
|
||||
for i in z.infolist():
|
||||
if i.filename.lower().endswith(".bmp"):
|
||||
out += z.read(i)
|
||||
if len(out) >= limit:
|
||||
return bytes(out[:limit])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(1)
|
||||
def text_corpus(limit):
|
||||
# Python's own stdlib sources: real text, deterministic for a given Python
|
||||
base = os.path.dirname(os.__file__)
|
||||
out = bytearray()
|
||||
for name in sorted(os.listdir(base)):
|
||||
if name.endswith(".py"):
|
||||
with open(os.path.join(base, name), "rb") as f:
|
||||
out += f.read()
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return bytes(out[:limit])
|
||||
|
||||
def skin_bmps(limit):
|
||||
out = bytearray()
|
||||
if os.path.isdir(SKINS):
|
||||
for name in sorted(os.listdir(SKINS)):
|
||||
if name.lower().endswith(".wsz"):
|
||||
with zipfile.ZipFile(os.path.join(SKINS, name)) as z:
|
||||
for i in z.infolist():
|
||||
if i.filename.lower().endswith(".bmp"):
|
||||
out += z.read(i)
|
||||
if len(out) >= limit:
|
||||
return bytes(out[:limit])
|
||||
return bytes(out)
|
||||
|
||||
corpora = {
|
||||
"empty": b"",
|
||||
"one": b"a",
|
||||
"text": text_corpus(160000),
|
||||
"random": rng.randbytes(40000),
|
||||
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
|
||||
"far": (lambda r: r + rng.randbytes(20000) + r)(rng.randbytes(12000)),
|
||||
"bmp": skin_bmps(120000),
|
||||
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)),
|
||||
}
|
||||
|
||||
cases = [] # (name, kind, corpus, compressed)
|
||||
for cname, data in corpora.items():
|
||||
for level in range(10):
|
||||
cases.append(("%s/zlib%d" % (cname, level), "zlib", cname, zlib.compress(data, level)))
|
||||
for sname, strat in (("fixed", zlib.Z_FIXED), ("huffman", zlib.Z_HUFFMAN_ONLY), ("rle", zlib.Z_RLE), ("filtered", zlib.Z_FILTERED)):
|
||||
c = zlib.compressobj(6, zlib.DEFLATED, -15, 8, strat)
|
||||
cases.append(("%s/raw-%s" % (cname, sname), "raw", cname, c.compress(data) + c.flush()))
|
||||
for wbits, mem in ((-9, 1), (-12, 9)):
|
||||
c = zlib.compressobj(9, zlib.DEFLATED, wbits, mem)
|
||||
cases.append(("%s/raw-w%d-m%d" % (cname, -wbits, mem), "raw", cname, c.compress(data) + c.flush()))
|
||||
# flushes in the middle: empty stored blocks, byte alignment, several block types in one stream
|
||||
c = zlib.compressobj(5, zlib.DEFLATED, -15)
|
||||
parts = []
|
||||
step = max(1, len(data) // 5)
|
||||
for i in range(0, len(data), step):
|
||||
parts.append(c.compress(data[i:i + step]))
|
||||
parts.append(c.flush(zlib.Z_SYNC_FLUSH if (i // step) % 2 == 0 else zlib.Z_FULL_FLUSH))
|
||||
parts.append(c.flush())
|
||||
cases.append(("%s/raw-flushes" % cname, "raw", cname, b"".join(parts)))
|
||||
cases.append(("%s/gzip" % cname, "gzip", cname, gzip.compress(data, 6, mtime=0)))
|
||||
|
||||
# gzip with a file name / comment / extra / header CRC (written by hand), and multi-member
|
||||
def gzip_full(data):
|
||||
hdr = bytearray(b"\x1f\x8b\x08\x1e\0\0\0\0\x00\x03") # FEXTRA | FNAME | FCOMMENT | FHCRC
|
||||
hdr += (4).to_bytes(2, "little") + b"ab\x01\x00"
|
||||
hdr += b"name.txt\0" + b"a comment\0"
|
||||
hdr += (zlib.crc32(bytes(hdr)) & 0xFFFF).to_bytes(2, "little")
|
||||
c = zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
body = c.compress(data) + c.flush()
|
||||
return bytes(hdr) + body + zlib.crc32(data).to_bytes(4, "little") + (len(data) & 0xFFFFFFFF).to_bytes(4, "little")
|
||||
corpora["multi"] = corpora["text"][:50000] + corpora["runs"] + b"" + corpora["one"]
|
||||
multi = gzip.compress(corpora["text"][:50000], 9, mtime=0) + gzip_full(corpora["runs"]) + gzip.compress(b"", mtime=0) + gzip.compress(b"a", 1, mtime=0) + b"\0" * 7
|
||||
cases.append(("multi/gzip-members", "gzip", "multi", multi))
|
||||
cases.append(("runs/gzip-fullheader", "gzip", "runs", gzip_full(corpora["runs"])))
|
||||
|
||||
|
||||
ctx.emit("deflate", {
|
||||
"corpora": corpora,
|
||||
"cases": [{"name": n, "kind": k, "corpus": c, "data": d} for n, k, c, d in cases],
|
||||
})
|
||||
# bench corpus: ~6 MB of text and BMPs, zlib level 6
|
||||
bench = (corpora["text"] + corpora["bmp"]) * 1
|
||||
while len(bench) < 6_000_000:
|
||||
bench += corpora["text"] + skin_bmps(600000) + corpora["binary"]
|
||||
bench = bench[:6_000_000]
|
||||
|
||||
ctx.emit("deflate_bench", {"size": len(bench), "crc": zlib.crc32(bench), "zlib": zlib.compress(bench, 6),
|
||||
"gzip": gzip.compress(bench, 6, mtime=0)})
|
||||
@@ -0,0 +1,165 @@
|
||||
# PNG fixtures (tools/fixtures.py). Ported from png-luau tools/fixtures.py.
|
||||
# tests/gen/png_suite.luau the PngSuite (tests/fixtures/pngsuite, licence in licenses/) with the committed reference
|
||||
# decodes (tests/fixtures/pngsuite_ref.txt, from pypng: tools/fixtures/_png_reference.py)
|
||||
# tests/gen/png_gen.luau images written by a small PNG writer here: every colour type and bit depth, plain and
|
||||
# Adam7, odd sizes, every filter, split IDATs, tRNS keys; with the CRC-32 of the RGBA8 pixels
|
||||
# tests/gen/png_bench.luau 1024 x 768 RGBA / RGB / Adam7 / palette images for tools/bench.luau
|
||||
import os, random, struct, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/pngsuite", "tests/fixtures/pngsuite_ref.txt"]
|
||||
|
||||
# --- a small PNG writer
|
||||
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
PASSES = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]
|
||||
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
|
||||
def pack_row(samples, depth):
|
||||
if depth == 8:
|
||||
return bytes(samples)
|
||||
if depth == 16:
|
||||
return b"".join(struct.pack(">H", s) for s in samples)
|
||||
out, acc, nb = bytearray(), 0, 0
|
||||
for s in samples:
|
||||
acc = (acc << depth) | s
|
||||
nb += depth
|
||||
if nb == 8:
|
||||
out.append(acc)
|
||||
acc, nb = 0, 0
|
||||
if nb:
|
||||
out.append(acc << (8 - nb))
|
||||
return bytes(out)
|
||||
|
||||
def paeth(a, b, c):
|
||||
p = a + b - c
|
||||
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
||||
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
|
||||
|
||||
def filt(row, prev, bpp, ft):
|
||||
out = bytearray([ft])
|
||||
for i, x in enumerate(row):
|
||||
a = row[i - bpp] if i >= bpp else 0
|
||||
b = prev[i] if prev else 0
|
||||
c = prev[i - bpp] if prev and i >= bpp else 0
|
||||
pred = (0, a, b, (a + b) // 2, paeth(a, b, c))[ft]
|
||||
out.append((x - pred) & 255)
|
||||
return out
|
||||
|
||||
def encode(w, h, ct, depth, px, interlace, rng, plte=None, trns=None, filters=None, idat_split=1, level=6):
|
||||
# px[y][x] = tuple of samples at depth
|
||||
ch = CHANNELS[ct]
|
||||
bpp = max(1, ch * depth // 8)
|
||||
raw = bytearray()
|
||||
passes = PASSES if interlace else [(0, 0, 1, 1)]
|
||||
for (x0, y0, dx, dy) in passes:
|
||||
prev = None
|
||||
for y in range(y0, h, dy):
|
||||
xs = range(x0, w, dx)
|
||||
if not len(xs):
|
||||
break
|
||||
row = pack_row([s for x in xs for s in px[y][x]], depth)
|
||||
ft = filters(rng) if filters else rng.randrange(5)
|
||||
raw += filt(row, prev, bpp, ft)
|
||||
prev = row
|
||||
z = zlib.compress(bytes(raw), level)
|
||||
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, depth, ct, 0, 0, interlace))
|
||||
out += chunk(b"tEXt", b"Comment\0made by formats-luau tools/fixtures/png.py")
|
||||
if plte:
|
||||
out += chunk(b"PLTE", b"".join(bytes(c[:3]) for c in plte))
|
||||
if trns is not None:
|
||||
out += chunk(b"tRNS", trns)
|
||||
step = max(1, -(-len(z) // idat_split))
|
||||
for i in range(0, len(z), step):
|
||||
out += chunk(b"IDAT", z[i:i + step])
|
||||
return out + chunk(b"IEND", b"")
|
||||
|
||||
def rgba8(ct, depth, s, plte=None, palpha=None, key=None):
|
||||
def sc(v):
|
||||
return v >> 8 if depth == 16 else (v if depth == 8 else v * 255 // ((1 << depth) - 1))
|
||||
if ct == 3:
|
||||
c = plte[s[0]] if s[0] < len(plte) else (0, 0, 0)
|
||||
a = palpha[s[0]] if palpha and s[0] < len(palpha) else 255
|
||||
return bytes((c[0], c[1], c[2], a))
|
||||
if ct == 0:
|
||||
return bytes((sc(s[0]),) * 3 + (0 if key == s[0] else 255,))
|
||||
if ct == 2:
|
||||
return bytes((sc(s[0]), sc(s[1]), sc(s[2]), 0 if key == tuple(s) else 255))
|
||||
if ct == 4:
|
||||
return bytes((sc(s[0]),) * 3 + (sc(s[1]),))
|
||||
return bytes(sc(v) for v in s)
|
||||
|
||||
def image(w, h, ct, depth, rng, photo=False):
|
||||
m = (1 << depth) - 1
|
||||
ch = CHANNELS[ct]
|
||||
px = []
|
||||
for y in range(h):
|
||||
row = []
|
||||
for x in range(w):
|
||||
if photo:
|
||||
base = [(x * 255 // max(1, w - 1) + rng.randrange(-6, 7)) & 255, (y * 255 // max(1, h - 1)) & 255, ((x + y) // 3 + rng.randrange(-3, 4)) & 255, 255 - ((x ^ y) & 63)]
|
||||
row.append(tuple(v * m // 255 for v in base[:ch]) if ct != 3 else (base[0] * m // 255,))
|
||||
else:
|
||||
row.append(tuple(rng.randrange(m + 1) if rng.random() < 0.5 else (x * 7 + y * 3 + k * 50) % (m + 1) for k in range(ch)))
|
||||
px.append(row)
|
||||
return px
|
||||
|
||||
def make(w, h, ct, depth, interlace, rng, photo=False, **kw):
|
||||
px = image(w, h, ct, depth, rng, photo)
|
||||
want_key = kw.pop("key", True)
|
||||
plte = palpha = trns = key = None
|
||||
if ct == 3:
|
||||
n = min(1 << depth, 256) - (1 if depth > 1 else 0) # leave an index past the palette now and then
|
||||
plte = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(n)]
|
||||
palpha = [rng.randrange(256) for _ in range(rng.randrange(n + 1))]
|
||||
trns = bytes(palpha) if palpha else None
|
||||
elif ct in (0, 2) and want_key:
|
||||
key = px[h // 2][w // 2] if ct == 2 else px[h // 2][w // 2][0]
|
||||
trns = b"".join(struct.pack(">H", v) for v in (key if ct == 2 else (key,)))
|
||||
key = tuple(key) if ct == 2 else key
|
||||
data = encode(w, h, ct, depth, px, interlace, rng, plte=plte, trns=trns, **kw)
|
||||
exp = b"".join(rgba8(ct, depth, px[y][x], plte, palpha, key) for y in range(h) for x in range(w))
|
||||
return data, exp
|
||||
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
suite = []
|
||||
for line in open(os.path.join(ctx.root, "tests", "fixtures", "pngsuite_ref.txt")).read().split("\n"):
|
||||
if not line:
|
||||
continue
|
||||
parts = line.split()
|
||||
data = ctx.read(os.path.join("tests", "fixtures", "pngsuite", parts[0]))
|
||||
if parts[1] == "corrupt":
|
||||
suite.append({"name": parts[0], "corrupt": True, "data": data})
|
||||
else:
|
||||
suite.append({"name": parts[0], "width": int(parts[1]), "height": int(parts[2]), "crc": int(parts[3], 16), "data": data})
|
||||
ctx.emit("png_suite", suite)
|
||||
|
||||
rng = random.Random(5)
|
||||
cases = []
|
||||
for ct, depths in ((0, (1, 2, 4, 8, 16)), (2, (8, 16)), (3, (1, 2, 4, 8)), (4, (8, 16)), (6, (8, 16))):
|
||||
for depth in depths:
|
||||
for interlace in (0, 1):
|
||||
for (w, h) in ((1, 1), (3, 2), (13, 11), (37, 29)):
|
||||
data, exp = make(w, h, ct, depth, interlace, rng, idat_split=rng.choice((1, 1, 3)))
|
||||
cases.append(("ct%d-d%d-%s-%dx%d" % (ct, depth, "adam7" if interlace else "plain", w, h), w, h, data, exp))
|
||||
for ft in range(5): # one filter for the whole image
|
||||
data, exp = make(41, 23, 6, 8, 0, rng, filters=lambda r, ft=ft: ft)
|
||||
cases.append(("filter%d" % ft, 41, 23, data, exp))
|
||||
data, exp = make(41, 23, 0, 2, 1, rng, filters=lambda r, ft=ft: ft)
|
||||
cases.append(("filter%d-grey2-adam7" % ft, 41, 23, data, exp))
|
||||
data, exp = make(200, 150, 6, 8, 0, rng, photo=True, idat_split=40)
|
||||
cases.append(("photo-200x150-40idat", 200, 150, data, exp))
|
||||
data, exp = make(64, 64, 2, 8, 0, rng, key=False, level=0)
|
||||
cases.append(("stored-zlib", 64, 64, data, exp))
|
||||
|
||||
ctx.emit("png_gen", [{"name": n, "width": w, "height": h, "crc": zlib.crc32(exp), "data": d} for n, w, h, d, exp in cases])
|
||||
|
||||
# --- bench images (Paeth / up / sub mix, as encoders choose)
|
||||
bench = []
|
||||
for label, ct, interlace in (("rgba8", 6, 0), ("rgb8", 2, 0), ("rgba8-adam7", 6, 1), ("palette8", 3, 0)):
|
||||
data, exp = make(1024, 768, ct, 8, interlace, rng, photo=True, key=False, filters=lambda r: r.choice((1, 2, 4, 4)))
|
||||
bench.append((label, data, zlib.crc32(exp)))
|
||||
|
||||
ctx.emit("png_bench", [{"name": l, "width": 1024, "height": 768, "crc": c, "data": d} for l, d, c in bench])
|
||||
Reference in new issue
Block a user