"""4-bit IMA ADPCM for the sample stream: the quality gate before any driver work. The other streaming ROMs all use 4-bit ADPCM, and it halves the audio's share of the cartridge: 3.71 MB of raw 8-bit samples becomes 1.86 MB. Whether that is acceptable is a listening question - no metric here can stand in for an ear - so this produces the listening test first, and the numbers alongside it, before a single Z80 cycle is spent. IMA ADPCM is the plain, documented codec (the step and index tables below are the standard ones, as in the IMA/DVI spec and every reference decoder). Each nibble is a scaled difference from a running predictor whose scale adapts by table. Our source is 8-bit, so it is widened to 16 for the codec and the decoded result narrowed back to the 8 bits the YM2612's DAC can take; that narrowing is the DAC's limit, not the codec's. python tools/adpcm.py out/full/audio.u8 out/adpcm -> out/adpcm/raw.wav the stream as it is, 17,594 Hz -> out/adpcm/ima4.wav after one encode/decode round trip, the same rate -> out/adpcm/stream.ima the nibbles, two samples per byte, as the ROM would hold -> printed: SNR, byte savings, and the worst local error """ from __future__ import annotations import argparse import struct from pathlib import Path import numpy as np SAMPLE_RATE = 17594 STEP_TABLE = np.array([ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, ], dtype=np.int64) # fmt: skip INDEX_TABLE = np.array([-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8], dtype=np.int64) def encode(samples16: np.ndarray) -> np.ndarray: """16-bit samples -> one nibble (0-15) per sample. Plain IMA, no lookahead.""" out = np.empty(len(samples16), dtype=np.uint8) pred, index = 0, 0 for i, s in enumerate(samples16): step = int(STEP_TABLE[index]) diff = int(s) - pred nibble = 0 if diff < 0: nibble = 8 diff = -diff delta = step >> 3 if diff >= step: nibble |= 4 diff -= step delta += step if diff >= step >> 1: nibble |= 2 diff -= step >> 1 delta += step >> 1 if diff >= step >> 2: nibble |= 1 delta += step >> 2 pred = pred - delta if nibble & 8 else pred + delta pred = max(-32768, min(32767, pred)) index = max(0, min(88, index + int(INDEX_TABLE[nibble]))) out[i] = nibble return out def decode(nibbles: np.ndarray) -> np.ndarray: """The decoder the driver would have to match, nibble for nibble.""" out = np.empty(len(nibbles), dtype=np.int64) pred, index = 0, 0 for i, n in enumerate(nibbles): n = int(n) step = int(STEP_TABLE[index]) delta = step >> 3 if n & 4: delta += step if n & 2: delta += step >> 1 if n & 1: delta += step >> 2 pred = pred - delta if n & 8 else pred + delta pred = max(-32768, min(32767, pred)) index = max(0, min(88, index + int(INDEX_TABLE[n]))) out[i] = pred return out def write_wav(path: Path, samples_u8: np.ndarray, rate: int = SAMPLE_RATE) -> None: """Mono 16-bit WAVE from unsigned 8-bit samples, widened so players agree on level.""" data = ((samples_u8.astype(np.int16) - 128) << 8).astype(" int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("source", type=Path, help="unsigned 8-bit samples at 17,594 Hz (out/full/audio.u8)") ap.add_argument("out", type=Path, nargs="?", default=Path("out/adpcm")) ap.add_argument("--seconds", type=float, help="encode only this much, for a quick listen") args = ap.parse_args(argv) raw = np.frombuffer(args.source.read_bytes(), dtype=np.uint8) if args.seconds: raw = raw[: int(args.seconds * SAMPLE_RATE)] wide = (raw.astype(np.int64) - 128) << 8 nibbles = encode(wide) back = decode(nibbles) narrow = np.clip((back >> 8) + 128, 0, 255).astype(np.uint8) args.out.mkdir(parents=True, exist_ok=True) write_wav(args.out / "raw.wav", raw) write_wav(args.out / "ima4.wav", narrow) packed = (nibbles[0::2] << 4) | nibbles[1::2] if len(nibbles) % 2 == 0 else \ (np.append(nibbles, 0)[0::2] << 4) | np.append(nibbles, 0)[1::2] (args.out / "stream.ima").write_bytes(packed.astype(np.uint8).tobytes()) signal = raw.astype(np.float64) - 128.0 noise = narrow.astype(np.float64) - raw.astype(np.float64) snr = 10 * np.log10(np.sum(signal * signal) / max(np.sum(noise * noise), 1e-9)) err = np.abs(noise) win = SAMPLE_RATE // 10 local = err[: len(err) - len(err) % win].reshape(-1, win).mean(axis=1) worst = int(np.argmax(local)) print(f"{len(raw):,} samples ({len(raw) / SAMPLE_RATE:.1f} s)") print(f"raw 8-bit : {len(raw):,} bytes") print(f"IMA 4-bit : {len(packed):,} bytes ({100 * len(packed) / len(raw):.0f}%, saves " f"{(len(raw) - len(packed)) / 1e6:.2f} MB on the full song)") print(f"SNR after the round trip: {snr:.1f} dB mean |error| {err.mean():.2f} of 255 " f"max {err.max()} samples off by more than 4: {100 * np.mean(err > 4):.2f}%") print(f"worst 100 ms window: {worst * 0.1:.1f} s, mean |error| {local[worst]:.1f}") print(f"\nlisten: {args.out / 'raw.wav'} vs {args.out / 'ima4.wav'}") return 0 if __name__ == "__main__": raise SystemExit(main())