#!/usr/bin/env python3 """Rung 5: Nuked-PSG run as a closed box beside the core (docs/validation.md). Nuked-PSG (Nuke.YKT, GPL-2.0-or-later) models the PSG inside the Mega Drive's VDP, so it is compared with ``YM7101_PSG`` and with nothing else. It is a DETECTOR: a difference says where to look and proves nothing about a console. Its source was not read (docs/restart.md rule 8). ``nuked_harness.c`` drives it through the calls its header declares; everything said about it below was learned from its output. python validation/closed_box.py build if needed, run every stream python validation/closed_box.py --list name the streams python validation/closed_box.py NAME ... run some python validation/closed_box.py --sweeps the timing and test-bit tables as well Three normalisations are applied, all measured from the model's output: 1. One ``YMPSG_Clock`` call is one input clock (a tone value of n gives a cycle of 32n calls). 2. Tick phase. The model's tone edges fall on the 7th, 23rd, ... clock after its ``YMPSG_Init``; the core's fall on every 16th input clock from power-on (a choice, spec U10). The model is run ``PRE_ROLL`` clocks before each stream so the two coincide. The model also ignores writes in its first 5 clocks. 3. Levels. The model's sixteen attenuation levels are not the ideal 2 dB curve (see ``measure_levels``). They are measured and handed to the core as its volume table for the comparison, so that what is compared is the waveform. The two curves are reported side by side and the core's is left as it was. Exit status is 0 whether or not streams differ: a difference is a finding, and docs/validation.md records each one. """ from __future__ import annotations import argparse import dataclasses import math import random import struct import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "validation")) from as_observed import AsObserved from sn76489_python import CLOCKS_PER_SAMPLE, SN76489, YM7101_PSG MODEL = ROOT / "reference" / "nuked-psg" BUILD = ROOT / "validation" / "build" HARNESS = BUILD / "nuked_harness" #: Clocks the model is run before a stream starts (normalisation 2). PRE_ROLL = 7 #: Largest difference between two levels still called equal. The model returns #: 32-bit floats; its levels are spaced far wider than this. TOLERANCE = 1e-4 # A stream is a list of events (input clock, kind, value) in time order, kind # being "w" (the write port) or "t" (the test bits), and a length in clocks. Event = tuple[int, str, int] Stream = tuple[list[Event], int] def build() -> None: """Compile the harness against the fetched model. Compiler messages are kept out of sight (-w, stderr to a file): they would quote the model's source.""" sources = [ROOT / "validation" / "nuked_harness.c", MODEL / "ympsg.c"] for source in sources: if not source.exists(): sys.exit(f"{source} is missing: run scripts/fetch_references.py") if HARNESS.exists() and all( HARNESS.stat().st_mtime > source.stat().st_mtime for source in sources ): return BUILD.mkdir(parents=True, exist_ok=True) command = ["cc", "-O2", "-w", "-I", str(MODEL), "-o", str(HARNESS), *map(str, sources)] with (BUILD / "cc.log").open("wb") as log: if subprocess.run(command, stderr=log, check=False).returncode: sys.exit("the harness did not compile; validation/build/cc.log is not to be read") def model_clocks(commands: list[str]) -> list[float]: """Feed harness commands; return the model's output after every clock.""" result = subprocess.run( [str(HARNESS)], input="\n".join(commands).encode(), capture_output=True, check=True ) return list(struct.unpack(f"<{len(result.stdout) // 4}f", result.stdout)) def model_ticks(stream: Stream, pre_roll: int = PRE_ROLL) -> list[float]: """The model's level at each of the core's tick boundaries.""" events, length = stream commands, now = [f"c {pre_roll}"], 0 for clock, kind, value in events: commands.append(f"c {clock - now}") commands.append(f"{kind} {value}") now = clock commands.append(f"c {length - now}") output = model_clocks(commands) return output[pre_roll + CLOCKS_PER_SAMPLE - 1 :: CLOCKS_PER_SAMPLE] def core_ticks(stream: Stream, variant, chip=SN76489) -> tuple[list[float], list[dict]]: """The core's left level at each tick, and its registers at each tick. ``chip`` may be the stand-in of ``as_observed.py`` instead of the core. """ events, length = stream psg, now = chip(variant), 0 registers: list[dict] = [] def advance(until: int) -> None: nonlocal now before = len(psg.samples) psg.run(until - now) now = until snapshot = {"tone": list(psg.tone), "noise": psg.noise, "volume": list(psg.volume)} registers.extend([snapshot] * (len(psg.samples) - before)) for clock, kind, value in events: advance(clock) if kind == "w": psg.write(value) else: psg.write_test(value) advance(length) return [pair[0] for pair in psg.take_samples()], registers def measure_levels() -> tuple[float, ...]: """The model's output for one channel held at each attenuation in turn.""" levels = [] for attenuation in range(16): output = model_clocks(["c 64", "w 0x81", "c 64", "w 0x00", "c 64"] + [f"w {0x90 | attenuation}", "c 512"]) # fmt: skip levels.append(max(output)) return tuple(levels) # -- the streams ------------------------------------------------------------------- def spaced(writes: list[int | tuple[str, int]], gap: int = 16 * 40, start: int = 8) -> Stream: """Writes ``gap`` clocks apart, each in the middle of a tick (offset 8 of 16), away from the tick boundary, where the two could differ for timing alone.""" events, clock = [], start for write in writes: kind, value = write if isinstance(write, tuple) else ("w", write) events.append((clock, kind, value)) clock += gap return events, clock + gap def tone(channel: int, value: int) -> list[int]: return [0x80 | (channel << 5) | (value & 0x0F), (value >> 4) & 0x3F] def streams() -> dict[str, Stream]: table: dict[str, Stream] = {} table["power-on, nothing written"] = ([], 16 * 4000) table["first write is a data byte"] = spaced([0x3F, 0x90, 0xB0, 0xD0], gap=16 * 2100) table["every register code"] = spaced( [*tone(0, 9), *tone(1, 14), *tone(2, 23), 0x90, 0xB0, 0xD0, 0xF0] + [0x80 | (code << 4) | 0x05 for code in range(8)] ) for channel in range(3): table[f"every attenuation, tone {channel}"] = spaced( tone(channel, 5) + [0x90 | (channel << 5) | step for step in range(16)] ) table["every attenuation, noise"] = spaced( [0xE4] + [0xF0 | step for step in range(16)], gap=16 * 700 ) for value in (0, 1, 2, 3, 4, 0x3FF): table[f"tone value ${value:03X}"] = spaced( [*tone(0, 6), 0x90, *tone(0, value)], gap=16 * 1500 ) table["three tones together"] = spaced( [*tone(0, 3), *tone(1, 7), *tone(2, 0x155), 0x92, 0xB5, 0xD8], gap=16 * 300 ) for control in range(8): table[f"noise control {control:03b}"] = spaced( [0xF0, *tone(2, 6), 0xE0 | control], gap=16 * 6000 ) for value in (0, 1, 2, 3, 37, 0x3FF): for control in (3, 7): name = ( f"noise {'white' if control & 4 else 'periodic'} at rate 3, tone 2 = ${value:03X}" ) gap = 16 * (2 * max(value, 1) * 40) table[name] = spaced([0xF0, 0xD3, *tone(2, value), 0xE0 | control], gap=gap) table["tone 2 rewritten under noise at rate 3"] = spaced( [0xF0, 0xD3, *tone(2, 7), 0xE7, *tone(2, 3), *tone(2, 11), *tone(2, 2), *tone(2, 9)], gap=16 * 500, ) table["same noise value rewritten"] = spaced([0xF0, 0xE4, 0xE4, 0xE4, 0xE5, 0xE5], gap=16 * 900) table["data byte to attenuation"] = spaced([*tone(0, 5), 0x9F, 0x00, 0x07, 0x0F, 0x02]) table["data byte to noise"] = spaced([0xF0, 0xE5, 0x04, 0x00, 0x06], gap=16 * 3000) table["latch byte alone moves a tone"] = spaced( [*tone(0, 0x123), 0x90, 0x87, 0x8F, 0x80], gap=16 * 2400 ) for source in range(4): table[f"test override, source {source}"] = spaced( [*tone(0, 3), *tone(1, 5), *tone(2, 7), 0xE4, 0x92, 0xB5, 0xD8, 0xFB] + [("t", 0x0200 | (source << 10)), ("t", source << 10)], gap=16 * 400, ) for seed in range(4): table[f"random writes {seed}"] = random_stream(seed) for seed in range(4): table[f"random writes {seed}, never leaving noise rate 3 for a fixed rate"] = random_stream( seed, leave_rate_3=False ) return table def random_stream(seed: int, writes: int = 400, leave_rate_3: bool = True) -> Stream: """Latch and data bytes at mid-tick moments, weighted toward audible states. With ``leave_rate_3`` false, a write that would take the noise from rate 3 to a fixed rate is left out: that one transition is where the stand-in of ``as_observed.py`` is known not to follow the model. """ rng = random.Random(seed) shadow = SN76489(YM7101_PSG) events: list[Event] = [] clock = 8 for channel in range(4): events.append((clock, "w", 0x90 | (channel << 5) | rng.randrange(8))) clock += 16 * 3 for _ in range(writes): roll = rng.random() if roll < 0.5: value = 0x80 | (rng.randrange(8) << 4) | rng.randrange(16) elif roll < 0.8: value = rng.randrange(0x40) if rng.random() < 0.5 else rng.randrange(4) else: value = 0x90 | (rng.randrange(4) << 5) | rng.randrange(16) before = (shadow.noise, shadow.latched) shadow.write(value) if not leave_rate_3 and before[0] & 3 == 3 and shadow.noise & 3 != 3: shadow.noise, shadow.latched = before continue events.append((clock, "w", value)) clock += 16 * rng.randrange(1, 400) return events, clock + 16 * 2000 # -- comparison and report --------------------------------------------------------- def differing_ticks(ours: list[float], theirs: list[float]) -> list[int]: return [k for k in range(min(len(ours), len(theirs))) if abs(ours[k] - theirs[k]) > TOLERANCE] def compare(stream: Stream, variant) -> dict: ours, registers = core_ticks(stream, variant) theirs = model_ticks(stream) differing = differing_ticks(ours, theirs) result = {"ticks": min(len(ours), len(theirs)), "differing": len(differing)} if differing: first = differing[0] result["first"] = first result["ours"] = round(ours[first], 4) result["theirs"] = round(theirs[first], 4) result["registers"] = registers[first] if any(kind == "t" for _, kind, _ in stream[0]): result["stand-in"] = None # the stand-in says nothing about the test bits else: observed, _ = core_ticks(stream, variant, AsObserved) result["stand-in"] = len(differing_ticks(observed, theirs)) return result def write_timing_sweep(variant) -> None: """Where in the 16-clock tick a write must land to count for the next tick. For 64 consecutive input clocks a write is placed at that clock. The model's output is then compared with the stand-in's for the same stream and for the write moved a tick earlier or later; which it equals says in which tick the model took the write. (The core takes any write at the next tick boundary: spec U9, a choice. The stand-in already holds tone and noise writes back by the one tick of its behaviour 1.) """ print("\nSub-tick write timing in the model (spec U9), from 64 consecutive clocks") print(" offset of the write within the core's tick -> the tick the model acts in,") print(" relative to the stand-in given the write at the same clock") base = 16 * 301 for label, setup, probe in ( ("attenuation", [*tone(0, 1), 0x9F], 0x90), ("tone value", [*tone(0, 40), 0x90], 0x83), ("noise control", [0xF0, *tone(2, 2), 0xE3], 0xE3), ): verdicts: dict[int, set[str]] = {} for offset in range(64): prefix, _ = spaced(setup, gap=16 * 20) length = base + offset + 16 * 300 theirs = model_ticks(([*prefix, (base + offset, "w", probe)], length)) verdict = "none of these" for shift, name in ((0, "same"), (16, "one later"), (-16, "one earlier")): moved = ([*prefix, (base + offset + shift, "w", probe)], length) if not differing_ticks(core_ticks(moved, variant, AsObserved)[0], theirs): verdict = name break verdicts.setdefault(offset % 16, set()).add(verdict) print(f" {label}:") for offset in range(16): print(f" {offset:2d}: {' / '.join(sorted(verdicts[offset]))}") def tone_rewrite_sweep(variant) -> None: """Spec U11 as the model sees it: a tone value changed k ticks into a half-cycle.""" print("\nA tone value rewritten mid half-cycle (spec U11): length in ticks of the") print(" half-cycle the write fell in, core / model, by ticks already elapsed") for old, new in ((47, 33), (33, 47)): cells = [] for elapsed in range(1, old, 5): start = old * 10 events = [(8, "w", 0x80 | (old & 15)), (40, "w", old >> 4), (72, "w", 0x90)] events.append((16 * (start + elapsed) + 8, "w", 0x80 | (new & 15))) stream = (events, 16 * (start + old * 6)) lengths = [] for levels in (core_ticks(stream, variant)[0], model_ticks(stream)): edges = [k for k in range(1, len(levels)) if levels[k] != levels[k - 1]] after = min(edge for edge in edges if edge >= start + elapsed) before = max(edge for edge in edges if edge < start + elapsed) lengths.append(after - before) cells.append(f"{start + elapsed - before}: {lengths[0]}/{lengths[1]}") print(f" {old} -> {new}: " + " ".join(cells)) def test_override_levels(levels: tuple[float, ...]) -> None: """Spec U15: what the model's output is with its test input's bit 9 set.""" print("\nTest override (spec section 11, U15): held output with bit 9 set") print(" attenuations 2, 5, 8, 11 on the four channels; source chosen by bits 11-10") print(" source model model minus its level for attenuation 15 core (4 x level)") floor = None for source in range(4): events, length = spaced( [0x92, 0xB5, 0xD8, 0xFB, 0xE4, ("t", 0x0200 | (source << 10))], gap=16 * 60 ) held = set(model_ticks((events, length))[-50:]) if floor is None: silent, _ = spaced([0x9F, ("t", 0x0200)], gap=16 * 60) floor = model_ticks((silent, 16 * 200))[-1] value = held.pop() if len(held) == 1 else float("nan") attenuation = (2, 5, 8, 11)[source] print( f" {source} {value:7.3f} {value - floor:6.3f} (its level for " f"{attenuation} is {levels[attenuation]:.3f}) {4 * levels[attenuation]:.3f}" ) print(f" the model's held output with the source channel at attenuation 15: {floor:.3f}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("names", nargs="*", help="streams to run (default: all)") parser.add_argument("--list", action="store_true", help="name the streams and stop") parser.add_argument("--sweeps", action="store_true", help="also print the timing tables") args = parser.parse_args() table = streams() if args.list: print("\n".join(table)) return 0 build() levels = measure_levels() ideal = YM7101_PSG.volume_table print("Attenuation levels (one channel, full scale 1.0)") print(" step model core's ideal 2 dB model in dB") for step in range(16): decibels = "off" if levels[step] == 0 else f"{-20 * math.log10(levels[step]):6.2f}" print(f" {step:4d} {levels[step]:6.3f} {ideal[step]:6.3f} {decibels}") variant = dataclasses.replace(YM7101_PSG, volume_table=levels) names = args.names or list(table) agree = explained = 0 print("\nStreams: the level at every tick, the model's levels given to the core.") print("'stand-in' is validation/as_observed.py: the core with three timing changes.") for name in names: result = compare(table[name], variant) stand_in = result["stand-in"] note = ( "stand-in not applicable" if stand_in is None else "stand-in same" if stand_in == 0 else f"stand-in differs at {stand_in} ticks" ) if result["differing"] == 0: agree += 1 print(f" same {name}: {result['ticks']} ticks; {note}") else: explained += stand_in == 0 registers = result["registers"] print( f" DIFFERS {name}: {result['differing']} of {result['ticks']} ticks, first at " f"tick {result['first']} (core {result['ours']}, model {result['theirs']}; tone " f"{registers['tone']} noise {registers['noise']} volume {registers['volume']}); " f"{note}" ) print(f"\n{agree} of {len(names)} streams: the core equals the model at every tick") print(f"{explained} more: the stand-in equals the model at every tick") print(f"{len(names) - agree - explained} left over") if args.sweeps: write_timing_sweep(variant) tone_rewrite_sweep(variant) test_override_levels(levels) return 0 if __name__ == "__main__": sys.exit(main())