pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! ウェーブテーブル:1 周期の波形を何枚か並べた「表」を、位置(`wt_pos`)で滑らかに混ぜながら読む
//! 発振器の部品。表は式(倍音の振幅)から作り、ファイルは同梱しない。
//!
//! ## なぜこの形か
//!
//! ダブステップのうなり・ヴォーカルのような音・デジタルな音は、波形そのものを時間で動かす音で、
//! フィルターの LFO では作れない。波形を何枚か(列)並べ、2 枚の間を混ぜながら動かす。
//!
//! ## 表の作り方と約束
//!
//! - 表は 8 種類([`TABLES`])で、どれも 8 枚の列([`COLS`])を持つ。列は 1 周期 [`SIZE`] サンプル。
//! - 折り返し雑音(エイリアシング)を避けるため、倍音の数を 1 オクターブごとに減らした波形
//!   ([`MIPS`] 段)を持つ。読むときは、音の高さで倍音がナイキストを超えない段を使う。倍音の
//!   振幅は段によらず同じなので、音の高さを上げても倍音の大きさは変わらず、数だけが減る。
//! - 作るときは、サイン波の表を整数の添字で引いて足すだけにする(三角関数の呼び出しは最初の
//!   サイン波の表だけ)。どの機種でも同じ値になる(`m` だけを使う)。
//! - 表はプロセスで 1 つを共有する([`tables`])。最初に使うときに作るので、音源を作るとき
//!   (`VaSynth::new`)に呼んでおく。`render()` では確保しない。
//! - 列の最大値は、どの段でも 0.9 を超えないようにそろえる(低い段で小さくなるのは、倍音が減るため)。

use crate::synth::va::m;
use std::sync::OnceLock;

/// 1 周期のサンプル数(2 の冪)。
pub(super) const SIZE: usize = 1024;
/// 表の種類の数。
pub(super) const TABLES: usize = 8;
/// 1 つの表の列の数。
pub(super) const COLS: usize = 8;
/// 倍音を減らした段の数。
pub(super) const MIPS: usize = 9;
/// 表を作るとき、足し算の待ち時間を隠すために同時に進めるサンプルの数(位相をそろえた表・
/// 列ごとに位相が違う表。どちらも [`SIZE`] を割り切る数)。
const UNIFORM_LANES: usize = 4;
const DIGITAL_LANES: usize = 8;

/// 段 `k` に入れる最大の倍音の番号(ナイキストの手前)。
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
}

/// 0〜1 の値にした [`hash`]。
fn unit(x: u32) -> f32 {
    (hash(x) >> 8) as f32 / (1u32 << 24) as f32
}

/// 第 1 種ベッセル関数 `J_n(x)`(`x` は小さい範囲、級数。四則演算だけなのでどの機種でも同じ)。
fn bessel(n: usize, x: f64) -> f64 {
    let half = x / 2.0;
    // (x/2)^n / n!
    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
}

/// 母音の 2 つのフォルマントの位置(基本周波数の約 110Hz を基準にした倍音の番号)。
/// 順に a・e・i・o・u。
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)];

/// 表 `table` の列 `col` の、倍音 `h`(1 以上)の(振幅、位相)。位相は、その倍音の周期を 1 と
/// した 0〜1。
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)
        }
        // パルス幅を 50% から 5% まで掃引する
        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))
        }
        // 母音(a → e → i → o → u)
        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))
        }
        // オルガン:ドローバー(1・2・3・4・6・8・10・12 次)を、フルート的な音から全部引いた音まで
        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)
        }
        // FM 風:ベッセル関数の並びを倍音にする(指数を列とともに上げる)
        _ => {
            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)
        }
    }
}

/// 全部の表。`data` は `[表][列][段][SIZE]` の順。
pub(super) struct Wavetables {
    data: Vec<f32>,
}

impl Wavetables {
    fn index(table: usize, col: usize, mip: usize) -> usize {
        ((table * COLS + col) * MIPS + mip) * SIZE
    }

