135 lines
5.6 KiB
Python
135 lines
5.6 KiB
Python
# 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)
|