#!/usr/bin/env python3 """Census of the local Jaguar library: counts, formats, headers, boot ROMs. Reads everything in place (zip members in memory; 7z archives by listing only); copies nothing. Writes a plain-text report to stdout: python -I scripts/census.py > tests/detectors/census-2026-11-11.txt What it measures for each cartridge image (docs/file-formats.md explains): - size, CRC-32, SHA-1; - the container: ``cart`` (size a multiple of 1 MiB, or 128 KiB), ``alpine`` (size + 0x2000 a multiple of 1 MiB: a cart without its first 0x2000 bytes), ``abs1`` (60 1B), ``abs2/coff`` (01 50), ``jagserver`` (60 1A + "JAG"), ``gemdos`` (60 1A), ``elf``, else ``other``; - for a ``cart``: the bytes at $400 (the boot ROM copies them to MEMCON1), the start address at $404, the flags at $408; whether the 0x2000-byte header is the common retail one (most frequent SHA-1 of bytes 0..0x1FFF with the three per-cart fields masked out is not attempted: the raw header hash is used); - for the No-Intro "(ROM)" set: whether each image equals the "(J64)" image of the same name with its first 0x2000 bytes removed. """ from __future__ import annotations import hashlib import os import re import subprocess import sys import zipfile import zlib from collections import Counter from pathlib import Path def local(variable: str, *parts: str) -> Path: """A local ROM folder from an environment variable (no machine path lives here). Unset, it is a path that does not exist, so the folder counts as absent: MAME_ROMPATH (MAME non-merged), NO_INTRO_DIR, REDUMP_DIR, CURATED_ROMS (a frontend library with jaguar/). """ value = os.environ.get(variable) if not value: print(f"{variable} is unset: its folder counts as absent", file=sys.stderr) return Path(value or f"${variable}", *parts) NOINTRO = local("NO_INTRO_DIR") REDUMP = local("REDUMP_DIR") MAME = local("MAME_ROMPATH") SETS = { "J64": NOINTRO / "Atari - Atari Jaguar (J64)", "J64-Aftermarket": NOINTRO / "Atari - Atari Jaguar (J64) (Aftermarket)", "ROM": NOINTRO / "Atari - Atari Jaguar (ROM)", } CD_NONREDUMP = NOINTRO / "Non-Redump - Atari - Atari Jaguar CD" CD_REDUMP = REDUMP / "Atari - Jaguar CD Interactive Multimedia System" RETROBAT = local("CURATED_ROMS", "jaguar") MIB = 1 << 20 def container(data: bytes) -> str: if data[:4] == b"\x7fELF": return "elf" if data[:2] == b"\x60\x1b": return "abs1" if data[:2] == b"\x01\x50": return "abs2/coff" if data[:2] == b"\x60\x1a": return "jagserver" if data[0x1C:0x1F] == b"JAG" else "gemdos" if len(data) % MIB == 0 or len(data) == 131072: return "cart" if (len(data) + 0x2000) % MIB == 0: return "alpine" return "other" def members(path: Path): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if not info.is_dir(): yield info.filename, archive.read(info) def cart_set(label: str, directory: Path) -> dict[str, bytes]: print(f"\n== {label}: {directory}") files = sorted(directory.glob("*.zip")) kinds: Counter[str] = Counter() sizes: Counter[int] = Counter() exts: Counter[str] = Counter() memcon: Counter[str] = Counter() start: Counter[str] = Counter() flags: Counter[str] = Counter() headers: Counter[str] = Counter() first_byte: Counter[str] = Counter() images: dict[str, bytes] = {} rows = [] for path in files: for name, data in members(path): kind = container(data) kinds[kind] += 1 sizes[len(data)] += 1 exts[Path(name).suffix.lower()] += 1 images[path.stem] = data detail = "" if kind == "cart" and len(data) >= 0x2000: memcon[data[0x400:0x404].hex()] += 1 start[data[0x404:0x408].hex()] += 1 flags[data[0x408:0x40C].hex()] += 1 headers[hashlib.sha1(data[:0x400]).hexdigest()[:12]] += 1 first_byte[f"{data[0]:02x}"] += 1 detail = ( f" memcon={data[0x400:0x404].hex()} start={data[0x404:0x408].hex()}" f" flags={data[0x408:0x40C].hex()} blocks={256 - data[0] if data[0] else 0}" ) rows.append( f"{len(data):>8} {zlib.crc32(data):08x} {hashlib.sha1(data).hexdigest()} " f"{kind:<9} {name}{detail}" ) print(f"archives: {len(files)}; images: {len(rows)}") print("extensions:", dict(exts)) print("containers:", dict(kinds)) print("sizes:", {f"{size / MIB:g} MiB" if size % 1024 == 0 else size: n for size, n in sorted(sizes.items())}) print("bytes $400-$403 (-> MEMCON1 width/speed):", dict(memcon)) print("start address $404:", dict(start.most_common(8)), f"({len(start)} distinct)") print("flags $408:", dict(flags.most_common(8)), f"({len(flags)} distinct)") print("first byte (negated RSA block count):", dict(first_byte.most_common(8))) print("distinct SHA-1 of bytes 0-$3FF:", len(headers), "; most common:", headers.most_common(4)) for row in rows: print(row) return images def cd_set(label: str, directory: Path) -> None: print(f"\n== {label}: {directory}") files = sorted(directory.glob("*.zip")) exts: Counter[str] = Counter() for path in files: with zipfile.ZipFile(path) as archive: infos = [info for info in archive.infolist() if not info.is_dir()] for info in infos: exts[Path(info.filename).suffix.lower()] += 1 total = sum(info.file_size for info in infos) print(f"{total:>11} {len(infos):>3} files {path.name}") print(f"archives: {len(files)}; member extensions: {dict(exts)}") def retrobat(known: dict[int, str]) -> None: print(f"\n== retrobat: {RETROBAT}") files = sorted(RETROBAT.glob("*.7z")) exts: Counter[str] = Counter() where: Counter[str] = Counter() for path in files: listing = subprocess.run( ["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=False ).stdout for block in listing.split("\n\n"): name = re.search(r"^Path = (.+)$", block, re.M) crc = re.search(r"^CRC = ([0-9A-F]{8})$", block, re.M) size = re.search(r"^Size = (\d+)$", block, re.M) if not (name and crc and size): continue exts[Path(name[1]).suffix.lower()] += 1 origin = known.get(int(crc[1], 16), "not in the No-Intro sets") where[origin] += 1 print(f"{int(size[1]):>8} {crc[1].lower()} {origin:<16} {name[1]}") print(f"archives: {len(files)}; extensions: {dict(exts)}; origin by CRC-32: {dict(where)}") def bios() -> None: print("\n== boot ROMs (MAME 0.285 sets, read in place)") for archive_name in ("jaguar.zip", "jaguarcd.zip"): path = MAME / archive_name if not path.exists(): print(f"missing: {path}") continue for name, data in members(path): print( f"{len(data):>7} crc {zlib.crc32(data):08x} sha1 {hashlib.sha1(data).hexdigest()} " f"{archive_name}/{name}" ) def main() -> int: bios() images = {label: cart_set(label, directory) for label, directory in SETS.items()} print("\n== No-Intro (ROM) against (J64)") same = other = missing = 0 for name, data in sorted(images["ROM"].items()): j64 = images["J64"].get(name) if j64 is None: missing += 1 print(f"no J64 of that name: {name}") elif j64[0x2000:] == data: same += 1 else: other += 1 print(f"differs from J64[0x2000:]: {name} ({len(data)} vs {len(j64)})") print(f"ROM == J64 minus its first 0x2000 bytes: {same}; differs: {other}; no J64: {missing}") only = sorted(set(images["J64"]) - set(images["ROM"])) print(f"J64 titles with no (ROM) twin: {len(only)}") for name in only: print(f" {name}") known: dict[int, str] = {} for label, group in images.items(): for data in group.values(): known.setdefault(zlib.crc32(data), label) retrobat(known) cd_set("Jaguar CD, Non-Redump (No-Intro)", CD_NONREDUMP) cd_set("Jaguar CD, Redump", CD_REDUMP) return 0 if __name__ == "__main__": sys.exit(main())