rumpl 0.3.0

Sample-free General MIDI player and renderer
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! Modal model of a struck piano string.
//!
//! A piano note is the sum of a string's vibration modes (partials). Each mode
//! is a damped sinusoid, so the whole note is a bank of decaying complex
//! rotors: `z ← z·c` with `c = r·e^{iω}` per sample, and the output is the sum
//! of the imaginary parts. What makes it sound like a piano rather than an
//! organ is how those rotors are set up at note-on:
//!
//! - **Inharmonicity.** A stiff string's partials are stretched sharp:
//!   `fₙ = n·f₀·√(1 + B·n²)`, with `B` rising towards the treble. This gives the
//!   characteristic metallic "bloom", especially in the bass.
//! - **Unisons.** Most notes have two or three strings tuned a fraction of a
//!   cent apart, so every partial beats slowly.
//! - **Two-stage decay.** Coupling between the unison strings and the bridge
//!   makes the sound die away quickly at first (prompt sound, ~20 dB/s at
//!   middle C, doubling every two octaves up) and then ring on quietly for much
//!   longer (aftersound, around -30 dB; louder in the bass). Each partial gets
//!   one extra slowly decaying rotor for the aftersound.
//! - **Frequency-dependent losses.** Higher partials decay somewhat faster than
//!   the fundamental.
//! - **The hammer.** Partial amplitudes fall steeply as `n^-1.15`, and the felt
//!   acts as a low-pass (~-22 dB/oct) above a corner near 2.4 kHz at mf that
//!   rises almost in proportion to hammer speed: soft notes are mellow, loud
//!   notes bright. This steep, dark spectrum is what keeps a piano round; a
//!   flatter one full of strong upper partials sounds plucked or buzzy. The
//!   strings speak within ~2 ms from the middle up and ease in along an S-curve
//!   over ~8 ms in the low bass, and hard felt on steel gives the upper
//!   partials a brief extra burst that dies within ~50 ms. Each partial starts at a fixed random phase
//!   (the soundboard scrambles them); in-phase partials would add up to a
//!   buzzy click once per period. The striking point (about 1/8 of the string) shallowly weakens
//!   partials near multiples of 8, and band-passed noise adds the hammer's
//!   contact noise.
//! - **Soundboard.** The bridge and soundboard pass partials on with an
//!   irregular frequency response (peaks and dips of several dB, fixed per
//!   instrument) and radiate poorly below ~85 Hz, so bass notes get their
//!   pitch from their upper partials. The hammer blow also knocks the
//!   soundboard and frame: a bank of fixed, quickly decaying body modes
//!   (centred about 0.7× the note's pitch, as measured) with scattered phases, faded in over a few
//!   milliseconds, gives the attack a soft wooden thud rather than a click (an
//!   impulsive attack is what makes a string model sound plucked).
//!
//! - **Dampers.** Releasing the key drops the felt damper on the strings, which
//!   stops every partial at one rate. The top keys of a real piano have no dampers
//!   and simply ring out.
//! - **Stretch tuning.** Octaves are tuned slightly wide to match the stretched
//!   partials (Railsback curve): the bass is a little flat, the treble sharp.
//!
//! Spectrum, decay, aftersound and attack were fitted to 182 dry recorded notes
//! of a Yamaha grand (every few keys, three dynamics), used for analysis only.

use crate::synth::filter::{FilterMode, Svf};
use crate::synth::patches::PianoSpec;

/// Rotors are processed in fixed-width lanes so the inner loop vectorizes.
const LANES: usize = 8;
/// Upper bound on partials per string (reached only in the bass).
const MAX_PARTIALS: usize = 90;
/// Highest partial frequency worth synthesizing.
const MAX_PARTIAL_HZ: f32 = 14_000.0;
/// Rotors quieter than this (relative to the note's initial level) are dropped.
const CULL_LEVEL: f32 = 2e-5;
/// Keys above this have no dampers (as on most grand pianos).
const HIGHEST_DAMPED_KEY: u8 = 88;

