#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of Atari 2600 bankswitch schemes over the local No-Intro sets, and the board's own detector counted against Stella's ``-rominfo`` (milestone 5's judge). Read-only: every dump is read in place from its zip (in memory). The sets are the directories ``Atari - Atari 2600*`` under ``$NO_INTRO_DIR`` (no machine path in this repository). Each dump is classified three ways: (a) MAME 0.285's software list ``hash/a2600.xml`` (CC0): the part's ```` by SHA-1, and a ``ram`` data area for Super Chip. (b) Stella, as a closed box: the binary built from the pin (reference/build-stella-sdl, docs/validation.md), run once per dump with ``-rominfo``; only what it prints is read (its source and its properties database are never opened: docs/restart.md). A "*" after its value means Stella detected the scheme rather than looking the dump up. (c) The board: ``a2600_python.cartridge.detect`` alone (its own detector, as for a dump MAME's list does not carry), and ``identify`` (the list first). nice python3 scripts/count_bankswitch.py [--jobs 2] [--json tests/detector_runs/coverage.json] Prints markdown tables; writes the JSON (gitignored) that scripts/sweep_stella.py reads. """ from __future__ import annotations import argparse import collections import hashlib import json import os import re import subprocess import sys import zipfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a2600_python.cartridge import ( # noqa: E402 MAME_HASH, UnsupportedCartridge, _mame_list, detect_super_chip, identify, ) from a2600_python.cartridge.detect import detect # noqa: E402 ROM_EXT = (".a26", ".bin") STELLA_BIN = ROOT / "reference" / "build-stella-sdl" / "stella" / "stella" SDL3_LIB = ROOT / "reference" / "build-stella-sdl" / "sdl3" / "lib" ROMINFO = re.compile(r"^\s*(Bankswitch Type|Controller 0|Controller 1|Display Format):\s*(.*)$") PORT_SUFFIX = re.compile(r"\s+in (left|right) port$") # Stella's spellings of the board's schemes (comparison families). SAME = {"2K": "2K/4K", "4K": "2K/4K", "4KSC": "4KSC"} def sets() -> list[Path]: base = os.environ.get("NO_INTRO_DIR") if not base: raise SystemExit("set NO_INTRO_DIR to the No-Intro root (it holds 'Atari - Atari 2600')") return sorted(Path(base).glob("Atari - Atari 2600*")) def walk(): for folder in sets(): for path in sorted(folder.glob("*.zip")): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if info.filename.lower().endswith(ROM_EXT): yield folder.name, path, archive.read(info) def classify(name: str) -> str: """licensed / proto / unl / aftermarket, from the No-Intro name's tags.""" tags = re.findall(r"\(([^)]*)\)", name) def has(word): return any(t == word or t.startswith(word + " ") for t in tags) if has("Aftermarket") or has("Homebrew"): return "aftermarket" if has("Unl") or has("Pirate"): return "unl" if any(has(w) for w in ("Proto", "Beta", "Demo", "Sample", "Program")): return "proto" return "licensed" def stella_rominfo(zip_path: Path) -> dict: """Scheme, controllers and format as ``stella -rominfo`` prints them (closed box). Stella opens the zip itself, so the dump is read in place, never copied. """ env = {**os.environ, "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy", "LD_LIBRARY_PATH": str(SDL3_LIB)} # fmt: skip text = subprocess.run([str(STELLA_BIN), "-rominfo", str(zip_path)], env=env, capture_output=True, text=True, timeout=60, check=False).stdout # fmt: skip fields = {m.group(1): m.group(2).strip() for m in map(ROMINFO.match, text.splitlines()) if m} if "Bankswitch Type" not in fields: return {"scheme": "?", "detected": False, "controllers": [], "format": ""} scheme = fields["Bankswitch Type"].split(" (")[0] controllers = [ PORT_SUFFIX.sub("", fields.get(k, "")).rstrip("*").strip() for k in ("Controller 0", "Controller 1") ] # fmt: skip return {"scheme": scheme.rstrip("*"), "detected": scheme.endswith("*"), "controllers": controllers, "format": fields.get("Display Format", "").rstrip("*")} # fmt: skip def board_detector(data: bytes) -> str: try: family = detect(data) except ValueError: return "?" if family in ("F8", "F6", "F4") and detect_super_chip(data): family += "SC" return family def board_identify(data: bytes) -> str: try: family, sc, _, _ = identify(data) except UnsupportedCartridge: return "?" return family + ("SC" if sc else "") def family(name: str) -> str: return SAME.get(name, name) def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--jobs", type=int, default=2) ap.add_argument("--json", type=Path, default=ROOT / "tests/detector_runs/coverage.json") ap.add_argument("--no-stella", action="store_true", help="skip the closed-box column") args = ap.parse_args() if not args.no_stella and not STELLA_BIN.is_file(): raise SystemExit(f"need the Stella SDL build at {STELLA_BIN} (docs/validation.md)") mame = _mame_list(MAME_HASH) rows, seen = [], set() for folder, path, data in walk(): sha1 = hashlib.sha1(data).hexdigest() if sha1 in seen: continue seen.add(sha1) slot, ram, _ = mame.get(sha1, ("", False, "")) rows.append({"name": path.stem, "set": folder, "sha1": sha1, "size": len(data), "group": classify(path.stem), "mame": slot, "mame_ram": ram, "detector": board_detector(data), "board": board_identify(data), "_path": path}) # fmt: skip if not args.no_stella: with ThreadPoolExecutor(args.jobs) as pool: infos = list(pool.map(lambda r: stella_rominfo(r["_path"]), rows)) for row, info in zip(rows, infos, strict=True): row["stella"] = info["scheme"] row["stella_detected"] = info["detected"] row["controllers"] = info["controllers"] row["format"] = info["format"] for row in rows: del row["_path"] print(f"{len(rows)} distinct dumps in {', '.join(s.name for s in sets())}") by_group = collections.Counter(r["group"] for r in rows) print("groups:", dict(by_group)) print("\n| Scheme (board) | All | Licensed |\n| --- | ---: | ---: |") counts = collections.Counter(r["board"] for r in rows) licensed = collections.Counter(r["board"] for r in rows if r["group"] == "licensed") for scheme, n in counts.most_common(): print(f"| {scheme} | {n} | {licensed[scheme]} |") if not args.no_stella: for label, key in (("detector alone", "detector"), ("identify (list first)", "board")): agree = [r for r in rows if family(r[key]) == family(r["stella"])] print(f"\nboard {label} vs Stella -rominfo: {len(agree)} of {len(rows)} agree") lic = [r for r in rows if r["group"] == "licensed"] lic_agree = [r for r in lic if family(r[key]) == family(r["stella"])] print(f" licensed: {len(lic_agree)} of {len(lic)}") print( " | dump | size | board | Stella | MAME slot |\n | --- | ---: | --- | --- | --- |" ) for r in rows: if family(r[key]) != family(r["stella"]): print(f" | {r['name']} | {r['size']} | {r[key]} | {r['stella']}" f"{'*' if r['stella_detected'] else ''} | {r['mame'] or '-'} |") # fmt: skip args.json.parent.mkdir(parents=True, exist_ok=True) args.json.write_text(json.dumps({"dumps": rows}, indent=1), encoding="utf-8") print(f"\nwrote {args.json}") return 0 if __name__ == "__main__": sys.exit(main())