# rick-roll-md — build plan A Mega Drive cartridge that plays a full music video (3:31) with sound, built with Overdrive 2's tricks, developed and verified entirely against `megadrive-python` (which matches Nuked-MD, the die-derived model). Target: **16 MB on Krikzz's Extended SSF mapper**, activated by the `"SEGA SSF"` header — the exact header and mapper Overdrive 2 (8 MB) ships with, and the only mapper a real flashcart can be *asked* for by a ROM. The premise is a joke; the engineering is not. > **Correction (2026-10-09).** An earlier draft targeted 32 MB on "the standard Sega > mapper, Overdrive 2's own board". That was wrong, and the emulator's own worklog > (`docs/worklog.md`, "Krikzz's Extended SSF") is what caught it: Overdrive 2 is > **8 MB**, its header reads `"SEGA SSF"`, and a flashcart activates the mapper from > that header — Krikzz's Extended SSF, **5-bit page field, 32 × 512 KB = 16 MB**. > MAME's 6-bit `rom_titan`/`rom_ssf2` device is chosen by *ROM hash from a software > list*, which no flashcart does and which our ROM can never be in. No path above > 16 MB is documented in any reference this project holds. 16 MB is the proven > ceiling; it is also what the user asked for first. Every number below comes from the emulator's own docs (`docs/timing.md`, `cartridge.py`, `render.py`, `ym2612.py`) or from measurements made with `encoder_prototype.py`. Nothing is a guess; where something is still unmeasured it says so. --- ## 1. What "impressive" means — the claims we intend to be able to make 1. **Full-screen 320-wide FMV at the source's native 25 fps**, tear-free, for the whole 211 s song, from a cartridge that boots on a stock console. 2. **Per-cell palette-line and shade selection** — the "washed-out" problem solved on hardware terms. Measured in Phase 1: per-cell shadow is the big win (42–82 % of cells choose it on this dark source). Raster-band palette reloads (up to 448 CRAM colours/frame) and per-pixel sprite-mask shading are *available* and will be built if the budget allows, but Phase-1 measurement puts their gain at only 2–18 % and 7–15 % of remaining error on this footage — the source's own colour range, not the hardware, is the ceiling. They are features, not the headline. 3. **Streamed 8-bit PCM** that does not crackle during the heaviest DMA frames — the classic Genesis FMV failure, designed out rather than tolerated. 4. **Every frame byte-identical to the encoder's prediction** when run in the emulator — the whole thing is reproducible from one build command, with the emulator as the test oracle. This is the vibe-coding story: not "it looks right", but "5,275 frames, 0 mismatches". --- ## 2. Fixed facts and budgets ### Display (decided: V28 320×224, dual-region — see Decisions) | | value | source | |---|---|---| | Video source | 25 fps, top-field-first, PAL | ffprobe | | Target mode | H40, 320 px wide | — | | Hardware frames per video frame | 2 (PAL 49.70 Hz) | `machine.py` | | Lines/frame, PAL | 313 | `docs/timing.md` | | Blank lines/frame, PAL V28 / V30 | 89 / 73 | 313 − 224 / 240 | | DMA to VRAM, H40 blanking | 205 B/line | Manual table, board gives 205.1 | | DMA to VRAM, H40 active display | 18 B/line | same | | 68000 cycles per hardware frame, PAL | ~152,900 (7.60 MHz / 49.70) | `machine.py` | | 68000 cost of a slow (64 KB VRAM) DMA | ~4.78 cycles/word, + ~7 start-up | `docs/timing.md` | **DMA bandwidth per video frame** (two VBlanks + two active periods, V30): 2 × (73 × 205 + 240 × 18) ≈ **38.6 KB** ≈ 1,200 tiles' worth. In V28: 2 × (89 × 205 + 224 × 18) ≈ **44.5 KB**. Either way DMA bandwidth is *not* the binding constraint — a full 1,200-cell refresh fits. The binding constraint is VRAM (next table). ### VRAM (64 KB) | region | bytes | |---|---| | Plane A name table, 64×32 cells | 4,096 | | Plane B name table (points at an all-blank table; must exist) | 2,048 (32×32) or share | | Sprite attribute table (80 sprites) | 640 | | H-scroll table (whole-screen mode) | 4 | | **Tile cache** | **~57 KB ≈ 1,790 slots** (tile 0 reserved blank) | A 320×240 frame is 1,200 cells. With a single name table flipped atomically in VBlank, new tiles for frame N+1 can only land in slots *not referenced by frame N*: ≈ **590 free slots** (V30) or **≈ 670** (V28, 1,120 cells). That is the per-frame "new tile" ceiling — the encoder's rate controller enforces it. Measured change rates (two 15 s clips, VQ tolerance 150k): **~40 % of cells change per frame** ≈ 480 tiles. Fits, with ~20 % headroom. Peaks (cuts) exceed it — handled by lookahead prefetch (section 4.4), never by dropping frames. ### Colour | | value | |---|---| | CRAM | 64 colours = 4 palette lines × 16, 9-bit RGB (8 DAC steps/channel, non-linear ramp) | | Per-cell attributes (name-table word) | priority (bit 15), palette line (14–13), vflip (12), hflip (11), tile (10–0) | | Shadow/highlight mode (reg 12 bit 3) | low-priority cells render through the shadow ramp: a **free second brightness level per cell** | | Measured benefit of per-cell shade | 42–60 % of tiles prefer shadow; 31–52 % lower quantization error per band | ### Audio | | value | source | |---|---|---| | YM2612 DAC | 8-bit, replaces ch. 6 when $2B bit 7 set; data at $2A | `ym2612.py` | | Hardware sample ceiling | 52,781 Hz PAL (1 sample / 24 internal cycles) | `ym2612.py` | | Timer A as sample clock, period = (1024 − NA) FM samples | NA=1020 → 13,195 Hz; 1021 → 17,594 Hz; 1022 → 26,390 Hz (PAL) | derived | | Z80 clock, PAL | 3.547 MHz → ~201 cycles per sample at 17.6 kHz | `machine.py` | | Z80 RAM | 8 KB | — | | Z80 sees ROM through | 32 KB bank window $8000–$FFFF, bank reg at $6000 | — | | The trap | Z80 reads of the 68000 bus **stall during 68000→VDP DMA** (68000 is off the bus, so is anyone else wanting it) | `docs/timing.md`, `arbiter.py` | PCM ROM cost for 211 s, mono 8-bit: 13.2 kHz → 2.78 MB; **17.6 kHz → 3.71 MB**; 26.4 kHz → 5.57 MB. ### ROM budget (16,777,216 bytes — hard) | region | allocation | |---|---| | Video: tile codebook | ≤ 8.5 MB | | Video: per-frame command + name-table stream | ≤ 3.5 MB | | Audio: PCM | 3.71 MB at 17.6 kHz (fallback 2.78 MB at 13.2 kHz if the rate controller needs it) | | Code, title, credits, palettes, header, slack | ≤ 0.5 MB | Measured so far (greedy VQ, tol. 150k, no flips, no luma weighting, index+band keyed): codebook ~1.33 MB / 30 s (→ ~9.4 MB if linear; growth was *sub*-linear at this tolerance: segment 2 added 30 % fewer tiles than segment 1), delta stream ~10 MB at a lazy 4 B/cell. **The plain prototype does not fit 16 MB.** **Phase-2 streaming baseline (2026-10-09, 15 s clip, no ROM-side dedup at all):** 305 new tiles/frame mean (plan assumed 480), 3.66 MB tile data + 0.95 MB patches (4 B/cell) = 4.99 MB ROM for 15 s → **~70 MB/song if nothing else were done**. 12 of 375 frames needed a tolerance retry (all at cuts, one-frame softening); 0 hit the ring-exhaustion fallback. This is the number the ROM-side VQ codebook (every new VRAM tile is currently stored again even when an identical one exists earlier in ROM), cross-shot reuse, stream packing and the rate controller must bring under ~12 MB. The optimizations in section 4 are therefore *mandatory*, not polish, and the two-pass rate controller (4.6) is what guarantees the target is hit: it spends exactly the budget there is. The levers already measured individually: hysteresis 300→3,000 gave 1.6× fewer tiles on one clip; stream packing takes 10 MB → ~3 MB; flips and index-only keying are unmeasured but structurally ≥ 1×. Stacked, 12 MB of video is the working assumption — to be confirmed in Phase 2 on the two test clips before Phase 5. --- ## 3. Architecture — all intelligence offline ``` source .m2v ──ffmpeg──► fields (PNG) ──┐ source audio ──ffmpeg──► mono WAV ─────┤ ▼ ┌──────────── encoder (Python) ────────────┐ │ shot detection → palettes → quantize → │ │ VQ codebook → VRAM cache sim (Bélády) → │ │ 2-pass rate control → ROM layout → │ │ emits: rom.bin + expected/NNNNN.png │ └───────────────────────────────────────────┘ │ ▼ megadrive-python (--machine megadrive / nuked-md, PAL, TMSS ROM) │ board_frames.py ──► actual/NNNNN.png ──compare──► 0 mismatches --wav ──► actual.wav ──compare──► input WAV ``` The 68000 program is deliberately dumb: a **DMA-list executor** that reads pre-formatted commands from ROM and feeds the VDP, plus an H-interrupt handler that reloads CRAM at band boundaries. The Z80 program is a **timer-clocked PCM ring-buffer player**. All decisions — which tile goes in which VRAM slot, when, which palette a cell uses, where in ROM each byte sits — are made by the encoder, which can see the entire future of the video. That is Overdrive 2's philosophy and it is what makes byte-exact verification possible. ### 3.1 Encoder (`rrmd/encode/`) Grows out of `encoder_prototype.py`. Stages, each independently measurable: 1. **Ingest**: one top field per frame → 320×240 (or 320×224, D1) LANCZOS. Audio: user's `ffmpeg -vn -ac 1 -ar -f u8` (the encoder never touches the MPEG itself). 2. **Shot detection**: frame-difference threshold → shot boundaries. Palettes and VQ codebooks are fitted *per shot*; the cache simulator prefetches across them. 3. **Palettes**: per shot, per band (6 bands of 40 lines = 5 tile rows), **4 palette lines of 16**, fitted by k-means (or median-cut as now) on that band's pixels across the shot, snapped to the 8-step DAC ramp. Colour 0 of each line is transparent on sprites but opaque on planes — usable. 4. **Per-cell assignment**: for each cell choose (palette line, shade) minimizing **luma-weighted** squared error (Y-weighting is cheap and is where the eye lives); then quantize pixels with **temporal hysteresis** (tolerance 300 as validated by eye; sweep again under the new colour system). 5. **VQ codebook**: tiles keyed by *index pattern only* (a pattern reused under a different palette line is still one tile), matched under **all four flips** (free ×4 reuse via name-table bits), greedy-first-match in quadrant-average buckets as now, then an LBG/k-means refinement pass per shot. 6. **VRAM cache simulation**: exact model of the 1,790 slots. Eviction is **Bélády-optimal** (evict the tile whose next use is farthest away — the encoder knows). Prefetch: when free slots exist, pre-load tiles for upcoming frames so cuts don't exceed the per-frame ceiling. 7. **Rate control, two-pass**: pass 1 measures per-frame demand (new tiles, stream bytes) at a base tolerance; pass 2 assigns a per-frame VQ tolerance so that (a) every frame's new-tile count ≤ free slots, (b) total ROM ≤ target, (c) tolerance varies smoothly (no quality pumping). Exactly how x264's 2-pass works, with "bits" = tiles. 8. **ROM layout**: tiles stored in **first-use order per frame** so each frame's new tiles are one or two contiguous DMA runs. A tile already in ROM but needed again after eviction is either DMA'd from its old address (one extra DMA descriptor, ~80 68000 cycles + stall) or **duplicated** into the new frame's run (32 bytes of ROM). The encoder picks per tile with an explicit cost model — ROM is the cheap resource here. 9. **Name-table stream**: per frame, bitmask of changed cells (1,200 bits = 150 B) + one packed 16-bit attribute word per changed cell. Decoded by the 68000 into a RAM copy, then one DMA to VRAM. ~1.1 KB/frame at 40 % change → ~6 MB/song; LZ-style compression of the stream is the fallback if the budget needs it (68000 has ~250k spare cycles per video frame; a 25-cycle/byte decompressor handles 10 KB/frame). 10. **Emit**: `rom.bin`, `expected/NNNNN.png` (the encoder's own render of what the screen must show, through the exact `render.py` ramp and S/H rules), and a JSON report (per-frame tolerance, new tiles, DMA bytes, 68000 cycle estimate, ROM map). ### 3.2 ROM format ``` $000000 vector table, header: console field "SEGA SSF" (activates Krikzz's Extended SSF on flashcarts AND in megadrive-python's Cartridge.from_image), region, checksum; TMSS unlock $000200 68000 player + Z80 driver binary + title/credits tiles & palettes $010000 frame index: 5,275 × (stream offset, 32-bit) $020000 frame streams (variable length): u16 flags (band-palette reload mask, name-table flip, prefetch-only) u8 n_dma; n_dma × { u32 ROM src | u16 VRAM dst | u16 words } u8 n_cram; n_cram × { u8 band | 128 bytes } (only when palettes change) name-table delta: 140-byte bitmask + changed cells' u16 words ~$1xxxxx tile data (first-use ordered runs), 32 B each, 4bpp ~$Cxxxxx PCM, u8 unsigned, contiguous, aligned to 32 KB (Z80 bank-window friendly) ``` Bank switching (Extended SSF, `extended_ssf-v2.txt` as summarized in the emulator's worklog): page field is **5 bits**; windows 1–7 ($080000–$3FFFFF) are paged by word writes to $A130F2–$A130FE (the low byte lands on the odd address, which is what the emulator's `write_time` decodes). **Do not touch $A130F0/F1** — on this board it is mapper control (protect, first-bank switch, LED), not SRAM control, and the one open MAME-vs-spec conflict in the emulator's polish list lives there. The player keeps window 0 fixed (code), maps the current frame's tile runs and stream pages into windows 1–7. The encoder lays out ROM so that one frame never needs more than seven 512 KB pages at once (trivially true at ~40 KB/frame). ### 3.3 68000 player (`rrmd/player/main.asm`) Boot: TMSS unlock (write "SEGA" to $A14000 if version ≥ 1), region/PAL detect from $A10001, VDP init (H40, V30 or V28, S/H on, plane A at the name table, plane B at blank), load Z80 driver, start Z80. Then per hardware frame, in the VBlank interrupt: 1. If this is hardware frame 2 of a video frame: DMA the staged name table (one 3,840-byte DMA, 68000 RAM → VRAM) — the atomic flip. 2. Walk the frame's DMA list: `move.l (a1)+,(a0)` × 4 per descriptor (the stream stores VDP-ready control words), ~80 cycles + stall each. 3. Decode the next frame's name-table delta into the staging buffer. 4. Advance audio-synchronized frame counter (3.5). H-interrupt (reg 10 counter = band height − 1): at each band boundary, **display off for one line** (reg 1 bit 6) — in that line DMA runs at the blanking rate (205 B), enough for a full 128-byte CRAM reload (64 words) with margin; display back on. Cost: 5 black lines per 240 (a scanline-gap aesthetic, invisible on CRT). Backdrop set to colour 0 = black so the display-off lines are black. This is the CRAM-dots-free way to reload palettes mid-frame; Overdrive 2 uses display-off windows for the same reason. Budget check per hardware frame: DMA stall ~20 KB × 4.78/2 ≈ 48k cycles worst case; descriptor overhead 30 × 80 = 2.4k; name-table decode ~20k; slack > 80k cycles. Comfortable. ### 3.4 Z80 PCM driver (`rrmd/player/pcm.z80`) - Ring buffer in Z80 RAM, 4 KB (= 230 ms at 17.6 kHz — absorbs any DMA stall; the longest is one full VBlank ≈ 4.7 ms). - **Output clocked by YM2612 Timer A** (poll status bit 0, write sample to $2A, re-arm): deterministic rate independent of bus stalls. NA chosen per region at boot so rates differ by only the FM-clock ratio (0.9 %). - **Refill** between ticks, in bounded chunks, from the ROM bank window; refill is skipped while the VDP status register ($7F04 from the Z80's map) shows VBlank — so the Z80 *voluntarily* stays off the bus during the DMA-heavy window instead of being stalled mid-tick. - Exposes a 32-bit **samples-played counter** in Z80 RAM. - Never BUSREQ'd by the 68000 after start (the 68000 reads the counter with a brief bus request once per hardware frame; ~5 µs, inaudible with timer-clocked output). ### 3.5 A/V sync — audio is the master clock The 68000 derives the current video frame from the Z80's samples-played counter (`frame = samples × 25 / rate`), so audio and video can never drift, on any region, regardless of frame-rate pulldown. Video pacing is a *consequence* of audio position, not a parallel counter. ### 3.6 Title / outro Static tile art + text, auto-advances after a few seconds (nobody should have to press Start to be rickrolled). Credits at the end: tools, the emulator, the oracles (Nuked-MD, Kabuto's research), the source's provenance. Small, in the 2 MB code region. --- ## 4. Optimization levers, in order of expected payoff | lever | expected effect | status | |---|---|---| | 4.1 Per-cell palette line (4 lines) instead of 1 line per band | built in Phase 1 | **done** | | 4.2 Per-cell shade (priority bit, S/H mode) | built in Phase 1; 82 % of cells chose shadow on the test frame | **done** | | 4.3 Luma-weighted error metric | built in Phase 1 | **done** | | 4.3b **Better palette fitter** (joint across lines; current k-means+median-cut is noisy — 2 bands scored *worse* than 1 on one frame, which a sound fitter cannot do) | real, unmeasured; likely larger than any raster trick | Phase 3 | | 4.4 Bélády eviction + cut prefetch | removes the per-frame new-tile ceiling as a quality limiter at cuts | Phase 2 | | 4.5 Codebook keyed on index pattern only + 4 flips | flips built in Phase 1; cross-line keying in Phase 2 | partly | | 4.6 Two-pass rate control | hits the ROM target exactly, smooth quality | Phase 5 | | 4.7 Hysteresis re-sweep under new colour system | stacking with VQ untested | Phase 2 | | 4.8 Name-table stream packing / LZ | 10 MB → ~3–6 MB | Phase 2 | | 4.9 Ordered (Bayer) dither, *not* error diffusion | if dither is wanted at all | decision | | 4.10 Raster-band palette reloads (7 bands × 4 lines) | **measured 2–18 % error reduction, frame-dependent** (Phase 1, 3 frames) | Phase 3, after 4.3b | | 4.11 Per-pixel S/H sprite mask | **measured 7–15 %** (Phase 1, 3 frames); highest hardware risk | only if all else is done | --- ## 5. Verification — the emulator is the oracle - **Frames**: `scripts/board_frames.py rom.bin actual --machine megadrive --tmss-rom --range 0:N` then a pixel diff against `expected/`. Pass = **0 differing pixels on every frame** (the encoder renders through the same ramp and S/H rules as `render.py`, so equality is the expectation, not similarity). Reuse the repo's `compare_frames.py` tooling. - **Audio**: `--wav` capture, resample-compare to the encoder's input WAV; assert no dropouts (a dropout is a run of repeated samples where the source had none) during the 50 heaviest-DMA frames specifically. - **Timing**: assert from the emulator's own counters that no VBlank DMA list ever overruns VBlank (frame flag read back), and log 68000 idle cycles per frame. - **Cross-oracle**: spot-check a handful of frames on `--machine nuked-md` as well as `megadrive`; run the ROM through BlastEm (`scripts/blastem_frames.py` via WSL) as the independent third opinion. - **Speed**: a full 10,550-hardware-frame run needs **PyPy** (16–21 fps with FM per the repo's own note → ~10 min; CPython is hours). Install PyPy for the `megadrive-python` venv before Phase 5. - **Qualitative**: the user judges `expected/*.png` and the live frontend run by eye; the agent reports numbers only. --- ## 6. Toolchain - **Assembler**: `vasm` (`vasmm68k_mot` for the 68000, `vasmz80_oldstyle` for the Z80 — one tool, both CPUs, Windows binaries available). Fallback only if vasm is a problem: a tiny Python assembler for the ~40 opcodes the player uses. - **Encoder**: Python 3.12 + numpy + Pillow (system `py -3.12`, as now). ffmpeg for field/audio extraction. - **Emulator**: `d:\dev\megadrive-python` venv; add PyPy. - **Build**: `python -m rrmd build` → `out/rickroll.bin`, `out/expected/`, `out/report.json`; `python -m rrmd verify` → runs the emulator and diffs. - **Repo**: `d:\dev\rick-roll-md`, git-init it; never commit the source video or extracted fields/audio (gitignore `encoder-prototype/`, `*.m2v`, `*.wav`, `out/`). --- ## 7. Phases and exit criteria | phase | build | exit criterion (all measured in the emulator) | |---|---|---| | **0 Feasibility** | `encoder_prototype.py` — done | sizes known; 32 MB chosen; S/H benefit measured | | **1 Hello, VDP** | vasm toolchain; boot, TMSS, PAL detect; display ONE encoded frame with 4 palette lines + per-cell shade; emulator screenshot | **DONE 2026-10-09**: 0 of 71,680 pixels differ on `megadrive` and on `nuked-md` through the real TMSS boot ROM (commit b5d72f4). GNU binutils instead of vasm (site unreachable). | | **2 Streaming** | encoder v1 (cache sim, DMA lists, name-table flip); player's VBlank executor; 15 s clip | **DONE 2026-10-09**: 375 video frames over 757 hardware frames, **0 unknown frames, all in order, exactly 2 hw frames each** (`verify-clip` PASS, commit after 3876b47). ROM 4.99 MB — crosses 4 MB, so Extended SSF window-1 paging is exercised and works in the emulator. Two hardware traps found and fixed by the oracle: stale-VINT double fire; DMA source wrap at 128 KB. | | **3 Colour** | H-int band reload with display-off lines; per-band 4-line palettes; shot detection | frames match; user confirms "not washed out" by eye | | **4 Audio** | Z80 driver, Timer A, ring buffer, VBlank-aware refill; audio-master sync | **DONE 2026-10-10** (commit 64879fe): 15 s clip + 36 s test stream over 1,900 hw frames: 375/375 frames at exact 2:1, sound and picture start on the same frame, **633,384 of 633,384 DAC samples exact**, 96.3 % held exactly 3 FM periods, 512 KB page crossing served, playback continues past the video. Video is paced by the Z80's sample counter (frame due at k x 707.976 samples). Residuals: one sample ~38 us late per video frame (BUSREQ), ~250 us at each 32 KB bank switch. | | **5 Full song** | 2-pass rate control; flips; luma metric; ROM layout; title/credits; header+checksum | **DONE 2026-10-10** (commit 4d99d73): 14.78 MB ROM, 10,555 hw frames on `megadrive2`, all 5,274 frames in order, audio 99.897 % within jitter, 0 drift. **Encoder update 2026-10-12** (commit ab7a1d4): the retry ladder, not the rate floor, was capping quality - 84 % of frames were re-encoded at ~50 % of the VBlank budget after the controller's cumulative term wound up. Bisection to the tightest fitting tolerance + the controller stepping from the effective multiplier: full song at 2,330 B/frame (the most the 16 MiB cart takes with audio on pages 24-31) is error 254.7 vs 269.7, 8 % of frames retried, 83 min encode; `out/rickroll_bisect2330.bin` 16,352,978 bytes, verify-clip PASS on `megadrive2` (5,273/5,274 shown - the last frame falls outside the default hw window - exact 2:1, audio 99.860 % within jitter, 0 drift, longest glitch 107 FM periods). **Driver race fixed 2026-10-12**: the "early Model 1 freeze" (frame 0 for ever on `--machine megadrive`, the Phase 5 ROM included) was not the mapper. Tracing both CPUs: the 68000 idled in STOP with VBlank B deferring every frame because V_PLAYED stayed 0; the Z80 driver was spinning at its first timer sync, waiting to *see the Timer A flag clear* after writing the reset, while an overflow had landed one FM cycle after the reset and set the flag again before the Z80's next read. That is the chip's documented behaviour (Nuked `OPN2_DoTimerA`: the reset clears in its cycle, the overflow ORs in the next), so on hardware a random power-on phase would hang the ROM about once in 36 boots; which ROMs and models hit it in the emulator depended only on where V_RUN fell against the free-running timer. `pcm.z80` now waits for BUSY to clear (32 FM cycles, the reset long landed) and then for the flag to set. `check_audio` also passed a flat DAC capture at 100 % on sign-of-change machines; it now fails when the DAC barely changes. Verified after the fix: 600-frame clip on `megadrive` (the model that froze) 599/600 in order, audio 99.978 % within jitter, 0 drift, longest glitch 7 periods; the same on `megadrive2` (99.863 %) and on `megadrive-tmss` with the boot ROM (600/600, 99.978 %; verify-clip counts the splash's 157 frames as unknown). Full song on `megadrive`: the emulator was killed by the host at hw frame 10,258 of 10,556 (low memory), and the captured part scores 5,124 of 5,274 frames in order, exact 2:1, audio 99.979 % within jitter, 0 drift, longest glitch 8 periods; `out/rickroll_bisect2330.bin` is the rebuilt ROM (`_oldsync` keeps the previous driver). | | **6 Stretch** | per-pixel S/H mask (section 9); NTSC pulldown build (D1); run on the user's real flashcart | hardware video matches emulator on the frames compared | Each phase ends with the test from section 5 green, a short entry in a `WORKLOG.md`, and the memory file updated. Nothing moves to the next phase on "looks right". --- ## 8. Risks — honest list - **Emulator divergence is real and has already bitten once.** A Z80 read through its banked window does not see an Extended SSF page the 68000 mapped after the Z80's last bank-register write, in BlastEm 1.0.1-pre but not in `megadrive-python`. It cost the audio stream 1.86 s of wrong music at every 512 KB crossing. Repro ROM, mechanism, per-emulator results and the workaround are in `tools/mapper_test/README.md`; the real-hardware row there is still empty and is a phase 6 item. - **Emulator vs hardware on the exotic bits.** The display-off line (the board shows backdrop; Kabuto describes bus garbage on real hardware — `render.py`'s own docstring flags this as unmodelled), CRAM write timing, and S/H edge rules are exactly where emulators and silicon can disagree. Mitigation: keep the display-off lines black-backdrop so garbage would be dark; cross-check BlastEm; **test on real hardware before any public showing** (Phase 6). The emulator's rules here are Kabuto's hardware measurements, so the odds are good, not certain. - **Z80 stall budget.** The ring buffer design makes stalls harmless *if* the refill rate budget holds; measure it in Phase 4 under the real DMA load, not a synthetic one. - **Per-frame new-tile ceiling (~590 slots).** Hard cuts need prefetch; a cut immediately after another cut (no prefetch window) is the pathological case. The rate controller must degrade gracefully (raise tolerance for that frame), never stall the stream. - **Encoder run time.** The greedy VQ needed a vectorization fix to finish 30 s; the full song is 7× that plus a second pass. Budget encoder time; profile early; consider caching intermediate stages to disk. - **Content handling.** The agent reports numbers and diffs; it does not view or describe the video. The user is the eyes. Keep it that way. ## Rejected / not doing - Interlace mode 2 (480-line) — doubles tile cost for a gimmick; the source's interlace is better spent as 25 clean fields. - 32 MB on MAME's 6-bit `rom_titan` device — chosen by software-list hash, not by anything a ROM can declare; no flashcart path above 16 MB is documented here. - Error-diffusion dither — destroys tile reuse (4.9). - 9-bit DAC via test register $2C — modelled in the emulator, but hardware-variant dependent; not worth the risk for ~1 bit. - FM chiptune arrangement instead of PCM — a different (composition) project. --- ## 9. Stretch: per-pixel 3-level shading with sprite operator masks `render.py`'s mixer (Kabuto's S/H rules) says: over a **high-priority** cell, a sprite pixel of colour 62 (line 3, pen 14) → **highlight**, colour 63 → **shadow**, the sprite pixel itself is not drawn. So a sprite layer whose tiles contain only pens {0, 14, 15} of palette line 3 is a **per-pixel 3-level luminance mask** over the picture. Sprite budget in H40: 80 sprites, 20 per line, 40 tiles per line — ten 32-px-wide sprites cover a 320-px line, 80 sprites cover 320×256: **the whole screen**. Mask tiles are 1.6-bit patterns and dedupe extremely well; VRAM cost is the constraint (each mask tile is still 32 bytes; budget ~200 slots ≈ 6 KB). The encoder decides per 32×32 region whether a mask earns its slot by error reduction. Effective colours: 384 × 3 brightness levels. Verify against the emulator first, then **real hardware** — this is the single most hardware-sensitive trick in the plan. --- ## Decisions (taken 2026-10-09) - **D1 — Resolution/region: (b) V28, 320×224, one dual-region ROM.** 16 lines (6.7 %) cropped from the 4:3 source; PAL 2:1 and NTSC 3:2 pulldown fall out of audio-master sync for free; ~670 free cache slots per frame. (Rejected: PAL-only V30 320×240 — NTSC consoles roll in V30.) - **D2 — Audio: 17.6 kHz** (Timer A NA = 1021; 3.71 MB of ROM). Rate differs 0.9 % between regions (FM clock ratio) — ~16 cents of pitch, the same as every PAL/NTSC game conversion; sync is unaffected because audio is the master clock. - **D3 — The user runs the ffmpeg audio extraction** (`ffmpeg -i -vn -ac 1 -ar 17594 -f u8 audio.u8`); the encoder consumes the raw u8 file.