// Spectral envelope of the struck string, fitted to 182 recorded notes of a
// grand piano (61 keys × soft/medium/hard): partial amplitude falls as
// n^-TILT, and a felt low-pass (FELT_ORDER, in units of a one-pole's -6 dB/oct)
// sets in above a corner that rises almost linearly with hammer speed. The
// steep tilt is what keeps a piano "pure"; a flatter spectrum full of strong
// upper partials is what makes a string model sound plucked or buzzy.
const TILT: f32 = 1.15;
const FELT_CORNER_MF: f32 = 2_400.0;
const FELT_SPEED_EXP: f32 = 0.96;
const FELT_ORDER: f32 = 3.7;
/// Bass radiation cut-off: the soundboard barely radiates the fundamentals of
/// the lowest octave (measured 25–40 dB below their 2nd–3rd partials).
const BASS_CUT_HZ: f32 = 85.0;
const BASS_CUT_ORDER: i32 = 6;
const COMB_FLOOR: f32 = 0.8;
/// Hammer knock: centre (× note pitch), width (octaves, 1σ) and level.
const KNOCK_CENTRE: f32 = 0.7;
const KNOCK_WIDTH_OCT: f32 = 0.9;
const KNOCK_LEVEL: f32 = 0.25;
/// Strike transient: level (× partial amplitude at 2 kHz, mf) and decay (dB/s).
const STRIKE_GAIN: f32 = 1.0;
const STRIKE_RATE: f32 = 250.0;
/// Per-partial level scatter (± dB, uniform) around the smooth envelope.
const PARTIAL_SCATTER_DB: f32 = 5.0;
/// Per-rotor frequency scatter (± Hz) that sets each partial's beat rate.
const BEAT_HZ: f32 = 0.45;
/// Per-rotor decay-rate scatter (± fraction).
const DECAY_SCATTER: f32 = 0.3;
/// Onset time of the soundboard knock (it builds up; it is not a click).
const BODY_ONSET: f32 = 0.005;

#[derive(Clone, Debug, Default)]
struct RotorBlock {
  re: [f32; LANES],
  im: [f32; LANES],
  cr: [f32; LANES],
  ci: [f32; LANES],
  /// Partial frequency in Hz, used to derive damper losses at note-off.
  freq: [f32; LANES],
}

#[derive(Clone, Debug)]
pub struct Piano {
  /// String partials (prompt sound and aftersound).
  blocks: Vec<RotorBlock>,
  /// Soundboard/frame knock modes; not damped, faded in with `body_ramp`.
  body: Vec<RotorBlock>,
  /// Onset envelopes (approach 1). Strings: two cascaded one-pole stages, an
  /// S-shaped onset. Body and hammer noise: one stage over `BODY_ONSET`.
  string_ramp: [f32; 2],
  string_ramp_k: f32,
  body_ramp: f32,
  body_ramp_k: f32,
  sr: f32,
  key: u8,
  damper_time: f32,
  damped: bool,
  // Hammer / action noise.
  thump: Svf,
  thump_env: f32,
  thump_coef: f32,
  rng: u32,
  /// Sum of rotor magnitudes at the last cull, for idle detection.
  level: f32,
  /// Pitch factor the string rotors are currently tuned to, relative to the
  /// tuning at note-on.
  bend: f32,
}

