#!/usr/bin/env python3 """Census of the CPS-3 sets: MAME's own list against the local libraries. Asks ``mame -listxml`` for every machine of ``capcom/cps3.cpp`` and reports, per set: parent, BIOS file (name, CRC, SHA-1 as MAME lists it), CHD (name and SHA-1) or the SIMM images of a NO CD set (count and bytes), and where the set is present locally. Zip members are matched by CRC from the zip directory; the BIOS file's SHA-1 is computed from the bytes when the file is found. Nothing is copied or unpacked to disk. python -I scripts/census.py > tests/detectors/census-YYYY-MM-DD.txt """ from __future__ import annotations import hashlib import os import subprocess import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path def local(variable: str, *parts: str) -> Path: """A local ROM folder from an environment variable (no machine path lives here). Unset, it is a path that does not exist, so the folder counts as absent: MAME_ROMPATH (MAME non-merged), MAME_MERGED_ROMPATH, MAME_CHDS (MAME CHDs, merged), FBNEO_DIR (FinalBurn Neo arcade), CURATED_ROMS (a frontend library with mame/ and fbneo/). """ value = os.environ.get(variable) if not value: print(f"{variable} is unset: its folder counts as absent", file=sys.stderr) return Path(value or f"${variable}", *parts) ZIP_DIRS = { "retrobat-mame": local("CURATED_ROMS", "mame"), "retrobat-fbneo": local("CURATED_ROMS", "fbneo"), "mame-merged": local("MAME_MERGED_ROMPATH"), "mame-nonmerged": local("MAME_ROMPATH"), } CHD_DIRS = { "retrobat-mame": local("CURATED_ROMS", "mame"), "mame-chds": local("MAME_CHDS"), } SOURCE = "capcom/cps3.cpp" def machines() -> list[ET.Element]: names = [ line.split()[0] for line in subprocess.run( ["mame", "-listsource"], capture_output=True, text=True, check=True ).stdout.splitlines() if line.rstrip().endswith("cps3.cpp") ] found = [] for name in names: xml = subprocess.run( ["mame", "-listxml", name], capture_output=True, text=True, check=True ).stdout for machine in ET.fromstring(xml).findall("machine"): if machine.get("name") == name and machine.get("sourcefile") == SOURCE: found.append(machine) return found def zip_crcs(path: Path) -> dict[int, zipfile.ZipInfo]: if not path.exists(): return {} with zipfile.ZipFile(path) as archive: return {info.CRC: info for info in archive.infolist()} def main() -> int: sets = machines() by_name = {machine.get("name"): machine for machine in sets} bios_seen: dict[str, tuple[str, str, str]] = {} print(f"MAME: {subprocess.run(['mame', '-version'], capture_output=True, text=True).stdout.strip()}") print(f"sets in {SOURCE}: {len(sets)}\n") header = f"{'set':12} {'parent':9} {'kind':6} {'simm files':>10} {'simm bytes':>11} where (complete)" print(header) print("-" * len(header)) for machine in sorted(sets, key=lambda m: (m.get("cloneof") or m.get("name"), m.get("name"))): name = machine.get("name") parent = machine.get("cloneof") or "-" roms = machine.findall("rom") disks = machine.findall("disk") simms = [rom for rom in roms if rom.get("region", "").startswith("simm")] bios = [rom for rom in roms if rom.get("region") == "bios"] kind = "CD" if disks else "NO CD" where = [] for label, directory in ZIP_DIRS.items(): crcs: dict[int, zipfile.ZipInfo] = {} holder = {} for candidate in (name, parent): path = directory / f"{candidate}.zip" for crc, info in zip_crcs(path).items(): crcs[crc] = info holder[crc] = path have = [rom for rom in roms if int(rom.get("crc", "0"), 16) in crcs] if roms and len(have) == len(roms): where.append(label) elif have: where.append(f"{label}({len(have)}/{len(roms)})") for rom in bios: crc = int(rom.get("crc"), 16) if crc in crcs and rom.get("name") not in bios_seen: with zipfile.ZipFile(holder[crc]) as archive: digest = hashlib.sha1(archive.read(crcs[crc])).hexdigest() bios_seen[rom.get("name")] = (rom.get("crc"), rom.get("sha1"), digest) for disk in disks: for label, directory in CHD_DIRS.items(): for candidate in (name, parent): if (directory / candidate / f"{disk.get('name')}.chd").exists(): where.append(f"chd:{label}") break simm_bytes = sum(int(rom.get("size")) for rom in simms) print( f"{name:12} {parent:9} {kind:6} {len(simms):>10} {simm_bytes:>11} {' '.join(where) or 'ABSENT'}" ) print("\nBIOS (security cartridge flash, 524,288 bytes each)") for machine in sorted(sets, key=lambda m: m.get("name")): for rom in machine.findall("rom"): if rom.get("region") == "bios": seen = bios_seen.get(rom.get("name")) state = "sha1 of local bytes matches" if seen and seen[1] == seen[2] else "NOT FOUND LOCALLY" print(f" {machine.get('name'):12} {rom.get('name'):48} crc {rom.get('crc')} sha1 {rom.get('sha1')} {state}") print("\nCHDs") listed = set() for machine in sorted(sets, key=lambda m: m.get("name")): for disk in machine.findall("disk"): key = (disk.get("name"), disk.get("sha1")) users = [m.get("name") for m in sets if any((d.get("name"), d.get("sha1")) == key for d in m.findall("disk"))] if key in listed: continue listed.add(key) places = [] for label, directory in CHD_DIRS.items(): for candidate in {by_name[user].get("cloneof") or user for user in users} | set(users): path = directory / candidate / f"{key[0]}.chd" if path.exists(): places.append(f"{label}:{candidate} ({path.stat().st_size:,} bytes)") print(f" {key[0]:58} sha1 {key[1]} used by {len(users)} sets {'; '.join(sorted(places)) or 'ABSENT'}") return 0 if __name__ == "__main__": sys.exit(main())