"""A minimal PNG reader for MAME's snapshots (8-bit RGB or RGBA, not interlaced). Standard library only, so the comparison also runs on PyPy without Pillow. """ from __future__ import annotations import struct import zlib def read_png(path) -> tuple[int, int, list[list[tuple[int, int, int]]]]: """(width, height, rows of (r, g, b)).""" data = open(path, "rb").read() if data[:8] != b"\x89PNG\r\n\x1a\n": raise ValueError(f"{path}: not a PNG") pos = 8 idat = b"" width = height = depth = colour = interlace = 0 while pos < len(data): (length,) = struct.unpack(">I", data[pos : pos + 4]) kind = data[pos + 4 : pos + 8] body = data[pos + 8 : pos + 8 + length] pos += 12 + length if kind == b"IHDR": width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", body) elif kind == b"IDAT": idat += body elif kind == b"IEND": break if depth != 8 or colour not in (2, 6) or interlace: raise ValueError(f"{path}: unsupported PNG (depth {depth}, colour type {colour})") channels = 3 if colour == 2 else 4 raw = zlib.decompress(idat) stride = width * channels rows: list[list[tuple[int, int, int]]] = [] previous = bytearray(stride) p = 0 for _ in range(height): kind = raw[p] line = bytearray(raw[p + 1 : p + 1 + stride]) p += 1 + stride for i in range(stride): left = line[i - channels] if i >= channels else 0 up = previous[i] corner = previous[i - channels] if i >= channels else 0 if kind == 1: line[i] = (line[i] + left) & 0xFF elif kind == 2: line[i] = (line[i] + up) & 0xFF elif kind == 3: line[i] = (line[i] + ((left + up) >> 1)) & 0xFF elif kind == 4: estimate = left + up - corner pa, pb, pc = abs(estimate - left), abs(estimate - up), abs(estimate - corner) if pa <= pb and pa <= pc: predictor = left elif pb <= pc: predictor = up else: predictor = corner line[i] = (line[i] + predictor) & 0xFF rows.append([tuple(line[x * channels : x * channels + 3]) for x in range(width)]) previous = line return width, height, rows