#!/usr/bin/env python """Census of the MSM6295 sample ROMs in the local arcade sets. python scripts/mame_census.py # first: which machines, which ROMs python scripts/rom_census.py # then: which of them are on this disk python scripts/rom_census.py --family capcom/cps1.cpp # one driver's table Reads reference/census/machines.json, finds each machine's zip in the local trees (read in place, never copied), reads the sample ROMs out of it by CRC, checks each against MAME's SHA-1, puts the files of a region at their offsets and reads the phrase table at the start of the region: 127 entries of eight bytes from address 8 (the data sheet's layout). It decodes no ADPCM; it only counts what the tables say. Writes reference/census/roms.json (ignored) and prints the totals. """ from __future__ import annotations import argparse import hashlib import os import sys import json import zipfile from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parent.parent MACHINES = ROOT / "reference" / "census" / "machines.json" OUT = ROOT / "reference" / "census" / "roms.json" #: Romset folders from MAME_ROMPATH (separated by ';' as MAME's -rompath is), each #: named by its folder. The first is the tree the ROM bytes are read from: put a #: non-merged set first, where every machine has its own complete zip. _ROMPATH = [Path(part) for part in os.environ.get("MAME_ROMPATH", "").split(";") if part] if not _ROMPATH: sys.exit("set MAME_ROMPATH (romset folders separated by ';', a non-merged set first)") TREES = {f"{index}-{path.name}": path for index, path in enumerate(_ROMPATH)} READ_TREE = next(iter(TREES)) ADDRESS_MASK = 0x3FFFF def read_roms(zip_path: Path, wanted: list[dict]) -> dict[str, bytes]: """The wanted ROMs' bytes by SHA-1, matched in the zip by CRC-32.""" found: dict[str, bytes] = {} try: archive = zipfile.ZipFile(zip_path) except (OSError, zipfile.BadZipFile): return found with archive: by_crc = {f"{info.CRC:08x}": info for info in archive.infolist()} for rom in wanted: info = by_crc.get(rom["crc"] or "") if info is None: continue data = archive.read(info) if hashlib.sha1(data).hexdigest() == rom["sha1"]: found[rom["sha1"]] = data return found def table_facts(region: bytes) -> dict: """What the phrase table at the start of a region says.""" facts = Counter() lengths = [] for phrase in range(128): entry = region[phrase * 8 : phrase * 8 + 8] if len(entry) < 8: break blank = entry in (bytes(8), b"\xff" * 8) if phrase == 0: facts["entry0_blank" if blank else "entry0_used"] += 1 if not blank: facts["entry0_all_same_byte"] += len(set(entry)) == 1 continue if blank: facts["blank"] += 1 continue raw_start = int.from_bytes(entry[0:3], "big") raw_stop = int.from_bytes(entry[3:6], "big") start, stop = raw_start & ADDRESS_MASK, raw_stop & ADDRESS_MASK facts["used"] += 1 if raw_start != start or raw_stop != stop: facts["bits_above_a17"] += 1 if entry[6:8] != b"\x00\x00": facts["spare_bytes_nonzero"] += 1 if start < stop: facts["start_lt_stop"] += 1 lengths.append(stop - start + 1) if start < 0x400: facts["starts_inside_table"] += 1 if stop >= len(region): facts["stop_beyond_region"] += 1 elif start == stop: facts["start_eq_stop"] += 1 else: facts["start_gt_stop"] += 1 result = dict(facts) result["adpcm_bytes"] = sum(lengths) result["longest"] = max(lengths, default=0) return result def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--family", help="print the regions of one driver source file") args = parser.parse_args(argv) data = json.loads(MACHINES.read_text()) machines = data["machines"] present = {name: {p.stem for p in tree.glob("*.zip")} for name, tree in TREES.items()} print(f"MAME {data['build']}: {len(machines)} machines with an MSM6295") for name, stems in present.items(): have = sum(1 for machine in machines if machine in stems) print(f" {name:<16} {len(stems):>6} zips, {have:>5} of them MSM6295 machines") anywhere = sum(1 for m in machines if any(m in stems for stems in present.values())) print(f" in at least one tree: {anywhere}") regions: dict[str, dict] = {} missing_roms = 0 read_machines = 0 for name, machine in sorted(machines.items()): if name not in present[READ_TREE] or not machine["roms"]: continue wanted = [rom for rom in machine["roms"] if rom["sha1"] and rom["status"] != "nodump"] found = read_roms(TREES[READ_TREE] / f"{name}.zip", wanted) read_machines += 1 by_region: dict[str, list[dict]] = {} for rom in wanted: by_region.setdefault(rom["region"], []).append(rom) for tag, roms in by_region.items(): if any(rom["sha1"] not in found for rom in roms): missing_roms += 1 continue size = max(rom["offset"] + rom["size"] for rom in roms) image = bytearray(b"\xff" * size) for rom in sorted(roms, key=lambda rom: rom["offset"]): image[rom["offset"] : rom["offset"] + rom["size"]] = found[rom["sha1"]] key = hashlib.sha1(bytes(image)).hexdigest() entry = regions.setdefault( key, { "size": size, "files": [ {k: rom[k] for k in ("name", "size", "offset", "sha1")} for rom in sorted(roms, key=lambda rom: rom["offset"]) ], "machines": [], "sourcefiles": [], "table": table_facts(bytes(image)), }, ) entry["machines"].append(f"{name}:{tag}") if machine["sourcefile"] not in entry["sourcefiles"]: entry["sourcefiles"].append(machine["sourcefile"]) OUT.write_text(json.dumps(regions, indent=1)) print(f"machines read from {READ_TREE}: {read_machines}") print(f"regions with a file missing or failing its SHA-1: {missing_roms}") print(f"distinct sample regions (by SHA-1 of the assembled image): {len(regions)}") sizes = Counter(region["size"] for region in regions.values()) print("region sizes:", {f"{size:#x}": count for size, count in sorted(sizes.items())}) over = sum(count for size, count in sizes.items() if size > 0x40000) print(f"regions larger than the chip's 256 KB address space (banked by the board): {over}") totals = Counter() for region in regions.values(): for key, value in region["table"].items(): if key != "longest": totals[key] += value for key in sorted(totals): print(f" {key:<22} {totals[key]}") for key in ("start_eq_stop", "start_gt_stop", "stop_beyond_region", "bits_above_a17", "spare_bytes_nonzero", "starts_inside_table", "entry0_used"): with_it = sum(1 for region in regions.values() if region["table"].get(key)) print(f" regions with {key}: {with_it}") print(f" longest phrase: {max(r['table']['longest'] for r in regions.values())} bytes") if args.family: print(f"\nregions of {args.family}:") for key, region in sorted(regions.items(), key=lambda item: item[1]["machines"][0]): if args.family not in region["sourcefiles"]: continue table = region["table"] files = " + ".join(f"{f['name']} {f['sha1']}" for f in region["files"]) users = [m.split(":")[0] for m in region["machines"]] print( f"{users[0]:<10} {len(users):>3} sets {region['size']:#07x} " f"{table.get('start_lt_stop', 0):>3} phrases {table['adpcm_bytes']:>6} bytes {files}" ) return 0 if __name__ == "__main__": raise SystemExit(main())