"""The ROM image: the player, a frame index, and one record per video frame. Record (big-endian, 2-byte aligned, never crossing a 512 KB page): u16 flags bit 0: a 64-word CRAM image follows the header u16 n_patches u16 n_runs u16 n_tiles [u16 x 64] CRAM, if flags bit 0 n_patches x { u16 byte offset into the 28x64 name table, u16 word } n_runs x { u32 reg19|reg20, u32 reg21|reg22, u16 reg23, u32 VRAM command } - the exact VDP writes for one 68000->VRAM DMA, source already expressed as the 68000 address the record is seen at n_tiles x 32 B the frame's new tiles, in run order The index is one u32 physical ROM address per video frame. Records below $080000 are reached directly (page 0 is always mapped); any other record is mapped into window 1 ($080000) by the player before use, so a record's DMA sources are pre-formatted for whichever of those two views applies. """ from __future__ import annotations import struct from pathlib import Path from .stream import FrameRecord from .vdp import CELLS_X, PLANE_W PAGE = 0x80000 DATA_BASE = 0x10000 WINDOW_1 = 0x80000 ROW_BYTES = PLANE_W * 2 def _dma_words(src: int, dst: int, words: int) -> bytes: assert src % 2 == 0 and words < 0x10000 half = src >> 1 reg19_20 = (0x9300 | (words & 0xFF)) << 16 | (0x9400 | (words >> 8)) reg21_22 = (0x9500 | (half & 0xFF)) << 16 | (0x9600 | ((half >> 8) & 0xFF)) reg23 = 0x9700 | ((half >> 16) & 0x7F) command = 0x40000080 | ((dst & 0x3FFF) << 16) | (dst >> 14) return struct.pack(">IIHI", reg19_20, reg21_22, reg23, command) DMA_BANK = 0x20000 # a 68000->VDP DMA source wraps inside a 128 KB bank (reg 23 is not carried into) def _split_runs(runs: list[tuple[int, int, int]], tiles_at: int) -> list[tuple[int, int, int]]: """Runs whose source would cross a 128 KB boundary, cut at it.""" out: list[tuple[int, int, int]] = [] for slot, first, count in runs: while count: src = tiles_at + first * 32 room = (DMA_BANK - (src % DMA_BANK)) // 32 # whole tiles before the boundary take = min(count, room) out.append((slot, first, take)) slot += take first += take count -= take return out def encode_record(rec: FrameRecord, view_base: int) -> bytes: """``view_base`` is the 68000 address at which the record's first byte is seen.""" flags = 1 if rec.cram is not None else 0 cram = b"".join(w.to_bytes(2, "big") for w in rec.cram) if rec.cram is not None else b"" patches = b"".join( struct.pack(">HH", (cell // CELLS_X) * ROW_BYTES + (cell % CELLS_X) * 2, word) for cell, word in rec.patches ) # The run count depends on where the tiles land, which depends on the run count: # settle it by iterating (each extra descriptor moves the tiles 14 bytes). Tiles # are 32-byte aligned so no tile straddles a 128 KB boundary. If the count and # the position chase each other across an alignment step, extra padding breaks # the cycle (padding only ever grows, so this terminates). n_runs = len(rec.runs) extra = 0 for attempt in range(64): unaligned = view_base + 8 + len(cram) + len(patches) + 14 * n_runs pad = (-unaligned) % 32 + extra tiles_at = unaligned + pad runs = _split_runs(rec.runs, tiles_at) if len(runs) == n_runs: break n_runs = len(runs) if attempt % 6 == 5: extra += 32 else: raise RuntimeError("DMA run splitting did not converge") header = struct.pack(">HHHH", flags, len(rec.patches), len(runs), len(rec.tiles)) run_bytes = b"".join( _dma_words(tiles_at + first * 32, slot * 32, count * 16) for slot, first, count in runs ) body = header + cram + patches + run_bytes + b"\0" * pad + b"".join(rec.tiles) if len(body) % 2: body += b"\0" return body def _view(addr: int) -> int: return addr if addr < PAGE else WINDOW_1 | (addr & (PAGE - 1)) def layout(records: list[FrameRecord]) -> tuple[bytes, bytes]: """-> (index.bin, data.bin) with data.bin starting at DATA_BASE in the ROM.""" data = bytearray() index = bytearray() for rec in records: addr = DATA_BASE + len(data) body = encode_record(rec, _view(addr)) if addr // PAGE != (addr + len(body) - 1) // PAGE: pad = (addr // PAGE + 1) * PAGE - addr data += b"\0" * pad addr += pad body = encode_record(rec, _view(addr)) data += body index += struct.pack(">I", addr) return bytes(index), bytes(data) def write_layout(records: list[FrameRecord], out: Path) -> dict[str, int]: out.mkdir(parents=True, exist_ok=True) index, data = layout(records) (out / "index.bin").write_bytes(index) (out / "data.bin").write_bytes(data) return {"frames": len(records), "index_bytes": len(index), "data_bytes": len(data), "rom_bytes": DATA_BASE + len(data)} # fmt: skip # -- codebook layout (rrmd.codebook): one tile store, descriptors carry their page ------- WINDOW_2 = 0x100000 DESCRIPTOR_SIZE = 8 def _descriptor(page: int, src_view: int, dst: int, count: int) -> bytes: """u8 page, u8 tiles, u16 VRAM byte address, u32 source/2 - the player expands it.""" assert 1 <= count <= 255 and src_view % 2 == 0 return struct.pack(">BBHI", page, count, dst, src_view >> 1) def _split_store_runs(runs: list[tuple[int, int, int]], store_base: int) -> list[tuple[int, int, int]]: """(slot, tile, count) runs cut so no run's source crosses a 128 KB boundary.""" out = [] for slot, tile, count in runs: while count: src = store_base + tile * 32 room = (DMA_BANK - (src % DMA_BANK)) // 32 take = min(count, room, 255) out.append((slot, tile, take)) slot += take tile += take count -= take return out def encode_record2(rec, store_base: int) -> bytes: flags = (1 if rec.cram is not None else 0) | 2 # bit 1: packed patches cram = b"".join(w.to_bytes(2, "big") for w in rec.cram) if rec.cram is not None else b"" mask = bytearray(CELLS_X * 28 // 8) words = bytearray() for cell, word in sorted(rec.patches): mask[cell >> 3] |= 0x80 >> (cell & 7) words += struct.pack(">H", word) patches = bytes(mask) + bytes(words) runs = _split_store_runs(rec.runs, store_base) descriptors = b"" for slot, tile, count in runs: src = store_base + tile * 32 view = src if src < PAGE else WINDOW_2 | (src & (PAGE - 1)) descriptors += _descriptor(src // PAGE, view, slot * 32, count) header = struct.pack(">HHHH", flags, len(rec.patches), len(runs), 0) body = header + cram + patches + descriptors if len(body) % 2: body += b"\0" return body def layout2(records, store_pens) -> tuple[bytes, bytes, dict[str, int]]: """-> (index.bin, data.bin, sizes). data.bin = tile store, then records.""" from .vdp import tile_bytes store = b"".join(tile_bytes(p.reshape(8, 8)) for p in store_pens) data = bytearray(store) index = bytearray() for rec in records: body = encode_record2(rec, DATA_BASE) addr = DATA_BASE + len(data) if addr // PAGE != (addr + len(body) - 1) // PAGE: pad = (addr // PAGE + 1) * PAGE - addr data += b"\0" * pad addr += pad data += body index += struct.pack(">I", addr) sizes = {"frames": len(records), "store_bytes": len(store), "record_bytes": len(data) - len(store), "rom_bytes": DATA_BASE + len(data)} # fmt: skip return bytes(index), bytes(data), sizes def write_layout2(records, store_pens, out: Path) -> dict[str, int]: index, data, sizes = layout2(records, store_pens) (out / "index.bin").write_bytes(index) (out / "data.bin").write_bytes(data) return sizes def finalize_header(rom: Path) -> dict: """Write the Mega Drive header checksum and check the fields the player cannot. The checksum is the sum of every 16-bit big-endian word from $200 to the end of the ROM, modulo $10000, stored at $18E. Neither the console nor TMSS verifies it, but flashcart menus and ROM tools do, and a few games check their own, so a ROM that ships with $0000 there looks broken to anything that looks. The region field is also checked rather than trusted: every timing constant in the player comes from PAL frame geometry (313 lines x 3420 master clocks at 50 Hz), so a header that lets an emulator choose NTSC gives 60 Hz, 262 lines and an A/V relationship that was never designed. It must say E and nothing else. """ blob = bytearray(rom.read_bytes()) if len(blob) % 2: raise RuntimeError(f"{rom}: odd length {len(blob)}, cannot checksum whole words") total = 0 for i in range(0x200, len(blob), 2): total += (blob[i] << 8) | blob[i + 1] checksum = total & 0xFFFF blob[0x18E] = checksum >> 8 blob[0x18F] = checksum & 0xFF # Krikzz's Extended SSF addresses pages with a 5-bit field: 32 windows of 512 KB, # so 16 MB is the last byte any page register can reach, not a preference. A larger # image assembles and even runs until the stream crosses into a page that cannot be # selected, which is a confusing way to find out. LIMIT = 32 * 0x80000 if len(blob) > LIMIT: raise RuntimeError(f"{rom}: {len(blob):,} bytes is past the mapper's reach " f"({LIMIT:,} = 32 pages of 512 KB, a 5-bit page field)") # fmt: skip declared_end = int.from_bytes(blob[0x1A4:0x1A8], "big") region = blob[0x1F0:0x200].decode("ascii", "replace").rstrip() problems = [] if declared_end != len(blob) - 1: problems.append(f"ROM end field {declared_end:#x} but the ROM ends at {len(blob) - 1:#x}") if region != "E": problems.append(f"region field {region!r}, expected 'E': the player is PAL-locked") if blob[0x100:0x110] != b"SEGA SSF ": problems.append(f"console name {blob[0x100:0x110]!r} does not select the SSF mapper") if problems: raise RuntimeError(f"{rom}: " + "; ".join(problems)) rom.write_bytes(bytes(blob)) return {"bytes": len(blob), "checksum": f"{checksum:#06x}", "region": region, "rom_end": f"{declared_end:#x}"} # fmt: skip