absorb: image/bmp (reader from bmp-luau b86aed6 + new encoder: 8 bpp paletted / 24 / 32 bpp, V4 alpha or BI_RGB); BMP Suite vs Pillow, encoder byte-exact vs Pillow
This commit is contained in:
1 parent
5bda4f8cbc
commit
bad0fce095
113 files changed
+1402
No files matched your search
@@ -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,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)
|
||||
Reference in new issue
Block a user