# SPDX-License-Identifier: MIT """Milestone 5: every local dump through the loader's front door, read in place. Part (a): load each No-Intro zip (``$NO_INTRO_DIR/Atari - Atari 5200``) and each image in ``$A5200_EXTRA_DIRS`` (the census's 7z copies; scripts/romsets.py) with ``load_cartridge``, record mapping and mapping_from, and check that a ``.car`` built in memory from the payload (with the class's CART type) resolves to the same payload SHA-1 and table entry; Bounty Bob's payload is also wrapped as a type-159 image (fixed 8K first) and must come back as the type-7 payload. Part (b) (``--run N``) runs each image N frames and reports whether the CPU jammed and whether it left the BIOS (PC in the cartridge). python scripts/formats_sweep.py # loads only python scripts/formats_sweep.py --run 900 --only "Pac-Man" python scripts/formats_sweep.py --tsv out.tsv Nothing is written next to the sets. The census `.tsv` of Phase 0 lists the same images. """ from __future__ import annotations import argparse import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from romsets import cartridge_sets # noqa: E402 from a5200_python.cartridge import CartridgeError, load_cartridge, make_car # noqa: E402 CAR_TYPE = {"4k": 20, "8k": 19, "16k-one": 16, "16k-two": 6, "32k": 4, "bbsb": 7} def images(only: str | None): for folder in cartridge_sets(): if not folder.is_dir(): continue for path in sorted(folder.iterdir()): if path.suffix.lower() not in (".zip", ".7z") or path.name.startswith("[BIOS]"): continue if only and only.lower() not in path.name.lower(): continue yield folder.name, path def check_car(cart) -> str: kind = CAR_TYPE.get(cart.mapping) if kind is None: return "-" again = load_cartridge(make_car(cart.payload, kind)) if again.sha1 != cart.sha1: return "SHA-1 MISMATCH" if (again.table_row or {}).get("title") != (cart.table_row or {}).get("title"): return "TABLE MISMATCH" if cart.mapping == "bbsb": alternative = cart.payload[0x8000:] + cart.payload[:0x8000] twin = load_cartridge(make_car(alternative, 159)) if twin.sha1 != cart.sha1: return "TYPE-159 MISMATCH" return "ok (+159)" return "ok" def run(cart, frames: int, png_dir: Path | None = None) -> str: """Run; report jam / left BIOS, and the controller use seen (U4, part d).""" from a5200_python.media import write_png from a5200_python.system import Console console = Console(cart) board = console.board consol: set[int] = set() pots: set[int] = set() trigs: set[int] = set() def observe(kind: str, address: int, value: int, cycle: int) -> None: if kind == "W" and 0xC000 <= address < 0xD000 and address & 0x1F == 0x1F: consol.add(value & 0x0F) elif kind == "R": if 0xE800 <= address < 0xF000 and address & 0x0F <= 8: pots.add(address & 0x0F) elif 0xC000 <= address < 0xD000 and 0x10 <= address & 0x1F <= 0x13: trigs.add(address & 0x03) board.bus_observers.append(observe) left_bios = False outcome = "" for _ in range(frames): console.run_frames(1) if 0x4000 <= board.cpu.pc < 0xC000: left_bios = True if board.cpu.halted: outcome = f"JAM at frame {board.frames}" break if not outcome: outcome = "left BIOS" if left_bios else "still in BIOS" blank = len(set(board.frame)) <= 1 if png_dir is not None: png_dir.mkdir(parents=True, exist_ok=True) write_png(png_dir / f"{Path(cart.source).stem.replace(' ', '_')}-{frames}.png", board.frame) ports = sorted({v & 3 for v in consol}) return ( f"{outcome}; screen {'blank' if blank else 'non-blank'}; CONSOL ports {ports}" f" pot-power {'on' if any(v & 4 for v in consol) else 'off'}; POT/ALLPOT read" f" {sorted(pots)}; TRIG read {sorted(trigs)}" ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--only") parser.add_argument("--run", type=int, default=0, metavar="FRAMES") parser.add_argument("--tsv", type=Path) parser.add_argument("--list", type=Path, help="file of No-Intro names (tests/smoke_dumps.txt)") parser.add_argument("--png-dir", type=Path) parser.add_argument("--shard", default="0/1", help="I/N: every Nth image from the Ith") args = parser.parse_args() rows = [] counts: dict[str, int] = {} failures = 0 wanted = None if args.list: wanted = { line.strip() for line in args.list.read_text("utf-8").splitlines() if line.strip() and not line.startswith("#") } shard, shards = (int(v) for v in args.shard.split("/")) selected = [ item for item in images(args.only) if wanted is None or (item[0].startswith("Atari") and item[1].name in wanted) ] for set_name, path in selected[shard::shards]: start = time.perf_counter() try: cart = load_cartridge(path) except CartridgeError as error: rows.append((set_name, path.name, "-", "-", "refused", str(error), "")) failures += 1 continue car = check_car(cart) if not car.startswith(("ok", "-")): failures += 1 key = f"{set_name}:{cart.mapping_from}" counts[key] = counts.get(key, 0) + 1 outcome = run(cart, args.run, args.png_dir) if args.run else "" rows.append((set_name, path.name, cart.mapping, cart.mapping_from, car, cart.sha1, outcome)) if args.run: print( f"{path.name}: {cart.mapping} ({cart.mapping_from}) {outcome} " f"[{time.perf_counter() - start:.0f}s]", flush=True, ) for key in sorted(counts): print(f"{key}: {counts[key]}") print(f"images: {len(rows)}; load or .car failures: {failures}") if args.tsv: lines = ["set\tfile\tmapping\tmapping_from\tcar\tsha1\trun"] lines += ["\t".join(map(str, row)) for row in rows] args.tsv.write_text("\n".join(lines) + "\n", encoding="utf-8") return 0 if failures == 0 else 1 if __name__ == "__main__": raise SystemExit(main())