#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Calls libatari800 (GPL-2.0-or-later) as an external library through its public # API; the key codes and state offsets below are interface facts, no code taken. """Drive a locally built Atari800 (libatari800) headless in 5200 mode: frame digests, CPU, RAM. Atari800 is GPL-2.0-or-later. It is run here as an external shared library and asked questions through its public C API (``src/libatari800/libatari800.h``); none of its code is in this repository. The library is this tool's own build, ``build/libatari800.so`` (``build.py``, since 2026-11-25; before, a5200-python's hand build, ``reference/build-atari800/libatari800.so``, from its docs/validation.md recipe); ``--lib`` names another. python "$A5200_GPL_TOOLS/atari800_run.py" "/path/Pac-Man (USA).zip" --frames 600 python "$A5200_GPL_TOOLS/atari800_run.py" cart.a52 --cart-type 6 --frames 300 --every 60 python "$A5200_GPL_TOOLS/atari800_run.py" cart.zip --bios a --pgm out.pgm (from an a5200-python checkout, with its venv). The cartridge is read in place (zip, 7z or loose) and handed to the library as a temporary file under ``tests/detector_runs/`` (gitignored), never written next to the set. The BIOS is read from the MAME set in ``$MAME_ROMPATH`` (``a5200.zip``, or ``a5200a.zip`` in a non-merged set), found by SHA-1. Cartridge type: a raw image carries none. ``--cart-type`` gives Atari800's number (DOC/cart.txt: 4 = 32K, 6 = two-chip 16K, 16 = one-chip 16K, 19 = 8K, 20 = 4K, 7 = Bounty Bob 40K). Without it this script picks by size, and for 16K asks MAME's software list by SHA-1 (CC0 data, read through count_carts.py); a 16K image the list does not know needs ``--cart-type``. Output per sampled frame: frame number, SHA-1 of the 384x240 palette-index screen (GTIA colour register values, not RGB), PC, A, X, Y, S, P and ANTIC's DMACTL as the library's state block reports them. """ from __future__ import annotations import argparse import ctypes import hashlib import os import sys from pathlib import Path # Moved out of a5200-python (scripts/) into emu-tools-gpl on 2026-11-22: a ctypes # declaration of a GPL library's C API is a GPL tool by the family's rule of 2026-11-19. # The board's checkout is A5200_PYTHON_ROOT, else the working directory; its scripts/ # provides the census helpers imported below, and the paths below are that checkout's. ROOT = Path(os.environ.get("A5200_PYTHON_ROOT", Path.cwd())).resolve() sys.path.insert(0, str(ROOT / "scripts")) import count_carts # our own census helpers from romsets import BIOS_SHA1, mame_bios # $MAME_ROMPATH, by SHA-1 #: This tool's own build (build.py), since 2026-11-25. LIB = Path(__file__).resolve().parent / "build" / "libatari800.so" BY_SIZE = {0x1000: 20, 0x2000: 19, 0x8000: 4, 0xA000: 7} WIDTH, HEIGHT = 384, 240 STATE_SIZE = 256 + 210000 # emulator_state_t: two 128-byte unions and the state bytes def cart_type(data: bytes) -> int: if len(data) in BY_SIZE: return BY_SIZE[len(data)] if len(data) == 0x4000: if data[:0x2000] == data[0x2000:]: return 16 entry = count_carts.softlist().get(hashlib.sha1(data).hexdigest()) if entry: return 6 if entry[1] == "a5200_2chips" else 16 raise SystemExit(f"no type known for this {len(data)}-byte image: pass --cart-type") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--frames", type=int, default=600) parser.add_argument("--every", type=int, default=60, help="report every Nth frame") parser.add_argument("--bios", choices=sorted(BIOS_SHA1), default="orig") parser.add_argument("--cart-type", type=int) parser.add_argument( "--work", type=Path, help="ignored run directory for the temporary copies (parallel runs)" ) parser.add_argument("--pgm", type=Path, help="write the last frame's index image") parser.add_argument("--lib", type=Path, default=LIB) parser.add_argument( "--press", action="append", default=[], help="FRAME:KEY:FRAMES on port 1 (keys 0-9 * # start pause reset trigger)", ) parser.add_argument("--wav", type=Path, help="write the library's sound output") args = parser.parse_args() presses = [] for item in args.press: frame, key, length = item.split(":") presses.append((int(frame), key, int(length))) if not args.lib.exists(): print(f"no {args.lib}: run build.py beside this script, or pass --lib", file=sys.stderr) return 3 name, data = count_carts.members(args.cart.resolve())[0] kind = args.cart_type or cart_type(data) work = args.work or ROOT / "tests" / "detector_runs" / "atari800" work.mkdir(parents=True, exist_ok=True) image = work / "cart.a52" image.write_bytes(data) bios = work / f"bios-{args.bios}.rom" bios.write_bytes(mame_bios(args.bios)) config = work / "empty.cfg" config.write_text("", encoding="utf-8") lib = ctypes.CDLL(str(args.lib)) lib.libatari800_get_screen_ptr.restype = ctypes.POINTER(ctypes.c_ubyte) lib.libatari800_get_main_memory_ptr.restype = ctypes.POINTER(ctypes.c_ubyte) lib.libatari800_error_message.restype = ctypes.c_char_p argv = [ "atari800", "-config", str(config), "-5200", "-5200_rom", str(bios), # "custom" would select an empty slot: the file is filed by its CRC. "-5200-rev", args.bios, "-ntsc", "-cart-type", str(kind), "-cart", str(image), ] # fmt: skip c_argv = (ctypes.c_char_p * len(argv))(*[a.encode() for a in argv]) if not lib.libatari800_init(len(argv), c_argv): print("libatari800_init failed:", lib.libatari800_error_message().decode()) return 1 inputs = ctypes.create_string_buffer(64) # input_template_t, all zero: nothing pressed lib.libatari800_clear_input_array(inputs) state = ctypes.create_string_buffer(STATE_SIZE) print(f"{name}: {len(data)} bytes, Atari800 cart type {kind}, BIOS {args.bios}") print("frame screen-sha1 PC A X Y S P DMACTL") screen = b"" sound = bytearray() for frame in range(1, args.frames + 1): held = [key for f, key, n in presses if f <= frame < f + n] lib.libatari800_clear_input_array(inputs) for key in held: if key == "trigger": inputs[9] = 1 # input_template_t.trig0 (keychar, keycode, ..., joy0, trig0) elif key in AKEY_5200: inputs[1] = AKEY_5200[key] # .keycode: a raw AKEY code lib.libatari800_next_frame(inputs) if args.wav: length = lib.libatari800_get_sound_buffer_len() sound += ctypes.string_at(lib.libatari800_get_sound_buffer(), length) if frame % args.every and frame != args.frames: continue screen = ctypes.string_at(lib.libatari800_get_screen_ptr(), WIDTH * HEIGHT) lib.libatari800_get_current_state(state) raw = state.raw # statesav_tags_t: nine 32-bit offsets into state[] (size, cpu, pc, # base_ram, base_ram_attrib, antic, gtia, pia, pokey). tags = [int.from_bytes(raw[i * 4 : i * 4 + 4], "little") for i in range(9)] base = 256 a, p, s, x, y = raw[base + tags[1] : base + tags[1] + 5] pc = int.from_bytes(raw[base + tags[2] : base + tags[2] + 2], "little") antic = raw[base + tags[5] : base + tags[5] + 40] digest = hashlib.sha1(screen).hexdigest()[:16] print(f"{frame} {digest} {pc:04X} {a:02X} {x:02X} {y:02X} {s:02X} {p:02X} {antic[0]:02X}") if args.pgm: args.pgm.write_bytes(b"P5\n%d %d\n255\n" % (WIDTH, HEIGHT) + screen) print(f"wrote {args.pgm}") if args.wav: write_wav( args.wav, bytes(sound), lib.libatari800_get_sound_frequency(), lib.libatari800_get_sound_sample_size(), lib.libatari800_get_num_sound_channels(), ) print(f"wrote {args.wav}") lib.libatari800_exit() # The copies under tests/detector_runs/ go as soon as the run is over. image.unlink() bios.unlink() return 0 # Atari800's raw key codes for the 5200 keypad (src/akey.h, facts restated). AKEY_5200 = { "start": 0x39, "pause": 0x31, "reset": 0x29, "0": 0x25, "1": 0x3F, "2": 0x3D, "3": 0x3B, "4": 0x37, "5": 0x35, "6": 0x33, "7": 0x2F, "8": 0x2D, "9": 0x2B, "#": 0x23, "*": 0x27, } # fmt: skip def write_wav(path: Path, data: bytes, rate: int, width: int, channels: int) -> None: def chunk(tag: bytes, body: bytes) -> bytes: return tag + len(body).to_bytes(4, "little") + body fmt = ( (1).to_bytes(2, "little") + channels.to_bytes(2, "little") + rate.to_bytes(4, "little") + (rate * width * channels).to_bytes(4, "little") + (width * channels).to_bytes(2, "little") + (8 * width).to_bytes(2, "little") ) path.write_bytes(chunk(b"RIFF", b"WAVE" + chunk(b"fmt ", fmt) + chunk(b"data", data))) if __name__ == "__main__": sys.exit(main())