"""Save states: the whole machine between two instructions, as bytes, and back. A save state is everything that changes as the machine runs: the Z80 (z80-python's ``CPUState``), the system's own counters, the board with its RAM, the VDP, the PSG and FM chips and their resamplers, the cartridge with its mapper and RAM, the controller ports, the keyboard, and the SF-7000 with its disk. It is *not* the wiring: a state is loaded into a :class:`~sms_python.system.System` built from the same cartridge (and BIOS) on the same machine, which already holds the configuration (``Machine``, the chip variants, the ROM images), the callables that connect the parts, and the references between them. Loading writes the saved values into that system's objects, in place, so the references stay as they were built. This is what a frontend's rewind and run-ahead are made of (libretro's ``retro_serialize``), and :class:`Rewind` is the same thing for this package's own window. The design is famicom-python's ``state.py``, with three changes this board needs: a ``bytearray`` is refilled in place, because some are shared by reference (a cartridge's RAM that replaces the console's, the disk the caller handed in); a frozen value that is state and not configuration is saved (``VALUES``, empty since the restarted ym2413-python keeps its state in plain attributes); and a long list of integers (a row of the picture) is packed rather than spelt out. **What is saved**, by walking the object graph from the system: every attribute of an object whose class belongs to ``sms_python``, ``sn76489_python`` or ``ym2413_python``, depth first in attribute order, as plain data. Not saved: - callables (the clocks handed to devices, the H counter latch); - frozen dataclasses (the configuration: ``Machine``, ``VDPVariant``, ``PSGVariant``, ``OPLLVariant``), except the classes in ``VALUES``; - the CPU object (its ``capture_state`` is saved instead); - a second path to an object already saved (the SC-3000's keyboard names the joypads the I/O chip owns): it is written as a reference; - ``bytes``: the ROM images and what is derived from them, which a system built from the same files already holds. **The format** is zlib-compressed JSON: a header (format, version, a SHA-1 of the cartridge and BIOS images, the machine's name) and the encoded graph, each value tagged by type. It holds no code: loading creates nothing but these packages' own classes and plain data, and refuses a state for another cartridge or machine. **Equivalence** is the test (tests/test_state.py, scripts/state_roundtrip.py): a run saved at some instruction boundary and loaded into a fresh system continues exactly as the run that was never interrupted: frames, sound samples, CPU, RAM. """ from __future__ import annotations import base64 import dataclasses import hashlib import importlib import json import zlib from array import array from collections import deque from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from .system import System FORMAT = "sms-python state" VERSION = 1 # Packages whose objects are part of the state. MODULES = ("sms_python", "sn76489_python", "ym2413_python") # Frozen dataclasses that are state, by qualified name: values a chip replaces # whole as it runs. Every other frozen dataclass is configuration. VALUES: tuple[str, ...] = () # The system's own attributes, beside its board and CPU. SYSTEM_FIELDS = ("cycles", "instructions", "_access_t", "_advanced", "_int_sampled", "console_text") # Lists of integers at least this long are packed (a row of the picture is 256). PACK_FROM = 64 class StateError(ValueError): """A state that cannot be loaded into this system.""" def _images_sha1(system: System) -> str: board = system.board digest = hashlib.sha1() for device in (board.cartridge, board.bios): digest.update(b"\x00" if device is None else b"\x01" + device.image) return digest.hexdigest() def _qualified(value: object) -> str: cls = type(value) return f"{cls.__module__}.{cls.__qualname__}" def _ours(value: object) -> bool: return type(value).__module__.split(".", 1)[0] in MODULES def _frozen(value: object) -> bool: params = getattr(type(value), "__dataclass_params__", None) return dataclasses.is_dataclass(value) and params is not None and params.frozen def _is_value(value: object) -> bool: return _frozen(value) and _qualified(value) in VALUES def _wiring(attribute: object) -> bool: """A function, a lambda or a bound method (or a list of them): not state.""" if callable(attribute) and not _ours(attribute): return True return ( isinstance(attribute, (list, tuple)) and bool(attribute) and all(callable(item) and not _ours(item) for item in attribute) ) class _Encoder: def __init__(self, cpu: object) -> None: self.cpu = cpu self.seen: dict[int, str] = {} def value(self, value: Any, path: str) -> Any: if value is None or isinstance(value, (bool, int, str, float)): return value if isinstance(value, bytes): return {"rom": len(value)} if isinstance(value, bytearray): return {"bytearray": base64.b64encode(value).decode()} if isinstance(value, array): return {"array": value.typecode, "data": base64.b64encode(value.tobytes()).decode()} if isinstance(value, list): if len(value) >= PACK_FROM and all(type(item) is int for item in value): try: packed = array("q", value).tobytes() except OverflowError: pass else: return {"ints": base64.b64encode(packed).decode()} return [self.value(item, f"{path}[{i}]") for i, item in enumerate(value)] if isinstance(value, tuple): return {"tuple": [self.value(item, f"{path}[{i}]") for i, item in enumerate(value)]} if isinstance(value, (set, frozenset)): return {"set": sorted(self.value(item, path) for item in value)} if isinstance(value, dict): pairs = [ [self.value(k, path), self.value(v, f"{path}[{k!r}]")] for k, v in value.items() ] return {"dict": pairs} if _is_value(value): fields = { field.name: self.value(getattr(value, field.name), f"{path}.{field.name}") for field in dataclasses.fields(value) } return {"value": _qualified(value), "fields": fields} if _ours(value) and not _frozen(value): if id(value) in self.seen: return {"ref": self.seen[id(value)]} self.seen[id(value)] = path return self.object(value, path) raise StateError(f"{path}: cannot save a {type(value).__qualname__}") def object(self, value: object, path: str) -> dict: fields = {} for name, attribute in vars(value).items(): if attribute is self.cpu or isinstance(attribute, type) or _wiring(attribute): continue if _frozen(attribute) and not _is_value(attribute): continue # configuration fields[name] = self.value(attribute, f"{path}.{name}") return {"object": _qualified(value), "fields": fields} def save_state(system: System) -> bytes: """The state of ``system`` as bytes (between two of its steps).""" body = { "format": FORMAT, "version": VERSION, "images_sha1": _images_sha1(system), "machine": system.board.machine.name, "cpu": dataclasses.asdict(system.cpu.capture_state()), "system": {name: getattr(system, name) for name in SYSTEM_FIELDS}, "board": _Encoder(system.cpu).value(system.board, "board"), } return zlib.compress(json.dumps(body, separators=(",", ":")).encode(), 1) class _Decoder: """Applies an encoded graph to a system, in place where it can. The encoder writes each object once, at the first path that reaches it, and a reference at every later one. The decoder walks in the same order, keeps each object it restores by that path, and gives a reference the object restored there, so sharing is as it was saved. An existing object is updated in place only by the first path that claims it; another path saved with an object of its own gets a new one. """ def __init__(self) -> None: self.objects: dict[str, object] = {} # restored objects by their saved path self.claimed: set[int] = set() # existing objects already updated def fresh(self, encoded: Any, path: str) -> Any: """A value built from ``encoded`` with nothing to update in place.""" if encoded is None or isinstance(encoded, (bool, int, str, float)): return encoded if isinstance(encoded, list): return [self.fresh(item, f"{path}[{i}]") for i, item in enumerate(encoded)] if "ref" in encoded: return self.reference(encoded) if "bytearray" in encoded: return bytearray(base64.b64decode(encoded["bytearray"])) if "ints" in encoded: out = array("q") out.frombytes(base64.b64decode(encoded["ints"])) return out.tolist() if "array" in encoded: out = array(encoded["array"]) out.frombytes(base64.b64decode(encoded["data"])) return out if "tuple" in encoded: items = encoded["tuple"] return tuple(self.fresh(item, f"{path}[{i}]") for i, item in enumerate(items)) if "set" in encoded: return {self.fresh(item, path) for item in encoded["set"]} if "dict" in encoded: out = {} for k, v in encoded["dict"]: key = self.fresh(k, path) out[key] = self.fresh(v, f"{path}[{key!r}]") return out if "value" in encoded: if encoded["value"] not in VALUES: raise StateError(f"not a value a state may hold: {encoded['value']}") fields = { name: self.fresh(value, f"{path}.{name}") for name, value in encoded["fields"].items() } return _class(encoded["value"])(**fields) if "object" in encoded: cls = _class(encoded["object"]) obj = cls.__new__(cls) self.objects[path] = obj for name, value in encoded["fields"].items(): setattr(obj, name, self.fresh(value, f"{path}.{name}")) return obj if "rom" in encoded: raise StateError(f"{path}: a ROM image with no system to take it from") raise StateError(f"cannot load {str(encoded)[:80]}") def reference(self, encoded: dict) -> object: try: return self.objects[encoded["ref"]] except KeyError: raise StateError(f"a reference to nothing saved: {encoded['ref']}") from None def into(self, current: Any, encoded: Any, path: str) -> Any: """``encoded`` applied to ``current``: updated in place where it is an object, a ``bytearray`` or a container of the same shape, else built fresh. Returns the value the attribute should hold.""" if not isinstance(encoded, (dict, list)): return encoded if isinstance(encoded, list): if isinstance(current, list) and len(current) == len(encoded): for i, item in enumerate(encoded): current[i] = self.into(current[i], item, f"{path}[{i}]") return current return self.fresh(encoded, path) if "rom" in encoded: if not isinstance(current, bytes) or len(current) != encoded["rom"]: raise StateError(f"{path}: the system's ROM image is not the state's") return current if "ref" in encoded: return self.reference(encoded) if "bytearray" in encoded and isinstance(current, bytearray): data = base64.b64decode(encoded["bytearray"]) if len(data) == len(current): current[:] = data # in place: another object may hold the same one return current if "object" in encoded: if ( _ours(current) and _qualified(current) == encoded["object"] and id(current) not in self.claimed ): self.claimed.add(id(current)) self.objects[path] = current for name, value in encoded["fields"].items(): held = getattr(current, name, None) setattr(current, name, self.into(held, value, f"{path}.{name}")) return current return self.fresh(encoded, path) if "tuple" in encoded and isinstance(current, tuple): items = encoded["tuple"] if len(items) == len(current): return tuple( self.into(c, e, f"{path}[{i}]") for i, (c, e) in enumerate(zip(current, items, strict=True)) ) if "dict" in encoded and isinstance(current, dict): out = {} for k, v in encoded["dict"]: key = self.fresh(k, path) out[key] = self.into(current.get(key), v, f"{path}[{key!r}]") return out return self.fresh(encoded, path) def _class(name: str) -> type: """A class of these packages by its qualified name.""" module, _, qualname = name.rpartition(".") while module and module.split(".", 1)[0] in MODULES: try: found: Any = importlib.import_module(module) except ModuleNotFoundError: module, _, outer = module.rpartition(".") qualname = f"{outer}.{qualname}" continue for part in qualname.split("."): found = getattr(found, part, None) if isinstance(found, type): return found break raise StateError(f"not a class a state may hold: {name}") def load_state(system: System, data: bytes) -> None: """Put ``system`` in the state ``data`` was saved from (same images and machine).""" try: body = json.loads(zlib.decompress(data)) except (zlib.error, ValueError) as error: raise StateError(f"not a save state: {error}") from None if not isinstance(body, dict) or (body.get("format"), body.get("version")) != (FORMAT, VERSION): raise StateError(f"not a {FORMAT} version {VERSION}") if body["images_sha1"] != _images_sha1(system): raise StateError("a state of another cartridge") if body["machine"] != system.board.machine.name: raise StateError(f"a state of the {body['machine']}, not the {system.board.machine.name}") _Decoder().into(system.board, body["board"], "board") cpu = system.cpu cpu.restore_state(type(cpu.capture_state())(**body["cpu"])) for name in SYSTEM_FIELDS: setattr(system, name, body["system"][name]) class Rewind: """A window of the recent past: a state every few frames, the oldest dropped. ``record`` is called once a frame and keeps a state every ``every`` frames; ``back`` loads the newest one kept and forgets it, so holding a key steps back through them until the oldest, which stays. The default keeps about a minute at a state every tenth of a second. """ def __init__(self, system: System, every: int = 6, keep: int = 600) -> None: self.system = system self.every = every self.states: deque[bytes] = deque(maxlen=keep) self._frames = 0 def record(self) -> None: if self._frames % self.every == 0: self.states.append(save_state(self.system)) self._frames += 1 def back(self) -> bool: """Go back one kept state; False when there is none.""" if not self.states: return False state = self.states.pop() if len(self.states) > 1 else self.states[0] load_state(self.system, state) self._frames = 1 # the state just loaded is the one at frame 0 return True