# SPDX-License-Identifier: MIT """Save states: a restored machine runs on exactly as the original did. methodology.md "Save states in the gate": a state loaded into a fresh console must continue identically. Saves are taken at frame boundaries and inside a frame (any instruction boundary: a WSYNC stall pending, a POKEY interrupt rising, a CX53 trak-ball rolling), restored from a pickled copy made after the original has played on (so a snapshot that shares a list or set with the live machine shows), and restored twice from the same snapshot (as rewind does). """ from __future__ import annotations import os import pickle import zlib from pathlib import Path import pytest from helpers import fake_bios from test_picture import _program from a5200_python import state from a5200_python.cartridge import load_cartridge from a5200_python.media import AudioTap from a5200_python.system import Console def test_restore_replays_identically(): code, ram = _program(0x22, 0x42) console = Console(load_cartridge(bytes(0x8000)), bios=fake_bios(code)) for address, value in ram.items(): console.board.ram[address] = value console.run_frames(3) saved = state.snapshot(console) console.run_frames(2) first = (bytes(console.board.frame), console.board.cycles, console.board.cpu.pc) state.restore(console, saved) console.run_frames(2) second = (bytes(console.board.frame), console.board.cycles, console.board.cpu.pc) assert first == second # -- a synthetic BIOS that keeps every part of the machine busy ---------------- _LOOP = 0xF848 def _busy_bios() -> bytes: """Display list DMA, a VBI NMI, POKEY timer and keyboard interrupts, two tones, pot scans (pot power on every other frame), the keypad, a trigger and a WSYNC every 32 passes of the loop.""" init = bytes( ( 0x78, 0xD8, 0xA2, 0xFF, 0x9A, # SEI CLD LDX #$FF TXS 0xA9, 0x04, 0x8D, 0x1F, 0xC0, # CONSOL = 4: pot power 0xA9, 0x02, 0x8D, 0x0F, 0xE8, # SKCTL = 2: keyboard scan, no debounce (aliased keys) 0xA9, 0x60, 0x8D, 0x00, 0xE8, # AUDF1 0xA9, 0xA8, 0x8D, 0x01, 0xE8, # AUDC1: pure tone 0xA9, 0x30, 0x8D, 0x02, 0xE8, # AUDF2 0xA9, 0xC6, 0x8D, 0x03, 0xE8, # AUDC2 0xA9, 0x41, 0x8D, 0x0E, 0xE8, # IRQEN: keyboard, timer 1 0x8D, 0x09, 0xE8, # STIMER 0x8D, 0x0B, 0xE8, # POTGO 0xA9, 0x00, 0x8D, 0x02, 0xD4, # DLISTL = $00 0xA9, 0x10, 0x8D, 0x03, 0xD4, # DLISTH = $10 0xA9, 0xF8, 0x8D, 0x09, 0xD4, # CHBASE = $F8 0xA9, 0x22, 0x8D, 0x00, 0xD4, # DMACTL: normal playfield, display list 0xA9, 0x40, 0x8D, 0x0E, 0xD4, # NMIEN: VBI 0x58, # CLI ) ) # fmt: skip assert 0xF800 + len(init) == _LOOP loop = bytes( ( 0xE6, 0x80, 0xA5, 0x80, 0x8D, 0x02, 0xE8, # INC $80; AUDF2 = $80 0xAD, 0x0A, 0xE8, 0x85, 0x82, # RANDOM 0xAD, 0x00, 0xE8, 0x85, 0x83, # POT0 0xAD, 0x02, 0xE8, 0x85, 0x88, # POT2 0xAD, 0x09, 0xE8, 0x85, 0x85, # KBCODE 0xAD, 0x0F, 0xE8, 0x85, 0x86, # SKSTAT 0xAD, 0x10, 0xC0, 0x85, 0x87, # TRIG0 0xA5, 0x80, 0x29, 0x1F, 0xD0, 0x03, 0x8D, 0x0A, 0xD4, # every 32nd pass: WSYNC 0x4C, _LOOP & 0xFF, _LOOP >> 8, ) ) # fmt: skip nmi = bytes( ( 0x48, 0xE6, 0x81, # PHA INC $81 0xA5, 0x81, 0x29, 0x01, 0x0A, 0x0A, 0x8D, 0x1F, 0xC0, # pot power every other frame 0x8D, 0x0B, 0xE8, 0x68, 0x40, # POTGO PLA RTI ) ) # fmt: skip irq = bytes( ( 0x48, 0xA9, 0x00, 0x8D, 0x0E, 0xE8, 0xA9, 0x41, 0x8D, 0x0E, 0xE8, # acknowledge 0xE6, 0x84, 0xA5, 0x84, 0x09, 0x40, 0x8D, 0x00, 0xE8, # AUDF1 = $84 | $40 0x68, 0x40, ) ) # fmt: skip image = bytearray([0xEA]) * 2048 image[: len(init)] = init image[len(init) : len(init) + len(loop)] = loop image[0x100 : 0x100 + len(nmi)] = nmi image[0x180 : 0x180 + len(irq)] = irq image[0x7FA:0x800] = bytes((0x00, 0xF9, 0x00, 0xF8, 0x80, 0xF9)) return bytes(image) _DLIST = bytes((0x70, 0x70, 0x70, 0x42, 0x00, 0x20, *([0x02] * 7), 0x41, 0x00, 0x10)) def _busy_console() -> Console: console = Console(load_cartridge(bytes(0x8000)), bios=_busy_bios()) console.board.ram[0x1000 : 0x1000 + len(_DLIST)] = _DLIST console.board.ram[0x2000:0x2140] = bytes((i * 7) & 0x7F for i in range(0x140)) return console def _drive(console: Console, f: int) -> None: """Frame f's inputs: on port 1 (the port the program scans) a trak-ball changing speed, its buttons and the keypad, the keys set mutated in place as a frontend may; a stick on port 2.""" ball, pad = console.controllers.pads[0], console.controllers.pads[1] ball.trakball = True ball.vx = (3.0, 8.0, -2.0, 0.0, 5.5)[f % 5] ball.vy = (-4.0, 1.0, 6.0)[f % 3] ball.trigger = f % 4 == 1 ball.top = f % 3 == 2 ball.keys.clear() if f % 3: ball.keys.add(("1", "5", "start", "#", "0")[f % 5]) pad.x = 20.0 + (f * 37) % 200 pad.y = 228.0 - (f * 11) % 200 RECORD_FIELDS = ( "frames", "cycles", "frame CRC", "RAM", "CPU", "POKEY", "GTIA", "pot targets", "pot charge", "pad positions", ) # fmt: skip def _record(console: Console) -> tuple: board, controllers = console.board, console.controllers return ( board.frames, board.cycles, zlib.crc32(board.frame), bytes(board.ram), board.cpu.capture_state(), board.pokey.snapshot(), board.gtia.snapshot(), list(controllers.rc.target), list(controllers.rc.charge), [(p.x, p.y) for p in controllers.pads], ) def _continue(console: Console, start: int, frames: int, drive=_drive) -> list[tuple]: """Finish the current frame without new inputs, then play ``frames`` more.""" tap = AudioTap(console.board) console.board.audio = tap console.board.run_frame() records = [_record(console)] for f in range(start, start + frames): drive(console, f) console.run_frames(1) records.append(_record(console)) console.board.audio = None records.append(bytes(tap.samples)) return records def _round_trip(make, saved: dict, start: int, frames: int, expected: list, drive=_drive) -> None: """Restore ``saved`` into two fresh consoles in turn, one from a pickled copy and one from the very dict; each must play on exactly as the original did.""" copied = pickle.loads(pickle.dumps(saved, protocol=4)) for source in (copied, saved): fresh = make() state.restore(fresh, source) got = _continue(fresh, start, frames, drive) for n, (a, b) in enumerate(zip(expected, got, strict=True)): if n == len(expected) - 1: assert a == b, "audio samples differ" continue for field, x, y in zip(RECORD_FIELDS, a, b, strict=True): assert x == y, f"{field} differs at record {n} (0 = the end of the saved frame)" # Where inside the frame the save is taken: a cycle count past the frame boundary # (0 = at the boundary), or the first instruction boundary at which a condition holds. SAVE_POINTS = { "frame-boundary": 0, "cycle-1": 1, "cycle-7001": 7001, "cycle-15013": 15013, "cycle-29801": 29801, "wsync-pending": lambda board: board.antic.wsync_at >= 0, "irq-edge-unsynced": lambda board: board._irq_next != board._irq_line, "irq-held": lambda board: board._irq_line and board.cpu.p & 0x04, "nmi-pending": lambda board: board.cpu.capture_state().non_maskable_interrupt_pending, } def _run_to(console: Console, where) -> None: board = console.board if callable(where): for _ in range(200_000): board.step() if where(board): return raise AssertionError("save point never reached") board.run_cycles(where) @pytest.mark.parametrize("where", list(SAVE_POINTS), ids=list(SAVE_POINTS)) def test_save_anywhere_continues_identically(where): original = _busy_console() for f in range(3): _drive(original, f) original.run_frames(1) _run_to(original, SAVE_POINTS[where]) # The frontend changes the pads after this frame's inputs were applied: the # machine still holds what was applied, and so must the save. pads = original.controllers.pads pads[0].vx, pads[1].x, pads[1].trakball = 7.0, 3.0, True saved = state.snapshot(original) expected = _continue(original, 3, 2) _round_trip(_busy_console, saved, 3, 2, expected) def test_trakball_save_mid_roll_restores_the_lag_unstepped(): """a5200-rust's finding (2026-11-14): the lag output was not saved, and restore stepped it.""" original = _busy_console() for f in range(4): _drive(original, f) original.run_frames(1) saved = state.snapshot(original) fresh = _busy_console() state.restore(fresh, saved) for a, b in zip(original.controllers._balls, fresh.controllers._balls, strict=True): assert a.out == b.out assert original.controllers.rc.target == fresh.controllers.rc.target assert [(p.x, p.y) for p in original.controllers.pads] == [ (p.x, p.y) for p in fresh.controllers.pads ] # -- commercial images (pytest -m slow; need $NO_INTRO_DIR and the BIOS) -------- def _image(name: str) -> Path: root = os.environ.get("NO_INTRO_DIR") path = Path(root or "/nonexistent") / "Atari - Atari 5200" / f"{name}.zip" if not path.is_file(): pytest.skip(f"needs $NO_INTRO_DIR with {name}") return path @pytest.mark.slow def test_missile_command_trakball_save_continues(): """The repro a5200-rust sent (scripts/trak_state_repro.py there): a trak-ball rolling from frame 480, saved at frame 500; lag 164.0 at the save read 139.0 after the restore, POT0's target ten frames on 18696 against 18693.""" rom = _image("Missile Command (USA)") def drive(console, f): pad = console.controllers.pads[0] pad.trakball = True pad.vx = 4.0 if f >= 480 else 0.0 original = Console(rom) for f in range(1, 501): drive(original, f) original.run_frames(1) saved = state.snapshot(original) expected = [] for f in range(501, 511): drive(original, f) original.run_frames(1) expected.append(_record(original)) fresh = Console(rom) state.restore(fresh, saved) for n, f in enumerate(range(501, 511)): drive(fresh, f) fresh.run_frames(1) assert _record(fresh) == expected[n], f"diverged at frame {f}" def _title_drive(kind: str): def drive(console, f): pad = console.controllers.pads[0] pad.keys.clear() if 300 <= f < 310: pad.keys.add("start") pad.trigger = f >= 400 and f % 20 < 5 if kind == "trak": pad.trakball = True pad.vx = (6.0, -3.0, 0.0, 2.5)[(f // 7) % 4] pad.vy = (-5.0, 4.0, 1.0)[(f // 5) % 3] elif kind == "keypad": if f >= 400 and f % 9 < 3: pad.keys.add(("1", "4", "7", "0", "#", "*")[(f // 9) % 6]) pad.x = 114.0 + ((f % 60) - 30) * 3 else: pad.x = (20.0, 114.0, 220.0)[(f // 15) % 3] pad.y = (114.0, 220.0, 20.0)[(f // 25) % 3] return drive TITLES = { "Missile Command (USA)": "trak", "Centipede (USA)": "trak", "Star Raiders (USA)": "keypad", "Pac-Man (USA)": "stick", } @pytest.mark.slow @pytest.mark.parametrize("name", list(TITLES)) def test_mid_frame_save_continues_on_titles(name): rom = _image(name) drive = _title_drive(TITLES[name]) original = Console(rom) for f in range(600): drive(original, f) original.run_frames(1) _run_to(original, 12_345) saved = state.snapshot(original) expected = _continue(original, 600, 6, drive) _round_trip(lambda: Console(rom), saved, 600, 6, expected, drive)