impl Piano {
  /// Build the rotor bank for `key` struck at `velocity` (0..1, already through
  /// the synth's velocity curve). `tuning_semitones` is added to the key's
  /// pitch (pitch bend at note-on).
  pub fn new(
    spec: &PianoSpec,
    key: u8,
    velocity: f32,
    tuning_semitones: f32,
    sr: f32,
  ) -> Self {
    let k = key as f32;
    // Undo the squared velocity curve: hammer speed drives timbre linearly.
    let hammer_speed = velocity.clamp(0.0, 1.0).sqrt();

    let b = inharmonicity(k);
    let target = 440.0
      * 2f32
        .powf((k + tuning_semitones - 69.0) / 12.0 + stretch_cents(k) / 1200.0);
    // Choose f₀ so that the first (stretched) partial lands on the target.
    let f0 = target / (1.0 + b).sqrt();

    let strings = unison_count(key);
    let detunes = unison_detunes(key, strings, spec.unison_cents);

    // Prompt-sound decay rate in dB/s, measured on recorded notes: ~9 dB/s in
    // the low bass, ~22 at middle C, ~55 at G#6 — doubling every two octaves.
    // `spec.decay` is the resulting T60 at middle C.
    let t60_fund =
      (spec.decay * 2f32.powf(-(k - 60.0) / 24.0)).clamp(0.25, 40.0);
    let rate_fund = 60.0 / t60_fund;

    // Felt low-pass corner: rises with hammer speed and patch brightness.
    const MF_SPEED: f32 = 80.0 / 127.0;
    let speed_ratio = hammer_speed.max(0.05) / MF_SPEED;
    let corner = spec.brightness.max(0.1)
      * FELT_CORNER_MF
      * speed_ratio.powf(FELT_SPEED_EXP);
    let beta = spec.strike_pos.clamp(0.02, 0.5);

    let nyq = (sr * 0.45).min(MAX_PARTIAL_HZ);
    let mut partials: Vec<(f32, f32, f32)> = Vec::new(); // (freq, amp, rate dB/s)
    for n in 1..=MAX_PARTIALS {
      let nf = n as f32;
      let f = nf * f0 * (1.0 + b * nf * nf).sqrt();
      if f >= nyq {
        break;
      }
      // Spectral tilt × felt low-pass × shallow strike-position comb (a real
      // hammer is several cm wide) × soundboard response.
      let felt = (1.0 + (f / corner).powi(2)).powf(-0.5 * FELT_ORDER);
      let comb = COMB_FLOOR
        + (1.0 - COMB_FLOOR) * (nf * std::f32::consts::PI * beta).sin().abs();
      let amp = nf.powf(-TILT) * felt * comb * soundboard_gain(f);
      // Losses grow with frequency (air and internal friction ~f, bridge and
      // soundboard ~f²), but only gently: a piano note keeps its colour while
      // it sustains. Steep high-frequency losses give the bright-then-dull
      // sweep of a plucked string.
      let khz = f / 1000.0;
      let rate = rate_fund + 0.3 * khz + 0.25 * khz * khz;
      partials.push((f, amp, rate));
    }

    // Normalize so loudness doesn't depend on how many partials fit, then
    // let the treble fall off as on a real instrument.
    let norm = partials
      .iter()
      .map(|p| p.1 * p.1)
      .sum::<f32>()
      .sqrt()
      .max(1e-6);
    let key_level = db_to_lin(-9.0 * ((k - 72.0).max(0.0) / 24.0).powi(2));

    // Share of each partial carried by the slow aftersound.
    // Measured: notes fall quickly for about a second, then level off into a
    // tail that fades only slowly — around -30 dB in the middle, rising to
    // about -15 dB in the low bass and sinking to -38 dB in the top octaves.
    let aftersound = db_to_lin(
      -30.0 + 15.0 * ((52.0 - k) / 24.0).clamp(0.0, 1.0)
        - 8.0 * ((k - 76.0) / 20.0).clamp(0.0, 1.0),
    );
    const AFTERSOUND_SLOWDOWN: f32 = 20.0;

    // (freq, amp, rate dB/s, dampable)
    //
    // Measured on recorded notes, what makes the partials sound alive rather
    // than synthetic is that each one moves differently: neighbouring partials
    // differ by several dB, every partial beats at its own rate (two or more
    // components 0.1–1 Hz apart, from mistuned unisons and the two
    // polarizations of each string coupling through the bridge) and decays at
    // its own rate. All of it is seeded by key and partial, so it is
    // deterministic and fixed per key, like a real instrument.
    let seed = |n: usize, salt: u32| lattice(key as i32 * 256 + n as i32, salt);
    // A single bass string still beats against itself (polarizations).
    let voices = strings.max(2);
    let mut rotors: Vec<(f32, f32, f32, bool)> = Vec::new();
    // Starting phase of each rotor. The soundboard is a dense resonant system,
    // so it shifts every partial's phase essentially at random. With all
    // partials in phase the waveform is a click once per period — a buzzy,
    // plucked attack, most audible in the bass where periods are long.
    let mut phases: Vec<f32> = Vec::new();
    for (n, &(f, amp, rate)) in partials.iter().enumerate() {
      let phase = std::f32::consts::PI * seed(n, 0x3C6E_F372);
      let a = amp / norm
        * key_level
        * db_to_lin(PARTIAL_SCATTER_DB * seed(n, 0x1B87_3593));
      let weights: Vec<f32> = (0..voices)
        .map(|s| 0.55 + 0.45 * seed(n * 8 + s, 0x68E3_1DA4))
        .collect();
      let wsum: f32 = weights.iter().sum();
      for (s, w) in weights.iter().enumerate() {
        let cents_off = detunes.get(s).copied().unwrap_or(0.0);
        let hz_off = BEAT_HZ * seed(n * 8 + s, 0x5BD1_E995);
        let r = rate * (1.0 + DECAY_SCATTER * seed(n * 8 + s, 0x27D4_EB2F));
        rotors.push((
          f * cents(cents_off) + hz_off,
          a * (1.0 - aftersound) * w / wsum,
          r,
          true,
        ));
        phases.push(phase);
      }
      // The aftersound sits near the mean pitch of the unison, slightly offset
      // so it beats gently against the prompt sound.
      rotors.push((
        f * cents(0.15 * spec.unison_cents)
          + 0.5 * BEAT_HZ * seed(n, 0x1656_67B1),
        a * aftersound,
        rate / AFTERSOUND_SLOWDOWN,
        true,
      ));
      phases.push(phase);
      // Strike transient: hard felt on steel gives the upper partials a brief
      // extra burst that dies within ~50 ms; stronger for harder blows.
      let strike = STRIKE_GAIN * (f / 2_000.0).sqrt().min(1.5) * speed_ratio;
      rotors.push((f, a * strike, STRIKE_RATE, true));
      phases.push(phase);
    }

    // The string onset ramp fades them in, so the non-zero starting
    // output doesn't click.
    let blocks = pack(&rotors, sr, |i| phases[i]);

    // The hammer blow also knocks the soundboard and frame, whose low wooden
    // modes ring briefly underneath the attack. Their phases are scattered so
    // they sum to a soft thud rather than an impulse, and they fade in over
    // `BODY_ONSET`. Harder blows knock relatively harder.
    let knock =
      KNOCK_LEVEL * spec.body * key_level * (0.6 + 0.6 * hammer_speed);
    let body_rotors: Vec<(f32, f32, f32, bool)> = BODY_MODES
      .iter()
      .filter(|m| m.0 < nyq)
      .map(|&(f, a, t60)| {
        // Measured: the knock's energy is centred an octave or so around the
        // note's own pitch (≈125 Hz for G2, 250 Hz for G4, 500–1000 Hz for G5).
        let oct = (f / (KNOCK_CENTRE * target)).log2() / KNOCK_WIDTH_OCT;
        let bell = (-0.5 * oct * oct).exp();
        // In the treble the knock is about as loud as the strings and rings
        // on (the undamped top strings resonate with it).
        let treble = ((k - 82.0) / 10.0).clamp(0.0, 1.0);
        (
          f,
          a * knock * bell * db_to_lin(15.0 * treble),
          60.0 / (t60 * (1.0 + 4.0 * treble)),
          false,
        )
      })
      .collect();
    let body = pack(&body_rotors, sr, |i| {
      std::f32::consts::PI * lattice(i as i32 + key as i32 * 64, 0x7F4A_7C15)
    });

    let thump_freq = (target * 1.5).clamp(150.0, 2_500.0);
    let thump_t = 0.012 + 0.02 * (1.0 - (k - 21.0) / 87.0).clamp(0.0, 1.0);

    let ramp_k = |tau: f32| 1.0 - (-1.0 / (tau.max(1e-4) * sr)).exp();
    Self {
      blocks,
      body,
      string_ramp: [0.0; 2],
      // Measured per partial: from the middle up the strings reach their
      // decay line within 5–10 ms of the blow; the bass eases in along an
      // S-curve. (A single one-pole stage is steepest at its first
      // sample, which sounds like a hard edge even when slow.)
      string_ramp_k: ramp_k(
        0.0007 + 0.0025 * ((48.0 - k) / 27.0).clamp(0.0, 1.0),
      ),
      body_ramp: 0.0,
      body_ramp_k: ramp_k(BODY_ONSET),
      sr,
      key,
      damper_time: (spec.damper * 2f32.powf(-(k - 60.0) / 36.0))
        .clamp(0.08, 1.5),
      damped: false,
      thump: Svf::new(FilterMode::Band, sr, thump_freq, 0.8),
      thump_env: spec.hammer * 0.1 * hammer_speed * hammer_speed * key_level,
      thump_coef: db_per_sample(60.0 / thump_t, sr),
      rng: 0x2545_F491 ^ (key as u32).wrapping_mul(0x9E37_79B9),
      level: 1.0,
      bend: 1.0,
    }
  }

