"""How to hand a cartridge image to MAME so that it uses the right board. Given a file (``-cart game.gg``), MAME 0.285 guesses the board from the code (sega8_slot.cpp ``get_cart_type``: it counts ``LD (nnnn),A`` targets) and can guess wrong: Ernie Els Golf writes only $4000 in its first 32 KB, so MAME takes it for a plain Sega-mapper board and the game shows a black screen. Loaded by its software-list name, MAME uses the board the list gives. So an image that a list names, and whose board MAME would guess wrong, is offered under that name, from a scratch rompath holding just that image, stored in a zip under the file name the list expects. """ from __future__ import annotations import hashlib import zipfile from functools import cache from pathlib import Path from xml.etree import ElementTree from sms_python.cartridge import identify MAME_HASH = Path("/usr/share/games/mame/hash") # The software list each driver's cartridge slot reads. DRIVER_LIST = { "sg1000": "sg1000", "sms": "sms", "sms1": "sms", "smspal": "sms", "sms1pal": "sms", "smsj": "sms", "sms1kr": "sms", "gamegear": "gamegear", "gamegeaj": "gamegear", } @cache def _entries(listname: str) -> dict[str, tuple[str, str]]: """SHA-1 -> (set name, ROM file name) for single-ROM entries of one list.""" entries: dict[str, tuple[str, str]] = {} path = MAME_HASH / f"{listname}.xml" if not path.exists(): return entries for software in ElementTree.parse(path).getroot().iter("software"): # Sega Cards (interface sms_card) go in a card slot the SMS2 does not have; # given as a file, MAME puts the same image in the cartridge slot. if any(not p.get("interface", "").endswith("_cart") for p in software.iter("part")): continue roms = [r for r in software.iter("rom") if r.get("sha1")] if len(roms) == 1: entries[roms[0].get("sha1", "")] = (software.get("name", ""), roms[0].get("name", "")) return entries def cart_arguments( image: bytes, driver: str, work: Path, image_path: Path, rompath: str ) -> list[str]: """MAME's ``-cart``, ``-hashpath`` and ``-rompath`` arguments for this image. A software-list name if the driver's list has the image (a scratch rompath under ``work`` then holds it), else ``image_path``, which the caller has written. """ listname = DRIVER_LIST.get(driver) entry = _entries(listname).get(hashlib.sha1(image).hexdigest()) if listname else None if entry is None or mame_board(image, driver) == mame_guess(image): # Only where the guess would be wrong: a list entry can also leave things # out, such as the cartridge RAM Super Momotarou Dentetsu III uses, which # MAME's file loader always provides. return ["-cart", str(image_path), "-rompath", rompath] setname, romname = entry softlist = work / "softlist" (softlist / listname).mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(softlist / listname / f"{setname}.zip", "w") as archive: archive.writestr(romname, image) # -noreadconfig drops MAME's configured hash path, so name it. return ["-cart", setname, "-hashpath", str(MAME_HASH), "-rompath", f"{softlist};{rompath}"] def mame_guess(image: bytes) -> str: """The board MAME 0.285 guesses for an image given as a file, as a software-list slot name (sega8_slot.cpp ``get_cart_type``, which it credits to MEKA). It counts ``LD (nnnn),A`` instructions by target in the first 32 KB, then checks a few signatures and sizes. Only a listed image escapes the guess (cart_arguments), so an unlisted one whose guess differs from our board runs on a different board in MAME and cannot be compared. """ length = len(image) guess = "rom" if length >= 0x8000: counts = {"0002": 0, "8000": 0, "a000": 0, "ffff": 0, "3ffe": 0, "4000": 0, "6000": 0} targets = {0xFFFF: "ffff", 0x0002: "0002", 0x0003: "0002", 0x0004: "0002", 0x8000: "8000", 0xA000: "a000", 0x3FFE: "3ffe", 0x4000: "4000", 0x6000: "6000"} # fmt: skip i = 0 while i < 0x8000: if image[i] == 0x32 and i + 2 < length: key = targets.get(image[i + 1] | image[i + 2] << 8) if key is not None: counts[key] += 1 i += 2 i += 1 ffff = counts["ffff"] def beats(key: str) -> bool: return counts[key] > ffff + 2 or (counts[key] > 0 and ffff == 0) if length > 0x10000 and beats("0002"): guess = "zemina" if ( length == 0x20000 and image[:3] == bytes(3) and image[0x1E000:0x1E003] == b"\xf3\xed\x56" ): guess = "nemesis" elif beats("8000"): guess = "codemasters" elif beats("a000"): guess = "korean" elif counts["3ffe"] > 0: guess = "4pak" elif counts["4000"] and counts["6000"] and counts["8000"] and counts["a000"]: guess = "janggun" low, high, ff = 0, 0, image[0x2000:0x4000].count(0xFF) i = 0 while i < 0x8000: if image[i] == 0x32 and i + 2 < length: page = image[i + 2] & 0xF0 if page in (0x20, 0x30): low += 1 i += 2 elif page in (0xD0, 0xE0, 0xF0): high += 1 i += 2 i += 1 if ff == 0x2000 and (high > 10 or low > 10): guess = "dahjee_typeb" if high > low else "dahjee_typea" signatures = [ (0x226C, b"LICENSEDFROMBRODERBUND@SOFTWARE@INC", "rom", length == 0x8000), (0x13B3, b"annakmn", "terebi", True), (0x1CC3, b"ASCII 1986", "castle", True), (0x6A20, b"SC-3000 BASIC Level 3 ver 1.0", "level3", True), (0x0841, b"PIANO", "music_editor", True), (0x0841, b"music", "music_editor", True), ] for at, text, board, applies in signatures: if applies and image[at : at + len(text)] == text: guess = board if length == 0x200000: guess = "multicart" elif length == 0x400000: guess = "megacart" elif length == 0x2000: guess = "xterminator" return guess def mame_board(image: bytes, driver: str) -> str: """The board MAME runs this image on: its software list's if listed, else its guess.""" listname = DRIVER_LIST.get(driver) if listname and hashlib.sha1(image).hexdigest() in _entries(listname): listed = identify(image) if listed: return listed[2] return mame_guess(image)