use crate::synth::va::m;
use std::sync::OnceLock;
pub(super) const SIZE: usize = 1024;
pub(super) const TABLES: usize = 8;
pub(super) const COLS: usize = 8;
pub(super) const MIPS: usize = 9;
const UNIFORM_LANES: usize = 4;
const DIGITAL_LANES: usize = 8;
const fn max_harmonic(mip: usize) -> usize {
(SIZE / 2 - 1) >> mip
}
fn hash(x: u32) -> u32 {
let mut h = x.wrapping_mul(0x9E37_79B1);
h ^= h >> 15;
h = h.wrapping_mul(0x85EB_CA6B);
h ^= h >> 13;
h
}
fn unit(x: u32) -> f32 {
(hash(x) >> 8) as f32 / (1u32 << 24) as f32
}
fn bessel(n: usize, x: f64) -> f64 {
let half = x / 2.0;
let mut term = 1.0f64;
for k in 1..=n {
term *= half / k as f64;
if term == 0.0 {
return 0.0;
}
}
let mut sum = term;
for mm in 1..16 {
term *= -(half * half) / (mm as f64 * (mm + n) as f64);
sum += term;
}
sum
}
const VOWELS: [(f32, f32); 5] = [(6.6, 9.9), (4.8, 16.7), (2.5, 20.8), (5.2, 7.6), (2.7, 7.9)];
fn partial(table: usize, col: usize, h: usize) -> (f32, f32) {
let hf = h as f32;
let c = col as f32 / (COLS - 1) as f32;
match table {
0 => {
let even = if h % 2 == 0 { 1.0 - c } else { 1.0 };
(even / hf, 0.0)
}
1 => {
let d = 0.5 - 0.45 * c;
let a = 2.0 * m::sin(core::f32::consts::PI * hf * d) / (core::f32::consts::PI * hf);
(a, (0.25 - hf * d / 2.0).rem_euclid(1.0))
}
2 => {
let t = c * (VOWELS.len() - 1) as f32;
let i = (t as usize).min(VOWELS.len() - 2);
let f = t - i as f32;
let f1 = VOWELS[i].0 + (VOWELS[i + 1].0 - VOWELS[i].0) * f;
let f2 = VOWELS[i].1 + (VOWELS[i + 1].1 - VOWELS[i].1) * f;
let g = |center: f32| {
let w = 1.5 + 0.1 * center;
m::exp(-((hf - center) / w).powi(2))
};
let shape = 0.15 + g(f1) + 0.7 * g(f2);
(shape / m::powf(hf, 0.9), 0.0)
}
3 => {
let spacing = 2.0 + 6.0 * c;
let comb = 0.25 + 0.75 * m::cos(core::f32::consts::PI * hf / spacing).abs();
(comb / m::powf(hf, 0.7), 0.0)
}
4 => {
let key = (h as u32) * 131 + (col as u32) * 977 + 31;
let u = unit(key);
((0.2 + 0.8 * u * u) / hf.sqrt(), unit(key ^ 0xA5A5))
}
5 => {
const BARS: [usize; 8] = [1, 2, 3, 4, 6, 8, 10, 12];
const FLUTE: [f32; 8] = [1.0, 0.4, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0];
const FULL: [f32; 8] = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3];
let a = BARS
.iter()
.position(|&b| b == h)
.map_or(0.0, |i| FLUTE[i] + (FULL[i] - FLUTE[i]) * c);
(a, 0.0)
}
6 => {
let center = 2.0 + 20.0 * c;
let peak = m::exp(-((hf - center) / 3.0).powi(2));
(peak / m::powf(hf, 0.2) + 0.3 / hf, 0.0)
}
_ => {
let index = 0.5 + 6.0 * c as f64;
let a = bessel(h - 1, index) as f32;
(a / m::powf(hf, 0.1), 0.0)
}
}
}
pub(super) struct Wavetables {
data: Vec<f32>,
}
impl Wavetables {
fn index(table: usize, col: usize, mip: usize) -> usize {
((table * COLS + col) * MIPS + mip) * SIZE
}
fn build() -> Self {
let sine: Vec<f32> = (0..SIZE)
.map(|i| m::sin(core::f32::consts::TAU * i as f32 / SIZE as f32))
.collect();
let mut data = vec![0.0f32; TABLES * COLS * MIPS * SIZE];
let mut acc = vec![[0.0f32; COLS]; SIZE];
for table in 0..TABLES {
acc.fill([0.0; COLS]);
let mut h = 1;
for mip in (0..MIPS).rev() {
let top = max_harmonic(mip);
Self::add_harmonics(&mut acc, &sine, table, h..=top);
h = top + 1;
for col in 0..COLS {
let at = Self::index(table, col, mip);
for (n, row) in acc.iter().enumerate() {
data[at + n] = row[col];
}
}
}
for col in 0..COLS {
let first = Self::index(table, col, 0);
let peak = data[first..first + MIPS * SIZE]
.iter()
.fold(0.0f32, |a, &b| a.max(b.abs()));
if peak > 1e-6 {
let k = 0.9 / peak;
for v in &mut data[first..first + MIPS * SIZE] {
*v *= k;
}
}
}
}
Wavetables { data }
}
fn add_harmonics(
acc: &mut [[f32; COLS]],
sine: &[f32],
table: usize,
hs_range: core::ops::RangeInclusive<usize>,
) {
let (mut hs, mut amps, mut offs) = (Vec::new(), Vec::new(), Vec::new());
for h in hs_range {
let mut a = [0.0f32; COLS];
let mut off = [0usize; COLS];
for col in 0..COLS {
let (amp, phase) = partial(table, col, h);
a[col] = amp;
off[col] = (phase * SIZE as f32) as usize % SIZE;
}
if a.iter().any(|&x| x != 0.0) {
hs.push(h);
amps.push(a);
offs.push(off);
}
}
let uniform = amps
.iter()
.zip(&offs)
.all(|(a, off)| (0..COLS).all(|c| a[c] == 0.0 || off[c] == 0));
if uniform {
for (g, rows) in acc.chunks_exact_mut(UNIFORM_LANES).enumerate() {
let mut r: [[f32; COLS]; UNIFORM_LANES] = core::array::from_fn(|k| rows[k]);
for (&h, a) in hs.iter().zip(&s) {
for (k, rk) in r.iter_mut().enumerate() {
let s = sine[(h * (g * UNIFORM_LANES + k)) % SIZE];
for c in 0..COLS {
rk[c] += a[c] * s;
}
}
}
rows.copy_from_slice(&r);
}
} else {
for c in 0..COLS {
let terms: Vec<(usize, f32, usize)> = (0..hs.len())
.filter(|&i| amps[i][c] != 0.0)
.map(|i| (hs[i], amps[i][c], offs[i][c]))
.collect();
for (g, rows) in acc.chunks_exact_mut(DIGITAL_LANES).enumerate() {
let mut r: [f32; DIGITAL_LANES] = core::array::from_fn(|k| rows[k][c]);
for &(h, a, off) in &terms {
for (k, rk) in r.iter_mut().enumerate() {
*rk += a * sine[(h * (g * DIGITAL_LANES + k) + off) % SIZE];
}
}
for (row, v) in rows.iter_mut().zip(r) {
row[c] = v;
}
}
}
}
}
pub(super) fn mip_for(dt: f32) -> usize {
let allowed = (0.5 / dt.max(1e-6)) as usize;
(0..MIPS)
.find(|&k| max_harmonic(k) <= allowed)
.unwrap_or(MIPS - 1)
}
pub(super) fn read(&self, table: usize, pos: f32, mip: usize, phase: f32) -> f32 {
let pos = pos.clamp(0.0, (COLS - 1) as f32);
let c0 = (pos as usize).min(COLS - 1);
let c1 = (c0 + 1).min(COLS - 1);
let cf = pos - c0 as f32;
let at = phase.rem_euclid(1.0) * SIZE as f32;
let i = (at as usize).min(SIZE - 1);
let f = at - i as f32;
let j = (i + 1) % SIZE;
let col = |c: usize| {
let base = Self::index(table, c, mip);
let a = self.data[base + i];
let b = self.data[base + j];
a + (b - a) * f
};
let a = col(c0);
if cf == 0.0 {
a
} else {
a + (col(c1) - a) * cf
}
}
}
fn sine_table() -> &'static [f32] {
static SINE: OnceLock<Vec<f32>> = OnceLock::new();
SINE.get_or_init(|| {
(0..SIZE)
.map(|i| m::sin(core::f32::consts::TAU * i as f32 / SIZE as f32))
.collect()
})
}
#[derive(Clone)]
pub(super) struct UserWave {
data: Vec<f32>,
}
impl UserWave {
const SETS: usize = 4;
pub(super) fn new() -> Self {
let mut w = UserWave {
data: vec![0.0; Self::SETS * SIZE],
};
let mut sine = [0i8; pikopiko_runtime::WAVE_LEN];
for (n, v) in sine.iter_mut().enumerate() {
*v = (127.0 * m::sin(core::f32::consts::TAU * n as f32 / 32.0)) as i8;
}
w.set(&sine);
w
}
pub(super) fn set(&mut self, wave: &[i8]) {
const N: usize = pikopiko_runtime::WAVE_LEN;
let sine = sine_table();
let mut w = [0.0f32; N];
for (d, &s) in w.iter_mut().zip(wave) {
*d = s as f32;
}
let step = SIZE / N;
let mut ab = [(0.0f32, 0.0f32); N / 2 - 1];
for (h0, c) in ab.iter_mut().enumerate() {
let h = h0 + 1;
let (mut a, mut b) = (0.0f32, 0.0f32);
for (n, &v) in w.iter().enumerate() {
let at = (h * n * step) % SIZE;
a += v * sine[(at + SIZE / 4) % SIZE];
b += v * sine[at];
}
*c = (a * (2.0 / N as f32), b * (2.0 / N as f32));
}
let mut acc = [0.0f32; SIZE];
let mut set = Self::SETS;
for (h0, &(a, b)) in ab.iter().enumerate() {
let h = h0 + 1;
for (i, y) in acc.iter_mut().enumerate() {
let at = (h * i) % SIZE;
*y += a * sine[(at + SIZE / 4) % SIZE] + b * sine[at];
}
if matches!(h, 1 | 3 | 7 | 15) {
set -= 1;
self.data[set * SIZE..(set + 1) * SIZE].copy_from_slice(&acc);
}
}
let peak = self.data[..SIZE]
.iter()
.fold(0.0f32, |a, &b| a.max(b.abs()));
let k = if peak > 1e-6 { 0.9 / peak } else { 0.0 };
for v in &mut self.data {
*v *= k;
}
}
pub(super) fn read(&self, mip: usize, phase: f32) -> f32 {
let set = match mip {
0..=5 => 0,
6 => 1,
7 => 2,
_ => 3,
};
let at = phase.rem_euclid(1.0) * SIZE as f32;
let i = (at as usize).min(SIZE - 1);
let f = at - i as f32;
let base = set * SIZE;
let a = self.data[base + i];
let b = self.data[base + (i + 1) % SIZE];
a + (b - a) * f
}
}
static TABLES_ONCE: OnceLock<Wavetables> = OnceLock::new();
pub(super) fn tables() -> &'static Wavetables {
TABLES_ONCE.get_or_init(Wavetables::build)
}
pub(super) fn built() -> bool {
TABLES_ONCE.get().is_some()
}
pub(super) fn warp(phase: f32, amount: f32) -> f32 {
if amount <= 0.0 {
return phase;
}
let k = amount.min(1.0) * 0.9;
let p = phase + k * m::sin(core::f32::consts::TAU * phase) / core::f32::consts::TAU;
p.rem_euclid(1.0)
}
#[cfg(test)]
mod tests {
use super::*;
impl Wavetables {
fn build_reference() -> Self {
let sine: Vec<f32> = (0..SIZE)
.map(|i| m::sin(core::f32::consts::TAU * i as f32 / SIZE as f32))
.collect();
let mut data = vec![0.0f32; TABLES * COLS * MIPS * SIZE];
let mut acc = vec![0.0f32; SIZE];
for table in 0..TABLES {
for col in 0..COLS {
acc.fill(0.0);
let mut h = 1;
for mip in (0..MIPS).rev() {
let top = max_harmonic(mip);
while h <= top {
let (a, phase) = partial(table, col, h);
if a != 0.0 {
let off = (phase * SIZE as f32) as usize % SIZE;
for (n, v) in acc.iter_mut().enumerate() {
*v += a * sine[(h * n + off) % SIZE];
}
}
h += 1;
}
let at = Self::index(table, col, mip);
data[at..at + SIZE].copy_from_slice(&acc);
}
let first = Self::index(table, col, 0);
let peak = data[first..first + MIPS * SIZE]
.iter()
.fold(0.0f32, |a, &b| a.max(b.abs()));
if peak > 1e-6 {
let k = 0.9 / peak;
for v in &mut data[first..first + MIPS * SIZE] {
*v *= k;
}
}
}
}
Wavetables { data }
}
}
#[test]
fn batched_build_matches_per_column_build_bit_for_bit() {
let a = Wavetables::build();
let b = Wavetables::build_reference();
assert_eq!(a.data.len(), b.data.len());
for (i, (x, y)) in a.data.iter().zip(&b.data).enumerate() {
assert_eq!(x.to_bits(), y.to_bits(), "data[{i}]");
}
}
#[test]
fn mip_follows_pitch() {
assert_eq!(Wavetables::mip_for(20.0 / 48_000.0), 0);
assert!(Wavetables::mip_for(100.0 / 48_000.0) <= 2);
assert!(Wavetables::mip_for(2_000.0 / 48_000.0) >= 4);
assert_eq!(Wavetables::mip_for(0.49), MIPS - 1);
}
#[test]
fn every_column_is_finite_and_balanced() {
let t = tables();
for table in 0..TABLES {
for col in 0..COLS {
for mip in 0..MIPS {
let base = Wavetables::index(table, col, mip);
let s = &t.data[base..base + SIZE];
assert!(s.iter().all(|v| v.is_finite()), "{table}/{col}/{mip}");
let peak = s.iter().fold(0.0f32, |a, &b| a.max(b.abs()));
assert!(peak <= 0.9 + 1e-4, "{table}/{col}/{mip} の最大 {peak}");
let mean = s.iter().sum::<f32>() / SIZE as f32;
assert!(mean.abs() < 0.05, "{table}/{col}/{mip} のかたより {mean}");
}
let base = Wavetables::index(table, col, 0);
let peak = t.data[base..base + SIZE]
.iter()
.fold(0.0f32, |a, &b| a.max(b.abs()));
assert!(peak > 0.4, "{table}/{col} が小さすぎる: {peak}");
}
}
}
#[test]
fn columns_differ() {
let t = tables();
for table in 0..TABLES {
let a = Wavetables::index(table, 0, 0);
let b = Wavetables::index(table, COLS - 1, 0);
let diff: f32 = (0..SIZE)
.map(|i| (t.data[a + i] - t.data[b + i]).abs())
.sum();
assert!(diff > 1.0, "表 {table} の最初と最後の列が同じ");
}
}
#[test]
fn read_interpolates_between_columns() {
let t = tables();
let a = t.read(0, 0.0, 0, 0.1);
let b = t.read(0, 1.0, 0, 0.1);
let mid = t.read(0, 0.5, 0, 0.1);
assert!((mid - (a + b) / 2.0).abs() < 1e-5);
}
#[test]
fn warp_keeps_phase_moving_forward() {
let mut last = 0.0;
for i in 1..1000 {
let p = i as f32 / 1000.0;
let w = warp(p, 1.0);
assert!(w > last || (last > 0.9 && w < 0.1), "{p}");
last = w;
}
assert_eq!(warp(0.3, 0.0), 0.3);
}
}