#!/usr/bin/env python3 """Census of a ColecoVision cartridge library, read in place. Each ``.zip``/``.7z`` holds one image (``.col``, ``.rom`` or ``.bin``). The image is read into memory (``zipfile``, or ``7z x -so``); nothing is written to disk and nothing is run. For each image the script reports: - the size class (rounded up to 8K; a ColecoVision image has no header that states its size); - the two bytes at the cartridge's start: ``AA 55`` (the BIOS shows its title screen and waits) or ``55 AA`` (the BIOS jumps straight in); for images over 32K the header is looked for in the last 16K, where a MegaCart keeps it; - whether MAME 0.285's software lists know it (``coleco.xml`` and ``coleco_homebrew.xml`` under ``reference/src/mame/hash``; fetch them with ``scripts/fetch_references.py``). ``coleco.xml`` stores a cartridge as its individual ROM chips, so the image is cut at the list's offsets and each piece's CRC-32 compared. The lists carry the board a cartridge needs (````: ``megacart``, ``activision``, ``xin1``, ``sgc_1mbit``...) and a "req. Super Game Module" note: those columns are the lists' (emulator-derived, curated by the MAME team), not a decode. python -I scripts/count_carts.py "$NO_INTRO_DIR/Coleco - ColecoVision" python -I scripts/count_carts.py /colecovision --rows Only top-level files are read (``By Genre``/``Best Games`` in the curated tree are links to the same files). """ from __future__ import annotations import argparse import collections import hashlib import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] HASH = ROOT / "reference" / "src" / "mame" / "hash" IMAGE = {".col", ".rom", ".bin"} FLAG = re.compile(r"\((Beta|Proto|Demo|Unl|Pirate|Sample|Aftermarket|Homebrew)[^)]*\)") def images(archive: Path) -> list[tuple[str, bytes]]: """The cartridge images inside an archive, as (name, bytes).""" if archive.suffix.lower() == ".zip": with zipfile.ZipFile(archive) as z: return [(n, z.read(n)) for n in z.namelist() if Path(n).suffix.lower() in IMAGE] listing = subprocess.run( ["7z", "l", "-ba", "-slt", str(archive)], capture_output=True, text=True, check=True ).stdout names = [line[7:] for line in listing.splitlines() if line.startswith("Path = ")] names = [n for n in names if Path(n).suffix.lower() in IMAGE] out = [] for name in names: data = subprocess.run(["7z", "x", "-so", str(archive), name], capture_output=True, check=True).stdout out.append((name, data)) return out def load_lists() -> dict[int, list[dict]]: """CRC-32 of a cartridge's first chip -> the software entries that start with it.""" table: dict[int, list[dict]] = collections.defaultdict(list) for list_name in ("coleco", "coleco_homebrew"): for sw in ET.parse(HASH / f"{list_name}.xml").getroot().iter("software"): slot = "" for feature in sw.iter("feature"): if feature.get("name") == "slot": slot = feature.get("value", "") usage = "" for info in sw.iter("info"): if info.get("name") == "usage": usage = info.get("value", "") pieces, cursor = [], 0 for rom in sw.iter("rom"): if not rom.get("crc"): continue size = int(rom.get("size"), 0) offset = int(rom.get("offset"), 0) if rom.get("offset") else cursor pieces.append((offset, size, int(rom.get("crc"), 16))) cursor = offset + size if not pieces: continue pieces.sort() table[pieces[0][2]].append( { "list": list_name, "name": sw.get("name"), "title": sw.findtext("description", ""), "slot": slot, "usage": usage, "pieces": pieces, } ) return table def lookup(data: bytes, table: dict[int, list[dict]]) -> dict | None: for first in sorted({len(data), *(1 << n for n in range(12, 21))}): if first > len(data): break for entry in table.get(zlib.crc32(data[:first]), ()): pieces = entry["pieces"] if pieces[0][1] != first or pieces[-1][0] + pieces[-1][1] != len(data): continue if all(zlib.crc32(data[o : o + s]) == c for o, s, c in pieces): return entry return None def header(data: bytes) -> str: """'AA55' (title screen), '55AA' (straight in) or the two bytes found, in hex.""" start = data[-0x4000:] if len(data) > 0x8000 else data magic = start[:2].hex().upper() if len(data) > 0x8000 and magic not in {"AA55", "55AA"} and data[:2].hex().upper() in {"AA55", "55AA"}: return data[:2].hex().upper() + "@0" return magic def size_class(size: int) -> str: kib = -(-size // 8192) * 8 return f"{kib}K" if size % 8192 == 0 else f"<={kib}K (odd, {size} bytes)" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("directory", type=Path) parser.add_argument("--rows", action="store_true", help="one tab-separated row per image") args = parser.parse_args() table = load_lists() by_size: collections.Counter[str] = collections.Counter() by_header: collections.Counter[str] = collections.Counter() by_list: collections.Counter[str] = collections.Counter() by_slot: collections.Counter[str] = collections.Counter() by_flag: collections.Counter[str] = collections.Counter() by_region: collections.Counter[str] = collections.Counter() sgm, notable, files = [], [], 0 for archive in sorted(args.directory.iterdir()): if archive.suffix.lower() not in {".zip", ".7z"}: continue for name, data in images(archive): files += 1 entry = lookup(data, table) cls, magic = size_class(len(data)), header(data) bios = "[BIOS]" in archive.name slot = "bios" if bios else (entry["slot"] if entry and entry["slot"] else "plain") if not bios and len(data) > 0x8000 and slot == "plain": slot = "over 32K, board not named by the list" by_size[cls] += 1 by_header[magic] += 1 by_list[entry["list"] if entry else "unlisted"] += 1 by_slot[slot] += 1 flag = FLAG.search(archive.name) by_flag[flag.group(1) if flag else "release"] += 1 region = re.search(r"\(([^)]*)\)", archive.name) by_region[region.group(1) if region else "?"] += 1 if entry and "Super Game Module" in entry["usage"]: sgm.append(f"{archive.name}: {entry['usage']}") if slot not in {"plain"} or magic not in {"AA55", "55AA"}: notable.append(f"{archive.name}: {len(data)} bytes, header {magic}, {slot}") if args.rows: print( "\t".join( [ archive.name, str(len(data)), magic, f"{zlib.crc32(data):08x}", hashlib.sha1(data).hexdigest(), f"{entry['list']}:{entry['name']}" if entry else "unlisted", slot, ] ) ) if args.rows: return 0 print(f"{args.directory}: {files} images") for title, counter in ( ("size", by_size), ("header at the cartridge start", by_header), ("MAME 0.285 software list", by_list), ("board", by_slot), ("flag in the file name", by_flag), ("region in the file name", by_region), ): print(f"\n{title}:") for key, count in sorted(counter.items(), key=lambda kv: (-kv[1], kv[0])): print(f" {count:4d} {key}") print(f"\nneeds or uses the Super Game Module (per the list): {len(sgm)}") for line in sgm: print(f" {line}") print(f"\nnot a plain AA55/55AA cartridge of 32K or less: {len(notable)}") for line in notable: print(f" {line}") return 0 if __name__ == "__main__": sys.exit(main())