# SPDX-License-Identifier: MIT """The one loader: every file format people have, to one CartDescription. docs/cartridge.md "Formats: one loader". ``load(source)`` takes a path or bytes and answers, in this order (decided 2026-11-12, handoff-brief.md "Open decisions" 2, 3, 7): 1. **Container**: ``.zip`` through ``zipfile`` (one image member; text and pictures beside it are ignored; two images is an error naming them), ``.7z`` through the ``7z`` program (the family has no pure-Python reader), ProSystem's ``.cdf`` refused (SOUPER's asset manifest, milestone 7), anything else read whole. Nothing is ever written beside the input. 2. **A78 header** (recognised by content, not by extension): stripped; its fields are stated with source "a78 header v". 3. **The table** (cartridge/table.py: MAME's CC0 list and rows we confirmed), by the payload's bytes. A table row beats the header; every field where they differ is reported in ``notes``; ``trust="header"`` or ``"table"`` overrides. On a miss the lookup is retried with the header's size field applied and with uniform leading/trailing fill trimmed to a smaller standard size: a hit that way is "matched after trimming". 4. **a2600-python's identification by hash** (its MAME 2600 list): a 2600 dump. 5. **The BIOS's own test** (cartridge/bios_test.py) when a BIOS image is found: "2600" sends the image to a2600-python; "7800" goes on. 6. **Unknown headerless 7800 image**: 48 KiB or less loads as linear, TIA only, ProLine sticks, with ``certainty = "size"``; larger is refused (:class:`~.description.Refused`) with the payload's SHA-256 and the three ways forward. Identity is the payload's SHA-256 (``CartDescription.sha256``). Loader policy (formats, order, sizes, trimming) is not a hardware claim; the facts it relies on are DOC (the A78 specification, MAME's CC0 list) or the BIOS's own code. """ from __future__ import annotations import re import subprocess import zipfile from pathlib import Path from . import a78, table from .connector import Cartridge, Linear from .description import CartDescription, Refused NOT_IMAGES = (".txt", ".nfo", ".diz", ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".md", ".htm", ".html", ".xml", ".dat", ".url", ".sfv", ".md5") # fmt: skip # Dump sizes to try when trimming fill: loader policy, not a hardware value. STANDARD_SIZES = tuple(k * 1024 for k in (4, 8, 16, 32, 48, 52, 64, 96, 128, 144, 256, 272, 512)) LINEAR_LIMIT = 0xC000 # 48 KiB: the largest a flat mapping from $4000 holds (DOC: Stolberg) def read_source(source: str | Path | bytes) -> tuple[str, bytes]: """(a name for messages, the image's bytes), from a file, an archive or bytes.""" if isinstance(source, (bytes, bytearray)): return "", bytes(source) path = Path(source) suffix = path.suffix.lower() if suffix in NOT_IMAGES: raise Refused(f"{path.name}: a {suffix} file is not a cartridge image") if suffix == ".cdf": raise Refused( f"{path.name}: ProSystem .cdf manifests (SOUPER assets) are not supported yet" ) if suffix == ".zip": with zipfile.ZipFile(path) as z: members = [ i for i in z.infolist() if not i.is_dir() and not i.filename.lower().endswith(NOT_IMAGES) ] # fmt: skip if len(members) != 1: names = ", ".join(i.filename for i in members) or "none" raise Refused( f"{path.name}: expected one cartridge image in the zip, found {names}" ) return f"{path.name}:{members[0].filename}", z.read(members[0]) if suffix == ".7z": try: listing = subprocess.run(["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=True).stdout # fmt: skip except FileNotFoundError as error: raise Refused(f"{path.name}: .7z needs the 7z program, which was not found") from error entries = re.split(r"\n\n", listing.split("----------", 1)[-1]) members = [] for entry in entries: name = re.search(r"^Path = (.+)$", entry, flags=re.MULTILINE) folder = re.search(r"^Folder = \+", entry, flags=re.MULTILINE) if name and not folder and not name.group(1).lower().endswith(NOT_IMAGES): members.append(name.group(1)) if len(members) != 1: raise Refused(f"{path.name}: expected one cartridge image in the 7z, found " f"{', '.join(members) or 'none'}") # fmt: skip data = subprocess.run(["7z", "x", "-so", str(path), members[0]], capture_output=True, check=True).stdout # fmt: skip return f"{path.name}:{members[0]}", data return path.name, path.read_bytes() def _uniform(data: bytes) -> bool: return len(set(data)) <= 1 def trimmed_candidates(payload: bytes, header_size: int | None = None) -> list[tuple[bytes, str]]: """Smaller payloads the same cartridge might be, each with how it was obtained.""" out = [] if header_size and header_size < len(payload): out.append((payload[:header_size], f"header size field {header_size}")) for size in STANDARD_SIZES: if size >= len(payload): break cut = len(payload) - size if _uniform(payload[:cut]): out.append((payload[cut:], f"{cut} bytes of leading fill removed")) if _uniform(payload[size:]): out.append((payload[:size], f"{cut} bytes of trailing fill removed")) return out def _trims_to(long: bytes, short: bytes) -> bool: cut = len(long) - len(short) if cut < 0: return False if long[cut:] == short and _uniform(long[:cut]): return True return long[: len(short)] == short and _uniform(long[len(short) :]) def match_payloads(a: bytes, b: bytes, *, bankset: bool = False) -> str | None: """ "identical", "matched after trimming" (uniform fill removed from the longer), or None. A bankset payload is two images, SALLY's then MARIA's (docs/cartridge.md "Banksets"), and an EPROM-padded copy pads each half: with ``bankset`` the halves are matched separately.""" if a == b: return "identical" long, short = (a, b) if len(a) > len(b) else (b, a) if _trims_to(long, short): return "matched after trimming" if bankset and len(long) % 2 == 0 and len(short) % 2 == 0: lh, sh = len(long) // 2, len(short) // 2 if _trims_to(long[:lh], short[:sh]) and _trims_to(long[lh:], short[sh:]): return "matched after trimming (each bankset half)" return None def _from_row(desc: CartDescription, row: table.Row) -> CartDescription: source = row.source controllers = ("lightgun", "proline") if row.lightgun else desc.controllers fields = { "scheme": row.scheme, "at_4000": row.at_4000, "pokey": row.pokey, "hsc": row.hsc, "xm": row.xm, "controllers": controllers, "title": row.title, } # fmt: skip if row.region != "unknown": fields["region"] = row.region return desc.with_fields(source, **fields) def _apply_header(desc: CartDescription, header: a78.Header) -> CartDescription: source = f"a78 header v{header.version}" if header.version in (3, 4) else "a78 header" fields = dict(header.fields) if header.title: fields["title"] = header.title return desc.with_fields(source, **fields) BUILD_FIELDS = ("scheme", "at_4000", "pokey", "bankset", "ym2151", "hsc", "xm", "region") def load( source: str | Path | bytes, *, overrides: dict | None = None, trust: str | None = None, bios: bytes | None = None, use_bios_test: bool = True, ) -> CartDescription: """The one front door (see the module docstring).""" name, data = read_source(source) header = None notes: list[str] = [] if a78.is_a78(data): header = a78.parse(data) payload = data[a78.HEADER :] if header.size and header.size != len(payload): notes.append( f"header size field {header.size} differs from the payload's {len(payload)}" ) else: payload = data if not payload: raise Refused(f"{name}: empty image") desc = CartDescription(payload=payload, title=Path(name.split(":")[-1]).stem) row = table.lookup(payload) if row is None: for candidate, how in trimmed_candidates(payload, header.size if header else None): row = table.lookup(candidate) if row is not None: notes.append(f"matched after trimming ({how})") desc = CartDescription(payload=candidate, title=desc.title) break with_header = _apply_header(desc, header) if header else None with_row = _from_row(desc, row) if row else None if with_header and with_row: for field in BUILD_FIELDS: h, t = getattr(with_header, field), getattr(with_row, field) if h != t: notes.append(f"header and table differ on {field}: header {h!r}, table {t!r}") chosen = with_header if trust == "header" else with_row if trust == "header": notes.append("--trust header: the header's fields are used") else: chosen = with_row or with_header if chosen is None and overrides and "scheme" in overrides: chosen = desc # the user typed the image: the override is the whole description notes.append("headerless and in no table: described by the override alone") if chosen is None: chosen = _unknown_headerless(desc, name, bios if use_bios_test else None, notes, use_bios_test) # fmt: skip if overrides: chosen = chosen.with_fields("override", **overrides) certainty = _certainty(chosen) return CartDescription(**{**chosen.__dict__, "certainty": certainty, "notes": tuple(notes) + chosen.notes}) # fmt: skip def _certainty(desc: CartDescription) -> str: sources = [desc.provenance.get(field, "default") for field in ("scheme", "at_4000", "pokey")] from .description import SOURCES return max(sources, key=lambda s: SOURCES.index(s) if s in SOURCES else len(SOURCES)) def _unknown_headerless( desc: CartDescription, name: str, bios: bytes | None, notes: list[str], use_bios_test: bool ) -> CartDescription: payload = desc.payload from a2600_python.cartridge import UnsupportedCartridge, identify try: family, _super_chip, source, title = identify(payload) except UnsupportedCartridge: family, source, title = None, None, None if source == "MAME softlist": return desc.with_fields("softlist", console="2600", a2600_scheme=family, title=title or desc.title) # fmt: skip verdict = None region = "unknown" if use_bios_test and len(payload) <= LINEAR_LIMIT: from ..machine import NTSC, PAL from ..system import find_bios from .bios_test import bios_verdict ntsc = bios or find_bios(NTSC) if ntsc is not None: verdict = bios_verdict(ntsc, payload) notes.append(f"BIOS test: an NTSC console starts this image in {verdict} mode") if verdict == "7800": region = "ntsc" pal = find_bios(PAL) if verdict != "7800" else None if pal is not None: # The PAL BIOS checks the region byte only (C8; its own code): a 7800 verdict # there after a 2600 verdict on NTSC is a PAL (or unsigned) 7800 image. pal_verdict = bios_verdict(pal, payload) notes.append(f"BIOS test: a PAL console starts this image in {pal_verdict} mode") if pal_verdict == "7800": verdict, region = "7800", "pal" if verdict == "2600" else "unknown" elif verdict is None: verdict = pal_verdict if verdict is None: notes.append("no BIOS image found: the BIOS test was not run") if verdict == "2600": return desc.with_fields("bios test", console="2600", a2600_scheme=family) if len(payload) <= LINEAR_LIMIT: notes.append("typed by size alone: linear, TIA only, ProLine sticks (labelled)") return desc.with_fields("size", scheme="linear", at_4000="none", pokey=(), region=region) raise Refused( f"{name}: a {len(payload)}-byte headerless image in no table (SHA-256 " f"{desc.sha256}). Its scheme cannot be read from the bytes. Ways forward: an .a78 " "of the same game, an override (e.g. --as supergame,ram@4000,pokey@450), or a " "confirmed table row.", desc.sha256, ) def parse_as(text: str) -> dict: """``supergame,ram@4000,pokey@450`` -> override fields.""" fields: dict = {"pokey": ()} pokey = [] for part in filter(None, (p.strip() for p in text.split(","))): if part in ("linear", "supergame", "activision", "absolute", "souper"): fields["scheme"] = part elif part.startswith("pokey@"): pokey.append(int(part[6:], 16)) elif part.endswith("@4000"): fields["at_4000"] = {"ram": "ram16", "rom": "rom", "bank6": "fixed-bank", "mram": "mirror-ram-2k"}[part[:-5]] # fmt: skip elif part in ("hsc", "xm", "ym2151", "bankset"): fields[part] = True elif part == "bankram": # bankset RAM: 2 x 16 KiB at $4000, by HALT (DOC: wiki) fields["at_4000"] = "ram32-halt" elif part in ("pal", "ntsc"): fields["region"] = part else: raise ValueError(f"unknown hardware word {part!r}") fields["pokey"] = tuple(pokey) return fields def build(desc: CartDescription) -> Cartridge: """The connector object for a 7800 description (schemes grow by milestone).""" if desc.console != "7800": raise ValueError("a 2600 dump is built by a2600-python") if desc.scheme == "linear" and desc.at_4000 == "none" and not desc.pokey and not desc.bankset: return Linear(desc.payload) from . import schemes return schemes.build(desc)