# MAME as the board oracle
Galaga has no deterministic Python reference the way Galaxian had galemu
(z80-wasm, Milestone 4). The only reference board is MAME. This note records,
from runs on this machine, that MAME 0.285's Lua scripting can play that role:
it boots `galaga` headless, runs deterministically, and can emit a canonical
per-frame trace (RAM windows plus typed device events) that the Rust board can
reproduce byte for byte. The script is `oracle/mame_dump.lua`.
## Setup on this machine
- MAME 0.285 at `/usr/games/mame`, plugins at `/usr/share/games/mame/plugins`.
- ROM set: `galaga.zip` (non-merged, 16 files including `51xx.bin` and
`54xx.bin`) in the folder named by `MAME_ROMPATH` (a local copy of MAME's non-merged sets).
It is used in place through `-rompath`; no ROM byte enters this repository.
- No display, no `xvfb-run`, no `DISPLAY`. `-video none -sound none` is enough:
MAME 0.285 runs, emulates the screen bitmap, and saves PNGs without any
window system. `SDL_VIDEODRIVER=dummy` and `-video soft` were not needed.
- `-listxml galaga`: three Z80s at 3.072 MHz (`maincpu`, `sub`, `sub2`), the
51xx (MB8843) and 54xx (MB8844) MCUs, one raster screen 288x224 at
60.606061 Hz (`rotate="90"`), `driver status="good"`, and **no NVRAM device**
(no `nvram` chip in the XML, none in `manager.machine.devices`, and the
`-nvram_directory` stays empty after a run). So NVRAM needs no neutralising;
the option is still pointed at scratch so nothing lands in `$HOME`.
- What MAME does write: `cfg/galaga.cfg` and `cfg/default.cfg` at exit, and
`galaga.cfg` carries a coin counter. Use a fresh `-cfg_directory` per run so
no state crosses runs. `-noreadconfig` keeps `mame.ini` files out.
The command line that works (one run, one fresh directory `$d`):
```sh
GALAGA_FRAMES=1500 GALAGA_DUMP_EVERY=60 GALAGA_SNAPS=1000,1499 \
GALAGA_INPUTS="900:coin1:1,960:coin1:0,1100:start1:1,1130:start1:0,1250:p1_right:1,1310:p1_right:0,1330:p1_fire:1,1340:p1_fire:0" \
GALAGA_OUT=$d/galaga.jsonl GALAGA_SNAP_DIR=$d/snap \
timeout -s KILL 900 /usr/games/mame galaga \
-rompath "$MAME_ROMPATH" \
-video none -sound none -nothrottle -noreadconfig -skip_gameinfo \
-homepath $d -cfg_directory $d/cfg -nvram_directory $d/nvram -snapshot_directory $d/snap \
-autoboot_script oracle/mame_dump.lua
```
The script exits MAME itself at the last frame, so `-seconds_to_run` is not
used: with it, MAME additionally writes an automatic `snap/galaga/NNNN.png` at
exit (observed), and it prints a harmless "-video none doesn't make much sense
without -seconds_to_run" warning without it. `timeout -s KILL`: MAME ignores
SIGTERM under `-video none` (a stuck run survived a plain `timeout`). The
`ALSA ... /dev/snd/seq` line on stderr is noise.
## Lua API as it behaves in 0.285
Verified against (ref-core, ref-mem,
ref-devices, ref-input) and by running. Gotchas found by running:
- `screen.frame_number` is documented as a property but is a **method** here:
`manager.machine.screens[":screen"]:frame_number()`. As a property it is a
function value, so `== 100` never matches.
- `emu.add_machine_frame_notifier(fn)` and `emu.add_machine_stop_notifier(fn)`
return subscription objects. **Hold them in globals**: a subscription kept in
a local is garbage-collected and the callback silently stops firing (seen
after five frames). The legacy `emu.register_frame_done(fn)` keeps running.
- The frame notifier fires once per emulated frame with `frameskip 0`
(`manager.machine.video.frameskip == 0`, `throttled == false`), at the end
of frame N: `machine.time` is `(N+1) x 16.5 ms` (`0000.016,499,999` at
frame 0; 264 lines x 384 pixels / 6.144 MHz = 16.5 ms).
- `space:install_write_tap(lo, hi, name, fn)` / `install_read_tap` on
`machine.devices[":maincpu"].spaces["program"]` (and `:sub`, `:sub2`) work.
The callback gets `(offset, data, mask)`; keep the returned handler objects.
A `space:add_change_notifier` probe reported **no handler change in 1500
frames**, so no reinstall logic is needed. Two hazards: `tap:reinstall()` on
a tap still installed corrupted the heap (`corrupted double-linked list`),
and holding a change-notifier subscription until exit made MAME segfault
(exit 139) after all output was flushed. Neither is used.
- `space:read_range(lo, hi, 8)` returns the bytes as a binary string: one call
per RAM window instead of 2048 `read_u8` calls.
- `machine.ioport.ports[":IN1"].fields["Coin 1"]:set_value(1)` presses,
`:clear_value()` releases. Field names, from iterating `port.fields` (the
`-listxml` `` elements are empty): `:IN0` = `P1 Left` (0x08),
`P1 Right` (0x02), `P2 Left` (0x80), `P2 Right` (0x20); `:IN1` = `Coin 1`
(0x10), `Coin 2` (0x20), `1 Player Start` (0x04), `2 Players Start` (0x08),
`P1 Button 1` (0x01), `P2 Button 1` (0x02), `Service 1` (0x40), `Service
Mode` (0x80); `:DSWA`/`:DSWB` dip switches. `port:read()` reflects a
`set_value` only from the next frame (the record at the frame of the press
still shows 0xff).
- `screen:snapshot(path)` writes a PNG; an absolute path is honoured, a
relative one lands under `-snapshot_directory`. `screen:pixels()` also works
(returns the raw bitmap, w, h) if a diff is wanted in-process.
- `manager.machine:exit()` from the frame notifier ends the run cleanly (exit 0).
## Output format
`GALAGA_OUT` is JSONL: one object per dumped frame (every `GALAGA_DUMP_EVERY`
frames, plus the last frame). Fields, in this order, every value fixed-width:
```
{"frame":900,"time":"0014.866,499,999","in0":255,"in1":255,
"vram":"<4096 hex chars: 0x8000-0x87ff>",
"sprite1":"<256 hex: 0x8b80-0x8bff>","sprite2":"<256 hex: 0x9380-0x93ff>","sprite3":"<256 hex: 0x9b80-0x9bff>",
"events":[{"f":841,"cpu":"maincpu","kind":"star","addr":40960,"data":15}, ...]}
```
- `frame` is MAME's screen frame number (0-based); the record is taken at the
end of that frame, after the frame's scheduled inputs have been applied.
- `vram` is tile codes (0x8000-0x83ff) then attributes (0x8400-0x87ff)
(`galaga_state::galaga_map` in MAME `src/mame/namco/galaga.cpp`, tile
decode in `galaga_v.cpp` `tilemap_get_info`); the sprite windows are the
three shared RAMs (0x8800, 0x9000, 0x9800; 1 KB each) at offset 0x380, as
`galaga_v.cpp` `draw_sprites` reads them. The device windows below are from
the same `galaga_map`.
- `in0`/`in1` are the raw port values (active low) as MAME reads them.
- `events` are every access seen since the previous record, in bus order,
each stamped with `f`, the frame it happened in (accesses before the first
notifier call are `f:0`). `kind` and `addr` (decimal, absolute):
`wsg` 0x6800-0x681f, `latch` 0x6820-0x6827, `bus06` 0x7000-0x70ff,
`ctl06` 0x7100, `star` 0xa000-0xa007. `data` is the byte the Z80 put on the
bus (the 74LS259 latches use only D0, but the whole byte is recorded).
`"read":true` marks main-CPU reads of the 06xx window, which is how the
51xx's credit/input reply reaches the game. Write taps are installed on all
three CPUs and events say which one; observed: only `sub2` writes the WSG,
all three write the latch, only `maincpu` touches 06xx and the star latch.
The Rust side should emit exactly this and be compared with `cmp`.
## Determinism
Same command twice, fresh directories, compared byte for byte:
| Run | Frames | Inputs | JSONL SHA-256 | PNGs |
| --- | --- | --- | --- | --- |
| attract | 600 | none | `ab43dd9c…968ae` (both) | frames 100, 599 identical |
| game | 1500 | schedule above | `07953993…f4656b` (both) | frames 1000, 1499 identical |
The game run holds 26 records and 44,068 events. The starfield (MAME's
`namco_05xx` reconstruction) is part of the PNGs and matched, so no seeding
is involved; 0.285 has no `-seed` option at all (`-showusage` lists none).
## What the traces show
- Frames 0-~700 are the power-on RAM/ROM test: VRAM is being filled with test
patterns (screenshots at 100 and 599 show them), no 06xx traffic after the 5
boot writes in frame 0 (2x `ctl06`, 1x `bus06`, 2x `latch`). The main CPU
starts talking to the 51xx/54xx at frame 715 (11.8 s); from then on about 56
events per frame, 2,280 of every 3,360 being `sub2` WSG writes.
- Inputs go through the 51xx, so timing matters. A coin at frame 120 or 480
(during the test) and at 800 (attract mode had not started; presumably the
51xx was not yet in credit mode [unverified]) changed nothing. A coin at 900 works: the main CPU's read of 0x7000 goes from 0x00 to
0x01 (BCD credits) at frame 903, three frames after `set_value`, and VRAM
0x8035 (the CREDIT digit) becomes 1. A 5-frame tap is enough; a second tap at
1000 gives 2. Start at 1100 produced the "PLAYER 1" screen at 1300; holding
right shows as `in0 = 0xfd`, left as `0xf7`.
- Screenshots: with the default `-rotate`, PNGs are 224x288 (portrait, as the
cabinet). With `-norotate` they are 288x224 and `rot90(raw, 3)` equals the
rotated image exactly; the JSONL is identical either way. Frame 100 holds only
3 distinct colours (the test pattern).
## Speed (`-nothrottle`, this machine)
| Frames | Events | Wall | MAME "Average speed" | JSONL |
| --- | --- | --- | --- | --- |
| 600 | on | 0.5 s | 13,700% | 10 KB |
| 600 | off | 0.5 s | 13,600% | 10 KB |
| 3600 | on | 1.3 s | 5,570% | 8.4 MB |
| 3600 | off | 1.3 s | 5,500% | 35 KB |
About 0.4 s of each is start-up; the taps cost nothing measurable. A minute
of game is a second of wall time, so a run per reference is cheap.
## Limits of MAME as an oracle
- It is emulator-derived, not hardware-captured. Agreement with MAME is
agreement with MAME's model: the Z80 timings, the bus arbitration between
the three CPUs, and the interrupt latching are its interpretation.
- The 51xx and 54xx run MAME's `mb88xx` core on the dumped MCU ROMs. The
three-frame coin latency and the credit-mode window above are that core's
behaviour; a real board may differ by a poll.
- The starfield is MAME's `namco_05xx` reconstruction of an undumped custom
chip; matching it pixel for pixel is matching a reconstruction.
- The WSG and the 54xx noise/explosion sounds are not captured here (`-sound
none`); the register writes are, which is what a board must reproduce.
- The trace has no per-event PC (unlike galemu); events are ordered on the bus
and stamped only with the frame. Finer ordering, if ever needed, would use
`machine.time` in the tap callback.
- The record is taken at the frame notifier, which fires at the **start of
vblank** (MAME's frame runs from vblank start to vblank start; see
cpu-and-timing.md, "Where MAME's frame starts"). The Rust board samples at
the same boundary.
## What the Rust board reproduces (2026-09-11)
`cargo run --release --bin galaga-oracle` (or `cargo test --release` with the
set at `rom/galaga`) runs every run in `runs.json` and compares:
| Run | RAM at every record | main events | sub events | sub2 events |
| --- | --- | --- | --- | --- |
| boot-720 | identical (25 records) | identical | identical | identical |
| attract-1800 | identical (31 records) | identical (13,033) | identical | identical (60,885 total) |
| game-2400 | identical (41 records) | identical (20,235) | identical (3,375) | identical |
Until 2026-10-02 one difference was pinned: in `game-2400` the sub CPU wrote
the sound trigger byte `0x9aa2` a frame early, one shared-RAM race ordered
differently by the two schedulers. Reproducing MAME's scheduler
(`src/galaga/sched.rs`, below) removed it; nothing is pinned now.
Two facts established on the way, both now in the Rust board: MAME's
frame origin is the vblank start (above), and MAME's Z80 starts with F = 0x40
and IX = IY = 0xffff (probed through Lua `state` at frame 0).
## Movies on MAME (2026-10-02)
Any movie of the stock game (no mod: MAME's board has no daughter card)
plays on MAME 0.285 with `oracle/movie_on_mame.sh MOVIE FRAMES EVERY
OUT.jsonl`, and `galaga-mamecheck compare MOVIE OUT.jsonl [FROM]` runs our
board on the same inputs and compares. An input the movie holds during frame
f goes in the Lua schedule at f - 1 (applied after that frame); the movie's
DIP bytes go in whole (`GALAGA_DSW`). Schedules too long for the environment
go through `GALAGA_INPUTS_FILE`. `mame_dump.lua` also gained `GALAGA_PEEK`
(bytes in every record; the hit counter 0x9288), `GALAGA_WORKRAM` (the three
work RAMs), the PC on `GALAGA_WATCH` writes, and `GALAGA_TRACE` (one CPU's
reads and writes in a range, with PCs, during chosen frames). MAME's PC in a
tap is the next instruction's; ours is the current one's.
What it found:
- **The 51xx fire debounce** (docs/custom-io.md): with every reply byte
compared per frame, one-frame fire taps fired on our board and never on
MAME's. Fixed in `n51xx.rs`; the replies now match on every frame of the
test patterns.
- **The scheduling race, reproduced.** An idle game used to part from MAME
11 s after power-on (a sub CPU read of 0x9908 against a main CPU write in
the same slice). MAME's slicing, read from its source and checked against
its traces, is now reproduced (`src/galaga/sched.rs`,
docs/cpu-and-timing.md): attosecond arithmetic, its device list with the
two MCUs as clocks, its timers, its synchronizing writes, and the 51xx's
measured O-port writes (MAME's debugger tracing the MCU headless:
`trace FILE,:51xx:mcu,noloop,{logerror ...}` with the MCU as visible CPU,
`-debug -debugger none -log`). Results: an idle game (4,000 frames) and the
fire test match MAME on every frame; the three reference runs match with
nothing pinned; the 20-minute TAS movie (re-recorded on this scheduler)
matches MAME through frame 9,060, two and a half minutes of busy play
(the old scheduler parted from MAME by frame 1,682 even in an idle game),
and parts at a handshake race whose slice
boundary depends on an MCU's two-cycle instruction overshooting a slice end,
which only running the MCU programs would give (Aubrey chose the measured
approximation over that, 2026-10-02). The MCU traces show why: the 51xx
idles in a five-cycle loop (one two-cycle jump) whose phase each frame
depends on how long its handlers for the 06xx transfer ran.
- Records can differ for one frame where a write lands as the frame ends
(one emulator's snapshot sees it, the other's not); `galaga-mamecheck`
counts those and stops only at three differing frames in a row. Compare
work RAM without the CPU stacks (main and sub 0x9060-0x90ff, sub2
0x9a80-0x9aff): they hold whatever each CPU was doing at the frame's end.