#!/usr/bin/env python3 """Census of the Intellivision ROM library: formats and memory maps, by hashing only. No emulator runs. Every archive is read in place. For each image the script reports size, CRC-32, SHA-1, the container format, and what two existing databases say about its memory map: - MAME 0.285 software lists (``hash/intv.xml``, ``hash/intvecs.xml``): a cartridge there is a list of data areas (address, ROM piece). An image matches when the pieces, concatenated in order, have its length and each piece's CRC-32. - MAME's ``hash/intv.hsi``: whole-image CRC-32 with an ``extrainfo`` string (``mapper rom1 rom2 rom3 rom4 ram extra``; a rom byte is address/0x1000 in the high nibble and size/0x800 in the low one). No ``extrainfo`` means 8K at $5000. Until 2026-11-25 a third column parsed FreeIntv's fingerprint table out of its GPL-3.0 source, with a table of its load methods' address ranges; a program parsing GPL source is reading it (decision L4, docs/provenance.md), so both are gone. A load-method column rebuilt from documentation (the community .cfg memory maps) is owed. They are detectors (tier 5): where they disagree the row says so. python -I scripts/census.py # all three libraries, summary python -I scripts/census.py --rows > tests/detectors/census-rows.txt """ from __future__ import annotations import argparse import hashlib import os import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile import zlib from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = ROOT / "reference" / "src" / "mame" / "hash" 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), MAME_MERGED_ROMPATH, MAME_CHDS (MAME CHDs, merged), FBNEO_DIR (FinalBurn Neo arcade), CURATED_ROMS (a frontend library with mame/ and fbneo/). """ 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") LIBRARIES = { "nointro": NOINTRO / "Mattel - Intellivision", "aftermarket": NOINTRO / "Mattel - Intellivision (Aftermarket)", "retrobat": local("CURATED_ROMS", "intellivision"), } def images(path: Path): """Yield (inner name, bytes) for an archive or a plain file.""" suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as bundle: for info in bundle.infolist(): yield info.filename, bundle.read(info) elif suffix == ".7z": listing = subprocess.run( ["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout names = re.findall(r"^Path = (.+)$", listing, re.M)[1:] for name in names: data = subprocess.run( ["7z", "e", "-so", str(path), name], capture_output=True, check=True ).stdout yield name, data else: yield path.name, path.read_bytes() def container(data: bytes) -> str: if data[:3] == b"LTO": return "luigi" if len(data) > 3 and data[0] in (0xA8, 0x41, 0x61) and data[1] == data[2] ^ 0xFF: return "rom" # Intellicart/CC3: auto-baud byte, segment count, its complement if len(data) % 2 == 0: return "bin" # raw 16-bit big-endian words; needs a map from outside return "odd" def rom_map(data: bytes) -> str: """Segments and page attributes of an Intellicart-format (.rom) image. Layout, HYPOTHESIS (learned in Phase 0, before the 2026-11-14 rule, from a GPL emulator's source; owed a check against a document, decision L6): a baud byte, the segment count and its complement; per segment the first and last 256-word page, the words big-endian, a CRC-16; then 16 bytes of attributes (a nibble per 2K words: 1 read, 2 write, 4 narrow, 8 bank-switched), 32 bytes of fine ranges, a CRC-16; then optional metadata tags. DOC (Intellivision Wiki, "Intellicart"): the attributes are set per 2K-word range, 32 ranges, read, write and bank-switched, plus the 8-bit ("narrow") RAM attribute emulators add. """ at, out = 3, [] for _ in range(data[1]): low, high = data[at] << 8, (data[at + 1] << 8) + 0x100 out.append(f"{low:04X}-{high - 1:04X}") at += 2 + 2 * (high - low) + 2 flags = set() for page in range(32): attr = 0xF & (data[at + (page >> 1)] >> ((page & 1) * 4)) if attr & 2: flags.add(f"W@{page * 0x800:04X}" + ("n" if attr & 4 else "")) if attr & 8: flags.add(f"B@{page * 0x800:04X}") tail = len(data) - (at + 50) return " ".join(out + sorted(flags) + ([f"tags={tail}B"] if tail else [])) def mame_softlists() -> list[dict]: carts = [] for name in ("intv.xml", "intvecs.xml"): for software in ET.parse(MAME / name).getroot().iter("software"): for part in software.iter("part"): slot = [f.get("value") for f in part.iter("feature") if f.get("name") == "slot"] pieces = [] for area in part.iter("dataarea"): for rom in area.iter("rom"): if rom.get("crc"): pieces.append((area.get("name"), int(rom.get("size"), 0), rom.get("crc"))) carts.append( { "list": name[:-4], "name": software.get("name"), "slot": slot[0] if slot else "?", "pieces": pieces, } ) return carts def match_softlist(data: bytes, carts: list[dict]) -> dict | None: for cart in carts: if sum(size for _, size, _ in cart["pieces"]) != len(data) or not cart["pieces"]: continue at = 0 for _, size, crc in cart["pieces"]: if f"{zlib.crc32(data[at : at + size]):08x}" != crc: break at += size else: return cart return None def softlist_map(cart: dict) -> str: return " ".join(f"{area}+{size // 2:X}" for area, size, _ in cart["pieces"]) def mame_hsi() -> dict[str, str]: table = {} for entry in ET.parse(MAME / "intv.hsi").getroot().iter("hash"): extra = entry.find("extrainfo") table[entry.get("crc32")] = (extra.text or "").strip() if extra is not None else "" return table def hsi_map(extrainfo: str) -> str: if not extrainfo: return "5000+1000" mapper, *rest = (int(v) for v in extrainfo.split()) out = [] for value in rest[:4]: if value: out.append(f"{(value >> 4) * 0x1000:04X}+{(value & 15) * 0x800:X}") if rest[4]: out.append(f"RAM {(rest[4] >> 4) * 0x1000:04X}+{(rest[4] & 15) * 0x800:X}") if rest[5]: out.append({1: "ECS", 2: "voice", 3: "ECS+voice"}.get(rest[5], f"extra{rest[5]}")) if mapper: out.append(f"mapper{mapper}") return " ".join(out) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--rows", action="store_true", help="print one row per image") args = parser.parse_args() carts, hsi = mame_softlists(), mame_hsi() seen: dict[str, str] = {} for label, folder in LIBRARIES.items(): if not folder.is_dir(): print(f"== {label}: {folder} absent, skipped") continue files = sorted(p for p in folder.iterdir() if p.suffix.lower() in {".zip", ".7z"}) files += sorted(p for p in (folder / "Other").glob("*.7z")) if label == "retrobat" else [] counts: Counter[str] = Counter() for path in files: for inner, data in images(path): sha1 = hashlib.sha1(data).hexdigest() crc = f"{zlib.crc32(data):08x}" kind = container(data) soft = match_softlist(data, carts) in_hsi = crc in hsi counts["images"] += 1 counts[f"ext {Path(inner).suffix.lower()}"] += 1 counts[f"container {kind}"] += 1 counts[f"size {len(data) // 2048}K words"] += 1 counts["new to the census" if sha1 not in seen else "duplicate of an earlier library"] += 1 seen.setdefault(sha1, label) counts["softlist match" if soft else "softlist: none"] += 1 if soft: counts[f"softlist slot {soft['slot']} ({soft['list']})"] += 1 counts[f"softlist map {softlist_map(soft)}"] += 1 counts["hsi match" if in_hsi else "hsi: none"] += 1 own = rom_map(data) if kind == "rom" else "" if own: counts["rom: has RAM pages" if "W@" in own else "rom: ROM only"] += 1 counts["rom: bank-switched pages" if "B@" in own else "rom: no bank switching"] += 1 counts["rom: metadata tags" if "tags=" in own else "rom: no tags"] += 1 if not soft and not in_hsi and not own: counts["in no database"] += 1 if args.rows: print( f"{label}\t{inner}\t{len(data)}\t{crc}\t{sha1}\t{kind}\t" f"soft={soft['list'] + ':' + soft['name'] + ' ' + soft['slot'] + ' ' + softlist_map(soft) if soft else '-'}\t" f"hsi={hsi_map(hsi[crc]) if in_hsi else '-'}\t" f"rom={own or '-'}" ) out = sys.stderr if args.rows else sys.stdout print(f"== {label}: {folder} ({len(files)} archives)", file=out) for key in sorted(counts): print(f" {counts[key]:4d} {key}", file=out) return 0 if __name__ == "__main__": sys.exit(main())