#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 4's header census: the board's own header score against MAME's software list. For every licensed image in ``$NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System`` (read in place; the ``(Beta)``, ``(Proto)``, ``(Pirate)``, ``(Unl)``, ``(Sample)``, ``(Demo)``, ``(Program)`` and ``(Aftermarket)`` dumps are skipped, as count_carts.py does), ``snes_python.cartridge.find_header`` picks a header and a map (DESIGN, written from fullsnes alone). The check is MAME's software list ``hash/snes.xml`` (CC0-1.0, emulator-lineage sources.md: "code OK (with attribution)"; MAME's software-list contributors), matched by SHA-1: its ``slot`` feature names the board (``lorom``, ``hirom``, ``lorom_sa1``, ...) and its ``nvram`` data area the battery RAM. The list's slot is a curated record of each cartridge's board, so it is a document here (DOC), not a run of MAME. python -I scripts/header_census.py # summary python -I scripts/header_census.py --list wrong # the images the score maps wrongly Compared: the map family (LoROM or HiROM; MAME files ExHiROM boards under ``hirom``) and the SRAM size (the header's $FFD8 against the ``nvram`` size). Nothing is written. """ from __future__ import annotations import argparse import collections import hashlib import os import re import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from snes_python.cartridge import EXHIROM, HIROM, Cartridge UNLICENSED = re.compile(r"\((Beta|Proto|Pirate|Unl|Sample|Demo|Program|Aftermarket)[^)]*\)|\[b\]") SOFTLIST = [ ROOT / "reference" / "src" / "mame" / "hash" / "snes.xml", Path("/usr/share/games/mame/hash/snes.xml"), ] def load_softlist(path: Path) -> tuple[dict, dict]: """SHA-1 of the whole ROM (or of its first chunk, for split ROMs) -> entry.""" whole: dict[str, dict] = {} first: dict[tuple[int, str], dict] = {} for sw in ET.parse(path).getroot().findall("software"): for part in sw.findall("part"): if part.get("interface") != "snes_cart": continue feature = {f.get("name"): f.get("value") for f in part.findall("feature")} entry = {"name": sw.get("name"), "slot": feature.get("slot") or "", "nvram": 0} chunks = [] for area in part.findall("dataarea"): if area.get("name") == "rom": for rom in area.findall("rom"): if rom.get("sha1"): chunks.append( ( int(rom.get("offset", "0"), 0), int(rom.get("size"), 0), rom.get("sha1"), ) ) elif area.get("name") == "nvram": entry["nvram"] = int(area.get("size"), 0) chunks.sort() entry["chunks"] = chunks if len(chunks) == 1: whole[chunks[0][2]] = entry elif chunks: first[(chunks[0][1], chunks[0][2])] = entry return whole, first def lookup(image: bytes, whole: dict, first: dict, sizes: set[int]) -> dict | None: entry = whole.get(hashlib.sha1(image).hexdigest()) if entry is not None: return entry for size in sizes: entry = first.get((size, hashlib.sha1(image[:size]).hexdigest())) if entry is not None and all( hashlib.sha1(image[o : o + n]).hexdigest() == h for o, n, h in entry["chunks"] ): return entry return None def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--dir", type=Path) parser.add_argument("--softlist", type=Path) parser.add_argument("--list", choices=["wrong", "sram", "unmatched", "coprocessor"]) args = parser.parse_args() folder = args.dir or Path(os.environ.get("NO_INTRO_DIR", "")) / ( "Nintendo - Super Nintendo Entertainment System" ) if not folder.is_dir(): raise SystemExit("set NO_INTRO_DIR (or --dir)") softlist = args.softlist or next((p for p in SOFTLIST if p.exists()), None) if softlist is None: raise SystemExit("MAME's hash/snes.xml not found: pass --softlist") whole, first = load_softlist(softlist) sizes = {size for size, _ in first} counts: collections.Counter = collections.Counter() listed: list[str] = [] for path in sorted(folder.glob("*.zip")): if UNLICENSED.search(path.name): counts["skipped (not licensed)"] += 1 continue with zipfile.ZipFile(path) as z: names = [n for n in z.namelist() if n.lower().endswith((".sfc", ".smc"))] if len(names) != 1: counts["no single image"] += 1 continue image = z.read(names[0]) if len(image) % 1024 == 512: image = image[512:] counts["licensed images"] += 1 entry = lookup(image, whole, first, sizes) if entry is None: counts["not in the software list"] += 1 if args.list == "unmatched": listed.append(path.name) continue counts["matched"] += 1 slot = entry["slot"] plain = slot in ("lorom", "hirom") counts["plain (lorom/hirom)" if plain else "coprocessor or special board"] += 1 if not plain: if args.list == "coprocessor": listed.append(f"{slot}: {path.name}") if not slot.startswith(("lorom", "hirom")): continue cart = Cartridge(image) family = "hirom" if cart.kind in (HIROM, EXHIROM) else "lorom" want = "hirom" if slot.startswith("hirom") else "lorom" key = "plain" if plain else "special" if family == want: counts[f"{key}: map right"] += 1 if cart.kind == EXHIROM: counts[f"{key}: map right (ExHiROM)"] += 1 else: counts[f"{key}: map WRONG"] += 1 if args.list == "wrong": h = cart.header listed.append( f"{slot} scored {cart.kind} ({h.score}): {path.name} " f"[map ${h.map_mode:02X}, chipset ${h.chipset:02X}]" ) if plain: sram = len(cart.sram) if sram == entry["nvram"]: counts["plain: SRAM size right"] += 1 else: counts["plain: SRAM size differs"] += 1 if args.list == "sram": listed.append( f"header {sram} vs list {entry['nvram']}: {path.name} [{cart.kind}]" ) print(f"{folder.name}, software list {softlist.name}") for key in sorted(counts): print(f" {counts[key]:5} {key}") for line in listed: print(" ", line) return 0 if __name__ == "__main__": sys.exit(main())