#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only """Fetch Mednafen 1.32.1 at its pinned tarball and build one of its family builds. python3 -I build.py --machine pce # the PC Engine trace build: build/pce/bin/mednafen python3 -I build.py --machine ss # the Saturn build, as published: build/ss/bin/mednafen python3 -I build.py --version # mednafen-build 0.1.0 (Mednafen 1.32.1, de7eb94a) JOBS=2 python3 -I build.py ... # parallel jobs for make (default 2) Part of the mednafen tool in emu-tools-gpl2 (README.md; GPL-2.0-only). The steps were moved here on 2026-11-25 (decisions page T3) from two MIT emulator repositories, where alewman first wrote them: huc6280-python's ``scripts/build_mednafen.py`` (machine ``pce``) and sh2-python's ``scripts/build_referees.py`` (machine ``ss``); that permission is kept for those parts (``../../notices/MIT-emulator-family.txt``). Each build keeps its consumer's configure options, so it is the program the consumer built before. - ``pce``: every system but the PC Engine off (pce-fast off too), the instruction-trace patch ``patches/mednafen-trace.patch`` applied, installed under ``build/pce``. - ``ss``: every system but the Saturn off, no patch, installed under ``build/ss``. The tarball lands in ``upstream/`` and is checked against its SHA-256; each machine unpacks its own tree into ``build//src``. Both folders are git-ignored; Mednafen is never committed. ``build//build-info.json`` records the tarball, the patches and the options. Exit status as the family's tool contract says: 0 built (or already built), 2 a usage error, 3 the tarball could not be fetched or does not match its SHA-256, anything else a failed build. Nothing is ever deleted: a half-unpacked tree stops the script until it is moved aside. """ from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys import tarfile import tempfile import time from pathlib import Path from urllib.request import Request, urlopen TOOL, VERSION = "mednafen-build", "0.1.0" HERE = Path(__file__).resolve().parent UPSTREAM_DIR = HERE / "upstream" BUILD = HERE / "build" RELEASE = "1.32.1" URL = f"https://mednafen.github.io/releases/files/mednafen-{RELEASE}.tar.xz" SHA256 = "de7eb94ab66212ae7758376524368a8ab208234b33796625ca630547dbc83832" TARBALL = UPSTREAM_DIR / f"mednafen-{RELEASE}.tar.xz" EXIT_OK, EXIT_USAGE, EXIT_MISSING = 0, 2, 3 #: Every system module Mednafen 1.32.1's configure offers to turn off. SYSTEMS = ( "apple2", "gb", "gba", "lynx", "md", "nes", "ngp", "pce", "pce-fast", "pcfx", "psx", "sasplay", "sms", "snes", "snes-faust", "ss", "ssfplay", "vb", "wswan", ) # fmt: skip #: Each machine: the systems it keeps, its own configure options (as its consumer built it, #: in the same order) and its patches. MACHINES = { "pce": { "keep": ("pce",), "configure": ["--enable-pce", "--disable-pce-fast", "--disable-apple2", "--disable-gb", "--disable-gba", "--disable-lynx", "--disable-md", "--disable-nes", "--disable-ngp", "--disable-pcfx", "--disable-psx", "--disable-sasplay", "--disable-sms", "--disable-snes", "--disable-snes-faust", "--disable-ss", "--disable-ssfplay", "--disable-vb", "--disable-wswan", "--disable-nls", "--disable-alsa", "--disable-jack", "--disable-debugger", "--without-libflac"], "patches": ["mednafen-trace.patch"], "was": "huc6280-python scripts/build_mednafen.py", }, "ss": { "keep": ("ss",), "configure": ["--disable-alsa", "--disable-jack", "--without-libflac", *(f"--disable-{n}" for n in SYSTEMS if n != "ss")], "patches": [], "was": "sh2-python scripts/build_referees.py", }, } # fmt: skip def binary(machine: str) -> Path: """The built program's documented path.""" return BUILD / machine / "bin" / "mednafen" def fetch() -> None: """The release tarball, downloaded once and checked against its SHA-256.""" if not TARBALL.exists(): UPSTREAM_DIR.mkdir(parents=True, exist_ok=True) print(f"downloading {URL}", flush=True) partial = TARBALL.with_suffix(".partial") try: request = Request(URL, headers={"User-Agent": "emu-tools-gpl2"}) with urlopen(request, timeout=300) as response, partial.open("wb") as out: shutil.copyfileobj(response, out, 1 << 20) except OSError as error: print(f"could not fetch {URL}: {error}", file=sys.stderr) raise SystemExit(EXIT_MISSING) from error partial.rename(TARBALL) digest = hashlib.sha256(TARBALL.read_bytes()).hexdigest() if digest != SHA256: print(f"{TARBALL}: SHA-256 {digest} is not the pinned {SHA256}; move it aside", file=sys.stderr) # fmt: skip raise SystemExit(EXIT_MISSING) def unpack(machine: str) -> Path: """This machine's own pristine tree, ``build//src``.""" tree = BUILD / machine / "src" if (tree / ".complete").exists(): return tree if tree.exists(): raise SystemExit(f"{tree} is incomplete (an interrupted unpack?): move it aside first") tree.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=tree.parent) as temporary: with tarfile.open(TARBALL) as archive: archive.extractall(temporary, filter="data") (Path(temporary) / "mednafen").rename(tree) (tree / ".complete").write_text(SHA256 + "\n") return tree def patch(machine: str, tree: Path) -> None: for name in MACHINES[machine]["patches"]: marker = tree / f".patched-{name}" if marker.exists(): continue subprocess.run(["patch", "-p1", "-i", str(HERE / "patches" / name)], cwd=tree, check=True) marker.write_text("patched\n") def build(machine: str) -> Path: spec = MACHINES[machine] program = binary(machine) newest = max((HERE / "patches" / n).stat().st_mtime for n in spec["patches"]) if spec["patches"] else 0 if program.exists() and program.stat().st_mtime > newest: print(f"already built: {program}") return program fetch() tree = unpack(machine) patch(machine, tree) prefix = BUILD / machine jobs = os.environ.get("JOBS", "2") nice = ["nice", "-n", "10"] log = prefix / "build.log" with log.open("w", encoding="utf-8") as handle: for command in ( ["./configure", f"--prefix={prefix}", *spec["configure"]], ["make", f"-j{jobs}"], ["make", "install"], ): done = subprocess.run(nice + command, cwd=tree, stdout=handle, stderr=subprocess.STDOUT) if done.returncode: print(f"{' '.join(command[:2])} failed; see {log}", file=sys.stderr) raise SystemExit(1) info = { "tool": TOOL, "tool_version": VERSION, "machine": machine, "upstream": {"name": "Mednafen", "release": RELEASE, "url": URL, "sha256": SHA256}, "patches": spec["patches"], "configure": spec["configure"], "was": spec["was"], "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } (prefix / "build-info.json").write_text(json.dumps(info, indent=1) + "\n") print(f"built {program}") return program def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--machine", choices=sorted(MACHINES)) parser.add_argument("--version", action="store_true") try: args = parser.parse_args(argv) except SystemExit as error: return EXIT_USAGE if error.code else EXIT_OK if args.version: print(f"{TOOL} {VERSION} (Mednafen {RELEASE}, {SHA256[:8]})") return EXIT_OK if not args.machine: parser.print_usage(sys.stderr) return EXIT_USAGE build(args.machine) return EXIT_OK if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))