  /// Retune the strings to `ratio` × their note-on pitch (live pitch bend).
  /// Each string rotor is turned by the change in its angular step, which
  /// keeps its magnitude (decay and damper state) untouched. The soundboard
  /// knock is a property of the instrument and is not bent. Call once per
  /// render block.
  pub fn set_bend(&mut self, ratio: f32) {
    let delta = ratio - self.bend;
    if delta.abs() < 1e-6 {
      return;
    }
    self.bend = ratio;
    let k = std::f32::consts::TAU / self.sr * delta;
    for blk in &mut self.blocks {
      for j in 0..LANES {
        if blk.freq[j] <= 0.0 {
          continue;
        }
        let (s, c) = (k * blk.freq[j]).sin_cos();
        let (cr, ci) = (blk.cr[j], blk.ci[j]);
        blk.cr[j] = cr * c - ci * s;
        blk.ci[j] = cr * s + ci * c;
      }
    }
  }

  /// Drop the dampers onto the strings (key released, sustain pedal up).
  pub fn damp(&mut self) {
    if self.damped || self.key > HIGHEST_DAMPED_KEY {
      return;
    }
    self.damped = true;
    let base_rate = 60.0 / self.damper_time;
    for blk in &mut self.blocks {
      for j in 0..LANES {
        if blk.freq[j] <= 0.0 {
          continue; // body mode or empty lane
        }
        // The felt stops the whole string at once, so the note ends evenly
        // rather than darkening into a ringing tail.
        let d = db_per_sample(base_rate, self.sr);
        blk.cr[j] *= d;
        blk.ci[j] *= d;
      }
    }
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    let [r1, r2] = &mut self.string_ramp;
    *r1 += (1.0 - *r1) * self.string_ramp_k;
    *r2 += (*r1 - *r2) * self.string_ramp_k;
    self.body_ramp += (1.0 - self.body_ramp) * self.body_ramp_k;
    let strings = step_blocks(&mut self.blocks);
    let mut knock = step_blocks(&mut self.body);
    if self.thump_env > 1e-6 {
      self.rng = self.rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
      let white = (self.rng >> 8) as f32 / 8_388_608.0 - 1.0;
      knock += self.thump.tick(white) * self.thump_env;
      self.thump_env *= self.thump_coef;
    }
    strings * self.string_ramp[1] + knock * self.body_ramp
  }

