# SPDX-License-Identifier: MIT """Cartridge files: reading them, identifying the scheme, building the scheme. There is no header in a 2600 dump, so the scheme comes from, in order (docs/cartridge.md "File formats and identification"): 1. an explicit choice by the caller (``scheme=``, and ``super_chip=``); 2. MAME's software list (CC0), read at run time, never committed: the file ``$MAME_HASHPATH/a2600.xml`` if that variable is set, else the copy fetched into ``reference/src/mame/hash/`` (no machine path: without either, this step is skipped); the part's ``slot`` feature, a ``ram`` data area meaning Super Chip, by SHA-1; 3. this package's own detector (``detect.py``), written from the scheme descriptions, and for F8/F6/F4 the Super Chip test below. Every scheme the licensed dumps use is built (milestone 5): 2K, 4K, F8, F6, F4 and their Super Chip forms, FA, E0, 3F, FE, E7, CV, UA, F0, 32IN1, DPC and the Supercharger (AR). """ from __future__ import annotations import hashlib import os import subprocess import xml.etree.ElementTree as ET import zipfile from dataclasses import dataclass from functools import cache from pathlib import Path from .atari import Banked, Plain from .connector import Cartridge from .detect import detect from .dpc import DPC from .licensed import ( E0, UA, ActivisionFE, CommaVid, MegaboyF0, MNetworkE7, ThirtyTwoInOne, Tigervision3F, ) from .supercharger import Supercharger def _mame_hash() -> Path: override = os.environ.get("MAME_HASHPATH") if override: return Path(override) / "a2600.xml" return Path(__file__).resolve().parents[3] / "reference/src/mame/hash/a2600.xml" MAME_HASH = _mame_hash() ROM_SUFFIXES = (".a26", ".bin", ".rom") # DOC: nocash 2k6specs file extensions # Plain sizes: DOC: Horton's 2012 mapper document (F8 8K, F6 16K, F4 32K). SIZE_SCHEMES = {0x800: "2K", 0x1000: "4K", 0x2000: "F8", 0x4000: "F6", 0x8000: "F4"} # MAME slot names -> ours (DOC: MAME 0.285's CC0 hash/a2600.xml slot names). MAME_SLOTS = { "a26_2k_4k": None, "a26_f8": "F8", "a26_f8sw": "F8", "a26_f6": "F6", "a26_f4": "F4", "a26_fa": "FA", "a26_e0": "E0", "a26_3f": "3F", "a26_fe": "FE", "a26_e7": "E7", "a26_cv": "CV", "a26_ua": "UA", "a26_dc": "F0", "a26_32in1": "32IN1", "a26_dpc": "DPC", "a26_ss": "AR", } # fmt: skip # Scheme name -> builder (each builder's module carries its evidence). SCHEMES = { "FA": lambda image, **o: Banked(image, "FA", **o), "E0": E0, "3F": Tigervision3F, "FE": ActivisionFE, "E7": MNetworkE7, "CV": CommaVid, "UA": UA, "F0": MegaboyF0, "32IN1": ThirtyTwoInOne, "DPC": DPC, "AR": Supercharger, } # fmt: skip class UnsupportedCartridge(ValueError): pass @dataclass(frozen=True) class Loaded: cartridge: Cartridge scheme: str # e.g. "F6SC" source: str # "explicit", "MAME softlist", "detector" title: str | None # MAME's description when the list carries the dump sha1: str def read_image(path: str | Path) -> tuple[bytes, str]: """The ROM bytes and a name: a plain file, or the one ROM inside a .zip or .7z.""" path = Path(path) suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as archive: members = [n for n in archive.namelist() if n.lower().endswith(ROM_SUFFIXES)] if len(members) != 1: raise ValueError(f"{path}: expected one ROM, found {members}") return archive.read(members[0]), Path(members[0]).stem if suffix == ".7z": listing = subprocess.run( ["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout members = [ line[7:] for line in listing.splitlines() if line.startswith("Path = ") and line.lower().endswith(ROM_SUFFIXES) ] if len(members) != 1: raise ValueError(f"{path}: expected one ROM, found {members}") data = subprocess.run( ["7z", "x", "-so", str(path), members[0]], capture_output=True, check=True ).stdout return data, Path(members[0]).stem return path.read_bytes(), path.stem @cache def _mame_list(path: Path) -> dict[str, tuple[str, bool, str]]: """SHA-1 -> (slot, has RAM, description) from MAME's software list.""" table: dict[str, tuple[str, bool, str]] = {} if not path.is_file(): return table for software in ET.parse(path).getroot().iter("software"): description = software.findtext("description") or software.get("name", "") for part in software.iter("part"): slot = next( (f.get("value") for f in part.iter("feature") if f.get("name") == "slot"), None ) ram = any(area.get("name") == "ram" for area in part.iter("dataarea")) for rom in part.iter("rom"): sha1 = rom.get("sha1") if sha1: table[sha1] = (slot or "", ram, description) return table def detect_super_chip(image: bytes) -> bool: """Every 4K bank's first 256 bytes (the RAM's two windows) hold one value.""" if len(image) < 0x2000: return False return all(len(set(image[bank : bank + 0x100])) == 1 for bank in range(0, len(image), 0x1000)) def identify(image: bytes, mame_hash: Path = MAME_HASH) -> tuple[str, bool, str, str | None]: """(family, super chip, source, title) for ``image``.""" sha1 = hashlib.sha1(image).hexdigest() entry = _mame_list(mame_hash).get(sha1) if entry is not None and entry[0]: slot, ram, title = entry if slot not in MAME_SLOTS: raise UnsupportedCartridge(f"{title}: MAME slot {slot} is not built") family = MAME_SLOTS[slot] or SIZE_SCHEMES.get(len(image), "?") return family, ram and family in ("F8", "F6", "F4"), "MAME softlist", title title = entry[2] if entry else None try: family = detect(image) except ValueError as error: raise UnsupportedCartridge(str(error)) from None sc = family in ("F8", "F6", "F4") and detect_super_chip(image) return family, sc, "detector", title # Schemes with an oscillator of their own (DPC's music: an RC on the cartridge, # DOC Horton; "an internally generated asynchronous clock", DOC Crane's patent # US 4,644,495; the slot carries no clock, DOC nocash), which so need the # console's CPU clock to count it in CPU cycles: its hertz are fixed, its ticks # per CPU cycle are not. Every other scheme counts CPU cycles only. # System.from_rom passes the row's clock; a host building through load() or # build() passes its own row's (None means the NTSC console's). CLOCKED = frozenset({"DPC"}) def build( image: bytes, family: str, super_chip: bool = False, *, cpu_hz: float | None = None, **options ) -> Cartridge: """``cpu_hz``: the console's CPU clock, handed to the :data:`CLOCKED` schemes and ignored by the rest; None leaves each its NTSC default.""" if cpu_hz is not None and family in CLOCKED: options["cpu_hz"] = cpu_hz if family in ("2K", "4K"): return Plain(image) if family in ("F8", "F6", "F4"): return Banked(image, family, super_chip=super_chip, **options) if family not in SCHEMES: raise UnsupportedCartridge(f"scheme {family} is not built") return SCHEMES[family](image, **options) def load( rom: str | Path | bytes, *, scheme: str | None = None, super_chip: bool | None = None, mame_hash: Path = MAME_HASH, cpu_hz: float | None = None, **options, ) -> Loaded: """Read, identify and build a cartridge; ``options`` go to the scheme (``start_bank``). ``cpu_hz`` is the console's CPU clock for a clocked scheme (:func:`build`), safe to pass for any cartridge: a host passes its row's ``machine.timing.cpu_hz``.""" image = rom if isinstance(rom, bytes) else read_image(rom)[0] sha1 = hashlib.sha1(image).hexdigest() if scheme is not None: family, source, title = scheme.removesuffix("SC"), "explicit", None sc = scheme.endswith("SC") if super_chip is None else super_chip else: family, sc, source, title = identify(image, mame_hash) if super_chip is not None: sc = super_chip cartridge = build(image, family, sc, cpu_hz=cpu_hz, **options) return Loaded(cartridge, cartridge.name, source, title, sha1)