#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of the local Atari Lynx dumps, read in place: formats, sizes, block sizes, rotation, EEPROM, AUDIN, encrypted loaders, and how many payloads the public tables identify. Nothing is copied or written next to a ROM. Archives are read in memory (``zipfile``; ``7z e -so`` for .7z). Every image is reduced to its **payload**: the 64-byte ``LYNX`` header stripped if there is one. Payloads are hashed (SHA-1, the hash both public tables carry) so an ``.lnx`` and its ``.lyx`` meet at one key. Three data sources are joined on the payload SHA-1, none of them code: - the No-Intro DAT "Atari - Atari Lynx (LYX)" (names; its header skipper ``No-Intro_LNX.xml`` means its hashes are payload hashes); - MAME's software list ``hash/lynx.xml`` (CC0-1.0 per its own header): ``granularity`` (block size), ``rotation``, ``audin_offset``; - the headers of our own ``.lnx`` files whose payload matches. python -I scripts/count_carts.py # the table in docs/cartridge.md python -I scripts/count_carts.py --list misses # per-file detail for one section The size rule tested here: block size = payload size / 256 when the payload is exactly 64, 128, 256 or 512 KiB (256 blocks of 256/512/1024/2048 bytes). """ from __future__ import annotations import argparse import collections import hashlib import subprocess import sys import xml.etree.ElementTree as ET import zipfile from dataclasses import dataclass, field from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from lynx_python import romsets # Romsets by environment variable only (NO_INTRO_DIR, LYNX_EXTRA_SETS, LYNX_NOINTRO_DAT). SETS = romsets.all_sets() SOFTLIST = Path(__file__).resolve().parents[1] / "reference/src/mame/hash/lynx.xml" DAT = romsets.nointro_dat() RULE_SIZES = {65536: 256, 131072: 512, 262144: 1024, 524288: 2048} ROTATION = {0: "none", 1: "left", 2: "right"} EEPROM = {0: "none", 1: "93C46", 2: "93C56", 3: "93C66", 4: "93C76", 5: "93C86"} @dataclass class Image: source: str archive: str member: str kind: str # lnx, lyx, bll size: int # payload size sha1: str # payload SHA-1 first: int # first payload byte loader: str # SHA-1 (12 hex) of the encrypted frame, "" if the first byte is not a frame count header: dict = field(default_factory=dict) def members(path: Path): """Yield (member name, bytes) for a zip, a 7z or a loose file.""" suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as z: for info in z.infolist(): if not info.is_dir(): yield info.filename, z.read(info) elif suffix == ".7z": names = subprocess.run( ["7z", "l", "-ba", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout listed = [line[7:] for line in names.splitlines() if line.startswith("Path = ")] for name in listed: data = subprocess.run( ["7z", "e", "-so", str(path), name], capture_output=True, check=True ).stdout yield name, data elif suffix in (".lnx", ".lyx", ".o", ".bll", ".com"): yield path.name, path.read_bytes() def classify(source: str, archive: str, name: str, data: bytes) -> Image: if data[:4] == b"LYNX" and len(data) >= 64: payload = data[64:] b0 = int.from_bytes(data[4:6], "little") b1 = int.from_bytes(data[6:8], "little") header = { "bank0": b0, "bank1": b1, "version": int.from_bytes(data[8:10], "little"), "name": data[10:42].split(b"\0")[0].decode("latin-1"), "maker": data[42:58].split(b"\0")[0].decode("latin-1"), "rotation": data[58], "audin": data[59], "eeprom": data[60], "spare": data[61:64].hex(), } kind = "lnx" elif data[6:10] == b"BS93" and data[:2] == b"\x80\x08": payload, header, kind = data, { "load": int.from_bytes(data[2:4], "big"), "length": int.from_bytes(data[4:6], "big"), }, "bll" # fmt: skip else: payload, header, kind = data, {}, "lyx" first = payload[0] if payload else -1 frame = payload[: 1 + 51 * (256 - first)] if first >= 0xF0 else b"" return Image( source, archive, name, kind, len(payload), hashlib.sha1(payload).hexdigest(), first, hashlib.sha1(frame).hexdigest()[:12] if frame else "", header, ) # fmt: skip def load_softlist() -> dict[str, dict]: table = {} for software in ET.parse(SOFTLIST).getroot().iter("software"): features = {f.get("name"): f.get("value") for f in software.iter("feature")} for rom in software.iter("rom"): if rom.get("sha1"): table[rom.get("sha1")] = { "name": software.findtext("description"), "size": int(rom.get("size"), 0), **features, } return table def load_dat() -> dict[str, str]: return { rom.get("sha1").lower(): game.get("name") for game in ET.parse(DAT).getroot().iter("game") for rom in game.iter("rom") } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--list", choices=["misses", "rule", "headers", "loaders", "uncertain"]) args = parser.parse_args() images: list[Image] = [] for source, folder in SETS.items(): for path in sorted(folder.iterdir()): if path.is_file(): for name, data in members(path): images.append(classify(source, path.name, name, data)) softlist = load_softlist() dat = load_dat() out = print out("## Files by set and kind (kind is read from the bytes, not the extension)") by = collections.Counter((i.source, i.kind) for i in images) for source in SETS: kinds = ", ".join(f"{k} {n}" for (s, k), n in sorted(by.items()) if s == source) out(f"- {source}: {kinds}") carts = [i for i in images if i.kind != "bll"] unique: dict[str, list[Image]] = collections.defaultdict(list) for i in carts: unique[i.sha1].append(i) out(f"\n{len(carts)} cart images, {len(unique)} distinct payloads; " f"{sum(1 for i in images if i.kind == 'bll')} BLL programs") # fmt: skip out("\n## Distinct payloads by size") sizes = collections.Counter(v[0].size for v in unique.values()) for size, n in sorted(sizes.items()): rule = RULE_SIZES.get(size) out(f"- {size:>8} bytes ({size / 1024:g} KiB): {n}" + (f" -> rule says {rule}-byte blocks" if rule else " -> outside the size rule")) # fmt: skip out("\n## LNX headers (every .lnx image, before de-duplication)") lnx = [i for i in carts if i.kind == "lnx"] out(f"{len(lnx)} images") for label, key, names in (("bank 0 block size", "bank0", None), ("bank 1 block size", "bank1", None), ("version", "version", None), ("rotation", "rotation", ROTATION), ("AUDIN byte", "audin", None), ("EEPROM byte", "eeprom", None)): # fmt: skip count = collections.Counter(i.header[key] for i in lnx) text = ", ".join(f"{(names or {}).get(v, v)}: {n}" for v, n in sorted(count.items())) out(f"- {label}: {text}") out("- EEPROM byte decoded (low 3 bits = type, $40 = 8-bit organisation, $80 = SD-card save): " + ", ".join(f"${v:02X}={EEPROM.get(v & 7, '?')}" for v in sorted({i.header['eeprom'] for i in lnx}))) # fmt: skip out("\n## The size rule against the headers") agree, breaks = 0, [] for i in lnx: rule = RULE_SIZES.get(i.size) if rule == i.header["bank0"] and i.header["bank1"] == 0: agree += 1 else: breaks.append(i) out(f"{agree} of {len(lnx)} headers say exactly what the size rule says (bank 1 empty); " f"{len(breaks)} do not") # fmt: skip if args.list == "rule": for i in breaks: out(f" {i.size:>8} b0={i.header['bank0']} b1={i.header['bank1']} audin={i.header['audin']} " f"{i.source}: {i.member}") # fmt: skip reasons = collections.Counter() for i in breaks: h = i.header if h["bank1"]: reasons["bank 1 in use"] += 1 elif i.size == h["bank0"] * 256: reasons["256 blocks, but not a rule size"] += 1 elif i.size < h["bank0"] * 256: reasons["payload is fewer than 256 blocks of the header's size (128 x 2048 here)"] += 1 elif h["audin"] and i.size % (h["bank0"] * 256) == 0: reasons["AUDIN: several 256-block banks"] += 1 else: reasons["payload longer than 256 blocks, no AUDIN flag"] += 1 for reason, n in reasons.most_common(): out(f"- {reason}: {n}") out("\n## Payload identification (distinct payloads)") lyx_local = {i.sha1 for i in carts if i.kind == "lyx"} lnx_payloads = {i.sha1: i for i in lnx} hit_dat = sum(1 for s in lnx_payloads if s in dat) hit_local = sum(1 for s in lnx_payloads if s in lyx_local) hit_soft = sum(1 for s in lnx_payloads if s in softlist) out(f"- .lnx payloads: {len(lnx_payloads)} distinct; match a local headerless dump: {hit_local}; " f"match the No-Intro DAT: {hit_dat}; match MAME's softlist: {hit_soft}") # fmt: skip misses = [i for s, i in lnx_payloads.items() if s not in dat and s not in lyx_local] why = collections.Counter() by_size_dat = collections.Counter() for i in misses: if i.size not in RULE_SIZES: why["payload size is not 64/128/256/512 KiB (trimmed, padded or multi-bank)"] += 1 else: why["rule-sized payload absent from No-Intro (different dump, hack or homebrew)"] += 1 out(f"- .lnx payloads matching neither: {len(misses)}") for reason, n in why.most_common(): out(f" - {reason}: {n}") if args.list == "misses": for i in sorted(misses, key=lambda i: i.member): out(f" {i.size:>8} {i.sha1} {i.source}: {i.member} [{i.header['name']}]") del by_size_dat lyx_unique = {s: v[0] for s, v in unique.items() if any(i.kind == "lyx" for i in v)} out(f"- headerless payloads: {len(lyx_unique)} distinct; in the No-Intro DAT: " f"{sum(1 for s in lyx_unique if s in dat)}; in MAME's softlist: " f"{sum(1 for s in lyx_unique if s in softlist)}; with a matching local .lnx header: " f"{sum(1 for s in lyx_unique if s in lnx_payloads)}") # fmt: skip out("\n## Do the sources agree where they overlap?") conflicts = [] both = 0 for s, i in lnx_payloads.items(): if s in softlist: both += 1 soft = softlist[s] soft_rot = {None: 0, "LEFT": 1, "RIGHT": 2}[soft.get("rotation")] if int(soft["granularity"]) != i.header["bank0"]: conflicts.append( f"block size: softlist {soft['granularity']} vs header {i.header['bank0']}: {i.member}" ) if soft_rot != i.header["rotation"]: conflicts.append( f"rotation: softlist {soft.get('rotation')} vs header {ROTATION.get(i.header['rotation'])}: {i.member}" ) out( f"- payloads with both a softlist entry and a local header: {both}; disagreements: {len(conflicts)}" ) for c in conflicts: out(f" - {c}") same_payload = collections.defaultdict(set) for i in lnx: h = i.header same_payload[i.sha1].add((h["bank0"], h["bank1"], h["rotation"], h["audin"], h["eeprom"])) split = {s: v for s, v in same_payload.items() if len(v) > 1} out(f"- payloads carried by two local .lnx files whose headers differ: {len(split)}") for s, v in split.items(): out(f" - {lnx_payloads[s].member}: {sorted(v)}") out("\n## Headerless dumps: which fields are certain, and from where") full = rule_only = nothing = 0 uncertain = [] rot_known = 0 for s, i in lyx_unique.items(): block = RULE_SIZES.get(i.size) tabled = s in softlist or s in lnx_payloads if tabled: full += 1 elif block: rule_only += 1 uncertain.append(i) else: nothing += 1 uncertain.append(i) rot_known += tabled out(f"- every field from a table (softlist or a matching .lnx header): {full}") out(f"- block size from the size rule only; rotation, EEPROM, AUDIN unknown: {rule_only}") out(f"- not even the size rule applies: {nothing}") if args.list == "uncertain": for i in sorted(uncertain, key=lambda i: i.member): out(f" {i.size:>8} {i.source}: {i.member}") out("\n## The first block: encrypted loader frames (distinct payloads)") firsts = collections.Counter(v[0].first for v in unique.values()) out("- first byte (an encrypted frame starts with 256 - number of 51-byte blocks): " + ", ".join(f"${b:02X}: {n}" for b, n in sorted(firsts.items(), key=lambda kv: -kv[1]))) # fmt: skip loaders: dict[str, list[Image]] = collections.defaultdict(list) for v in unique.values(): loaders[v[0].loader].append(v[0]) out(f"- distinct encrypted frames: {sum(1 for k in loaders if k)}; payloads per frame, most " "common first (frame SHA-1 prefix, first byte, payloads, of which in the No-Intro " "licensed LYX set):") # fmt: skip licensed = {i.sha1 for i in carts if i.source == "No-Intro LYX"} for key, group in sorted(loaders.items(), key=lambda kv: -len(kv[1]))[:12]: n_lic = sum(1 for i in group if i.sha1 in licensed) out(f" - {key or '(no frame)'} ${group[0].first:02X}: {len(group)} ({n_lic} licensed)") rest = sorted(loaders.items(), key=lambda kv: -len(kv[1]))[12:] out(f" - {len(rest)} further frames cover {sum(len(g) for _, g in rest)} payloads") if args.list == "loaders": for key, group in sorted(loaders.items(), key=lambda kv: -len(kv[1])): out(f" {key}: " + "; ".join(i.member for i in group[:3])) return 0 if __name__ == "__main__": sys.exit(main())