  /// Drop inaudible rotors and repack the rest. Call once per render block.
  pub fn cull(&mut self) {
    self.level = cull_blocks(&mut self.blocks)
      + cull_blocks(&mut self.body)
      + self.thump_env;
  }

  pub fn is_silent(&self) -> bool {
    self.level < 1e-4
  }

  /// Stereo position of the key, -1 (bass, left) .. 1 (treble, right), as
  /// heard from the player's seat.
  pub fn key_pan(&self) -> f32 {
    ((self.key as f32 - 64.0) / 44.0).clamp(-1.0, 1.0)
  }
}

/// Advance every rotor one sample and return the summed output.
#[inline]
// Indexing all lane arrays with one counter keeps the loop trivially
// vectorizable; iterator zips over five arrays obscure that.
#[allow(clippy::needless_range_loop)]
fn step_blocks(blocks: &mut [RotorBlock]) -> f32 {
  let mut acc = [0.0f32; LANES];
  for blk in blocks {
    for j in 0..LANES {
      let (r, i) = (blk.re[j], blk.im[j]);
      blk.re[j] = r * blk.cr[j] - i * blk.ci[j];
      blk.im[j] = r * blk.ci[j] + i * blk.cr[j];
      acc[j] += blk.im[j];
    }
  }
  acc.iter().sum()
}

/// Build rotor blocks from `(freq, amp, rate dB/s, dampable)`, starting rotor
/// `i` at phase `phase(i)`. Non-dampable rotors get a negative frequency tag.
fn pack(
  rotors: &[(f32, f32, f32, bool)],
  sr: f32,
  phase: impl Fn(usize) -> f32,
) -> Vec<RotorBlock> {
  let mut blocks = Vec::with_capacity(rotors.len().div_ceil(LANES));
  for (c, chunk) in rotors.chunks(LANES).enumerate() {
    let mut blk = RotorBlock::default();
    for (j, &(f, a, rate, dampable)) in chunk.iter().enumerate() {
      let w = std::f32::consts::TAU * f / sr;
      let r = db_per_sample(rate, sr);
      let ph = phase(c * LANES + j);
      blk.re[j] = a * ph.cos();
      blk.im[j] = a * ph.sin();
      blk.cr[j] = r * w.cos();
      blk.ci[j] = r * w.sin();
      blk.freq[j] = if dampable { f } else { -f };
    }
    blocks.push(blk);
  }
  blocks
}

