# 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("> 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("= 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("