# SPDX-License-Identifier: MIT """Census of the MSX software and firmware on this machine, read in place. NO_INTRO_DIR=... python -I scripts/census.py nointro # the No-Intro MSX and MSX2 sets MAME_ROMPATH=... python -I scripts/census.py mame # MAME 0.285's MSX machines `nointro` lists every zip in the four No-Intro MSX folders, hashes each member (SHA-1), looks the hash up in MAME's software lists (reference/softlists/, CC0, fetched by fetch_references.py) for the cartridge type MAME assigns, and for images no list knows makes its own guess from the bank-switch writes in the code (`LD (nnnn),A` to the addresses each mapper decodes; Sean Young's "Megabit ROM Cartridges" for the addresses). Both are detectors: a list's slot type is MAME's opinion and the guess is a heuristic. `mame` asks MAME (`-listsource`, `-listxml`) for the machines of its msx/ drivers, the chips each one carries, and the SHA-1 of every ROM it wants, then checks which of those ROMs are present in `$MAME_ROMPATH` (in the machine's zip, its parent's or any zip of the same name), by SHA-1, not by name. Nothing is copied: listings go to reference/census/ (git-ignored) and a summary is printed. Environment variables name the libraries; no machine path is written here. """ from __future__ import annotations import argparse import collections import hashlib import os import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "reference" / "census" SOFTLISTS = ROOT / "reference" / "softlists" FOLDERS = ( "Microsoft - MSX", "Microsoft - MSX (Aftermarket)", "Microsoft - MSX2", "Microsoft - MSX2 (Aftermarket)", ) ROM_SUFFIXES = (".rom", ".mx1", ".mx2", ".bin", ".col") # The addresses each mapper's bank registers are written at, as Sean Young's page gives # them (the low address of each decoded range; games write those). Used only to guess. MAPPER_WRITES = { "konami": {0x6000, 0x8000, 0xA000}, "konami_scc": {0x5000, 0x7000, 0x9000, 0xB000}, "ascii8": {0x6000, 0x6800, 0x7000, 0x7800}, "ascii16": {0x6000, 0x7000, 0x77FF}, } def need_env(name: str) -> Path: value = os.environ.get(name) if not value: sys.exit(f"set {name} (see README.md)") return Path(value) def softlist_index() -> dict[str, tuple[str, str, str]]: """SHA-1 -> (list, software name, slot type) over every pinned software list.""" index: dict[str, tuple[str, str, str]] = {} for path in sorted(SOFTLISTS.glob("*.xml")): tree = ET.parse(path) for software in tree.getroot().iter("software"): for part in software.iter("part"): slot = "nomapper" for feature in part.iter("feature"): if feature.get("name") == "slot": slot = feature.get("value", "?") if part.get("interface", "").endswith("_cass"): slot = "cassette" elif "flop" in part.get("interface", ""): slot = "floppy" for rom in part.iter("rom"): sha1 = rom.get("sha1") if sha1: index.setdefault(sha1, (path.stem, software.get("name", "?"), slot)) return index def guess_mapper(data: bytes) -> str: """A heuristic only: plain for 64 KB or less, else the mapper whose addresses the code writes most often with LD (nnnn),A (opcode 32h).""" if len(data) <= 0x10000: return "plain?" counts = collections.Counter() for match in re.finditer(rb"\x32(..)", data, flags=re.DOTALL): address = int.from_bytes(match.group(1), "little") for mapper, addresses in MAPPER_WRITES.items(): if address in addresses: counts[mapper] += 1 if not counts: return "unknown?" # Konami and ASCII share 6000h: break ties towards the mapper with more distinct hits. best = max(counts, key=lambda m: (counts[m], m != "ascii8")) return best + "?" def nointro(args: argparse.Namespace) -> int: base = need_env("NO_INTRO_DIR") index = softlist_index() OUT.mkdir(parents=True, exist_ok=True) rows = [] for folder in FOLDERS: directory = base / folder if not directory.is_dir(): print(f"missing folder: {folder}") continue for path in sorted(directory.glob("*.zip")): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if info.is_dir(): continue data = archive.read(info) sha1 = hashlib.sha1(data).hexdigest() hit = index.get(sha1) rows.append({ "folder": folder, "zip": path.name, "member": info.filename, "size": len(data), "sha1": sha1, "bios": "[BIOS]" in path.name, "list": hit[0] if hit else "", "software": hit[1] if hit else "", "slot": hit[2] if hit else "", "guess": "" if hit else guess_mapper(data), }) # fmt: skip listing = OUT / "nointro.tsv" keys = ["folder", "zip", "member", "size", "sha1", "bios", "list", "software", "slot", "guess"] with listing.open("w", encoding="utf-8") as handle: handle.write("\t".join(keys) + "\n") for row in rows: handle.write("\t".join(str(row[k]) for k in keys) + "\n") print(f"wrote {listing.relative_to(ROOT)} ({len(rows)} members)") for folder in FOLDERS: mine = [r for r in rows if r["folder"] == folder] zips = {r["zip"] for r in mine} bios = [r for r in mine if r["bios"]] known = [r for r in mine if r["slot"] and not r["bios"]] print(f"\n## {folder}: {len(zips)} zips, {len(mine)} members, {len(bios)} BIOS members, " f"{len(known)} of {len(mine) - len(bios)} others found in MAME's lists") # fmt: skip suffixes = collections.Counter(Path(r["member"]).suffix.lower() for r in mine) print(" suffixes:", dict(suffixes.most_common())) sizes = collections.Counter(r["size"] // 1024 for r in mine if not r["bios"]) print(" sizes (KB):", dict(sorted(sizes.items()))) slots = collections.Counter(r["slot"] or r["guess"] for r in mine if not r["bios"]) print(" type (MAME list, or ? = heuristic):", dict(slots.most_common())) lists = collections.Counter(r["list"] for r in mine if r["list"]) if lists: print(" matched in:", dict(lists.most_common())) for r in bios: print(f" BIOS {r['sha1']} {r['size']:>7} {r['zip']} :: {r['member']}") return 0 MSX_SOURCES = ("msx/msx1.cpp", "msx/msx1_bruc100.cpp", "msx/msx1_v9938.cpp", "msx/msx2.cpp", "msx/msx2p.cpp", "msx/msxtr.cpp") # fmt: skip # The VDP is not a in -listxml, so it is read from the machine's device_ref list # (which also holds every slot option's devices: only the VDP names are taken from it). VDPS = ("tms9918", "tms9918a", "tms9928a", "tms9929a", "tms9118", "tms9128", "tms9129", "v9938", "v9958") # fmt: skip def chips_of(machine: ET.Element) -> list[str]: """The machine's own CPUs and sound chips, its VDP, and 'disk' for a built-in drive.""" found = set() for chip in machine.iter("chip"): tag = chip.get("tag", "") if ":fdc:" in tag: found.add("built-in disk") elif ":" not in tag and not tag.startswith("cartslot") and chip.get("name") not in ("Speaker", "Cassette"): found.add(chip.get("name", "?")) found |= {d.get("name") for d in machine.iter("device_ref")} & set(VDPS) return sorted(found) def mame(args: argparse.Namespace) -> int: rompath = need_env("MAME_ROMPATH") sources = subprocess.run(["mame", "-listsource"], capture_output=True, text=True, check=True).stdout names = [line.split()[0] for line in sources.splitlines() if len(line.split()) == 2 and line.split()[1] in MSX_SOURCES] # fmt: skip by_source = collections.Counter(line.split()[1] for line in sources.splitlines() if len(line.split()) == 2 and line.split()[1] in MSX_SOURCES) # fmt: skip xml = subprocess.run(["mame", "-listxml", *names], capture_output=True, text=True, check=True).stdout root = ET.fromstring(xml) machines = {m.get("name"): m for m in root.iter("machine")} zip_cache: dict[str, set[str]] = {} def zip_sha1s(name: str) -> set[str]: if name not in zip_cache: found: set[str] = set() path = rompath / f"{name}.zip" if path.exists(): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if not info.is_dir(): found.add(hashlib.sha1(archive.read(info)).hexdigest()) zip_cache[name] = found return zip_cache[name] OUT.mkdir(parents=True, exist_ok=True) listing = OUT / "mame-msx.tsv" chip_count = collections.Counter() totals = collections.Counter() with listing.open("w", encoding="utf-8") as handle: handle.write("machine\tsource\tparent\tdescription\tyear\tmanufacturer\tchips\troms\tpresent\tmissing\n") for name in names: machine = machines.get(name) if machine is None: continue source = machine.get("sourcefile", "") parent = machine.get("romof") or machine.get("cloneof") or "" chips = chips_of(machine) chip_count.update(chips) roms = [r for r in machine.iter("rom") if r.get("sha1") and r.get("status") != "nodump"] have = zip_sha1s(name) | (zip_sha1s(parent) if parent else set()) present = [r for r in roms if r.get("sha1") in have] missing = [r for r in roms if r.get("sha1") not in have] state = "complete" if roms and not missing else ("none" if not present else "partial") totals[state] += 1 handle.write("\t".join([ name, source, parent, machine.findtext("description", ""), machine.findtext("year", ""), machine.findtext("manufacturer", ""), ",".join(chips), ";".join(f"{r.get('name')}={r.get('sha1')}" for r in roms), str(len(present)), ";".join(r.get("name", "") for r in missing), ]) + "\n") # fmt: skip print(f"wrote {listing.relative_to(ROOT)}") print(f"machines by source: {dict(by_source)} (total {sum(by_source.values())})") print(f"ROM sets in MAME_ROMPATH by SHA-1: {dict(totals)}") print(f"machines carrying each chip: {dict(chip_count.most_common())}") return 0 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("nointro", help="the No-Intro MSX and MSX2 sets").set_defaults(run=nointro) sub.add_parser("mame", help="MAME's MSX machines and their ROMs").set_defaults(run=mame) args = parser.parse_args() return args.run(args) if __name__ == "__main__": sys.exit(main())