/// Drop rotors below `CULL_LEVEL`, repack, and return the summed magnitude.
fn cull_blocks(blocks: &mut Vec<RotorBlock>) -> f32 {
  let mut live: Vec<(f32, f32, f32, f32, f32)> = Vec::new();
  let mut level = 0.0;
  let mut dropped = false;
  for blk in blocks.iter() {
    for j in 0..LANES {
      let mag = (blk.re[j] * blk.re[j] + blk.im[j] * blk.im[j]).sqrt();
      if mag > CULL_LEVEL {
        level += mag;
        live.push((blk.re[j], blk.im[j], blk.cr[j], blk.ci[j], blk.freq[j]));
      } else if blk.freq[j] != 0.0 {
        dropped = true;
      }
    }
  }
  if dropped {
    blocks.clear();
    for chunk in live.chunks(LANES) {
      let mut blk = RotorBlock::default();
      for (j, &(re, im, cr, ci, f)) in chunk.iter().enumerate() {
        blk.re[j] = re;
        blk.im[j] = im;
        blk.cr[j] = cr;
        blk.ci[j] = ci;
        blk.freq[j] = f;
      }
      blocks.push(blk);
    }
  }
  level
}

/// Inharmonicity coefficient `B` across the keyboard, fitted to a recorded
/// concert grand: ~4e-5 at A1 (long wound bass strings), ~3e-4 at middle C,
/// ~6e-3 at C7.
fn inharmonicity(key: f32) -> f32 {
  3.2e-4 * 2f32.powf(1.45 * (key - 60.0) / 12.0)
}

/// Soundboard and bridge transfer function: a weak radiator below ~60 Hz,
/// and an irregular response elsewhere — peaks and dips of several dB that make
/// neighbouring partials (and neighbouring notes) differ the way they do on a
/// real instrument instead of falling off smoothly. The ripple is fixed per
/// instrument (deterministic in frequency), as a soundboard's is.
fn soundboard_gain(f: f32) -> f32 {
  let r = (f / BASS_CUT_HZ).powi(BASS_CUT_ORDER);
  let highpass = (r / (1.0 + r)).sqrt();
  let oct = (f.max(20.0) / 20.0).log2();
  let ripple_db = 4.0 * value_noise(oct * 10.0, 0x51ED_270B)
    + 2.0 * value_noise(oct * 3.0, 0x2C1B_3C6D);
  highpass * db_to_lin(ripple_db)
}

/// Smooth deterministic noise in -1..1 with unit lattice spacing.
fn value_noise(x: f32, seed: u32) -> f32 {
  let i = x.floor();
  let t = x - i;
  let t = t * t * (3.0 - 2.0 * t);
  let a = lattice(i as i32, seed);
  let b = lattice(i as i32 + 1, seed);
  a + (b - a) * t
}

fn lattice(i: i32, seed: u32) -> f32 {
  let mut h = (i as u32).wrapping_mul(0x9E37_79B9) ^ seed;
  h ^= h >> 15;
  h = h.wrapping_mul(0x2C1B_3C6D);
  h ^= h >> 12;
  h = h.wrapping_mul(0x297A_2D39);
  h ^= h >> 15;
  (h & 0xFFFF) as f32 / 32_767.5 - 1.0
}

/// Soundboard/frame modes knocked by the hammer: (frequency Hz, amplitude,
/// T60 s). Six per octave from 45 Hz to ~6 kHz, slightly jittered, with ±3 dB
/// level scatter; `Piano::new` weights them around the note's pitch. Low modes
/// ring longest.
static BODY_MODES: std::sync::LazyLock<Vec<(f32, f32, f32)>> =
  std::sync::LazyLock::new(|| {
    (0..42)
      .map(|i| {
        let jitter = lattice(i, 0x68E3_1DA4) / 12.0;
        let f = 45.0 * 2f32.powf(i as f32 / 6.0 + jitter);
        let db = 3.0 * lattice(i, 0x1B87_3593);
        let t60 = (0.3 * (f / 100.0).powf(-0.5)).clamp(0.05, 0.3);
        (f, db_to_lin(db), t60)
      })
      .collect()
  });

fn db_to_lin(db: f32) -> f32 {
  10f32.powf(db / 20.0)
}

/// Railsback stretch in cents: bass slightly flat, treble sharp.
fn stretch_cents(key: f32) -> f32 {
  let d = (key - 69.0) / 12.0;
  if d >= 0.0 {
    1.2 * d + 0.5 * d * d * d
  } else {
    2.0 * d + 0.3 * d * d * d
  }
}

/// Number of strings per key: one in the lowest bass, two in the upper bass,
/// three from the tenor up.
fn unison_count(key: u8) -> usize {
  match key {
    0..=31 => 1,
    32..=44 => 2,
    _ => 3,
  }
}

