#!/usr/bin/env python # SPDX-License-Identifier: MIT """Measure the phase step of every key code, key fraction and DT1 size on the closed-box referee, and compare it with IKAOPM's tables, ymfm's table and the application manual. python -I scripts/fetch_references.py && sh validation/build_referee.sh nice python -I scripts/referee_freq.py [--jobs 6] | tee reference/referee-freq.txt What is measured. One sine carrier (channel 0, operator C2, CON 7, TL 0, AR 31, MUL 1) is keyed and the referee's decoded output is read once per sample (`opm_ref ... 32`, the record after cycle 31 of each sample). The sign of a sine carrier is the top bit of its phase, so every sign change marks the phase crossing a multiple of 2^19 (of 2^20 per turn). Each crossing gives two linear inequalities in the start phase p0 and the step s; the script finds every integer s for which some p0 satisfies all of them. With a run longer than about s samples, exactly one integer is left: the phase step, in units of 2^-20 turn per sample, measured through opm.h only (OBSERVED, Nuked-OPM f209e6e). No model source is opened; the referee is a closed box (docs/restart.md rule 5). What it is compared with: * IKAOPM (Sehyeon Kim, BSD-2-Clause, commit 08a5b40): the frequency ROM is read at run time from reference/src/IKAOPM/src/IKAOPM_modules/IKAOPM_pg.v (`pg_submdl_fnumrom`); the rules applied to it (unused note codes move to the next code, KF interpolation, octave shift, DT1 from the PLA) are described in docs/phase-generator.md with their file:line citations (DIE). * ymfm (Aaron Giles, BSD-3-Clause, commit 81aec25): `s_phase_step` and `s_detune_adjustment`, parsed at run time from reference/src/ymfm/src/ymfm_fm.ipp. * Yamaha's application manual (DOC): 440 Hz at KC 0x4A, KF 0, 3.579545 MHz (PDF page 7) and equal temperament with KF in 1/64 semitone (Fig. 2.4, page 18); the DT1 table, Fig. 2.6 (page 18), whose D-FREQ column is in Hz; one unit of phase step is fM / 64 / 2^20 = 0.05334 Hz at 3.579545 MHz, so the column divided by 0.05334 is the DT1 step (MANUAL_DT1 below, transcribed by eye from the scan). Notices for IKAOPM and ymfm are in NOTICE. """ from __future__ import annotations import argparse import concurrent.futures import math import re import struct import os import subprocess import sys import tempfile from pathlib import Path import numpy as np 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 IKAOPM_PG = ROOT / "reference" / "src" / "IKAOPM" / "src" / "IKAOPM_modules" / "IKAOPM_pg.v" YMFM_FM = ROOT / "reference" / "src" / "ymfm" / "src" / "ymfm_fm.ipp" ADDRESS, DATA = 0, 1 HALF_TURN = 1 << 19 WARMUP = 64 # samples skipped after the key-on # Fig. 2.6 (application manual, PDF page 18), D-FREQ column in units of # 0.05334 Hz, rows KC' = KC >> 2 (octave * 4 + note >> 2), for DT1 = 1, 2, 3. MANUAL_DT1 = { 1: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10], 2: [1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 20], 3: [2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 20, 22, 22, 22, 22], } NOTE_SEMITONE = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 8: 7, 9: 8, 10: 9, 12: 10, 13: 11, 14: 12} # Fig. 2.4: note codes 0-2, 4-6, 8-10, 12-14 are C#, D, D#, E ... B, C (the C # belongs to the octave above C#); semitones counted from the octave's C. # ------------------------------------------------------------------ tables def ikaopm_rom() -> dict[int, int]: """The 64 x 17-bit frequency ROM, read from IKAOPM's source at run time.""" rom = {} pattern = re.compile(r"6'h([0-9A-F]{2}): o_DATA <= 17'b([01_]+);") for match in pattern.finditer(IKAOPM_PG.read_text()): rom[int(match.group(1), 16)] = int(match.group(2).replace("_", ""), 2) if len(rom) != 64: raise SystemExit(f"expected 64 ROM rows in {IKAOPM_PG}, found {len(rom)}") return rom def ikaopm_step(rom: dict[int, int], kc: int, kf: int, dt1: int = 0) -> int: """Phase step for MUL 1, DT2 0, no PM, by the rules in docs/phase-generator.md.""" # An unused note code (low two bits 3) becomes the next code; past 0x7E,63 # the pitch saturates (IKAOPM_pg.v:160-183, :229-247). if kc & 3 == 3: kc += 1 if kc > 0x7F: kc, kf = 0x7E, 63 pitch = (kc << 6) | kf data = rom[(pitch >> 4) & 63] # address: note code and KF bits 5-4 (:377-379) base = data >> 5 mcand = (data & 0b1110) | ((data >> 4) & 1) # scrambled bit order (:379) calcmode = data & 1 m = pitch & 15 # KF bits 3-0 interpolate between ROM rows (:383-432) if calcmode: v = 16 | mcand inc = sum((v >> k) for k, bit in enumerate((8, 4, 2, 1)) if m & bit) else: v = 16 | (mcand & 0b1110) | 1 inc = (v if m & 8 else 0) + ((v >> 1) if m & 4 else 0) + ((v >> 3) if m & 1 else 0) inc += 4 if (m & 12) == 12 and not mcand & 1 else 0 inc += (1 if m & 8 else 0) + (8 if m & 2 else 0) + (2 if m & 1 else 0) pdelta = base + (inc >> 1) # (:456) octave = pitch >> 10 step = pdelta >> (2 - octave) if octave < 2 else pdelta << (octave - 2) # (:517-526) return (step + ikaopm_dt1(pitch >> 8, dt1)) & 0x1FFFF # 17 bits, carry dropped (:563) def ikaopm_dt1(kcp: int, dt1: int) -> int: """DT1 displacement from the 5-bit KC' and DT1 (IKAOPM_pg.v:478-537).""" intensity = (kcp >> 2) + (1, 9, 11, 12)[dt1 & 3] select = 0 if kcp >= 28 else kcp & 3 base = 16 + ((6, 8, 11, 13) if intensity & 1 else (0, 1, 3, 4))[select] half = intensity >> 1 value = base >> (9 - half) if 5 <= half <= 9 else 0 return -value if dt1 & 4 else value def ymfm_tables() -> tuple[list[int], list[list[int]]]: text = YMFM_FM.read_text() block = text.split("s_phase_step[12*64] =", 1)[1].split("};", 1)[0] steps = [int(x) for x in re.findall(r"\d+", block)] block = text.split("s_detune_adjustment[32][4] =", 1)[1].split("};", 1)[0] flat = [int(x) for x in re.findall(r"\d+", block)] detune = [flat[i : i + 4] for i in range(0, 128, 4)] if len(steps) != 768 or len(detune) != 32: raise SystemExit("could not parse ymfm's tables") return steps, detune def ymfm_step(steps: list[int], detune: list[list[int]], kc: int, kf: int, dt1: int = 0) -> int: """ymfm 81aec25: ymfm_fm.ipp:206-321 (gap removal, table, octave shift) and ymfm_opm.cpp:336-344 (DT1 added after the shift).""" block, code = kc >> 4, kc & 15 eff = ((code - (code >> 2)) << 6) | kf if eff >= 768: eff -= 768 if block >= 7: return steps[767] + _ymfm_dt(detune, kc, dt1) block += 1 return (steps[eff] >> (block ^ 7)) + _ymfm_dt(detune, kc, dt1) def _ymfm_dt(detune: list[list[int]], kc: int, dt1: int) -> int: value = detune[kc >> 2][dt1 & 3] return -value if dt1 & 4 else value def manual_step(kc: int, kf: int) -> float: """Equal temperament anchored at 440 Hz = KC 0x4A, KF 0 (DOC), in steps.""" code = kc & 15 if code & 3 == 3: return float("nan") semis = (kc >> 4) * 12 + NOTE_SEMITONE[code] + kf / 64 a4 = 4 * 12 + NOTE_SEMITONE[10] return 440.0 * 2 ** ((semis - a4) / 12) / (3_579_545 / 64) * (1 << 20) # -------------------------------------------------------------- measuring def events_for(kc: int, kf: int, dt1: int) -> tuple[list[tuple[int, int, int]], int]: at, events = 64, [] for register, value in ( (0x20, 0xC7), # channel 0: both outputs, FB 0, CON 7 (0x28, kc), (0x30, kf << 2), (0x58, (dt1 << 4) | 1), # C2 of channel 0: DT1, MUL 1 (0x78, 0x00), # TL 0 (0x98, 0x1F), # KS 0, AR 31 (0xB8, 0x00), (0xD8, 0x00), (0xF8, 0x0F), # D1L 0, RR 15 (0x08, 0x40), # key on C2 of channel 0 ): events += [(at, ADDRESS, register), (at + 4, DATA, value)] at += 40 return events, at // 32 + 1 + WARMUP def run_signs(kc: int, kf: int, dt1: int, samples: int) -> np.ndarray: events, start = events_for(kc, kf, dt1) 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(" tuple[list[int], int]: """All integer steps consistent with the sign changes, and the number of samples whose output was exactly zero (ambiguous sign).""" negative = left < 0 zeros = int(np.count_nonzero(left == 0)) changes = np.flatnonzero(negative[1:] != negative[:-1]) + 1 if len(changes) < 3: return [], zeros k = np.arange(1, len(changes) + 1, dtype=np.int64) span = int(changes[-1] - changes[0]) estimate = (len(changes) - 1) * HALF_TURN / span radius = int(math.ceil(estimate / span * 4)) + 4 found = [] for s in range(max(1, int(estimate) - radius), int(estimate) + radius + 1): lower = np.max(k * HALF_TURN - changes * s) upper = np.min(k * HALF_TURN - (changes - 1) * s) if lower < upper: found.append(s) return found, zeros def measure(job: tuple[int, int, int, float]) -> tuple[int, int, int, list[int], int]: kc, kf, dt1, guess = job samples = int(1.5 * guess) + 4096 for _ in range(3): found, zeros = solve_step(run_signs(kc, kf, dt1, samples)) if len(found) == 1: break samples *= 2 return kc, kf, dt1, found, zeros # ------------------------------------------------------------------ report def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=6) parser.add_argument("--quick", action="store_true", help="KF 0 and 32 only") args = parser.parse_args(argv) 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 rom = ikaopm_rom() ysteps, ydetune = ymfm_tables() kfs = (0, 32) if args.quick else range(64) jobs = [(kc, kf, 0, ikaopm_step(rom, kc, kf)) for kc in range(128) for kf in kfs] # DT1: every KC' group at its lowest note (codes 0, 4, 8, 12) with KF 0 and 63 for kcp in range(32): kc = (kcp >> 2) << 4 | (kcp & 3) << 2 for kf in (0, 63): for dt1 in range(1, 8): jobs.append((kc, kf, dt1, ikaopm_step(rom, kc, kf, dt1))) results = {} with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool: for kc, kf, dt1, found, zeros in pool.map(measure, jobs): results[(kc, kf, dt1)] = (found, zeros) print("PHASE STEP per KC/KF (MUL 1, DT1 0, DT2 0, no LFO), units of 2^-20 turn per sample") print("measured on the closed box (OBSERVED, Nuked-OPM f209e6e) through opm.h") unresolved = [key for key, (found, _) in results.items() if len(found) != 1] print(f" runs: {len(results)}; resolved to one integer: {len(results) - len(unresolved)}") for key in unresolved[:10]: print(f" unresolved {key}: candidates {results[key][0][:6]}") zero_samples = sum(z for _, z in results.values()) print(f" samples with output exactly 0 (sign ambiguous): {zero_samples}") measured = {key: found[0] for key, (found, _) in results.items() if len(found) == 1} table = [(kc, kf) for kc in range(128) for kf in kfs if (kc, kf, 0) in measured] ika_eq = [key for key in table if measured[key + (0,)] == ikaopm_step(rom, *key)] ymf_eq = [key for key in table if measured[key + (0,)] == ymfm_step(ysteps, ydetune, *key)] print(f" equal to IKAOPM's ROM + rules: {len(ika_eq)} of {len(table)}") for key in [k for k in table if k not in set(ika_eq)][:12]: print(f" differs: KC 0x{key[0]:02X} KF {key[1]:2d}: measured {measured[key + (0,)]}, " f"IKAOPM {ikaopm_step(rom, *key)}") print(f" equal to ymfm's s_phase_step: {len(ymf_eq)} of {len(table)}") for key in [k for k in table if k not in set(ymf_eq)][:12]: print(f" differs: KC 0x{key[0]:02X} KF {key[1]:2d}: measured {measured[key + (0,)]}, " f"ymfm {ymfm_step(ysteps, ydetune, *key)}") valid = [key for key in table if key[0] & 3 != 3] cents = [1200 * math.log2(measured[key + (0,)] / manual_step(*key)) for key in valid] worst = max(range(len(valid)), key=lambda i: abs(cents[i])) print(f" against equal temperament from 440 Hz (manual): {len(valid)} valid codes, " f"mean {sum(cents) / len(cents):+.2f} cents, worst {cents[worst]:+.2f} cents " f"at KC 0x{valid[worst][0]:02X} KF {valid[worst][1]}") gap = [key for key in table if key[0] & 3 == 3] gap_next = [key for key in gap if (key[0] + 1, key[1], 0) in measured and measured[key + (0,)] == measured[(key[0] + 1, key[1], 0)]] print(f" unused note codes (low bits 3) sounding as the next code: {len(gap_next)} of " f"{len([k for k in gap if k[0] < 0x7F])} (KC 0x7F: measured " f"{[measured.get((0x7F, kf, 0)) for kf in (0, 32)]}, KC 0x7E KF 63: " f"{measured.get((0x7E, 63, 0))})") octave_ok = sum( 1 for kc in range(48, 128) for kf in kfs if (kc, kf, 0) in measured and (kc - 16, kf, 0) in measured and kc & 3 != 3 and measured[(kc, kf, 0)] == 2 * measured[(kc - 16, kf, 0)] ) print(f" octave o >= 3 exactly twice octave o-1 (valid codes): {octave_ok} of " f"{len([1 for kc in range(48, 128) for kf in kfs if kc & 3 != 3])} pairs from octave 3 up") print() print("DT1: measured displacement = step(DT1) - step(DT1 0), same KC/KF") rows = {} for kcp in range(32): kc = (kcp >> 2) << 4 | (kcp & 3) << 2 for kf in (0, 63): base = measured.get((kc, kf, 0)) for dt1 in range(1, 8): value = measured.get((kc, kf, dt1)) rows[(kcp, kf, dt1)] = None if base is None or value is None else value - base total = len(rows) agree_ika = sum(1 for (kcp, kf, dt1), d in rows.items() if d == ikaopm_dt1(kcp, dt1)) agree_ymf = sum(1 for (kcp, kf, dt1), d in rows.items() if d == _ymfm_dt(ydetune, kcp << 2, dt1)) agree_man = sum(1 for (kcp, kf, dt1), d in rows.items() if d == (MANUAL_DT1[dt1 & 3][kcp] if dt1 & 3 else 0) * (-1 if dt1 & 4 else 1)) print(f" {total} cases (32 KC' x KF 0, 63 x DT1 1-7)") print(f" equal to IKAOPM's PLA rule: {agree_ika} of {total}") print(f" equal to ymfm's s_detune_adjustment: {agree_ymf} of {total}") print(f" equal to the manual's Fig. 2.6: {agree_man} of {total}") print(" KC' | measured DT1 1, 2, 3 (KF 0) | manual Fig. 2.6 | IKAOPM | negative DT1 5, 6, 7 mirror?") for kcp in range(32): got = [rows[(kcp, 0, d)] for d in (1, 2, 3)] neg = [rows[(kcp, 0, d)] for d in (5, 6, 7)] mirror = all(n is not None and g is not None and n == -g for g, n in zip(got, neg)) man = [MANUAL_DT1[d][kcp] for d in (1, 2, 3)] ika = [ikaopm_dt1(kcp, d) for d in (1, 2, 3)] flag = "" if got == man == ika else " <-- differs" print(f" {kcp:3d} | {got} | {man} | {ika} | {mirror}{flag}") kf_same = sum(1 for kcp in range(32) for d in range(1, 8) if rows[(kcp, 0, d)] == rows[(kcp, 63, d)]) print(f" DT1 displacement the same at KF 0 and KF 63: {kf_same} of {32 * 7}") return 0 if __name__ == "__main__": sys.exit(main())