# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie # SPDX-License-Identifier: MIT """Holds the encoders' output against libjpeg, libpng and ImageMagick. `zig build samples` writes a baseline and a progressive JPEG for each case in `tools/samples.zig`. The two carry identical coefficients and differ only in how they are spelled, so libjpeg must decode them to the *same bytes* --- not nearly the same, exactly the same. A tolerance here would hide the very thing worth checking, which is that two quite different coders agree. zig build samples python3 tools/check_samples.py zig-out/samples It is a check the Zig test suite cannot make. That suite checks this encoder against this decoder, which would agree with itself about a mistake they shared; this one asks the decoder almost every other program on the machine is using. """ import pathlib, shutil, subprocess, sys from PIL import Image def load(path): with Image.open(path) as im: im.load() return im.convert("RGB").tobytes(), im.size, bool(im.info.get("progressive")) def main(argv): if len(argv) != 2: print("usage: check_samples.py ", file=sys.stderr) return 2 directory = pathlib.Path(argv[1]) pairs = sorted(p for p in directory.glob("*-baseline.jpg")) if not pairs: print(f"no samples in {directory}", file=sys.stderr) return 1 failures = 0 for base_path in pairs: name = base_path.name.removesuffix("-baseline.jpg") prog_path = base_path.with_name(f"{name}-progressive.jpg") base, base_size, base_prog = load(base_path) prog, prog_size, prog_prog = load(prog_path) problems = [] if base_prog: problems.append("the baseline file says it is progressive") if not prog_prog: problems.append("the progressive file does not say it is progressive") if base_size != prog_size: problems.append(f"sizes differ: {base_size} against {prog_size}") elif base != prog: worst = max(abs(a - b) for a, b in zip(base, prog)) differing = sum(1 for a, b in zip(base, prog) if a != b) problems.append( f"{differing} of {len(base)} channels differ, worst by {worst}" ) if problems: failures += 1 for problem in problems: print(f"FAIL {name}: {problem}") else: print( f"ok {name}: {base_size[0]}x{base_size[1]}, " f"{base_path.stat().st_size} -> {prog_path.stat().st_size} bytes, identical" ) profiles, profile_failures = check_profiles(directory) tags, tag_failures = check_orientations(directory) pcx, pcx_failures = check_pcx(directory) profile_failures += tag_failures + pcx_failures print(f"\n{len(pairs) - failures} of {len(pairs)} pairs agree with libjpeg exactly") if profiles: print( f"{profiles - (profile_failures - tag_failures)} of {profiles} " f"embedded profiles come back byte for byte" ) if tags: print(f"{tags - tag_failures} of {tags} orientation tags read as written") if pcx: print(f"{pcx - pcx_failures} of {pcx} PCX readings as written") return 1 if failures or profile_failures else 0 def check_profiles(directory): """Every file beside an `.icc` sidecar must hand that profile back. This is the other thing the Zig tests cannot do. They check that this library reads back what this library wrote, which would agree with itself about a mistake; Pillow reads the profile with libjpeg and libpng, which is what everything else on the machine uses. """ checked = 0 failures = 0 for sidecar in sorted(directory.glob("*.icc")): want = sidecar.read_bytes() stem = sidecar.name.removesuffix(".icc") carriers = sorted( p for p in directory.iterdir() if p.name.startswith(stem) and p.suffix in (".jpg", ".png") ) if not carriers: print(f"FAIL {stem}: a profile with no file carrying it") failures += 1 continue for path in carriers: checked += 1 with Image.open(path) as im: im.load() got = im.info.get("icc_profile") if got is None: print(f"FAIL {path.name}: no profile where one was written") failures += 1 elif got != want: print( f"FAIL {path.name}: profile differs, " f"{len(want)} bytes written and {len(got)} read back" ) failures += 1 else: print(f"ok {path.name}: {len(got)} byte profile, identical") return checked, failures def check_orientations(directory): """Every file beside an `.ori` sidecar must report that orientation. Written by this library and read by libjpeg and libpng, which is the half the Zig tests cannot do: they check this reader against this writer, and the two would agree about a mistake they shared. """ checked = 0 failures = 0 for sidecar in sorted(directory.glob("*.ori")): want = int(sidecar.read_text().strip()) stem = sidecar.name.removesuffix(".ori") carriers = sorted( p for p in directory.iterdir() if p.name.startswith(stem + "-") or p.name == stem + ".png" ) for path in carriers: if path.suffix not in (".jpg", ".png"): continue checked += 1 with Image.open(path) as im: im.load() got = im.getexif().get(0x0112) if got != want: print(f"FAIL {path.name}: orientation {got} where {want} was written") failures += 1 else: print(f"ok {path.name}: orientation {got}") return checked, failures # The PCX shapes Pillow reads. The others it refuses with "unknown PCX mode", # which is held to as well: doc/pcx.md says which readers read which shape, # and this is what keeps that true. PILLOW_PCX = {"rgb", "indexed_256", "planar_16"} def check_pcx(directory): """Every PCX beside a `.rgba` sidecar must decode to exactly those pixels. Read by Pillow and by ImageMagick, since between them they are most of what reads a PCX today and they do not read the same shapes. A paletted shape loses nothing, so exact is the only fair test. """ magick = shutil.which("magick") checked = 0 failures = 0 for sidecar in sorted(directory.glob("pcx-*.rgba")): want = sidecar.read_bytes() path = sidecar.with_suffix(".pcx") shape = path.stem.split("-")[1] checked += 1 try: with Image.open(path) as im: im.load() got = im.convert("RGBA").tobytes() except OSError as e: got = e if shape in PILLOW_PCX: if isinstance(got, Exception): print(f"FAIL {path.name}: Pillow refused it: {got}") failures += 1 elif got != want: print(f"FAIL {path.name}: Pillow reads other pixels") failures += 1 else: print(f"ok {path.name}: Pillow reads it as written") elif isinstance(got, Exception): print(f"ok {path.name}: Pillow refuses it, as doc/pcx.md says") else: print(f"FAIL {path.name}: Pillow reads it now; doc/pcx.md says it does not") failures += 1 if magick is None: print(f"skip {path.name}: no magick on PATH") continue checked += 1 result = subprocess.run( [magick, str(path), "-depth", "8", "rgba:-"], capture_output=True ) got = result.stdout if result.returncode != 0: print(f"FAIL {path.name}: ImageMagick refused it: {result.stderr.decode().strip()}") failures += 1 elif got != want: print(f"FAIL {path.name}: ImageMagick reads other pixels") failures += 1 else: print(f"ok {path.name}: ImageMagick reads it as written") return checked, failures if __name__ == "__main__": sys.exit(main(sys.argv))