/// Detune (cents) of each unison string. The pattern varies per key so chords
/// don't beat in lockstep; `spread` scales it.
fn unison_detunes(key: u8, strings: usize, spread: f32) -> Vec<f32> {
  let mut h = (key as u32).wrapping_mul(0x9E37_79B9) ^ 0x85EB_CA6B;
  let mut jitter = || {
    h ^= h >> 13;
    h = h.wrapping_mul(0xC2B2_AE35);
    h ^= h >> 16;
    0.6 + 0.8 * (h & 0xFFFF) as f32 / 65_535.0 // 0.6..1.4
  };
  match strings {
    1 => vec![0.0],
    2 => vec![-0.5 * spread * jitter(), 0.5 * spread * jitter()],
    _ => vec![
      -spread * jitter(),
      0.1 * spread * jitter(),
      spread * jitter(),
    ],
  }
}

fn cents(c: f32) -> f32 {
  2f32.powf(c / 1200.0)
}

/// Per-sample magnitude factor for a decay of `rate` dB per second.
fn db_per_sample(rate: f32, sr: f32) -> f32 {
  10f32.powf(-rate / 20.0 / sr)
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::synth::patches::gm_patch;

  const SR: f32 = 44_100.0;

  fn grand() -> PianoSpec {
    gm_patch(0).piano.expect("program 0 is a modelled piano")
  }

  fn render(p: &mut Piano, n: usize) -> Vec<f32> {
    (0..n)
      .map(|i| {
        if i % 512 == 0 {
          p.cull();
        }
        p.tick()
      })
      .collect()
  }

  fn rms(w: &[f32]) -> f32 {
    (w.iter().map(|x| x * x).sum::<f32>() / w.len() as f32).sqrt()
  }

  /// Magnitude of the DFT bin at `f` (Goertzel-style correlation).
  fn tone_level(x: &[f32], f: f32) -> f32 {
    let w = std::f32::consts::TAU * f / SR;
    let (mut s, mut c) = (0.0f64, 0.0f64);
    for (i, v) in x.iter().enumerate() {
      s += (*v * (w * i as f32).sin()) as f64;
      c += (*v * (w * i as f32).cos()) as f64;
    }
    ((s * s + c * c).sqrt() / x.len() as f64) as f32
  }

  #[test]
  fn a4_sounds_at_440_hz() {
    let mut p = Piano::new(&grand(), 69, 0.5, 0.0, SR);
    let x = render(&mut p, 16_384);
    let seg = &x[2_000..];
    let at = tone_level(seg, 440.0);
    let off = tone_level(seg, 440.0 * cents(60.0));
    assert!(at > 5.0 * off, "440 Hz {at} vs +60c {off}");
  }

  #[test]
  fn follows_live_pitch_bend() {
    let mut p = Piano::new(&grand(), 69, 0.5, 0.0, SR);
    render(&mut p, 2_000);
    p.set_bend(cents(200.0));
    let x = render(&mut p, 16_384);
    let bent = tone_level(&x, 440.0 * cents(200.0));
    let unbent = tone_level(&x, 440.0);
    assert!(bent > 5.0 * unbent, "+200c {bent} vs unbent {unbent}");
    // Bending back restores the pitch.
    p.set_bend(1.0);
    let y = render(&mut p, 16_384);
    let at = tone_level(&y, 440.0);
    let off = tone_level(&y, 440.0 * cents(200.0));
    assert!(at > 5.0 * off, "440 Hz {at} vs +200c {off}");
  }

  #[test]
  fn decays_and_goes_silent() {
    let mut p = Piano::new(&grand(), 60, 0.6, 0.0, SR);
    let x = render(&mut p, SR as usize * 2);
    let early = rms(&x[..4_410]);
    let late = rms(&x[x.len() - 4_410..]);
    assert!(early > 1e-3, "silent attack ({early})");
    assert!(late < early * 0.5, "no decay ({early} → {late})");

    p.damp();
    render(&mut p, SR as usize);
    assert!(p.is_silent(), "still sounding a second after damping");
  }

  #[test]
  fn louder_notes_are_brighter() {
    let centroid = |vel: f32| {
      let mut p = Piano::new(&grand(), 60, vel, 0.0, SR);
      let x = render(&mut p, 8_192);
      let f0 = 261.63;
      let (mut num, mut den) = (0.0, 0.0);
      for n in 1..=20 {
        let l = tone_level(
          &x,
          f0 * n as f32 * (1.0 + inharmonicity(60.0) * (n * n) as f32).sqrt()
            / (1.0 + inharmonicity(60.0)).sqrt(),
        );
        num += n as f32 * l;
        den += l;
      }
      num / den
    };
    let soft = centroid(0.05);
    let loud = centroid(1.0);
    assert!(loud > soft * 1.3, "soft {soft} vs loud {loud}");
  }

  // A piano attack is crisp — the strings speak within a few milliseconds and
  // the upper partials get a brief strike burst — but it doesn't spike and fall
  // away like a plucked string. Too soft (a slow swell) sounded like a felt
  // mallet; too impulsive sounded like a guitar.
  #[test]
  fn attack_is_struck_not_plucked() {
    let mf = (80.0f32 / 127.0).powi(2);
    for key in [48, 60, 72] {
      let mut p = Piano::new(&grand(), key, mf, 0.0, SR);
      let x = render(&mut p, 4_410);
      let first = rms(&x[..441]); // 0–10 ms
      let after = rms(&x[882..2_646]); // 20–60 ms
      let db = 20.0 * (first / after).log10();
      assert!(
        (-3.0..4.0).contains(&db),
        "key {key}: first 10 ms {db:+.1} dB re 20–60 ms"
      );
    }
  }

  // The steep spectral tilt keeps the middle register fundamental-dominated
  // (a plucked string has strong 3rd–6th partials instead). The margin leaves
  // room for the per-partial level scatter.
  #[test]
  fn middle_c_is_fundamental_dominated() {
    let mf = (80.0f32 / 127.0).powi(2);
    let mut p = Piano::new(&grand(), 60, mf, 0.0, SR);
    let x = render(&mut p, 8_192);
    let f0 = 261.63 / (1.0 + inharmonicity(60.0)).sqrt();
    let partial = |n: f32| {
      tone_level(&x, n * f0 * (1.0 + inharmonicity(60.0) * n * n).sqrt())
    };
    let p1 = partial(1.0);
    for n in 3..=6 {
      let db = 20.0 * (partial(n as f32) / p1).log10();
      assert!(
        db < -8.0,
        "partial {n} only {db:.1} dB below the fundamental"
      );
    }
  }

  /// Spectral centroid (Hz) of a 30 ms window starting at `t` seconds.
  fn centroid(x: &[f32], t: f32) -> f32 {
    let a = (t * SR) as usize;
    let w = &x[a..a + 1_323];
    let (mut num, mut den) = (0.0f32, 0.0f32);
    let mut f = 100.0;
    while f < 8_000.0 {
      let l = tone_level(w, f);
      num += f * l;
      den += l;
      f += 50.0;
    }
    num / den
  }

  // A plucked string sweeps from bright to dull within a few hundred
  // milliseconds; a held piano note keeps most of its colour.
  #[test]
  fn held_note_keeps_its_brightness() {
    let mf = (80.0f32 / 127.0).powi(2);
    for key in [60, 72] {
      let mut p = Piano::new(&grand(), key, mf, 0.0, SR);
      let x = render(&mut p, 22_050);
      // From 50 ms, past the hammer-noise transient.
      let (early, late) = (centroid(&x, 0.05), centroid(&x, 0.3));
      assert!(
        late > 0.7 * early,
        "key {key}: centroid {early:.0} Hz at 50 ms → {late:.0} Hz at 0.3 s"
      );
    }
  }

  // Releasing a key stops the note promptly instead of letting it ring on
  // like a plucked string.
  #[test]
  fn release_is_crisp() {
    let mf = (80.0f32 / 127.0).powi(2);
    let mut p = Piano::new(&grand(), 60, mf, 0.0, SR);
    let held = render(&mut p, 13_230); // 0.3 s
    let before = rms(&held[held.len() - 1_323..]);
    p.damp();
    let after = render(&mut p, 8_820); // 0.2 s
    let tail = rms(&after[after.len() - 1_323..]);
    let db = 20.0 * (before / tail).log10();
    assert!(db > 25.0, "only {db:.1} dB quieter 0.2 s after release");
  }

  #[test]
  fn top_keys_have_no_dampers() {
    let mut p = Piano::new(&grand(), 100, 0.6, 0.0, SR);
    render(&mut p, 2_000);
    p.damp();
    let x = render(&mut p, 4_410);
    assert!(rms(&x[2_205..]) > 1e-4, "undamped treble was damped");
  }
}