#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of the No-Intro Nintendo 64 sets: counts, sizes, CIC and save types. Reads the sets in place from $NO_INTRO_DIR (never copies a ROM). For each zip it decompresses only the first 4 KiB of the cartridge image (the header and IPL3), and writes one line per ROM plus a summary to tests/detectors/census-nointro-n64.txt. - CIC: the IPL3 (bytes 0x40-0xFFF) is grouped by CRC-32; each group is named by an anchor title from the n64brew CIC-NUS table (DOC, tier 3), e.g. the group holding "Star Fox 64 (USA)" is 6101. NTSC and PAL parts that share an IPL3 (6102/7101, 6103/7103, 6105/7105, 6106/7106) share a group; the header's region byte splits them. This is a FITTED label, not a CIC read. - Save type: the cartridge header does not say (only the homebrew "ED" header does). The save type here is ares's per-game database (mia/medium/nintendo-64.cpp, ISC, tier 5) keyed by the 3-letter game code, parsed for its simple rows only (the special cases that also look at the revision are reported as such). - BIOS: the [BIOS] zips are listed with each member's size and SHA-1 (hashed in memory; nothing is written). NO_INTRO_DIR=... python -I scripts/census_nointro.py """ from __future__ import annotations import collections import hashlib import os import re import sys import zipfile import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "tests" / "detectors" / "census-nointro-n64.txt" ARES_DB = ROOT / "reference" / "src" / "ares" / "mia" / "medium" / "nintendo-64.cpp" SETS = [ "Nintendo - Nintendo 64 (BigEndian)", "Nintendo - Nintendo 64 (BigEndian) (Aftermarket)", "Nintendo - Nintendo 64 (BigEndian) (Private)", ] DD_SET = "Nintendo - Nintendo 64DD" # Anchor titles from the n64brew CIC-NUS page's table (revision pinned in # scripts/pinned_wiki.json): the group that holds the anchor takes the name. ANCHORS = { "Star Fox 64 (USA)": "6101", "Lylat Wars (Australia) (En,Fr,De)": "7102", # No-Intro's only Lylat Wars entry "Banjo-Kazooie (USA)": "6103/7103", "Legend of Zelda, The - Ocarina of Time (USA)": "6105/7105", "F-Zero X (USA)": "6106/7106", "Super Mario 64 (USA)": "6102/7101", } PAL = set("DFHIPUWXYZL") # header region bytes that ares and n64brew call PAL def ares_database() -> dict[str, str]: if not ARES_DB.exists(): return {} saves: dict[str, str] = {} for line in ARES_DB.read_text(encoding="utf-8").splitlines(): ids = re.findall(r'id == "([A-Z0-9]{3})"', line) if not ids or "revision" in line: continue kinds = [] for name, value, unit in re.findall(r"\b(eeprom|sram|flash)\s*=\s*(\d+)(_KiB)?", line): size = int(value) * (1024 if unit else 1) if size: kinds.append(f"{name.upper() if name != 'flash' else 'FlashRAM'} {size // 1024 or size}" + ("K" if size >= 1024 else "B")) kinds = [k for k in kinds if k] if kinds: for game in ids: saves.setdefault(game, kinds[-1]) return saves def head_of(path: Path) -> tuple[str, int, bytes]: with zipfile.ZipFile(path) as archive: member = max(archive.infolist(), key=lambda info: info.file_size) with archive.open(member) as stream: return member.filename, member.file_size, stream.read(0x1000) def main() -> int: base = os.environ.get("NO_INTRO_DIR") if not base: print("set NO_INTRO_DIR to the No-Intro root") return 2 saves = ares_database() rows = [] bios = [] for set_name in SETS: folder = Path(base) / set_name for path in sorted(folder.glob("*.zip")): if path.name.startswith("[BIOS]"): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): bios.append((set_name, info.filename, info.file_size, hashlib.sha1(archive.read(info)).hexdigest())) continue member, size, head = head_of(path) ipl3 = zlib.crc32(head[0x40:0x1000]) & 0xFFFFFFFF # Printable ASCII only: homebrew leaves NULs here, which would make the report binary. code = "".join(chr(b) if 0x20 <= b < 0x7F else "." for b in head[0x3B:0x3F]) homebrew = head[0x3C:0x3E] == b"ED" rows.append(dict(set=set_name, name=path.stem, ext=Path(member).suffix, size=size, first=head[:4].hex(), entry=int.from_bytes(head[8:12], "big"), ipl3=ipl3, code=code, version=head[0x3F], homebrew=homebrew, save_byte=head[0x3F] if homebrew else None)) groups = collections.Counter(row["ipl3"] for row in rows) names = {} for row in rows: # Exact names: the LodgeNet and Virtual Console releases carry other IPL3s. if row["name"] in ANCHORS: names[row["ipl3"]] = ANCHORS[row["name"]] lines = ["# No-Intro Nintendo 64 census (scripts/census_nointro.py)", ""] lines.append("## Counts") for set_name in SETS: subset = [r for r in rows if r["set"] == set_name] sizes = collections.Counter(r["size"] // (1 << 20) for r in subset) lines.append(f"- {set_name}: {len(subset)} images; " f"extensions {dict(collections.Counter(r['ext'] for r in subset))}; " f"MiB sizes {dict(sorted(sizes.items()))}") lines.append(f" first word {dict(collections.Counter(r['first'] for r in subset).most_common(4))}") lines += ["", "## IPL3 groups (CRC-32 of 0x40-0xFFF), named by anchor titles"] for crc, count in groups.most_common(): label = names.get(crc, "unanchored") example = next(r["name"] for r in rows if r["ipl3"] == crc) pal = sum(1 for r in rows if r["ipl3"] == crc and r["code"][3:4] in PAL) lines.append(f"- {crc:08x} {label:>10}: {count:4d} images ({pal} PAL-region bytes); e.g. {example}") lines += ["", "## Save types from ares's game database (tier 5), main set, by game code"] main_rows = [r for r in rows if r["set"] == SETS[0]] # ares keys by bytes 0x3B-0x3D: the category letter and the two-letter id. save_count = collections.Counter(saves.get(r["code"][:3], "none listed") for r in main_rows) for kind, count in save_count.most_common(): lines.append(f"- {kind}: {count}") hb = [r for r in rows if r["homebrew"]] lines += ["", f"## Advanced homebrew header ('ED' at 0x3C): {len(hb)} images"] hb_saves = collections.Counter((r["save_byte"] >> 4) for r in hb) lines.append(f"- save field (bits 4-7 of 0x3F): {dict(sorted(hb_saves.items()))} " "(0 none, 1 EEPROM 4K, 2 EEPROM 16K, 3 SRAM 256K, 4 SRAM 768K, 5 FlashRAM, 6 SRAM 1M)") lines += ["", "## BIOS zips in the cartridge sets (SHA-1, hashed in memory)"] for set_name, name, size, sha in bios: lines.append(f"- {name}: {size} bytes, SHA-1 {sha}") dd = Path(base) / DD_SET if dd.exists(): lines += ["", f"## {DD_SET}"] for path in sorted(dd.glob("*.zip")): with zipfile.ZipFile(path) as archive: for info in archive.infolist(): sha = hashlib.sha1(archive.read(info)).hexdigest() if path.name.startswith("[BIOS]") else "" lines.append(f"- {info.filename}: {info.file_size} bytes {('SHA-1 ' + sha) if sha else ''}".rstrip()) lines += ["", "## Per image: set | name | size | IPL3 CRC | group | game code | version | save (ares)"] for r in rows: lines.append(" | ".join([r["set"].split("(BigEndian)")[1].strip() or "main", r["name"], str(r["size"]), f"{r['ipl3']:08x}", names.get(r["ipl3"], "unanchored"), r["code"], str(r["version"]), saves.get(r["code"][:3], "-")])) OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text("\n".join(lines) + "\n", encoding="utf-8") print("\n".join(lines[: lines.index("## Per image: set | name | size | IPL3 CRC | group | game code | version | save (ares)")])) return 0 if __name__ == "__main__": sys.exit(main())