#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of the Redump Wii set and the Wii's system titles, read in place. Discs: $REDUMP_DIR/"Nintendo - Wii - NKit RVZ [zstd-19-128k]", one zip per disc, each holding one .rvz. For each zip this reads the zip's central directory and decompresses only the first 0x200 bytes of the .rvz: the RVZ file header and the start of its disc structure, which carries a copy of the disc's first 0x80 bytes (game ID, maker, disc number, version, title, the Wii and GameCube magic words). Nothing else is read, nothing is decrypted, nothing is written but the report. The RVZ layout used here was checked on these files, not taken from Dolphin's source or documents (Dolphin is GPL, a closed box for this repository): offset 0x00 magic b"RVZ\\x01"; 0x24 the ISO's size (u64 BE); 0x48 the disc structure: disc type (u32: 1 GameCube, 2 Wii), compression (u32), compression level (s32), chunk size (u32), then the disc header copy at 0x58 (0x80 bytes), then the partition count (u32). Each field was checked against what it should hold: the Wii magic 0x5D1C9EA3 at disc offset 0x18, ISO sizes equal to the Redump DAT's sizes, game IDs agreeing with the titles (OBSERVED, docs/census.md). Redump's DAT (optional, --dat) gives each ISO's size and SHA-1; zips are matched to it by name. The SHA-1s in the report are the DAT's, never computed here: hashing an ISO would mean decompressing 4.7 GB. System titles: $NO_INTRO_DIR/"Nintendo - Wii (Digital) (CDN)", the entries tagged (System) and [BIOS]: Nintendo's firmware (boot2, IOS, MIOS, BC, the Wii Menu) as encrypted NUS contents. Each member is hashed in memory (SHA-1) for identification only; never copied, never decrypted, never committed. REDUMP_DIR=... NO_INTRO_DIR=... python -I scripts/census_redump.py [--dat DAT.zip] """ from __future__ import annotations import argparse import collections import hashlib import os import re import struct import sys import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT_DISCS = ROOT / "tests" / "detectors" / "census-redump-wii.txt" OUT_SYSTEM = ROOT / "tests" / "detectors" / "census-wii-system-titles.txt" DISC_SET = "Nintendo - Wii - NKit RVZ [zstd-19-128k]" CDN_SET = "Nintendo - Wii (Digital) (CDN)" WII_MAGIC = 0x5D1C9EA3 GC_MAGIC = 0xC2339F3D # Region letter (4th character of the game ID), as WiiBrew "Wii disc" lists them. REGIONS = {"E": "USA", "J": "Japan", "P": "PAL", "K": "Korea", "D": "Germany", "F": "France", "I": "Italy", "S": "Spain", "U": "Australia", "R": "Russia", "T": "Taiwan", "X": "PAL (other)", "Y": "PAL (other)", "Z": "PAL (other)", "W": "Taiwan (other)", "H": "Netherlands", "L": "Japanese import (PAL)", "M": "American import (PAL)", "N": "Japanese import (USA)", "Q": "Korea (Japanese)"} def env_dir(name: str) -> Path: value = os.environ.get(name) if not value: sys.exit(f"set {name} (see the family's environment profile)") return Path(value) def read_dat(path: Path) -> dict[str, tuple[int, str, str]]: """Game name -> (ISO size, SHA-1, category) from a Redump DAT (.dat or zipped).""" if path.suffix == ".zip": with zipfile.ZipFile(path) as archive: text = archive.read(archive.namelist()[0]).decode("utf-8") else: text = path.read_text(encoding="utf-8") games = {} for block in re.findall(r"(.*?)", text, re.S): name, body = block rom = re.search(r'size="(\d+)".*?sha1="([0-9a-f]{40})"', body) category = re.search(r"(.*?)", body) if rom: games[unescape(name)] = (int(rom.group(1)), rom.group(2), category.group(1) if category else "") return games def unescape(text: str) -> str: return (text.replace("&", "&").replace("'", "'").replace(""", '"') .replace("<", "<").replace(">", ">")) def rvz_head(path: Path) -> dict: with zipfile.ZipFile(path) as archive: info = archive.infolist()[0] with archive.open(info) as member: head = member.read(0x200) magic = head[:4] iso_size = struct.unpack_from(">Q", head, 0x24)[0] disc_type, compression, level, chunk = struct.unpack_from(">IIiI", head, 0x48) disc = head[0x58:0xD8] partitions = struct.unpack_from(">I", head, 0xD8)[0] return { "member": info.filename, "rvz_size": info.file_size, "magic": magic, "iso_size": iso_size, "disc_type": disc_type, "compression": compression, "level": level, "chunk": chunk, "game_id": disc[:6].decode("ascii", "replace"), "disc_number": disc[6], "version": disc[7], "wii_magic": struct.unpack_from(">I", disc, 0x18)[0] == WII_MAGIC, "gc_magic": struct.unpack_from(">I", disc, 0x1C)[0] == GC_MAGIC, "title": disc[0x20:0x80].split(b"\0")[0].decode("utf-8", "replace"), "partitions": partitions, } def census_discs(redump: Path, dat: dict[str, tuple[int, str, str]]) -> list[str]: folder = redump / DISC_SET zips = sorted(p for p in folder.iterdir() if p.suffix == ".zip") lines, problems = [], [] by_type = collections.Counter() by_region = collections.Counter() by_system = collections.Counter() sizes = collections.Counter() matched = 0 for path in zips: try: head = rvz_head(path) except (OSError, zipfile.BadZipFile, struct.error) as error: problems.append(f"UNREADABLE {path.name}: {error}") continue name = path.stem dat_size, dat_sha1, category = dat.get(name, (0, "-", "-")) if dat_size: matched += 1 if dat_size != head["iso_size"]: problems.append(f"SIZE {name}: rvz says {head['iso_size']}, DAT {dat_size}") if head["magic"] != b"RVZ\x01": problems.append(f"MAGIC {name}: {head['magic']!r}") if head["disc_type"] == 2 and not head["wii_magic"]: problems.append(f"NO WII MAGIC {name}") by_type[{1: "GameCube", 2: "Wii"}.get(head["disc_type"], str(head["disc_type"]))] += 1 by_region[REGIONS.get(head["game_id"][3:4], "other " + head["game_id"][3:4])] += 1 by_system[head["game_id"][:1]] += 1 sizes[head["iso_size"]] += 1 lines.append(f"{head['game_id']}\td{head['disc_number']}\tv{head['version']}\t" f"type{head['disc_type']}\tparts{head['partitions']}\t{head['iso_size']}\t" f"{dat_sha1}\t{category}\t{name}") summary = [ f"# Redump Wii set ({DISC_SET}), {len(zips)} zips; read in place, first 0x200 bytes of each .rvz", f"# DAT entries: {len(dat)}; zips matched to the DAT by name: {matched}", "# disc types: " + ", ".join(f"{k} {v}" for k, v in by_type.most_common()), "# regions (4th ID character): " + ", ".join(f"{k} {v}" for k, v in by_region.most_common()), "# first ID character (system code): " + ", ".join(f"{k} {v}" for k, v in by_system.most_common()), "# ISO sizes: " + ", ".join(f"{k} x{v}" for k, v in sizes.most_common(6)), f"# problems: {len(problems)}", *("# " + p for p in problems), "# game_id\tdisc\tversion\ttype\tpartitions(rvz)\tiso_size\tdat_sha1\tdat_category\tname", ] if dat: missing = sorted(set(dat) - {p.stem for p in zips}) cats = collections.Counter(dat[m][2] for m in missing) summary.insert(2, f"# DAT entries with no zip here: {len(missing)} (" + ", ".join(f"{k} {v}" for k, v in cats.most_common()) + ")") return summary + lines def census_system(no_intro: Path) -> list[str]: folder = no_intro / CDN_SET lines = [f"# Wii system titles in {CDN_SET} ((System) and [BIOS] entries): Nintendo firmware,", "# identified by SHA-1 only; never copied, decrypted or committed. Member = NUS content id,", "# 'tmd.N' = title metadata at version N, 'cetk' = the ticket."] entries = sorted(p for p in folder.iterdir() if p.suffix == ".zip" and ("(System)" in p.name or p.name.startswith("[BIOS]"))) for path in entries: with zipfile.ZipFile(path) as archive: for info in archive.infolist(): digest = hashlib.sha1() with archive.open(info) as member: for block in iter(lambda: member.read(1 << 20), b""): digest.update(block) lines.append(f"{path.stem}\t{info.filename}\t{info.file_size}\t{digest.hexdigest()}") lines.insert(3, f"# entries: {len(entries)}") return lines def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--dat", type=Path, help="Redump's Wii DAT (.dat or .zip), optional") parser.add_argument("--no-system", action="store_true", help="skip the system titles") args = parser.parse_args() dat = read_dat(args.dat) if args.dat else {} OUT_DISCS.parent.mkdir(parents=True, exist_ok=True) OUT_DISCS.write_text("\n".join(census_discs(env_dir("REDUMP_DIR"), dat)) + "\n", encoding="utf-8") print(f"wrote {OUT_DISCS.relative_to(ROOT)}") if not args.no_system: OUT_SYSTEM.write_text("\n".join(census_system(env_dir("NO_INTRO_DIR"))) + "\n", encoding="utf-8") print(f"wrote {OUT_SYSTEM.relative_to(ROOT)}") return 0 if __name__ == "__main__": sys.exit(main())