#!/usr/bin/env python # SPDX-License-Identifier: MIT """Measure the noise generator, the LFO and the envelope on the Nuked-OPM referee. python -I scripts/fetch_references.py && sh validation/build_referee.sh python -I scripts/referee_measure.py # about 5 s of CPU Phase 0 groundwork, like scripts/referee_probe.py: short directed register streams whose answers docs/envelope.md, docs/lfo-noise.md and docs/phase-generator.md quote. Output is kept in reference/referee-measure.txt when run with ``| tee``. The trick that makes the envelope readable: with noise enabled, channel 7's operator C2 outputs noise in place of a sine (Yamaha's application manual, register 0x0F), and its magnitude follows the slot's attenuation. That the magnitude is a direct, linear readout of the envelope level (plus TL and AM), one value per sample, is what this script's own runs show on the closed box (OBSERVED, Nuked-OPM f209e6e); the die-level reason is to be cited to IKAOPM (BSD-2) when the specification is rewritten (docs/restart.md). """ from __future__ import annotations import math import struct import os import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parent.parent #: The referee: nuked-harness's opm-events, a GPL tool outside this repository, at its #: documented path under EMU_TOOLS_GPL (docs/provenance.md, "History"). TOOL = "tools/nuked/build/opm-events" REFEREE = Path(os.environ["EMU_TOOLS_GPL"]) / TOOL if os.environ.get("EMU_TOOLS_GPL") else None ADDRESS, DATA = 0, 1 CLOCK = 3_579_545 SAMPLE_RATE = CLOCK / 64 def run(events, samples: int, chip: str = "ym2151") -> tuple[list[int], list[int]]: """Return (left, right): the referee's decoded output, one value per sample.""" cycles = samples * 32 with tempfile.TemporaryDirectory(dir=ROOT / "reference") as scratch: source = Path(scratch) / "events.bin" target = Path(scratch) / "out.bin" source.write_bytes(b"".join(struct.pack(" int: self.events.append((self.at, ADDRESS, register)) self.events.append((self.at + 4, DATA, value)) self.at += 40 return self.at def wait_samples(self, samples: int) -> None: self.at += samples * 32 def sample(self) -> int: """The sample index the next write falls in.""" return self.at // 32 def noise_voice(stream: Stream, nfrq: int, *, ar=31, d1r=0, d2r=0, d1l=0, rr=15, tl=0, kc=0x4A, ks=0, am=False, key=True, ch_ams=0) -> None: """Channel 7, C2 only (slot 31), noise on, CON 7, both outputs.""" stream.write(0x0F, 0x80 | nfrq) stream.write(0x27, 0xC7) stream.write(0x2F, kc) stream.write(0x3F, ch_ams) stream.write(0x5F, 0x01) stream.write(0x7F, tl) stream.write(0x9F, (ks << 6) | ar) stream.write(0xBF, (0x80 if am else 0) | d1r) stream.write(0xDF, d2r) stream.write(0xFF, (d1l << 4) | rr) if key: stream.write(0x08, 0x47) def changes(values: list[int]) -> list[int]: return [i for i in range(1, len(values)) if values[i] != values[i - 1]] # --------------------------------------------------------------------- noise def measure_noise() -> None: print("NOISE (slot 31 with NE = 1; CON 7, TL 0, AR 31, held)") for nfrq in (0, 1, 16, 24, 28, 29, 30, 31): stream = Stream() noise_voice(stream, nfrq) start = stream.sample() + 64 left, _ = run(stream.events, start + 32768) tail = left[start:] signs = [v > 0 for v in tail] flips = changes(signs) intervals = [b - a for a, b in zip(flips, flips[1:])] rate = len(flips) / len(tail) print( f" NFRQ {nfrq:2d}: magnitudes {sorted(set(abs(v) for v in tail))}, " f"sign changes per sample {rate:.4f} (1/(32-NFRQ) = {1 / (32 - nfrq):.4f}), " f"shortest gap between changes {min(intervals)} samples" ) # Period of the per-sample sign sequence at NFRQ 31: 2^17 - 1 = 131071 is prime, # so the sequence either repeats at exactly 131071 samples or is not that m-sequence. stream = Stream() noise_voice(stream, 31) start = stream.sample() + 64 left, _ = run(stream.events, start + 131071 + 4096) signs = [v > 0 for v in left[start:]] same = all(signs[i] == signs[i + 131071] for i in range(4096)) ones = sum(signs[:131071]) print( f" NFRQ 31: sign sequence repeats after 131071 samples: {same}; " f"positive samples in one period: {ones} (an m-sequence has 65536 of one kind)" ) stream = Stream() noise_voice(stream, 31, key=False) left, right = run(stream.events, stream.sample() + 4096) print(f" never keyed, NE = 1: max |output| = {max(map(abs, left + right))}") stream = Stream() noise_voice(stream, 31) stream.wait_samples(256) stream.write(0x08, 0x07) # key off, RR 15 stream.wait_samples(2048) left, _ = run(stream.events, stream.sample() + 2048) print(f" keyed then released (RR 15), last 2048 samples: max |output| = " f"{max(map(abs, left[-2048:]))}") for tl in (0, 1, 8, 64, 127): stream = Stream() noise_voice(stream, 31, tl=tl) start = stream.sample() + 64 left, _ = run(stream.events, start + 2048) tail = left[start:] print(f" TL {tl:3d}: output min {min(tail)}, max {max(tail)}") # ----------------------------------------------------------------------- LFO def measure_lfo() -> None: print("LFO period (square wave AM on the noise slot: AMS 1, AMD 127, edges of |output|)") for lfrq, periods in ((0xFF, 10), (0xF8, 10), (0xF0, 8), (0xE0, 6), (0xD0, 4), (0xC0, 3)): hi, lo = lfrq >> 4, lfrq & 15 expected = 2**30 / ((16 + lo) << hi) # ymfm's 4.4 floating step (a detector) stream = Stream() stream.write(0x1B, 0x01) # square stream.write(0x18, lfrq) stream.write(0x19, 0x7F) # AMD 127 noise_voice(stream, 31, am=True, ch_ams=1) start = stream.sample() + 64 left, _ = run(stream.events, start + int(expected * (periods + 1.2))) mags = [abs(v) for v in left[start:]] threshold = (min(mags) + max(mags)) / 2 loud = [m > threshold for m in mags] rises = [i for i in range(1, len(loud)) if loud[i] and not loud[i - 1]] if len(rises) < 2: print(f" LFRQ 0x{lfrq:02X}: fewer than two rising edges") continue measured = (rises[-1] - rises[0]) / (len(rises) - 1) gaps = sorted({b - a for a, b in zip(rises, rises[1:])}) print( f" LFRQ 0x{lfrq:02X}: {measured:9.2f} samples per period " f"(gaps {gaps}) = {SAMPLE_RATE / measured:8.4f} Hz at 3.579545 MHz; " f"ymfm 2^30/((16+lo)< int: """The noise slot's output as an attenuation level (0 = loudest, 1 unit = 0.09375 dB). Measured scale: TL 0 reads +2040 / -2044 and each TL step (8 units) moves it by 16, so 2 per unit, and the level's lowest bit is not seen.""" return (2040 - value) // 2 if value > 0 else (2044 + value) // 2 def measure_envelope() -> None: print("ENVELOPE (noise slot; |output| is linear in the attenuation level)") # Readout scale: |output| at TL 0..3 tells the step size per attenuation unit. mags = [] for tl in range(4): stream = Stream() noise_voice(stream, 31, tl=tl) start = stream.sample() + 64 left, _ = run(stream.events, start + 512) mags.append(max(abs(v) for v in left[start:])) print(f" max |output| at TL 0,1,2,3: {mags} (TL adds 8 attenuation units per step)") # EG clock and step: a decay at effective rate 12 and 26; plateau lengths. for d1r, kc in ((5, 0x4A), (6, 0x00), (12, 0x4A)): ksv = (((kc >> 4) << 2) | ((kc & 15) >> 2)) >> 3 stream = Stream() noise_voice(stream, 31, d1r=d1r, d1l=15, kc=kc) start = stream.sample() + 8 left, _ = run(stream.events, start + 40000) mags = [max(abs(v) for v in left[i : i + 1]) for i in range(start, len(left))] # |output| is sign-dependent by a few units; use positive-side values only pos = [(i, v) for i, v in enumerate(left[start:]) if v > 0] steps = [pos[k][0] for k in range(1, len(pos)) if pos[k][1] != pos[k - 1][1]] gaps = [b - a for a, b in zip(steps, steps[1:])][2:40] print( f" D1R {d1r:2d} KC 0x{kc:02X} KS 0 (effective rate {2 * d1r + ksv}): " f"samples between level changes {sorted(set(gaps))}, " f"first change of |output| {pos[0][1] - pos[steps[0]][1] if steps else None}" ) for d1r in (31,): stream = Stream() noise_voice(stream, 31, d1r=d1r, d1l=15) start = stream.sample() + 2 left, _ = run(stream.events, start + 120) levels = [level_of(v) for v in left[start:]] steps = changes(levels) print(f" D1R 31 (rate 63): level changes at samples {steps[:12]} ...; " f"sample index mod 3 of every change: {sorted({i % 3 for i in steps})}; " f"levels {levels[steps[0]-1:steps[0]+8]}") # D1L 15 means 93 dB: decay runs to the floor, the slot mutes, output exactly 0. for d1l in (14, 15): stream = Stream() noise_voice(stream, 31, d1r=31, d1l=d1l, d2r=0) start = stream.sample() left, _ = run(stream.events, start + 4096) tail = left[-1024:] print(f" D1L {d1l}, D1R 31, D2R 0: last 1024 samples |output| values " f"{sorted({abs(v) for v in tail})}") for d1l in (14, 15): stream = Stream() stream.write(0x20, 0xC7) stream.write(0x28, 0x4A) stream.write(0x58, 0x01) stream.write(0x78, 0x00) stream.write(0x98, 0x1F) stream.write(0xB8, 31) stream.write(0xD8, 0) stream.write(0xF8, (d1l << 4) | 15) stream.write(0x08, 0x40) left, _ = run(stream.events, stream.sample() + 4096) tail = left[-1024:] print(f" sine carrier, D1L {d1l}, D1R 31, D2R 0: last 1024 samples min {min(tail)} " f"max {max(tail)}") stream = Stream() noise_voice(stream, 31, key=False) left, _ = run(stream.events, stream.sample() + 4096) print(f" noise slot never keyed (muted, level 1023): output values {sorted(set(left[-2048:]))}") stream = Stream() noise_voice(stream, 31, tl=127) left, _ = run(stream.events, stream.sample() + 4096) print(f" noise slot keyed at TL 127: output values {sorted(set(left[-2048:]))}") # Attack time at effective rates 30 and 31 (raw AR 15), 10% to 90% of linear amplitude. for kc, label in ((0x00, 30), (0x20, 31)): stream = Stream() noise_voice(stream, 31, ar=15, kc=kc) start = stream.sample() left, _ = run(stream.events, start + 20000) att = [None if v <= 0 else v for v in left[start:]] peak = max(v for v in att if v is not None) # attenuation units from the readout: 1023 - |v|/4 (see scale above) def amplitude(v): return 10 ** (-level_of(v) * 0.09375 / 20) top = amplitude(peak) t10 = next(i for i, v in enumerate(att) if v is not None and amplitude(v) >= 0.1 * top) t90 = next(i for i, v in enumerate(att) if v is not None and amplitude(v) >= 0.9 * top) t100 = next(i for i, v in enumerate(att) if v == peak) print( f" AR 15, KC 0x{kc:02X}, KS 0 (effective rate {label}): 10% at {t10}, 90% at " f"{t90}, top at {t100} samples; 10-90% = {(t90 - t10) / SAMPLE_RATE * 1000:.1f} ms" ) # Rate 62/63: instant on a key-on edge; with the key held, no attack at all. stream = Stream() noise_voice(stream, 31, ar=31) start = stream.sample() left, _ = run(stream.events, start + 16) print(f" AR 31 key-on (rate 63): |output| in the first 6 samples after the write " f"{[abs(v) for v in left[start - 1 : start + 5]]}") for new_ar, kc in ((31, 0x00), (30, 0x00), (31, 0x4A)): stream = Stream() noise_voice(stream, 31, ar=10, kc=kc) stream.wait_samples(1200) mark = stream.sample() stream.write(0x9F, new_ar) left, _ = run(stream.events, mark + 3000) before = max(abs(v) for v in left[mark - 64 : mark]) after = max(abs(v) for v in left[mark + 1000 : mark + 1064]) ksv = (((kc >> 4) << 2) | ((kc & 15) >> 2)) >> 3 print( f" AR 10 keyed, then AR {new_ar} written with the key held (KC 0x{kc:02X}, " f"effective {min(63, 2 * new_ar + ksv)}): |output| {before} before, " f"{after} 1000 samples later" ) # Raw rate 0 never moves, whatever KS adds. stream = Stream() noise_voice(stream, 31, ar=0, ks=3, kc=0x7E) left, _ = run(stream.events, stream.sample() + 8192) print(f" AR 0, KS 3, KC 0x7E: max |output| over 8192 samples {max(map(abs, left))}") # ------------------------------------------------- phase: the four gap codes def zero_crossings(kc: int) -> int: stream = Stream() stream.write(0x20, 0xC7) stream.write(0x28, kc) stream.write(0x30, 0x00) stream.write(0x58, 0x01) stream.write(0x78, 0x00) stream.write(0x98, 0x1F) stream.write(0xF8, 0x0F) stream.write(0x08, 0x40) start = stream.sample() + 32 left, _ = run(stream.events, start + 32768) tail = left[start:] return sum(1 for a, b in zip(tail, tail[1:]) if a < 0 <= b) def measure_gap_codes() -> None: print("KEY CODE gaps: rising zero crossings in 32768 samples, one sine carrier") for kcs in ((0x42, 0x43, 0x44), (0x46, 0x47, 0x48), (0x4A, 0x4B, 0x4C), (0x4E, 0x4F, 0x50)): counts = [zero_crossings(kc) for kc in kcs] print(" " + ", ".join(f"KC 0x{kc:02X}: {n}" for kc, n in zip(kcs, counts))) # ------------------------------------------------------- key-on register latch def measure_key_on_latch() -> None: print("KEY-ON latch: two writes to 0x08 (ch 0 C2, then ch 1 C2) G cycles apart;" " ch 0 left only, ch 1 right only") for gap in (8, 16, 24, 32, 33, 40, 64): stream = Stream() for ch, rl in ((0, 0x47), (1, 0x87)): stream.write(0x20 + ch, rl) stream.write(0x28 + ch, 0x4A) stream.write(0x58 + ch, 0x01) stream.write(0x78 + ch, 0x00) stream.write(0x98 + ch, 0x1F) stream.write(0xF8 + ch, 0x0F) at = stream.at + 64 stream.events += [(at, ADDRESS, 0x08), (at + 8, DATA, 0x40), (at + 8 + gap, DATA, 0x41)] left, right = run(stream.events, at // 32 + 2048) print(f" G = {gap:2d}: ch 0 sounds {max(map(abs, left[-1024:])) > 0}, " f"ch 1 sounds {max(map(abs, right[-1024:])) > 0}") def main() -> int: if REFEREE is None or not REFEREE.exists(): print(f"the referee is missing: set EMU_TOOLS_GPL so that $EMU_TOOLS_GPL/{TOOL} exists " "(sh validation/build_referee.sh checks it)", file=sys.stderr) return 3 measure_noise() measure_lfo() measure_envelope() measure_gap_codes() measure_key_on_latch() return 0 if __name__ == "__main__": sys.exit(main())