# megadrive-python A readable, pure-Python emulator of the **Sega Mega Drive / Genesis**, built as a board on the family's cores: [m68000-python](https://github.com/alewman/m68000-python) for the main CPU, [z80-python](https://github.com/alewman/z80-python) for the sound CPU, [ym2612-python](https://github.com/alewman/ym2612-python) for the FM chip, and [sn76489-python](https://github.com/alewman/sn76489-python) for the PSG. The cores own their chips (the FM and PSG cores are the restarted ones of 2026-11-12/13, written from documents and installed from local checkouts until they have remotes; docs/validation.md, "Milestone 4 after the restart"); this repository owns everything around them: the memory maps and the bus arbiter between the two CPUs, the VDP (Sega 315-5313 / Yamaha YM7101), the FM chip's and the PSG's wiring, the I/O chip and pads, cartridges and their mappers, TMSS, and the clock that ties them together. **Status: milestones 1 to 9 of ten** ([docs/validation.md](docs/validation.md), "Certification record"): both CPUs run in lockstep with MAME over six games (119.8 M 68000 and 73.0 M Z80 instructions, every difference named); the VDP's ports, FIFO, DMA, counters and interrupts pass VDPFIFOTesting (121/122 on `genesis`, every test that passes on hardware: the one failure, "FIFO Wait States", passes on the die about once in 800 runs and is counted with Nemesis's intermittent tests; a Genesis 3 fails VSRAM tests as the hardware does) and reproduce 99.04 % of the words of Nemesis's 288 HV/status capture dumps; and the picture -- both planes, the window, sprites, priority, shadow/highlight, H32/H40, V28/V30 and both interlace modes -- gives Nemesis's sprite masking ROM the same nine results his MD1600 photographs show, in both widths, and matches MAME's frame pixel for pixel on every static screen of the six lockstep games. Sound is there too: the PSG and the YM2612 -- all six channels, channel 3's special mode, CSM, SSG-EG, the LFO, both timers, BUSY, the DAC and the ladder effect -- come from the restarted ym2612-python and sn76489-python cores, written from documents (the board's earlier in-board sound chips were translations of GPL models and were withdrawn; docs/provenance.md). `--wav` writes what a console would have played; the FM costs about three seconds of wall time per emulated second on PyPy, which is most of why the board runs at 16 to 21 frames a second with sound and 40 to 55 with the FM generator off (`--no-sound`; measured 2026-09-27 on a shared machine, so lower bounds; the 138 to 205 this line used to give was milestone 4's board with no sound chips at all, before the per-slot renderer and the timing work). Bus timing is in as well: the arbiter charges a Z80 bank access the 2 to 5 cycles Kabuto's footnote 1 gives and the 68000 about 11, which reproduces MoD's logic-analyser range exactly with the 68000 off the bus and lands on his mean, 2.91 against his 2.93, with it on the bus; the bus grant waits for the end of the Z80's machine cycle and then for the arbiter to report it; the DMA costs 2.37 and 4.78 68000 cycles a word against Kabuto's measured 2.4 and 4.7 with the 5.6-cycle start-up he measured, and moves the Manual's 16, 167, 18 and 205 bytes a raster line to within one byte; and after every stall the 68000 keeps 481 of a line's 488.6 clocks, which is Kabuto's "roughly 480". The picture is now drawn a piece at a time, so a write part way along a line lands there, CRAM dots and all. And all of that has now been held against **Nuked-MD**, the whole chipset modelled from decapped die photographs, built here headless with a bus tracer of our own: on one NTSC frame of each test ROM of milestones 2 to 5, five of the ten agree with it on **every** one of their 25,307 to 28,921 68000 bus cycles -- address, direction, size, the stall charged to each, and the data read -- and every difference elsewhere is sorted into a named cause. It settled four things nothing else could, and a timing session then adopted them: the DMA start-up cost Kabuto measured is real, the Z80's bus grant came about seven 68000 cycles early, a 68000 access to the Z80's space costs one clock more than the board charged -- which removed the largest named class of clock difference from the milestone-1 lockstep, now 119,755,782 68000 and 73,002,958 Z80 instructions with nothing unexplained and nothing named against MAME's own clock -- and the 68000 holds the bus for only 18 of a bus cycle's 28 master clocks, which had been making every Z80 bank access cost half a wait state too much. It also showed that the board has the two halves of a Z80 `pop` the wrong way round, which needs a change to z80-python to fix. Cartridges and peripherals are in as well: battery SRAM and FRAM, the serial EEPROMs from Eke-Eke's protocol document, the Sega (SSF2) mapper, the 3- and 6-button pads, TMSS with the real boot ROM, and the region and version register -- each judged by a game doing the right thing. **Sonic The Hedgehog 3 lays out its FRAM and NBA Jam writes its EEPROM's header, and every byte of both equals what MAME writes**; a save reloaded into a fresh machine is read back and left alone. **Super Street Fighter II pages in its top megabyte with the two writes its technical document quotes and reaches its title screen. The TMSS boot ROM draws its licence message and hands off to the cartridge at frame 189, and MAME's own TMSS driver agrees on every one of 71,680 pixels.** The two pads reproduce CMD's published table for all 4,352 combinations of their buttons, the games that want six buttons ask for them about once a frame and the ones that do not never ask, and r57shell's VDP tests -- blocked since milestone 3 on what turned out to be a misreading -- are walked and measured. Around the groundwork it was built from, in the shape that built sms-python (the author's Master System board, not public): - a primer on the machine; - the clock tree, the counters, the VRAM access slots, DMA and bus timing, with where each number came from; - the hardware quirks, the differences between models and revisions, the sources known to be wrong, and the open questions; - every oracle found, ranked by tier and pinned; - a fetch script that rebuilds the reference library from those pins; - a working, verified recipe for MAME traces of both CPUs and their bus traffic; - a handoff brief with ten milestones. See [docs/README.md](docs/README.md). ## Installing Python 3.11 or newer; PyPy 3.11 is several times faster and is what CI runs. The four cores are installed from their public GitHub repositories at the revisions `pyproject.toml` pins, so `pip` needs git: ``` pypy3.11 -m venv .venv-pypy .venv-pypy/bin/pip install -e ".[frontend]" # add ",dev" for pytest and ruff .venv-pypy/bin/python -m pytest -q # tests needing fetched files skip ``` ## What you supply No cartridge, BIOS or boot ROM is included or fetched. Bring your own dumps: a cartridge image (`.bin`, `.md`, `.gen`, `.smd`, or a `.zip` holding one), and, only if you want to boot through TMSS, the boot ROM (`--tmss-rom`). The test programs, captures and reference documents the validation scripts use are homebrew or published research, fetched from their authors' sites at pinned SHA-256s by `scripts/fetch_references.py` and never committed (one exception: Sega's MD Soft Checker, milestone 8's judge, is read from a local No-Intro set). The milestone 1, 7 and 8 scripts compare commercial cartridges against MAME and expect a local romset; their default paths are the author's and are set at the top of each script. ## Playing a cartridge Milestone 9 is a window, after sms-python's: picture, stereo sound, the keyboard and game controllers, paced by the audio queue and presented at the display's refresh. ``` .venv-pypy/bin/pip install -e ".[frontend]" # pygame-ce, which has PyPy wheels .venv-pypy/bin/megadrive-python-play "Sonic The Hedgehog (USA, Europe).zip" ``` Arrows, Z X C (or J K L) for A B C, A S D for X Y Z, Enter for Start, Q for Mode; Backspace for the console's reset button (the 68000 and the sound CPU, as on hardware, not a power cycle); Tab to fast-forward, F3 pause, F5 power cycle, F11 fullscreen, F12 screenshot. The machine comes from the header's country codes unless `--machine` names one; `--pad 6button`, `--save FILE` for battery RAM, `--tmss-rom` to boot through TMSS. **It does not reach full speed yet.** With the YM2612 running the board makes 16 to 21 frames a second on PyPy, about a third of real time; `--no-fm` turns the FM generator off (the game runs the same, silent but for the PSG) and `--skip N` draws one frame in N + 1, which together come close to 60. The title bar shows the speed. ## The machine | | | | --- | --- | | Main CPU | Motorola 68000, 7.67 MHz (7.60 PAL) | | Sound CPU | Zilog Z80 (NMOS), 3.58 MHz, 8 KB RAM, a 32 KB window onto the 68000's space | | Video | 315-5313 / YM7101: two planes, a window, 80 sprites, 64 KB VRAM, 9-bit colour from 64 CRAM entries, DMA, H32/H40, V28/V30, interlace; Mode 4 for the Master System | | Sound | YM2612 (OPN2): six 4-operator FM channels, one of them a DAC, and a YM3438-like ASIC on later models; the Sega PSG inside the VDP | | Memory | 64 KB work RAM; cartridge ROM up to 4 MB (more with the SSF2 mapper), battery SRAM or EEPROM | | I/O | three ports (two pads and an expansion port), the version register, TMSS on later models | | Models | Model 1 (VA0–VA7), Model 2, Genesis 3, Nomad; NTSC, PAL, Japanese | ## What is here | Path | What it is | Committed | | --- | --- | --- | | `docs/` | The documents listed in `docs/README.md` | yes | | `scripts/fetch_references.py` | Rebuilds `reference/` and `tests/test_roms/` from the pins | yes | | `scripts/pinned_files.json` | 96 files: URL, SHA-256, size, kind, tier, why (481 MB; 3 over 50 MB fetched only with `--large`) | yes | | `scripts/pinned_repos.json` | 14 git repositories at pinned revisions (sparse where large) | yes | | `scripts/mame_trace.py` | The MAME 0.285 two-run trace recipe for both CPUs and the device buses, verified | yes | | `src/megadrive_python/` | The board: machines, cartridge, I/O, both memory maps and the bus, the VDP and its renderer, the sound chips' wiring, the analogue path, the system clock | yes | | `scripts/lockstep_mame.py` | Milestone 1: both CPUs against MAME's logs | yes | | `scripts/run_hv_captures.py` | Milestone 2: Nemesis's HV/status captures, word for word | yes | | `scripts/run_vdpfifotesting.py` | Milestone 2: VDPFIFOTesting, read back from VRAM | yes | | `scripts/run_sprite_masking.py` | Milestone 3: the sprite masking ROM against Nemesis's MD1600 photographs | yes | | `scripts/run_z80_bus_test.py` | Milestone 3: MoD's `gen_test_z80_bus`, read off the screen | yes | | `scripts/compare_mame_frames.py` | Milestone 3: the board's picture against MAME's frame (a detector) | yes | | `validation/` | The harness that builds BlastEm as a closed-box referee; the three audio models' harnesses (Nuked-OPN2, Nuked-PSG, YM2608-LLE) left as GPL tools on 2026-11-21, and the models' sources are not fetched here since 2026-11-24; the scripts that drove the withdrawn sound cores against the audio models were retired on 2026-11-19. Nuked-MD's driver moved out on 2026-11-19 and is now the GPL-2.0-only tool `tools/nuked-md` of emu-tools-gpl2 (`$EMU_TOOLS_GPL2/tools/nuked-md`; outputs OBSERVED, Nuked-MD 594ca2a via nuked-md 0.2.0); it reads the model's pins only | yes | | `scripts/run_ssg_eg.py` | Milestone 4: Nemesis's SSG-EG test against his MD1600 recording, by measurement | yes | | `scripts/run_mdfourier.py` | Milestone 4: the MDFourier signal against the hardware recordings (a detector) | yes | | `scripts/run_bus_arbiter.py` | Milestone 5: MoD's two logic-analyser experiments, and the 68000's rate | yes | | `scripts/run_dma_cost.py` | Milestone 5: DMA cost per word and per raster line, against Kabuto and the Manual | yes | | `scripts/run_nuked_md.py` | Milestone 6: six comparisons against Nuked-MD, the die-derived referee | yes | | `scripts/run_pads.py` | Milestone 7: the 3- and 6-button pads against CMD's table, r57shell's `joy_speed`, and the games | yes | | `scripts/run_battery.py` | Milestone 7: battery SRAM and the EEPROMs, against the games and MAME's nvram | yes | | `scripts/run_mapper.py` | Milestone 7: the Sega (SSF2) mapper against `ssf2tnc.txt` and Super Street Fighter II | yes | | `scripts/run_tmss.py` | Milestone 7: the boot ROM, the hand-off, the header check and the VDP lock | yes | | `scripts/run_region.py` | Milestone 7: the version register against the Manual, and three games that check it | yes | | `scripts/run_r57shell_tests.py` | Milestone 7: r57shell's eight VDP-test screens | yes | | `scripts/run_soft_checker.py` | Milestone 8: Sega's own MD Soft Checker, read off the screen | yes | | `scripts/mame_media.py` | Milestone 8: which board MAME puts an image on, and how to hand it one | yes | | `scripts/compat_sweep.py` | Milestone 8: every cartridge of the romset against MAME's frame (a detector) | yes | | `scripts/triage_diffs.py` | Milestone 8: every difference sorted, by the lockstep and by the board's own timing | yes | | `tests/` | pytest: the board's tables, milestone 2's judges (fetched), milestone 1's replays (`-m slow`, local) | yes | | `reference/` | Fetched manuals, research documents, forum threads, source trees and die-derived models | no | | `tests/test_roms/` | Fetched test ROMs, logic-analyser captures and hardware audio recordings | no | | `tests/mame_traces/` | MAME runs | no | python -m megadrive_python CART --frames 600 --png frame.png --wav sound.wav python -m megadrive_python CART --pad 6button --save game.srm --tmss-rom BOOT.zip export EMU_TOOLS_GPL2=/path/to/emu-tools-gpl2 # milestone 6's referee: tools/nuked-md there # (GPL-2.0-only, outside this repository; builds on first use) python scripts/fetch_references.py # fetch everything missing python scripts/fetch_references.py --large # also the large recordings python scripts/fetch_references.py --verify # check the pins, fetch nothing ## Next - **Save states** (decided 2026-11-23): built here first, 2026-11-23 ([docs/save-states.md](docs/save-states.md): a state between any two 68000 steps, the format and its up-front refusals, the inventory; `megadrive_python.state.save_state` and `load_state`). 49 loads over eleven cartridges continue identically to the uninterrupted run ([docs/validation.md](docs/validation.md), "Save states"). Carried down the same day: megadrive-rust and megadrive-rust-fast (each with a save-state rung on its ladder, 80 of 80) and play-md (save states, rewind, run-ahead), all local until pushed and deployed. - **Socket 10, a socket device's own state** (2026-11-25, branch `device-state`, decisions B3 and B5): a 32X or Sega CD board saves its side through `sockets.SavedDevice` (`state_version`, `save_state`, `load_state`); the header names each device and its version and refuses another up front; state version 3. Socket 6 gains `Board.publish_lines(mclk)`. What the Rust tiers, segacd-python and sega32x-python do to adopt it: [docs/save-states.md](docs/save-states.md), "Adopting version 3". - **The drawing switch** (found 2026-11-23 by play-md's run-ahead check, fixed the same day): `VDP.rendering = False` skipped line $1FF's sprite scan and never set the sprite collision flag, so an undrawn frame was not the same frame. It now gates only the pixels (`tests/test_drawing_switch.py`). - **Virtua Racing's speedometer** (reported 2026-11-23 from play-md): the needle, sprites DMA'd from the ROM, came out split because the board read the SVP cartridge's ROM on time for DMA; svpdoc says the DMA is one word late from the ROM too, and so it is now (docs/undocumented-behavior.md, item 13). ## Licence MIT for what this repository contains. The fetched material keeps its own terms (recorded per entry in `scripts/pinned_files.json` and `scripts/pinned_repos.json`, and in `docs/validation.md`) and is never committed. Several of the reference emulators and die-derived models are GPL, AGPL or LGPL, and Genesis Plus GX's licence forbids commercial use. Those are built and run as closed boxes only, driven through harnesses written here; their source is not opened, and a value measured from one is tagged `OBSERVED` with the model and its commit. Of the Nuked models only Nuked-MD is fetched, because milestone 6's referee is built from it; Nuked-OPN2, Nuked-PSG and YM2608-LLE are cited by upstream commit and not fetched (Aubrey, 2026-11-24). Permissive sources (Exodus, MIT; MAME's BSD-3-Clause files; SEGAChips, CC0) are used with their notices kept (`NOTICE`). The rules, and where each part of the board came from, are in [docs/provenance.md](docs/provenance.md) (family rules: emulator-lineage's charter, "Licences and provenance").