Files
JIANT/tools/gen_wave_tables.py
T
Claude 161b8cae5f WAVE: a wavetable engine on engine 9 (PHYS's retired slot), JIANT BYTE's 16 tables
WAVE (engine 9, after ADD in ENGINE_ORDER, last in the PROGRAM CHANGE order): two tables A and B
of JIANT BYTE's 16 wave formulas (tools/gen_wave_tables.c/.py; firmware/src/wave_tables.h, 8186 B
Rice-coded int8, BYTE main 94f8ac9), POS over eight frames, WARP OFF SYNC BEND MIRROR QUANT FM with
AMT, MIX, DETUNE, SUB; U1..U8 named for user tables (empty: SINE). The frames decode into the part's
comb line (no new RAM; wv state in .pool), checked each block by a content signature (STRING / the
COMB's clear: decoded again, the part faded in). 26 presets.

Old data: a user preset of before (version < 4) or a project of phys < 4 with engine 9 is PHYS's and
plays as ANALOG / is refused as before; projects with a WAVE track are written phys 4. Favourites:
WAVE's in TRIO's retired row (bytes 0..3, cleared once: prefs revision 7).

No sound of another engine changes (golden: 26 added, 0 changed); the pinned audio layout unchanged
(eng_wave.c's tables and literals late, build.py); flash 19492 B free, RAM, RAM code and seg2 as
before, pool spare 8288 B. Tests: tests/wave_test.c (in voice-user-check), NRPN map regenerated,
ui_test's engine lists, ui_test's settings round trip zeroes its records (the stack's bold field).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
2026-12-05 00:29:17 +00:00

200 lines
7.7 KiB
Python

# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
"""WAVE's factory tables (firmware/src/wave_tables.h) from JIANT BYTE's 16 wave formulas.
python3 tools/gen_wave_tables.py BYTE_CHECKOUT (builds and runs tools/gen_wave_tables.c against it)
python3 tools/gen_wave_tables.py --frames FILE (the C tool's output, already made)
The C tool evaluates each formula with BYTE's own formula machine as BYTE's eng_wave.c draws its frames, at the eight
positions of FM's grid (frame k at POS k x 127 / 7): 16 x 8 frames of 128 int16. Here they become int8 (rounded: the
device's frames are int8, a user table's own format), and only the frames a table needs are kept: SINE one (POS does
not move it), SAWSQ ODD SINTR two (POS 0 and 127: A in them is linear, the six between are their blend, as BYTE draws
them), the twelve others eight. Each kept frame is coded on its own (byte-aligned): 2 bits its predictor (0 the point
before, 1 the line through the two before, 2 the frame before's point, 3 the frame before's point plus this frame's
step), 3 bits k, then each of the 128 residuals Rice-coded (zigzag u: u >> k one-bits, a zero, then u's low k bits,
LSB first). firmware/src/eng_wave.c wv_frame decodes one; the header is checked here by decoding it back.
The CI never runs this: the header is committed. Reproduces BYTE main 94f8ac9 (v1.2.1)."""
import math
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
OUT = os.path.join(ROOT, 'firmware', 'src', 'wave_tables.h')
NAMES = ['SINE', 'FM2', 'FMR', 'TRISY', 'SAWSQ', 'DRIVE', 'RING', 'FOLD', 'ODD', 'PULSE', 'STEP', 'BITS', 'FORMT',
'NOISE', 'SINTR', 'SATUR']
KEPT = [1, 8, 8, 8, 2, 8, 8, 8, 2, 8, 8, 8, 8, 8, 2, 8] # frames kept: 1 SINE, 2 the linear ones (A in them is linear)
def frames_text(byte):
exe = os.path.join(ROOT, 'build', 'host', 'gen_wave_tables')
os.makedirs(os.path.dirname(exe), exist_ok=True)
subprocess.check_call(['cc', '-O2', '-w', '-I' + os.path.join(byte, 'build', 'gen'), '-I' + os.path.join(byte, 'tests'),
'-I' + os.path.join(byte, 'firmware', 'src'), '-o', exe,
os.path.join(HERE, 'gen_wave_tables.c'), '-lm'])
return subprocess.check_output([exe]).decode()
def q8(v):
return max(-128, min(127, int(math.floor(v / 256.0 + 0.5))))
def pred(m, x, prev, i):
a = x[i - 1] if i else 0
if m == 0:
return a
if m == 1:
return 2 * a - (x[i - 2] if i > 1 else 0)
if m == 2:
return prev[i]
return prev[i] + a - (prev[i - 1] if i else 0)
class Bits:
def __init__(self):
self.b = bytearray()
self.n = 0
def put(self, v, k):
for j in range(k):
if self.n % 8 == 0:
self.b.append(0)
if (v >> j) & 1:
self.b[-1] |= 1 << (self.n % 8)
self.n += 1
def align(self):
self.n = len(self.b) * 8
def code_frame(x, prev):
best = None
for m in range(4 if prev else 2):
r = [x[i] - pred(m, x, prev, i) for i in range(128)]
u = [(d << 1) if d >= 0 else ((-d) << 1) - 1 for d in r]
for k in range(8):
n = sum((v >> k) + 1 + k for v in u)
if best is None or n < best[0]:
best = (n, m, k, u)
_, m, k, u = best
b = Bits()
b.put(m, 2)
b.put(k, 3)
for v in u:
b.put((1 << (v >> k)) - 1, v >> k)
b.put(0, 1)
b.put(v & ((1 << k) - 1), k)
return bytes(b.b)
def decode_frame(z, prev): # eng_wave.c wv_frame's, to check the header
pos = [0]
def bit():
v = (z[pos[0] >> 3] >> (pos[0] & 7)) & 1
pos[0] += 1
return v
def get(k):
return sum(bit() << j for j in range(k))
m = get(2)
k = get(3)
x = []
for i in range(128):
q = 0
while bit():
q += 1
u = (q << k) | get(k)
d = (u >> 1) if not (u & 1) else -((u + 1) >> 1)
x.append(pred(m, x, prev, i) + d)
return x
def expand(f, kept): # the eight frames the device makes of the kept ones
if KEPT[f] == 1:
return [kept[0]] * 8
if KEPT[f] == 2:
a, b = kept
return [[((a[i] * (7 - k) + b[i] * k + 896) * 2 + 7) // 14 - 128 for i in range(128)] for k in range(8)]
return kept
def main():
if len(sys.argv) == 3 and sys.argv[1] == '--frames':
txt = open(sys.argv[2]).read()
elif len(sys.argv) == 2:
txt = frames_text(sys.argv[1])
else:
sys.exit(__doc__)
fr = {}
for line in txt.splitlines():
a = list(map(int, line.split()))
fr[(a[0], a[1])] = a[2:]
assert len(fr) == 128 and all(len(v) == 128 for v in fr.values())
z = bytearray()
offs = []
snr = []
exp = []
for f in range(16):
idx = [0] if KEPT[f] == 1 else [0, 7] if KEPT[f] == 2 else list(range(8))
kept = []
prev = None
for k in idx:
x = [q8(v) for v in fr[(f, k)]]
offs.append(len(z))
c = code_frame(x, prev)
assert decode_frame(c, prev) == x
z += c
kept.append(x)
prev = x
ex = expand(f, kept)
exp.append(ex)
s = n = 0
for k in range(8): # the device's frames against BYTE's (int16) at every grid point
for i in range(128):
v = fr[(f, k)][i]
d = v - ex[k][i] * 256
s += v * v
n += d * d
snr.append(10 * math.log10(s / max(n, 1)))
offs.append(len(z))
assert len(z) < 65536
hashes = [] # (tests/wave_test.c) each table's eight frames as the device makes them
for f in range(16):
h = 2166136261
for k in range(8):
for v in exp[f][k]:
h = ((h ^ (v & 255)) * 16777619) & 0xFFFFFFFF
hashes.append(h)
o = ['/* SPDX-License-Identifier: GPL-3.0-only',
' * Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) */',
'/* Generated by tools/gen_wave_tables.py (tools/gen_wave_tables.c, JIANT BYTE main 94f8ac9): do not edit.',
' * WAVE\'s 16 factory tables, BYTE\'s formulas at FM\'s eight POS (k x 127 / 7), int8, Rice-coded a frame each',
' * (eng_wave.c wv_frame). Against BYTE\'s int16 frames (dB): ' +
' '.join('%s %.1f' % (NAMES[f], snr[f]) for f in range(16)) + ' */',
'#pragma once',
'#define WT_NF 16u',
'#define WT_ZSIZE %du' % len(z),
'/* the frames kept a table (1: SINE, 2: POS 0 and 127, the six between their blend; 8: the grid) */',
'static const uint8_t WT_KEPT[WT_NF] = {%s};' % ', '.join(map(str, KEPT)),
'/* each kept frame\'s first byte in WT_Z, the tables one after the other (the last: the end) */',
'static const uint16_t WT_FOFF[%d] = {' % len(offs)]
for i in range(0, len(offs), 16):
o.append(' ' + ', '.join(map(str, offs[i:i + 16])) + ',')
o.append('};')
o.append('/* (tests/wave_test.c) FNV-1a of each table\'s eight frames (1024 int8) as the device makes them */')
o.append('#define WT_HASH_INIT {' + ', '.join('0x%08xu' % h for h in hashes) + '}')
o.append('static const uint8_t WT_Z[WT_ZSIZE] = {')
for i in range(0, len(z), 24):
o.append(' ' + ', '.join('0x%02x' % b for b in z[i:i + 24]) + ',')
o.append('};')
open(OUT, 'w').write('\n'.join(o) + '\n')
print('wave_tables.h: %d frames kept, %d B coded (%d B raw int8), %d B of offsets' %
(len(offs) - 1, len(z), (len(offs) - 1) * 128, len(offs) * 2))
print('SNR against BYTE int16:', ', '.join('%s %.1f' % (NAMES[f], snr[f]) for f in range(16)))
if __name__ == '__main__':
main()