"""A desktop window: play a cartridge with picture, sound, keyboard and gamepads. sms-python "Sonic The Hedgehog (USA, Europe, Brazil) (En).zip" sms-python game.gg --scale 4 sms-python game.sms --machine smsj --bios bios.sms This is the only module that needs a library beyond z80-python: pygame-ce (the ``frontend`` extra), for SDL's window, audio and game controllers. Run it on PyPy: the emulator is pure Python, and CPython runs it at about a third of real time. Timing is audio-driven. SDL's audio thread drains a small buffer of samples; the main loop runs the console one frame at a time only while that buffer is short, so the console's own 59.92 Hz (or 49.70 Hz PAL) sets the pace and the sound never drifts or starves. The picture shows the latest complete frame. """ from __future__ import annotations import argparse import sys import threading import time import zipfile from array import array from collections.abc import Callable from itertools import chain from pathlib import Path from .board import MACHINES from .cartridge import IMAGE_SUFFIXES, Cartridge, load_image from .io import BUTTON_1, BUTTON_2, DOWN, LEFT, RIGHT, SC3000_KEYS, UP from .png import write_png from .state import Rewind, load_state, save_state from .system import System SAMPLE_RATE = 44_100 #: Frames of sound kept queued ahead of the speaker: the latency, and the margin a #: slow frame (a garbage collection) can use before the sound gaps. BUFFER_FRAMES = 3 # Machine by file extension; anything else runs on an export Master System II. MACHINE_BY_SUFFIX = { ".sg": "sg1000", ".sc": "sc3000", ".gg": "gamegear", ".sf": "sf7000", ".sf7": "sf7000", } # fmt: skip HELP = """\ Arrows D-pad Z / J button 1 X / K button 2 Enter Start (Game Gear) / Pause (Master System) Backspace the console's reset button (SMS1 and Mark III) Tab (hold) fast forward F3 pause emulation F5 power cycle F6 save a state F7 load it F8 (hold) rewind F11 fullscreen F12 screenshot (PNG) Esc quit""" # -- conversions (pure, tested without pygame) --------------------------------------- def frame_bytes(frame: list[list[int]]) -> bytes: """Rows of 0xRRGGBB as opaque BGRA bytes (little-endian 0xFFRRGGBB words).""" pixels = array("I", [0xFF000000 | p for p in chain.from_iterable(frame)]) if sys.byteorder == "big": pixels.byteswap() return pixels.tobytes() class DCBlocker: """The console's output capacitor: a one-pole high-pass filter per side. The PSG's output is unipolar (0.0 silent, 1.0 all channels at full volume); a speaker wants it centred on zero, and without the filter every note change moves the DC level and clicks. """ def __init__(self, pole: float = 0.995) -> None: self.pole = pole self._last_in = [0.0, 0.0] self._last_out = [0.0, 0.0] def samples_s16(self, samples: list[tuple[float, float]], gain: float = 0.7) -> bytes: """Stereo (left, right) pairs in 0.0-1.0 as interleaved signed 16-bit bytes.""" pole, last_in, last_out = self.pole, self._last_in, self._last_out scale = gain * 32767 out = array("h") for pair in samples: for side in (0, 1): x = pair[side] y = x - last_in[side] + pole * last_out[side] last_in[side], last_out[side] = x, y out.append(max(-32768, min(32767, int(y * scale)))) if sys.byteorder == "big": out.byteswap() return out.tobytes() class SoundBuffer: """Bytes queued for SDL's audio thread, which calls :meth:`fill`.""" def __init__(self) -> None: self._data = bytearray() self._lock = threading.Lock() def __len__(self) -> int: return len(self._data) def push(self, data: bytes) -> None: with self._lock: self._data += data def clear(self) -> None: with self._lock: self._data.clear() def fill(self, _device: object, stream: memoryview) -> None: """SDL's audio callback: copy what is queued, then silence.""" size = len(stream) with self._lock: chunk = bytes(self._data[:size]) del self._data[:size] stream[: len(chunk)] = chunk if len(chunk) < size: stream[len(chunk) :] = bytes(size - len(chunk)) def machine_for(path: Path) -> str: """The machine a cartridge file suggests, from its (or its zipped image's) suffix.""" suffix = path.suffix.lower() if suffix == ".zip" and zipfile.is_zipfile(path): with zipfile.ZipFile(path) as archive: images = [n for n in archive.namelist() if n.lower().endswith(IMAGE_SUFFIXES)] if images: suffix = Path(images[0]).suffix.lower() return MACHINE_BY_SUFFIX.get(suffix, "sms2") # -- the window ------------------------------------------------------------------------ class Frontend: """One console in one window. ``pygame`` is imported by :func:`main`.""" def __init__(self, pygame, rom: Path, machine: str, bios: Path | None, scale: int, audio: bool, fullscreen: bool) -> None: # fmt: skip self.pg = pygame self.rom, self.machine_name, self.bios_path = rom, machine, bios self.system = self._power_on() first = self.system.run_frame() self.frame_size = (len(first[0]), len(first)) self.frame = first self.scale, self.fullscreen = scale, fullscreen self.window = self._open_window(self.frame_size) pygame.display.set_caption(f"{rom.stem} — sms-python") self.sound = SoundBuffer() self.dc = DCBlocker() self.device = self._open_audio() if audio else None self.paused = False self.fast = False #: The recent past, a state every few frames; F8 walks back through it. self.rewind = Rewind(self.system) self.rewinding = False self._rewind_ticks = 0 self.saved: bytes | None = None # F6's state, kept until the window closes self.controllers: dict[int, object] = {} self._frames = 0 self._fps_since = time.perf_counter() def _open_window(self, size: tuple[int, int]): """A window whose surface is one frame: SDL scales it to the window on the GPU (SCALED, nearest-neighbour) and presents it at the display's refresh (vsync), so a frame is never shown half-drawn. pygame offers vsync only with SCALED.""" pg = self.pg flags = pg.SCALED | pg.RESIZABLE | (pg.FULLSCREEN if self.fullscreen else 0) try: surface = pg.display.set_mode(size, flags, vsync=1) except pg.error: # no vsync on this display: tearing, but a picture surface = pg.display.set_mode(size, flags) if not self.fullscreen: pg.Window.from_display_module().size = (size[0] * self.scale, size[1] * self.scale) return surface # -- console ------------------------------------------------------------------ def _power_on(self) -> System: machine = MACHINES[self.machine_name] bios = Cartridge.from_file(self.bios_path, board="rom") if self.bios_path else None if machine.disk_unit: # The file is a disk for the SF-7000, whose IPL ROM is --bios. Writes # stay in memory: the image on disk is never changed. return System(machine, None, bios, audio=True, disk=bytearray(load_image(self.rom))) cartridge = Cartridge.from_file(self.rom) return System(machine, cartridge, bios, audio=True) def _open_audio(self): from pygame._sdl2.audio import AUDIO_S16, AudioDevice from pygame._sdl2.sdl2 import INIT_AUDIO, init_subsystem try: init_subsystem(INIT_AUDIO) device = AudioDevice( devicename=None, iscapture=False, frequency=SAMPLE_RATE, audioformat=AUDIO_S16, numchannels=2, chunksize=512, allowed_changes=0, callback=self.sound.fill, ) # fmt: skip except Exception as error: # pygame._sdl2's own error type; no device, no sound print(f"no sound: {error}", file=sys.stderr) return None device.pause(0) return device @property def _frame_bytes(self) -> int: """Bytes of sound one frame makes: stereo 16-bit at the console's rate.""" return int(SAMPLE_RATE / self.system.board.machine.frame_rate) * 4 def run_frame(self) -> None: if self.rewinding: self._rewind_frame() return self._apply_inputs() self.rewind.record() self.frame = self.system.run_frame() samples = self.system.board.take_samples() if self.device is not None and not self.fast: self.sound.push(self.dc.samples_s16(samples)) self._frames += 1 def _rewind_frame(self) -> None: """One shown frame of rewinding: every third goes back one kept state (a tenth of a second), so the past plays at about twice its speed, silently. The picture is the one the state holds, its last complete frame.""" self._rewind_ticks += 1 if self._rewind_ticks % 3 == 1 and self.rewind.back(): self.frame = self.system.board.vdp.visible_frame() or self.frame self.system.board.take_samples() if self.device is not None: self.sound.push(bytes(self._frame_bytes)) # silence keeps the pace self._frames += 1 def _load_saved(self) -> None: if self.saved is not None: load_state(self.system, self.saved) self.frame = self.system.board.vdp.visible_frame() or self.frame self.sound.clear() # -- input -------------------------------------------------------------------- def _pad_state(self) -> tuple[set[int], bool]: """Pad 1's pressed buttons and Start/Pause, from the keyboard and pad 0.""" pg = self.pg keys = pg.key.get_pressed() pressed = { button for button, codes in ( (UP, (pg.K_UP,)), (DOWN, (pg.K_DOWN,)), (LEFT, (pg.K_LEFT,)), (RIGHT, (pg.K_RIGHT,)), (BUTTON_1, (pg.K_z, pg.K_j)), (BUTTON_2, (pg.K_x, pg.K_k)), ) if any(keys[code] for code in codes) } # fmt: skip start = bool(keys[pg.K_RETURN] or keys[pg.K_KP_ENTER]) controllers = list(self.controllers.values()) if controllers: pressed2, start2 = self._controller_state(controllers[0]) pressed |= pressed2 start = start or start2 return pressed, start def _controller_state(self, controller) -> tuple[set[int], bool]: pg = self.pg pressed = set() stick_x = controller.get_axis(pg.CONTROLLER_AXIS_LEFTX) / 32768 stick_y = controller.get_axis(pg.CONTROLLER_AXIS_LEFTY) / 32768 for button, name, stick in ( (UP, pg.CONTROLLER_BUTTON_DPAD_UP, stick_y < -0.5), (DOWN, pg.CONTROLLER_BUTTON_DPAD_DOWN, stick_y > 0.5), (LEFT, pg.CONTROLLER_BUTTON_DPAD_LEFT, stick_x < -0.5), (RIGHT, pg.CONTROLLER_BUTTON_DPAD_RIGHT, stick_x > 0.5), (BUTTON_1, pg.CONTROLLER_BUTTON_A, False), (BUTTON_2, pg.CONTROLLER_BUTTON_B, False), ): if stick or controller.get_button(name): pressed.add(button) return pressed, bool(controller.get_button(pg.CONTROLLER_BUTTON_START)) def _sc3000_keys(self) -> set[str]: """The SC-3000 keys held, by position on a PC keyboard.""" pg = self.pg keys = pg.key.get_pressed() held = { name for name in SC3000_KEYS if len(name) == 1 and name.isalnum() and keys[getattr(pg, f"K_{name.lower()}")] } # fmt: skip for name, key in ( (",", pg.K_COMMA), (".", pg.K_PERIOD), ("/", pg.K_SLASH), (";", pg.K_SEMICOLON), (":", pg.K_QUOTE), ("@", pg.K_LEFTBRACKET), ("[", pg.K_RIGHTBRACKET), ("]", pg.K_BACKSLASH), ("-", pg.K_MINUS), ("^", pg.K_EQUALS), ("YEN", pg.K_BACKQUOTE), ("PI", pg.K_INSERT), ("INS DEL", pg.K_BACKSPACE), ("HOME CLR", pg.K_HOME), ("BREAK", pg.K_END), ("CR", pg.K_RETURN), ("SPACE", pg.K_SPACE), ("UP", pg.K_UP), ("DOWN", pg.K_DOWN), ("LEFT", pg.K_LEFT), ("RIGHT", pg.K_RIGHT), ("SHIFT", pg.K_LSHIFT), ("SHIFT", pg.K_RSHIFT), ("CTRL", pg.K_LCTRL), ("GRAPH", pg.K_LALT), ("ENG DIER'S", pg.K_RALT), ("FUNC", pg.K_F1), ): # fmt: skip if keys[key]: held.add(name) return held def _apply_inputs(self) -> None: board = self.system.board if board.machine.decode == "sc3000": # The PC's keys are the computer's; the joysticks are game controllers. # Pause/Break is the RESET key, which is an NMI. controllers = list(self.controllers.values()) pads = [self._controller_state(c)[0] for c in controllers[:2]] + [set(), set()] board.io.pad1.pressed, board.io.pad2.pressed = pads[0], pads[1] board.keyboard.keys = self._sc3000_keys() reset = bool(self.pg.key.get_pressed()[self.pg.K_PAUSE]) if reset and not self._start_held: board.press_pause() self._start_held = reset return pressed, start = self._pad_state() board.io.pad1.pressed = pressed controllers = list(self.controllers.values()) board.io.pad2.pressed = ( self._controller_state(controllers[1])[0] if len(controllers) > 1 else set() ) if board.machine.decode == "gamegear": board.gg_ports.start_pressed = start elif start and not self._start_held: board.press_pause() # an edge: one NMI per press self._start_held = start board.io.reset_pressed = bool(self.pg.key.get_pressed()[self.pg.K_BACKSPACE]) _start_held = False # -- events ------------------------------------------------------------------- def _handle(self, event) -> bool: """Handle one event; False to quit.""" pg = self.pg if event.type == pg.QUIT: return False if event.type == pg.CONTROLLERDEVICEADDED: controller = pg._sdl2.controller.Controller(event.device_index) self.controllers[controller.id] = controller elif event.type == pg.CONTROLLERDEVICEREMOVED: self.controllers.pop(event.instance_id, None) elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: return False if event.key == pg.K_F3: self.paused = not self.paused self.sound.clear() elif event.key == pg.K_F5: self.system = self._power_on() self.rewind = Rewind(self.system) self.sound.clear() elif event.key == pg.K_F6: self.saved = save_state(self.system) elif event.key == pg.K_F7: self._load_saved() elif event.key == pg.K_F8: self.rewinding = True self.sound.clear() elif event.key == pg.K_F11: pg.display.toggle_fullscreen() elif event.key == pg.K_F12: self._screenshot() elif event.key == pg.K_TAB: self.fast = True self.sound.clear() elif event.type == pg.KEYUP and event.key == pg.K_TAB: self.fast = False elif event.type == pg.KEYUP and event.key == pg.K_F8: self.rewinding = False return True def _screenshot(self) -> None: folder = Path("screenshots") folder.mkdir(exist_ok=True) stamp = time.strftime("%Y%m%d-%H%M%S") path = folder / f"{self.rom.stem}-{stamp}.png" write_png(path, self.frame) print(f"saved {path}") # -- drawing ------------------------------------------------------------------ def draw(self) -> None: pg = self.pg frame = self.frame size = (len(frame[0]), len(frame)) if size != self.frame_size: # the game switched to 224 or 240 lines, or back self.frame_size = size self.window = self._open_window(size) self.window.blit(pg.image.frombuffer(frame_bytes(frame), size, "BGRA"), (0, 0)) pg.display.flip() # waits for the display's refresh now = time.perf_counter() if now - self._fps_since >= 1.0: fps = self._frames / (now - self._fps_since) state = ( " (paused)" if self.paused else " (rewinding)" if self.rewinding else " (fast)" if self.fast else "" ) # fmt: skip pg.display.set_caption(f"{self.rom.stem} — {fps:.0f} fps{state} — sms-python") self._frames, self._fps_since = 0, now # -- the loop ----------------------------------------------------------------- def run(self, max_frames: int | None = None, on_frame: Callable | None = None) -> None: pg = self.pg clock = pg.time.Clock() rate = self.system.board.machine.frame_rate target = BUFFER_FRAMES * self._frame_bytes shown = 0 while True: for event in pg.event.get(): if not self._handle(event): return ran = False if not self.paused: if self.fast: for _ in range(4): self.run_frame() ran = True elif self.device is not None: # Audio sets the pace: one frame each time the queue is short of # its target, so each is shown; a second only if the sound is # about to run dry. if len(self.sound) < target: self.run_frame() ran = True if len(self.sound) < self._frame_bytes: self.run_frame() else: self.run_frame() ran = True if ran: self.draw() shown += 1 if on_frame is not None: on_frame(self) if max_frames is not None and shown >= max_frames: return if self.device is None and not self.fast: clock.tick_busy_loop(rate) elif not ran: time.sleep(0.002) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="sms-python", description="Play a Sega 8-bit cartridge, or an SF-7000 disk.", epilog=HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "rom", type=Path, help="cartridge (.sg/.sc/.sms/.gg) or SF-7000 disk (.sf), or a zip of one" ) parser.add_argument( "--machine", choices=sorted(MACHINES), help="default: from the file (sms2 for .sms)" ) parser.add_argument( "--bios", type=Path, help="a BIOS to boot through (SMS), or the SF-7000's IPL ROM" ) parser.add_argument("--scale", type=int, default=3, help="window scale (default 3)") parser.add_argument("--no-audio", action="store_true") parser.add_argument("--fullscreen", action="store_true") args = parser.parse_args(argv) try: import pygame import pygame._sdl2.controller except ImportError: parser.error("the window needs pygame-ce: pip install 'sms-python[frontend]'") if sys.implementation.name != "pypy": print("note: CPython runs this emulator at about a third of real time; use PyPy.", file=sys.stderr) # fmt: skip load_image(args.rom) # fail early on a missing or empty file # Not pygame.init(): its mixer would take the audio device the frontend opens. pygame.display.init() pygame._sdl2.controller.init() print(HELP) frontend = Frontend( pygame, args.rom, args.machine or machine_for(args.rom), args.bios, max(1, args.scale), not args.no_audio, args.fullscreen, ) # fmt: skip try: frontend.run() finally: pygame.quit() return 0 if __name__ == "__main__": sys.exit(main())