    /// 全部の表を作る。8 つの列(振幅だけが違う)をまとめて足す:サイン波の表を引く添字は列によらない
    /// (位相をずらす表を除く)ので、1 回引いて 8 列に使い、足し算も 8 列を並べて行う(SIMD にできる)。
    /// 各列の値は、足す順(倍音の小さい順)も、1 回ごとの乗算と加算(融合しない)も、列ごとに別々に
    /// 作っていたときと同じ。
    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];
        // `[サンプル][列]`:同じサンプルの 8 列を隣に置く
        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 {
                // 列のどの段でも一番大きい値を 0.9 にそろえる(段ごとにそろえない。段ごとにそろえると、
                // 倍音が減っただけの高い音が大きくなってしまう)
                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 }
    }

    /// 倍音 `hs`(小さい順)を、表 `table` の 8 列に足す。
    ///
    /// サンプルごとに、8 列の途中の和をレジスタに持ったまま、倍音を小さい順に足していく(各列・各
    /// サンプルへ足す順は、倍音の小さい順で、倍音ごとに足していたときと同じ)。振幅が 0 の列には
    /// `+0.0` か `-0.0` を足すだけで和は変わらないので、列を分けずに足しても同じ値になる。
    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 {
            // 位相をずらさない表:サイン波の表を引く添字は列によらない。足し算の待ち時間を隠すため、
            // 4 サンプルを同時に進める(サンプルごとの足す順は変わらない)
            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(&amps) {
                    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 {
            // 位相が列ごとに違う表(デジタル):列ごとに、振幅が 0 でない倍音だけ別の添字で引く
            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;
                    }
                }
            }
        }
    }

    /// 音の 1 周期あたりの進み `dt`(周期/サンプル)で折り返しが出ない段。
    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)
    }

    /// 表 `table`・列の位置 `pos`(0〜`COLS - 1` の小数)・段 `mip` の、位相 `phase`(0〜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
        }
    }
}

/// 1 周期 [`SIZE`] 点のサイン波の表(`@wave` の波形を倍音に分けて組み直すのに使う。最初に使うとき
/// (`UserWave::new`、`VaSynth` を作るとき)に作るので、`set_wave` では確保しない)。
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()
    })
}

/// `@wave` で書いた波形(トラックごとの 1 枚)。`@13` の表の番号 [`TABLES`](`%wt=8`)で鳴らす。
///
/// 何のためにあるか:32 個の符号つき 8 ビットの波形メモリ(`Synth::set_wave`)を、ほかの音源と同じ
/// 書き方でシンセの発振器に使えるようにする。32 点の波形は最大 15 次の倍音だけで表せるので、
/// 離散フーリエ変換で倍音(直流を除く)に分けて 1 周期 [`SIZE`] 点に組み直す。こうすると補間の
/// 折り返し雑音がなく、高い音で倍音を間引く段([`MIPS`])も同じ考え方でそろえられる
/// (倍音が 15・7・3・1 次までの 4 枚。段 0〜5 は 15 次まで)。
///
/// 約束:`set` は確保しない(枠は `new` で用意する)。サイン波の表の添字は整数だけで決まるので、
/// どの機種でも同じ値になる。最大値は 0.9 にそろえる(ほかの表と同じ)。最初は純粋なサイン波。
#[derive(Clone)]
pub(super) struct UserWave {
    /// `[4 枚][SIZE]`:倍音が 15・7・3・1 次までの波形。
    data: Vec<f32>,
}

impl UserWave {
    /// 倍音の上限が 15・7・3・1 のときの枚数。
    const SETS: usize = 4;

    pub(super) fn new() -> Self {
        let mut w = UserWave {
            data: vec![0.0; Self::SETS * SIZE],
        };
        // 最初はサイン波(0 を中心に 1 周期を 32 点で刻む)
        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
    }

    /// 波形を書き換える(`Synth::set_wave` と同じ約束:短ければ残りは 0、長ければ先頭だけ)。
    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;
        }
        // 1〜15 次の倍音の係数(余弦・正弦)。位相は 1024 点の表の添字で引く
        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));
        }
        // 倍音を小さい順に足し、1・3・7・15 次まで足したところで写す
        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);
            }
        }
        // 15 次までの波形の最大値を 0.9 にそろえる(4 枚とも同じ倍率)
        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;
        }
    }

    /// 段 `mip`([`Wavetables::mip_for`])・位相 `phase`(0〜1)の値。サンプルの間は直線で混ぜる。
    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();

/// 共有の表(最初に呼んだときに作る)。使う曲だけが、再生の前に作っておく(`Synth::prepare_tone`)。
pub(super) fn tables() -> &'static Wavetables {
    TABLES_ONCE.get_or_init(Wavetables::build)
}

/// 表をもう作ったか。
pub(super) fn built() -> bool {
    TABLES_ONCE.get().is_some()
}

/// 位相のゆがみ(`wt_warp`、0〜1):位相を、サイン波の分だけ前後にずらして倍音を増やす。
/// ずらす量が 1 未満なので、位相はいつも増える向きに進む(途中で戻らない)。
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 {
        /// 表を列ごとに 1 本ずつ作る元の書き方(まとめて足す書き方と同じ値になることの基準)。
        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);
                    }
                    // 列のどの段でも一番大きい値を 0.9 にそろえる(段ごとにそろえない。段ごとにそろえると、
                    // 倍音が減っただけの高い音が大きくなってしまう)
                    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);
    }
}