# SPDX-License-Identifier: MIT """Save states of a Mega Drive with the Sega CD on its expansion port. megadrive-python's ``state`` module (its docs/save-states.md, state version 2) is the specification this follows, and its encoder is the one used: a state is the whole console between two main-68000 steps, written as plain data (JSON, zlib), with no code in it, refused up front when it belongs to another console, and loaded all or nothing into a console built the same way. This module adds what the CD needs on top: - **the device's objects are state.** The walk saves the objects of the packages in ``megadrive_python.state.MODULES``; while a CD state is saved or loaded this package is one of them (:func:`_with_cd`), so the gate array, the memories, the decoder, the drive, the graphics unit and the PCM are walked as the Mega Drive's own chips are; - **the sub CPU** is saved by its core's ``capture_state`` (``sub68k`` beside ``m68k`` and ``z80``) and is not walked, as the main CPUs are not; - **the disc** is a medium, as the cartridge's ROM is: written as its identity (:func:`disc_identity`), never by content; a state loads only into a console whose drive holds the same disc (or, as saved, none). The drive's lid can be opened and a disc changed at run time, so the identity is the one in the drive when the state was saved; - **the boot ROM** (your BIOS or mcd-verificator) is a byte string, so the walk writes it as an image and keeps the loader's; the header carries its SHA-1 and refuses another; - **the host's settings** are megadrive-python's (``state.HOST``: the sample rate, the FM generator's switch, the drawing switches ``VDP.rendering`` and ``VDP.undrawn_frame``): the loading console keeps its own. The device has none of its own. **What this module borrows.** megadrive-python offers no socket through which an expansion device adds itself to a state (reported: docs/sockets.md, "Save states"). So this module uses that module's encoder and decoder classes and its ``MODULES`` tuple, which are private, at the pinned revision (``pyproject.toml``); a change there fails ``tests/test_state.py`` at once. Nothing is copied from it. Where a state may be taken: between two main-68000 steps (``System.step``), as there. The sub CPU then stands between two of its instructions (it runs whole instructions, megacd.py), with the units' clocks and queues saved as they are. """ from __future__ import annotations import contextlib import dataclasses import hashlib import json import struct import zlib from collections.abc import Iterator from typing import TYPE_CHECKING, Any from m68000_python.state import CPUState as M68000State from megadrive_python import state as md from z80_python.state import CPUState as Z80State from .disc import Disc if TYPE_CHECKING: from megadrive_python.system import System from .megacd import MegaCD #: The first eight bytes of every state. MAGIC = b"MCDPYSTA" FORMAT = "segacd-python state" #: Raised whenever a saved attribute of this package is added, removed, renamed or #: changes meaning. megadrive-python's own version is in the header beside it and must #: match too (its ``state.VERSION``, which moves with the Mega Drive's graph and the #: cores'). VERSION = 1 StateError = md.StateError _LENGTH = struct.Struct(">I") @contextlib.contextmanager def _with_cd() -> Iterator[None]: """megadrive-python's walk with this package's objects counted as state.""" saved = md.MODULES md.MODULES = (*saved, "segacd_python") try: yield finally: md.MODULES = saved def disc_identity(disc: Disc | None) -> str: """What names a disc in a state: its track table (number, kind, start, end) and the SHA-1 of its first 16 sectors (the system area, where a Sega CD disc's header and title are). "" for an empty drive. Two images of one disc give one identity.""" if disc is None: return "" digest = hashlib.sha1() for track in disc.tracks: digest.update(f"{track.number}:{track.kind}:{track.start}:{track.end};".encode()) for lba in range(16): digest.update(disc.read_sector(lba)) return digest.hexdigest() class _Encoder(md._Encoder): def __init__(self, system: System, device: MegaCD, skipped: set[str] | None) -> None: super().__init__(system, skipped) self.cpus.add(id(device.sub)) def value(self, value: Any, path: str) -> Any: if type(value) is Disc: return {"disc": disc_identity(value)} return super().value(value, path) class _Decoder(md._Decoder): def into(self, current: Any, encoded: Any, path: str) -> Any: if isinstance(encoded, dict) and "disc" in encoded: return self._disc(current, encoded, path) return super().into(current, encoded, path) def fresh(self, encoded: Any, path: str) -> Any: if isinstance(encoded, dict) and "disc" in encoded: return self._disc(None, encoded, path) return super().fresh(encoded, path) def _disc(self, current: Any, encoded: dict, path: str) -> Disc: if not isinstance(current, Disc) or disc_identity(current) != encoded["disc"]: raise StateError(f"{path}: not the disc the state was saved with") return current def _device(system: System) -> MegaCD: from .megacd import MegaCD device = system.board.port if type(device) is not MegaCD: raise StateError("no Sega CD on the expansion port") if system.board.slot is not None: # A 32X in the slot: sega32x-python saves its SH-2 side its own way. raise StateError("a console with a device in the cartridge slot (a 32X)") return device def _header(system: System, device: MegaCD, host: dict) -> dict: return { "format": FORMAT, "version": VERSION, "megadrive": md._header(system), "bios_sha1": hashlib.sha1(device.bios).hexdigest(), "disc": disc_identity(device.cdd.disc), "host": host, } def _body(system: System, device: MegaCD, skipped: set[str] | None = None) -> dict: with _with_cd(): encoder = _Encoder(system, device, skipped) return { "m68k": dataclasses.asdict(system.m68k.capture_state()), "z80": dataclasses.asdict(system.z80.capture_state()), "sub68k": dataclasses.asdict(device.sub.capture_state()), "system": encoder.value(system, "system"), } def machine_state(system: System, skipped: set[str] | None = None) -> dict: """The state's body as a value to compare (the save-state check's judge).""" return _body(system, _device(system), skipped) def save_state(system: System, host: dict | None = None, *, skipped: set[str] | None = None) -> bytes: # fmt: skip """The console as bytes, between two of its steps. ``host``: plain data the host wants back with it (the command line keeps its frame number here); not the console's. ``skipped``: attribute names left out, for seeding faults only.""" device = _device(system) if system._in_z80: raise StateError("a state is saved between steps, not inside the Z80's catch-up") header = json.dumps(_header(system, device, host or {}), separators=(",", ":")).encode() body = json.dumps(_body(system, device, skipped), separators=(",", ":")).encode() return MAGIC + _LENGTH.pack(len(header)) + header + zlib.compress(body, 6) def read_header(data: bytes) -> tuple[dict, int]: """A state's header and where its body starts; refuses anything that is not a segacd-python state of this version on this megadrive-python's state version.""" if data[: len(MAGIC)] != MAGIC or len(data) < len(MAGIC) + _LENGTH.size: raise StateError("not a segacd-python save state") (length,) = _LENGTH.unpack_from(data, len(MAGIC)) start = len(MAGIC) + _LENGTH.size try: header = json.loads(data[start : start + length]) except ValueError as error: raise StateError(f"a damaged header: {error}") from None if header.get("format") != FORMAT: raise StateError(f"not a {FORMAT}") if header.get("version") != VERSION: raise StateError(f"a state of version {header.get('version')}, not {VERSION}") mega = header.get("megadrive", {}) if mega.get("format") != md.FORMAT or mega.get("version") != md.VERSION: raise StateError( f"a state of megadrive-python state version {mega.get('version')}, not {md.VERSION}" ) return header, start + length def load_state(system: System, data: bytes) -> dict: """Put ``system`` (built with the same cartridge, machine, wiring, BIOS and disc) in the state ``data`` was saved from, all or nothing. Returns the host's data.""" device = _device(system) header, start = read_header(data) md.check_header(system, header["megadrive"]) if header["bios_sha1"] != hashlib.sha1(device.bios).hexdigest(): raise StateError("a state of another BIOS") if header["disc"] != disc_identity(device.cdd.disc): raise StateError("a state with another disc in the drive (or none)") try: body = json.loads(zlib.decompress(data[start:])) except (zlib.error, ValueError) as error: raise StateError(f"a damaged body: {error}") from None try: m68k = M68000State( **{k: tuple(v) if type(v) is list else v for k, v in body["m68k"].items()} ) sub = M68000State( **{k: tuple(v) if type(v) is list else v for k, v in body["sub68k"].items()} ) z80 = Z80State(**body["z80"]) except (KeyError, TypeError, ValueError) as error: raise StateError(f"a CPU state its core refuses: {error}") from None with _with_cd(): before = _body(system, device) try: _Decoder().into(system, body["system"], "system") except Exception as error: _Decoder().into(system, before["system"], "system") raise StateError(f"a body this system cannot take: {error}") from None system.m68k.restore_state(m68k) system.z80.restore_state(z80) device.sub.restore_state(sub) return header["host"] __all__ = [ "FORMAT", "MAGIC", "VERSION", "StateError", "disc_identity", "load_state", "machine_state", "read_header", "save_state", ]