# SPDX-License-Identifier: MIT """The A78 header: parse it into description fields, and write one (the converter). Specification: the 7800 Development Wiki's "A78 Header Specification" (``reference/8bitdev-wiki/a78-header-spec.txt``, page revision 1120) and its reference assembly header ``a78header.asm`` v4.2. ``7800header.c`` (GPL) is not consulted. Offsets: 0 version | 1-16 "ATARI7800" + zeros | 17-48 title | 49-52 payload size (big endian) | 53-54 cart type (big endian bits) | 55, 56 controllers | 57 TV | 58 save device | 63 pass-through (bit 0 XM) | v4: 64 mapper, 65 mapper options, 66-67 audio, 68-69 interrupt | 100-127 "ACTUAL CART DATA STARTS HERE" v4 fields win over v3 fields in a v4 header (the specification says so). Every offset, bit and table below is the file format as the specification gives it (DOC: the wiki's A78 header specification, page revision 1120); none is a console behaviour. """ from __future__ import annotations from dataclasses import dataclass HEADER = 128 MAGIC = b"ATARI7800" END_MAGIC = b"ACTUAL CART DATA STARTS HERE" CART_TYPE_BITS = ( "pokey@4000", "supergame", "ram@4000", "rom@4000", "bank6@4000", "banked-ram", "pokey@450", "mirror-ram@4000", "activision", "absolute", "pokey@440", "ym2151@460", "souper", "banksets", "halt-banked-ram", "pokey@800", ) # fmt: skip CONTROLLERS = ( "none", "proline", "lightgun", "paddle", "trakball", "joystick2600", "driving", "keypad", "st-mouse", "amiga-mouse", "savekey", "snes2atari", "mega7800", ) # fmt: skip MAPPERS = ("linear", "supergame", "activision", "absolute", "souper") LINEAR_4000 = ("none", "ram16", "ram8-mirror", "ram32-halt") SUPERGAME_4000 = ("none", "ram16", "ram8-mirror", "ram32-halt", "rom", "fixed-bank", "ram32-latch") AUDIO_POKEY = ((), (0x440,), (0x450,), (0x450, 0x440), (0x800,), (0x4000,)) class HeaderError(ValueError): """A header whose fields cannot be built (contradictory cart-type bits, a bad size).""" @dataclass(frozen=True) class Header: version: int title: str size: int fields: dict # description fields this header states raw_cart_type: int def is_a78(data: bytes) -> bool: return len(data) >= HEADER and data[1:10] == MAGIC def parse(data: bytes) -> Header: """The header's statements as CartDescription fields (strictly what it says).""" if not is_a78(data): raise HeaderError("not an A78 header") version = data[0] title = data[17:49].split(b"\0")[0].decode("latin-1").strip() size = int.from_bytes(data[49:53], "big") bits = data[53] << 8 | data[54] names = {n for i, n in enumerate(CART_TYPE_BITS) if bits >> i & 1} fields: dict = {} # v3 cart type if "souper" in names: scheme = "souper" elif "activision" in names: scheme = "activision" elif "absolute" in names: scheme = "absolute" elif "supergame" in names: scheme = "supergame" else: scheme = "linear" if len(names & {"activision", "absolute", "souper"}) > 1: raise HeaderError(f"cart type ${bits:04X}: more than one bank scheme ({sorted(names)})") at = [n for n in ("ram@4000", "rom@4000", "bank6@4000", "mirror-ram@4000", "pokey@4000") if n in names] # fmt: skip if len(at) > 1: raise HeaderError(f"cart type ${bits:04X}: more than one device at $4000 ({at})") at_4000 = { "ram@4000": "ram16", "rom@4000": "rom", "bank6@4000": "fixed-bank", "mirror-ram@4000": "mirror-ram-2k", "pokey@4000": "pokey", }.get(at[0] if at else "", "none") # fmt: skip if at_4000 == "ram16" and "banked-ram" in names: at_4000 = "ram32-latch" if at_4000 in ("ram16", "none") and "halt-banked-ram" in names: # DOC, the wiki's bankset page: bit 14 alone marks the bankset RAM at $4000 at_4000 = "ram32-halt" pokey = tuple(a for n, a in (("pokey@450", 0x450), ("pokey@440", 0x440), ("pokey@800", 0x800), ("pokey@4000", 0x4000)) if n in names) # fmt: skip fields.update(scheme=scheme, at_4000=at_4000, pokey=pokey, bankset="banksets" in names, ym2151="ym2151@460" in names) # fmt: skip if version >= 4: mapper = data[64] if mapper >= len(MAPPERS): raise HeaderError(f"v4 mapper {mapper} is not defined") options = data[65] fields["scheme"] = MAPPERS[mapper] fields["bankset"] = bool(options & 0x80) if mapper == 0: choice = options & 0x03 fields["at_4000"] = LINEAR_4000[choice] elif mapper == 1: choice = options & 0x07 if choice >= len(SUPERGAME_4000): raise HeaderError(f"v4 SuperGame option {choice} is not defined") fields["at_4000"] = SUPERGAME_4000[choice] audio = data[66] << 8 | data[67] if audio & 7 >= len(AUDIO_POKEY): raise HeaderError(f"v4 audio POKEY field {audio & 7} is not defined") fields["pokey"] = AUDIO_POKEY[audio & 7] if fields["pokey"] == (0x4000,) and fields["at_4000"] == "none": fields["at_4000"] = "pokey" fields["ym2151"] = bool(audio & 0x08) fields["covox"] = bool(audio & 0x10) fields["adpcm"] = bool(audio & 0x20) irq = data[68] << 8 | data[69] fields["irq_sources"] = tuple( n for i, n in enumerate(("pokey1", "pokey2", "ym2151")) if irq >> i & 1 ) fields["bupchip"] = fields["scheme"] == "souper" c1, c2 = data[55], data[56] fields["controllers"] = tuple( CONTROLLERS[c] if c < len(CONTROLLERS) else f"unknown-{c}" for c in (c1, c2) ) tv = data[57] fields["region"] = "both" if tv & 4 else ("pal" if tv & 1 else "ntsc") fields["composite_artifacts"] = bool(tv & 2) fields["hsc"] = bool(data[58] & 1) fields["save"] = "savekey" if data[58] & 2 else "none" fields["xm"] = bool(data[63] & 1) return Header(version, title, size, fields, bits) def build(desc, version: int = 4) -> bytes: """A v4 header (with the v3 fields filled for older readers) stating ``desc``.""" if desc.console != "7800": raise HeaderError("an A78 header describes 7800 cartridges only") bits = 0 def bit(name: str) -> None: nonlocal bits bits |= 1 << CART_TYPE_BITS.index(name) if desc.scheme == "supergame": bit("supergame") elif desc.scheme in ("activision", "absolute", "souper"): bit(desc.scheme) v3_at = { "ram16": ("ram@4000",), "ram32-latch": ("ram@4000", "banked-ram"), "ram32-halt": ("ram@4000", "halt-banked-ram"), "rom": ("rom@4000",), "fixed-bank": ("bank6@4000",), "mirror-ram-2k": ("mirror-ram@4000",), "ram8-mirror": ("ram@4000",), } # fmt: skip for name in v3_at.get(desc.at_4000, ()): bit(name) for address, name in ((0x4000, "pokey@4000"), (0x450, "pokey@450"), (0x440, "pokey@440"), (0x800, "pokey@800")): # fmt: skip if address in desc.pokey: bit(name) if desc.ym2151: bit("ym2151@460") if desc.bankset: bit("banksets") out = bytearray(HEADER) out[0] = version out[1:10] = MAGIC out[17:49] = desc.title.encode("latin-1", "replace")[:32].ljust(32, b"\0") out[49:53] = len(desc.payload).to_bytes(4, "big") out[53:55] = bits.to_bytes(2, "big") out[55] = CONTROLLERS.index(desc.controllers[0]) if desc.controllers[0] in CONTROLLERS else 1 out[56] = CONTROLLERS.index(desc.controllers[1]) if desc.controllers[1] in CONTROLLERS else 1 out[57] = (desc.region == "pal") | desc.composite_artifacts << 1 | (desc.region == "both") << 2 out[58] = desc.hsc | (desc.save == "savekey") << 1 out[63] = int(desc.xm) if version >= 4: out[64] = MAPPERS.index(desc.scheme) table = LINEAR_4000 if desc.scheme == "linear" else SUPERGAME_4000 option = table.index(desc.at_4000) if desc.at_4000 in table else 0 out[65] = option | (0x80 if desc.bankset else 0) audio = AUDIO_POKEY.index(tuple(desc.pokey)) if tuple(desc.pokey) in AUDIO_POKEY else 0 audio |= desc.ym2151 << 3 | desc.covox << 4 | desc.adpcm << 5 out[66:68] = audio.to_bytes(2, "big") irq = sum(1 << i for i, n in enumerate(("pokey1", "pokey2", "ym2151")) if n in desc.irq_sources) # fmt: skip out[68:70] = irq.to_bytes(2, "big") out[100:128] = END_MAGIC return bytes(out)