#!/usr/bin/env python3 """Count memory maps and coprocessors over a local No-Intro SNES set, read in place. Each ``.zip`` is opened (never extracted to disk) and the internal header is found the way docs/cartridge.md "Header detection" describes: score the candidates at $7FC0 (LoROM), $FFC0 (HiROM) and $40FFC0 (ExHiROM), keep the best. The map mode byte ($xxD5) and the chipset byte ($xxD6, plus the subtype at $xxBF when the chipset's high nibble is $F) name the board. python -I scripts/count_carts.py "$NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System" python -I scripts/count_carts.py DIR --licensed # skip (Beta)/(Proto)/(Pirate)/(Unl)/... Prints the share of each board class and each coprocessor; ``--list CHIP`` prints the titles that use one. Nothing is written. """ from __future__ import annotations import argparse import collections import re import sys import zipfile from pathlib import Path UNLICENSED = re.compile(r"\((Beta|Proto|Pirate|Unl|Sample|Demo|Program|Aftermarket)[^)]*\)|\[b\]") # $xxD6 high nibble = coprocessor (low nibble 3-6 = it is present); fullsnes # "SNES Cartridge ROM Header" and the SNESdev wiki "ROM header". COPROCESSOR = { 0x0: "DSP (NEC uPD7725/96050: DSP-1..4, ST010/011)", 0x1: "GSU (Super FX)", 0x2: "OBC1", 0x3: "SA-1", 0x4: "S-DD1", 0x5: "S-RTC", 0xE: "other (Super Game Boy, Satellaview)", } CUSTOM = {0x00: "SPC7110", 0x01: "ST010/ST011", 0x02: "ST018", 0x10: "Cx4"} def score(rom: bytes, base: int) -> int: """How plausible a header at ``base`` is (higher is better); -1 if out of range.""" if base + 0x40 > len(rom): return -1 h = rom[base : base + 0x40] s = 0 checksum = h[0x1E] | h[0x1F] << 8 complement = h[0x1C] | h[0x1D] << 8 if checksum ^ complement == 0xFFFF: s += 8 mode = h[0x15] expected = { 0x7FC0: (0x20, 0x30, 0x23, 0x32), 0xFFC0: (0x21, 0x31, 0x35, 0x3A), 0x40FFC0: (0x25, 0x35), } if mode in expected.get(base, ()): s += 4 reset = h[0x3C] | h[0x3D] << 8 if reset >= 0x8000: s += 2 if all(0x20 <= c < 0x7F for c in h[0:21]): s += 2 if h[0x17] in range(0x07, 0x0E): # ROM size 128 KiB-4 MiB s += 1 return s def identify(rom: bytes) -> tuple[str, str, int]: if len(rom) % 1024 == 512: rom = rom[512:] base = max((0x7FC0, 0xFFC0, 0x40FFC0), key=lambda b: score(rom, b)) mode = rom[base + 0x15] chipset = rom[base + 0x16] mapping = {0x7FC0: "LoROM", 0xFFC0: "HiROM", 0x40FFC0: "ExHiROM"}[base] if chipset in (0x00, 0x01, 0x02): chip = "none" elif (chipset & 0x0F) in (3, 4, 5, 6, 9, 10): high = chipset >> 4 chip = ( CUSTOM.get(rom[base - 1], f"custom ${rom[base - 1]:02X}") if high == 0xF else COPROCESSOR.get(high, f"${high:X}") ) else: chip = f"unknown chipset ${chipset:02X}" return mapping, chip, mode def main() -> int: p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) p.add_argument("directory", type=Path) p.add_argument( "--licensed", action="store_true", help="skip betas, protos, pirates, unlicensed, aftermarket", ) p.add_argument( "--list", metavar="CHIP", help="print titles whose coprocessor name contains CHIP" ) a = p.parse_args() maps: collections.Counter[str] = collections.Counter() chips: collections.Counter[str] = collections.Counter() total = 0 for path in sorted(a.directory.glob("*.zip")): if a.licensed and UNLICENSED.search(path.name): continue with zipfile.ZipFile(path) as z: names = [n for n in z.namelist() if n.lower().endswith((".sfc", ".smc", ".bs", ".st"))] if not names: continue rom = z.read(names[0]) mapping, chip, _ = identify(rom) total += 1 maps[mapping] += 1 chips[chip] += 1 if a.list and a.list.lower() in chip.lower(): print(path.stem) print(f"{total} images in {a.directory.name}") for name, count in maps.most_common(): print(f" {count:5d} {100 * count / total:5.1f} % {name}") for name, count in chips.most_common(): print(f" {count:5d} {100 * count / total:5.1f} % {name}") return 0 if __name__ == "__main__": sys.exit(main())