#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Reads MAME's hash/a7800.xml (CC0-1.0) at run time; MAME_SLOTS describes the slot names # of MAME's bus/a7800/a78_slot.cpp (BSD-3-Clause, Fabio Priuli; facts). NOTICE, 1 and 2. """Census of the local Atari 7800 dumps: formats, cart schemes, and how many can be typed. Every dump is read in place and in memory (zip members with ``zipfile``, 7z members through ``7z x -so``); nothing is written beside a ROM. An ``.a78`` file's 128-byte header is parsed and stripped, and **the payload** (the bytes after the header, or the whole file when there is none) is what gets hashed, so a headered and a headerless copy of one cartridge resolve to the same key. A raw dump does not say what hardware its cartridge carries (docs/cartridge.md "Why a raw dump is not enough"). The script therefore asks two tables, each keyed by a hash of the payload, and reports what each knows: 1. MAME's ``hash/a7800.xml`` software list (CC0-1.0): SHA-1 per ROM chip, the slot device (scheme + RAM + POKEY), NTSC/PAL, light gun. 2. The A78 header of a local headered copy of the same payload, if any. Until 2026-11-25 it also parsed two GPL emulators' cartridge databases (JS7800's ``ProSystem.dat`` and A7800DS's ``Database.c``), empty since their trees stopped being fetched on 2026-11-24. A program parsing a GPL file is reading it (decision L4, docs/provenance.md), so those readers and their type maps are gone; a typing table for dumps neither source knows is owed, from documentation or from a closed-box run's output. It does **not** port any emulator's detection heuristic. The only inference it makes itself is the one a connector forces: a payload of 48 KiB or less with no table entry can only be mapped flat, ending at $FFFF (its sound hardware and controllers remain unknown). The dumps are the three 7800 folders below ``$NO_INTRO_DIR``, the BIOS sets below ``$MAME_ROMPATH``, and optionally a curated copy below ``$RETROBAT_DIR`` (src/a7800_python/romsets.py). python scripts/count_carts.py # the tables python scripts/count_carts.py --json coverage.json python scripts/count_carts.py --list # one line per dump """ from __future__ import annotations import argparse import collections import hashlib import json import re import subprocess import zipfile import zlib from dataclasses import dataclass, field from pathlib import Path from a7800_python import romsets ROOT = Path(__file__).resolve().parents[1] SETS = { "licensed": romsets.no_intro(romsets.LICENSED_7800), "aftermarket": romsets.no_intro(romsets.AFTERMARKET_7800), "private": romsets.no_intro(romsets.PRIVATE_7800), } if (_retrobat := romsets.retrobat_7800()) is not None: # optional: $RETROBAT_DIR SETS["retrobat"] = _retrobat MAME_SETS = romsets.mame_rompath() MAME_HASH = Path("/usr/share/games/mame/hash/a7800.xml") # BIOS images by SHA-1, as MAME 0.285 names them (mame -listxml a7800 / a7800p). BIOS = { "d9d134bb6b36907c615a594cc7688f7bfcef5b43": "NTSC 4K (7800.u7; C300558-001 production)", "14584b1eafe9721804782d4b1ac3a4a7313e455f": "NTSC 16K prototype with Asteroids (c300558-001a.u7)", "5a140136a16d1d83e4ff32a19409ca376a8df874": "PAL 16K with Asteroids (c300558-001b.u7)", } # A78 header, 7800 Development Wiki "A78 Header Specification" (v1-v4). CART_TYPE_BITS = [ "pokey@4000", "supergame", "ram@4000", "rom@4000", "bank6@4000", "banked-ram", "pokey@450", "mirror-ram@4000", "activision", "absolute", "pokey@440", "ym2151@460", "souper", "banksets", "halt-banked-ram", "pokey@800", ] # fmt: skip CONTROLLERS = [ "none", "7800 joystick", "lightgun", "paddle", "trakball", "2600 joystick", "2600 driving", "2600 keypad", "ST mouse", "Amiga mouse", "AtariVox/SaveKey", "SNES2Atari", "Mega7800", ] # fmt: skip # MAME slot device -> (scheme, extras). Read off src/devices/bus/a7800/a78_carts.h and # a78_slot.cpp's own table of header bits; written here as a description, not as code. MAME_SLOTS = { "a78_rom": ("linear", ()), "a78_pokey": ("linear", ("pokey@4000",)), "a78_sg": ("supergame", ()), "a78_sg_pokey": ("supergame", ("pokey@4000",)), "a78_sg_ram": ("supergame", ("ram@4000",)), "a78_sg9": ("supergame", ("bank6@4000",)), "a78_mram": ("linear", ("mirror-ram@4000",)), "a78_abs": ("absolute", ()), "a78_act": ("activision", ()), "a78_hsc": ("linear", ("hsc-cartridge",)), "a78_xboard": ("linear", ("xboard",)), "a78_xm": ("linear", ("xm",)), "a78_megacart": ("supergame", ("banked-ram(megacart)",)), "a78_versa": ("supergame", ("banked-ram(versaboard)",)), "a78_p450_t0": ("linear", ("pokey@450",)), "a78_p450_t1": ("linear", ("pokey@4000", "pokey@450")), "a78_p450_t6": ("supergame", ("ram@4000", "pokey@450")), "a78_p450_ta": ("supergame", ("bank6@4000", "pokey@450")), "a78_p450_vb": ("supergame", ("banked-ram(versaboard)", "pokey@450")), } @dataclass class Dump: source: str name: str member: str size: int # payload bytes header: dict | None crc: int md5: str sha1: str sha256: str payload: bytes = field(repr=False) def parse_header(data: bytes) -> dict | None: if len(data) < 128 or data[1:10] != b"ATARI7800": return None cart_type = data[53] << 8 | data[54] header = { "version": data[0], "title": data[17:49].split(b"\0")[0].decode("latin-1").strip(), "size": int.from_bytes(data[49:53], "big"), "cart_type": cart_type, "features": [n for i, n in enumerate(CART_TYPE_BITS) if cart_type >> i & 1], "controller1": data[55], "controller2": data[56], "tv": data[57], "save": data[58], "xm": data[63], } if data[0] >= 4: header.update(mapper=data[64], mapper_options=data[65], audio=data[66] << 8 | data[67], interrupt=data[68] << 8 | data[69]) # fmt: skip return header def make_dump(source: str, name: str, member: str, data: bytes) -> Dump: header = parse_header(data) payload = data[128:] if header else data return Dump(source, name, member, len(payload), header, zlib.crc32(payload), hashlib.md5(payload).hexdigest(), hashlib.sha1(payload).hexdigest(), hashlib.sha256(payload).hexdigest(), payload) # fmt: skip def read_set(source: str, folder: Path) -> list[Dump]: dumps = [] for path in sorted(folder.iterdir()): suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as z: for info in z.infolist(): if not info.is_dir(): dumps.append(make_dump(source, path.stem, info.filename, z.read(info))) elif suffix == ".7z": listing = subprocess.run( ["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout members = re.findall(r"^Path = (.+)$", listing, flags=re.MULTILINE)[1:] for member in members: data = subprocess.run( ["7z", "x", "-so", str(path), member], capture_output=True, check=True ).stdout dumps.append(make_dump(source, path.stem, member, data)) elif suffix in (".a78", ".bin"): dumps.append(make_dump(source, path.stem, path.name, path.read_bytes())) return dumps def mame_softlist() -> list[dict]: text = MAME_HASH.read_text(encoding="utf-8") entries = [] for block in re.findall(r"", text, flags=re.DOTALL): roms = [ (int(size, 0), sha1) for size, sha1 in re.findall(r']*size="([^"]+)"[^>]*sha1="([0-9a-f]{40})"', block) ] slot = re.search(r'feature name="slot" value="([^"]+)"', block) entries.append({ "name": re.search(r'(.*?)", block).group(1), "slot": slot.group(1) if slot else "a78_rom", "compat": (re.search(r'name="compatibility" value="([^"]+)"', block) or [None, "?"])[1], "lightgun": 'value="lightgun"' in block, "roms": roms, }) # fmt: skip return entries def softlist_index(entries: list[dict]) -> dict[int, list[dict]]: by_size = collections.defaultdict(list) for entry in entries: by_size[sum(size for size, _ in entry["roms"])].append(entry) return by_size def softlist_match(dump: Dump, by_size: dict[int, list[dict]]) -> dict | None: """An entry whose ROM chips, concatenated in list order, are this payload.""" for entry in by_size.get(dump.size, ()): offset = 0 for size, sha1 in entry["roms"]: if hashlib.sha1(dump.payload[offset : offset + size]).hexdigest() != sha1: break offset += size else: return entry return None def describe_header(header: dict) -> str: features = "+".join(header["features"]) or "linear" return f"v{header['version']} {features}" def scheme_of(dump: Dump, soft: dict | None, header: dict | None) -> tuple[str, str]: """(scheme description, the tier of the answer).""" if soft: scheme, extras = MAME_SLOTS.get(soft["slot"], (soft["slot"], ())) return "+".join((scheme, *extras)), "softlist" if header: return "+".join(header["features"]) or "linear", "a78-header" if dump.size <= 0xC000: return "linear (by size)", "size-only" return "unknown", "untyped" # Absolute stores (STA/STX/STY abs, STA abs,X / abs,Y) to the cartridge-port # sound and control locations. Counting these instruction bytes in a payload is # an indication that the program addresses the device, not proof (data can # look like code, and a program may probe a device it does not need). STORE_OPCODES = (0x8D, 0x8E, 0x8C, 0x9D, 0x99) DEVICE_RANGES = { "ym2151@460": (0x0460, 0x0461), "pokey@450": (0x0450, 0x045F), "pokey@440": (0x0440, 0x044F), "covox@430": (0x0430, 0x0430), "xctrl@470": (0x0470, 0x0470), "pokey@800": (0x0800, 0x080F), "pokey@4000": (0x4000, 0x400F), } def store_references(payload: bytes) -> dict[str, int]: found = collections.Counter() for i in range(len(payload) - 2): if payload[i] in STORE_OPCODES: address = payload[i + 1] | payload[i + 2] << 8 for device, (low, high) in DEVICE_RANGES.items(): if low <= address <= high: found[device] += 1 return dict(found) def region_of(name: str) -> str: tags = re.findall(r"\(([^)]*)\)", name) for tag in tags: if any(r in tag for r in ("USA", "Europe", "World", "Japan")): return tag for tag in tags: if tag in ("NTSC", "PAL"): return tag return "untagged" def bios_report() -> list[str]: lines = [] places = [(MAME_SETS / "a7800.zip"), (MAME_SETS / "a7800p.zip"), *sorted(SETS["licensed"].glob("[[]BIOS[]]*.zip"))] # fmt: skip for path in places: if not path.exists(): lines.append(f"missing: {path}") continue with zipfile.ZipFile(path) as z: for info in z.infolist(): data = z.read(info) sha1 = hashlib.sha1(data).hexdigest() lines.append( f"{path.parent.name}/{path.name}: {info.filename} {len(data)} bytes " f"sha1 {sha1} sha256 {hashlib.sha256(data).hexdigest()} = {BIOS.get(sha1, 'not a MAME BIOS hash')}" ) return lines def table(title: str, counter: collections.Counter, total: int | None = None) -> list[str]: lines = [f"\n{title}"] total = total or sum(counter.values()) for key, count in sorted(counter.items(), key=lambda kv: (-kv[1], str(kv[0]))): lines.append(f" {count:4} {100 * count / total:5.1f} % {key}") return lines def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--json", type=Path, help="write per-dump records here") parser.add_argument("--list", action="store_true", help="one line per dump") args = parser.parse_args() soft_entries = mame_softlist() by_size = softlist_index(soft_entries) sets = {name: read_set(name, folder) for name, folder in SETS.items()} out = [ f"MAME software list: {len(soft_entries)} entries ({MAME_HASH})", "\nBIOS images:", *(" " + line for line in bios_report()), ] # Payload identity across sets. nointro = {d.sha1: d for name in ("licensed", "aftermarket", "private") for d in sets[name]} headered = {d.sha1: d.header for dumps in sets.values() for d in dumps if d.header} records = [] for name, dumps in sets.items(): is_bios = [d for d in dumps if d.sha1 in BIOS or d.name.startswith("[BIOS]")] dumps = [d for d in dumps if d not in is_bios] out.append(f"\n===== {name}: {len(dumps)} cartridge dumps (+{len(is_bios)} BIOS), {SETS[name]}") out += table("format", collections.Counter( ("a78 v%d" % d.header["version"]) if d.header else "headerless" for d in dumps)) # fmt: skip out += table("payload size (KiB)", collections.Counter( f"{d.size / 1024:g}" + ("" if d.size % 4096 == 0 else " (not a 4K multiple)") for d in dumps)) # fmt: skip tiers, schemes, sound, regions, controllers = (collections.Counter() for _ in range(5)) for d in dumps: soft = softlist_match(d, by_size) header = d.header or headered.get(d.sha1) scheme, tier = scheme_of(d, soft, header) tiers[tier] += 1 schemes[scheme] += 1 regions[region_of(d.name) + (f" / softlist {soft['compat']}" if soft else "")] += 1 pokey = [] if soft: pokey = [x for x in MAME_SLOTS.get(soft["slot"], ("", ()))[1] if "pokey" in x or x in ("xm", "xboard")] controllers["lightgun (softlist)" if soft["lightgun"] else "joystick assumed (softlist names only light guns)"] += 1 elif header: pokey = [x for x in header["features"] if "pokey" in x or "ym2151" in x] controllers[f"header: {CONTROLLERS[header['controller1']] if header['controller1'] < len(CONTROLLERS) else header['controller1']}"] += 1 else: controllers["unknown"] += 1 sound["TIA + " + "+".join(pokey) if pokey else ("TIA only" if tier not in ("size-only", "untyped") else "unknown")] += 1 records.append({ "set": name, "name": d.name, "member": d.member, "size": d.size, "crc32": f"{d.crc:08x}", "md5": d.md5, "sha1": d.sha1, "sha256": d.sha256, "header": d.header, "softlist": soft and {k: soft[k] for k in ("name", "slot", "compat", "lightgun")}, "scheme": scheme, "tier": tier, "in_nointro": d.sha1 in nointro, "stores": store_references(d.payload), }) # fmt: skip if args.list: out.append(f" {tier:18} {scheme:38} {d.size:7} {d.name}") out += table("typing source (best available per dump)", tiers) out += table("scheme", schemes) out += table("sound hardware", sound) out += table("controller", controllers) out += table("region tag", regions) # The headered/headerless join asked for in docs/cartridge.md "Formats". retro = [r for r in records if r["set"] == "retrobat"] hit = [r for r in retro if r["in_nointro"]] out.append( f"\n===== retrobat payloads against No-Intro BIN payloads (SHA-1 of the payload): " f"{len(hit)} of {len(retro)} match" ) by_name = collections.defaultdict(list) for d in nointro.values(): by_name[d.name].append(d) for r in retro: if not r["in_nointro"]: same = by_name.get(r["name"]) why = "no No-Intro dump of that name" if same: why = f"same name in No-Intro but different bytes (No-Intro size {same[0].size})" out.append(f" miss: {r['name']} ({r['size']} bytes, header {'yes' if r['header'] else 'no'}): {why}") # Certainty. out.append("\n===== How many No-Intro BIN dumps get every field, by source") for name in ("licensed", "aftermarket", "private"): rows = [r for r in records if r["set"] == name] counts = collections.Counter(r["tier"] for r in rows) out.append(f" {name}: {len(rows)} dumps: " + ", ".join(f"{k} {v}" for k, v in counts.most_common())) out.append("\n===== Dumps whose code stores to a cartridge-port device (indicative; No-Intro sets)") for device in DEVICE_RANGES: rows = [r for r in records if r["set"] != "retrobat" and r["stores"].get(device, 0) >= 2] out.append(f" {device}: {len(rows)} dumps with two or more store instructions") if device in ("ym2151@460", "covox@430", "pokey@800", "pokey@440"): for r in rows: out.append(f" {r['stores'][device]:4} stores [{r['set']}] {r['name']}") print("\n".join(out)) if args.json: args.json.write_text(json.dumps(records, indent=1), encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main())