"""Takes apart a recording of the cart's audio test (C at the menu) and measures the YM2612's DAC "ladder": the step in its output where a wave crosses zero. python tools/audio.py REC.wav [REC2.wav ...] [--plot OUT.png] [--channel L|R|MIX] python tools/audio.py --selftest Give it several recordings (cold, then warm) and it puts them side by side. Each loop starts with a 0.5 s 981 Hz square, the mark; the parts after it follow `PARTS` below, which keeps src/main.c's table (`audio_parts`). For every sine part, averaged over the loops found: level the fundamental's amplitude, in steps of the 8-bit DAC (from DAC SINE 127, so the volume slider and the recorder's gain drop out) step the jump at each zero crossing, in the same steps: one period averaged, then fitted as a sine plus a sign wave (a perfect DAC gives 0) thd harmonics 2-15 against the fundamental, % noise what is left after the fundamental and harmonics, in DAC steps The console's output is filtered and AC-coupled, so the step comes out smoothed; compare recordings made the same way (same jack, slider and recorder), not absolute numbers. A smoothed step reads low: the selftest's 1.5 comes out ~1.34 (DAC) and ~1.2 (FM). """ import sys import wave from pathlib import Path import numpy as np LINE_HZ = 53_693_175 / 3_420 # one DAC sample a line MARK_HZ = LINE_HZ / 16 TWO_S, GAP = 31_400, 3_925 # (name, kind, arg, lines): kind "mark", "mid", "off", "dac" (amplitude), "fm" (TL) PARTS = [("MARK", "mark", 0, 7_850), ("OFF", "off", 0, GAP), ("DAC MIDDLE", "mid", 0, TWO_S), ("ALL OFF", "off", 0, TWO_S)] for amp in (127, 32, 8, 2): PARTS += [(f"DAC SINE {amp}", "dac", amp, TWO_S), ("OFF", "off", 0, GAP)] for tl in (0, 16, 32, 48, 64, 80): PARTS += [(f"FM SINE TL {tl}", "fm", tl, TWO_S), ("OFF", "off", 0, GAP)] LOOP_LINES = sum(p[3] for p in PARTS) DAC_HZ = 918 * LINE_HZ / 65536 # the phase step in main.c FM_HZ = 1083 * 2 ** 3 * (53_693_175 / 7) / (144 * 2 ** 20) def load(path, channel="MIX"): with wave.open(str(path)) as w: n, width, rate, frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes() raw = w.readframes(frames) if width == 3: b = np.frombuffer(raw, np.uint8).reshape(-1, 3) x = (b[:, 0].astype(np.int32) | b[:, 1].astype(np.int32) << 8 | b[:, 2].astype(np.int32) << 16) x = np.where(x >= 1 << 23, x - (1 << 24), x).astype(float) elif width == 2: x = np.frombuffer(raw, " 0 else 0 loud = rms > 0.25 * np.percentile(rms, 99) good = (ratio > 0.8) & loud need = int(0.4 / 0.005) marks, k = [], 0 while k < len(good): if good[k] and good[k:k + need].all(): marks.append(starts[k]) k += int(10 / 0.005) # the next mark is ~27 s away else: k += 1 return marks def fit_tone(seg, rate, f0, harmonics=15): """Least-squares fundamental + harmonics, frequency refined. (f, a1, phase, harm amps, resid)""" t = np.arange(len(seg)) / rate seg = seg - seg.mean() def solve(f): cols = [np.ones_like(t)] for h in range(1, harmonics + 1): cols += [np.sin(2 * np.pi * h * f * t), np.cos(2 * np.pi * h * f * t)] m = np.stack(cols, 1) c, *_ = np.linalg.lstsq(m, seg, rcond=None) return c, seg - m @ c lo, hi = f0 * 0.995, f0 * 1.005 for _ in range(40): # golden section on the residual a, b = lo + (hi - lo) * 0.382, lo + (hi - lo) * 0.618 if np.sum(solve(a)[1] ** 2) < np.sum(solve(b)[1] ** 2): hi = b else: lo = a f = (lo + hi) / 2 c, resid = solve(f) amps = np.hypot(c[1::2], c[2::2]) phase = np.arctan2(c[2], c[1]) # a1 sin(wt + phase) return f, amps[0], phase, amps, resid def step_fit(seg, rate, f, phase, bins=512): """One period averaged; fitted as a sine (any phase) + s * sign(sin) + c: returns 2s and the cycle.""" t = np.arange(len(seg)) / rate th = (2 * np.pi * f * t + phase) % (2 * np.pi) idx = (th / (2 * np.pi) * bins).astype(int) % bins cyc = np.bincount(idx, seg, bins) / np.maximum(np.bincount(idx, minlength=bins), 1) g = (np.arange(bins) + 0.5) / bins * 2 * np.pi m = np.stack([np.sin(g), np.cos(g), np.sign(np.sin(g)), np.ones_like(g)], 1) c, *_ = np.linalg.lstsq(m, cyc, rcond=None) return 2 * c[2], cyc def analyse(path, channel="MIX"): x, rate = load(path, channel) marks = find_marks(x, rate) if not marks: raise SystemExit(f"{path}: no mark found (is it the audio test, and loud enough?)") # the recorder's clock against the console's, from the marks' spacing if len(marks) > 1: scale = np.median(np.diff(marks)) / (LOOP_LINES / LINE_HZ * rate) else: scale = 1.0 per = {} loops = 0 for m in marks: pos = m if m + LOOP_LINES / LINE_HZ * rate * scale > len(x): break loops += 1 for name, kind, arg, lines in PARTS: n = lines / LINE_HZ * rate * scale a, b = int(pos + 0.25 * rate), int(pos + n - 0.15 * rate) seg = x[a:b] if kind in ("dac", "fm"): f0 = (DAC_HZ if kind == "dac" else FM_HZ) / scale f, a1, ph, amps, resid = fit_tone(seg, rate, f0) step, cyc = step_fit(seg - seg.mean(), rate, f, ph) per.setdefault(name, []).append(dict( a1=a1, step=step, thd=np.sqrt(np.sum(amps[1:] ** 2)) / a1 * 100, noise=np.std(resid), f=f * scale, cyc=cyc)) elif kind in ("mid", "off") and lines == TWO_S: per.setdefault(name, []).append(dict(noise=np.std(seg - seg.mean()))) pos += n if not loops: raise SystemExit(f"{path}: no whole loop after the first mark: record at least 30 s") full = np.mean([r["a1"] for r in per["DAC SINE 127"]]) / 127 # one 8-bit DAC step out = {} for name, rows in per.items(): o = {k: np.mean([r[k] for r in rows]) for k in rows[0] if k != "cyc"} o.update({k + "_sd": np.std([r[k] for r in rows]) for k in ("a1", "step") if k in rows[0]}) for k in ("a1", "a1_sd", "step", "step_sd", "noise"): if k in o: o[k] /= full if "cyc" in rows[0]: o["cyc"] = np.mean([r["cyc"] for r in rows], 0) / full out[name] = o return dict(path=str(path), rate=rate, loops=loops, clock=scale, parts=out) def report(results): names = [p[0] for p in PARTS if p[1] in ("dac", "fm") or (p[1] in ("mid", "off") and p[3] == TWO_S)] for r in results: print(f"{Path(r['path']).name}: {r['loops']} loop(s), {r['rate']} Hz, recorder/console clock " f"{r['clock']:.5f}") head = f"{'part':16}" + "".join(f"{Path(r['path']).stem[:30]:>34}" for r in results) print(head) print(f"{'':16}" + "".join(f"{'level':>8}{'step':>9}{'thd%':>8}{'noise':>9}" for _ in results)) for n in names: line = f"{n:16}" for r in results: o = r["parts"].get(n) if not o: line += f"{'-':>34}" elif "step" in o: line += f"{o['a1']:8.2f}{o['step']:9.3f}{o['thd']:8.2f}{o['noise']:9.3f}" else: line += f"{'':8}{'':9}{'':8}{o['noise']:9.3f}" print(line) print("level, step, noise: in steps of the 8-bit DAC; step: the jump at a zero crossing") def plot(results, out): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt show = ["DAC SINE 8", "DAC SINE 2", "FM SINE TL 64", "FM SINE TL 80"] fig, axes = plt.subplots(1, len(show), figsize=(4 * len(show), 3.2)) for ax, n in zip(axes, show): for r in results: o = r["parts"].get(n) if o is not None: ax.plot(np.linspace(0, 360, len(o["cyc"])), o["cyc"], label=Path(r["path"]).stem) ax.set_title(n) ax.set_xlabel("phase, degrees") ax.axhline(0, color="grey", lw=0.5) axes[0].set_ylabel("8-bit DAC steps") axes[0].legend(fontsize=7) fig.tight_layout() fig.savefig(out, dpi=120) print("plot:", out) def selftest(): """A made-up recording with a known step: the fit must find it.""" import tempfile rate = 48_000 out = [] for true_step in (0.0, 1.5): t_line = np.arange(int(LOOP_LINES * 2.2)) / LINE_HZ y = np.zeros_like(t_line) pos = 0 for name, kind, arg, lines in PARTS: s = slice(pos, pos + lines) tt = np.arange(lines) / LINE_HZ if kind == "mark": y[s] = np.where(np.arange(lines) & 8, -127, 127) elif kind == "dac": w = arg * np.sin(2 * np.pi * DAC_HZ * tt) y[s] = w + true_step / 2 * np.sign(w) elif kind == "fm": w = 127 * 10 ** (-arg * 0.75 / 20) * np.sin(2 * np.pi * FM_HZ * tt) y[s] = w + true_step / 2 * np.sign(w) pos += lines y[LOOP_LINES:2 * LOOP_LINES] = y[:LOOP_LINES] y[2 * LOOP_LINES:] = y[:len(y) - 2 * LOOP_LINES] ts = np.arange(int(len(y) / LINE_HZ * rate)) / rate rec = np.interp(ts, t_line, y) * 100 + np.random.default_rng(1).normal(0, 20, len(ts)) p = Path(tempfile.gettempdir()) / f"audio-selftest-{true_step}.wav" with wave.open(str(p), "wb") as w: w.setnchannels(1) w.setsampwidth(2) w.setframerate(rate) w.writeframes(np.clip(rec, -32768, 32767).astype("