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
//! Modal model of a struck cymbal (crash, splash, china, ride, ride bell).
//!
//! A cymbal is not filtered noise, but it is not a handful of clean partials
//! either. Its spectrum is thousands of inharmonic plate modes (a plate's
//! modal density is roughly constant in frequency): in recorded rides the
//! prominent ones stand 15–20 dB above a dense floor of weaker ones, 4–8 per
//! 100 Hz from 150 Hz to 14 kHz; in crashes the floor is so dense that the
//! peaks stand only ~10 dB out. Too few, too clean partials sound glassy and
//! bell-like; no partials sound like hiss. The prominent modes beat against
//! each other and decay at different rates, which is the shimmer. What makes
//! a crash *swell* is that the stick excites the low modes first and the
//! plate's nonlinearity then pumps energy up into the 1.6–12 kHz modes over
//! the first 50–150 ms (they rise 5–10 dB after the strike).
//!
//! The prominent modes are decaying complex rotors. The onset is a second
//! rotor at the same frequency and phase with a faster decay: amplitude −b·A
//! makes the mode grow from (1−b)·A towards A (bloom, b > 0); a positive extra
//! amplitude (b < 0) gives an initial excess that settles into the long ring
//! (the stick "ping" of a ride, the strike thump of the low modes). Ring time
//! falls with frequency (T60 = `ring` / (1 + (f/`ring_corner`)²)), so the
//! highs die first and the tail settles around 1–3 kHz, as in the recordings.
//! The dense floor is noise in half-octave bands whose level (`floor_db`
//! relative to the modes in the band), ring time and onset follow the modes
//! of that band. Above the highest synthesized mode, high-passed noise stands
//! in for the top partials and the stick contact.
//!
//! Mode frequencies, decays and a fixed level pattern belong to the cymbal
//! (seeded by `CymbalSpec::seed`). A cymbal is one object: hitting it while it
//! rings adds a new excitation to the modes already sounding (`strike`)
//! rather than starting a second cymbal. Each strike re-scatters mode levels
//! and phases (the stick lands somewhere else), so repeated hits differ.
//!
//! The crash and ride shapes were fitted to the crash and ride cymbals of
//! Logic Pro's Drum Kit Designer kits (analysis only, never shipped):
//! third-octave energy over time, partial density and peak-to-floor ratio.

use crate::synth::waveguide::{Biquad, Noise};

const LANES: usize = 8;
/// Highest mode frequency synthesized; noise covers the rest.
const MAX_MODE_HZ: f32 = 13_000.0;
/// Rotors below this magnitude are dropped.
const CULL_LEVEL: f32 = 5e-5;
/// Velocity (after the synth's squared curve) treated as mezzo-forte.
const MF_VELOCITY: f32 = 0.4;
/// Per-strike level scatter of every mode (strike position), ± dB.
const HIT_SCATTER_DB: f32 = 3.0;
/// Per-mode ring-time scatter, ± fraction.
const RING_SCATTER: f32 = 0.3;
/// Interval between the random targets of the wobble, seconds (sets how
/// far, in Hz, each partial is smeared).
const WOBBLE_STEP: f32 = 0.14;
/// Range of the frequency split of each mode pair, Hz.
const SPLIT_HZ: (f32, f32) = (0.7, 4.0);
/// Quality of the half-octave floor bands. Each band is `FLOOR_ORDER`
/// cascaded band-passes, so a strong band's skirt doesn't swamp a band 25 dB
/// weaker two octaves away (the 3 kHz wash vs. the dying 8 kHz highs).
const FLOOR_Q: f32 = 1.6;
const FLOOR_ORDER: usize = 3;
/// T60 of a choked cymbal, seconds.
const CHOKE_T60: f32 = 0.05;
/// Lane tag of an empty slot.
const EMPTY: u32 = u32::MAX;

/// One point of a cymbal's frequency-dependent shape; interpolated linearly
/// in log-frequency between points and held beyond the ends.
#[derive(Clone, Copy, Debug)]
pub struct CymbalBand {
  pub hz: f32,
  /// Settled mode level, dB (relative; the whole cymbal is normalised).
  pub db: f32,
  /// Onset: > 0 the mode grows from (1 − b) of its level (bloom); < 0 it
  /// starts (1 − b) times louder and settles.
  pub bloom: f32,
  /// Time constant of that onset, seconds.
  pub tau: f32,
}

#[derive(Clone, Copy, Debug)]
pub struct CymbalSpec {
  /// Seeds the mode frequencies, decays and fixed level pattern.
  pub seed: u32,
  /// Lowest mode, Hz.
  pub lo: f32,
  /// Highest mode, Hz (capped at `MAX_MODE_HZ`).
  pub hi: f32,
  /// Prominent modes per 100 Hz (spread evenly, each jittered in its slot).
  pub density: f32,
  /// Fixed per-mode level scatter, ± dB. Large values leave a few dominant
  /// partials (a bell).
  pub scatter_db: f32,
  /// Power of the dense mode floor relative to the prominent modes of the
  /// same band, dB. About 0 for a crash, −12 for a ride.
  pub floor_db: f32,
  pub bands: &'static [CymbalBand],
  /// T60 of the low and middle modes, seconds.
  pub ring: f32,
  /// Frequency at which the ring time has halved.
  pub ring_corner: f32,
  /// Stick hardness at mf: modes above this corner lose level at softer hits
  /// and gain it at harder ones.
  pub brightness: f32,
  /// High-passed noise: corner, stick-burst level and decay time constant,
  /// sustained sizzle level and its T60. Levels relative to the modes' RMS.
  pub noise_hz: f32,
  pub stick: f32,
  pub stick_tau: f32,
  pub sizzle: f32,
  pub sizzle_t60: f32,
  /// `tanh` drive on the output (the trashy edge of a china); 0 = clean.
  pub drive: f32,
  /// Peak (radians) of a smooth random phase wander of every mode, which
  /// smears each partial over a few Hz as the plate's nonlinear mode coupling
  /// does. Recorded partials are that wide; perfectly sharp lines sound
  /// glassy.
  pub wobble: f32,
}

/// A prominent mode: what the cymbal is, independent of how it is struck.
#[derive(Clone, Copy, Debug)]
struct Mode {
  f: f32,
  /// Level at mf, normalised so all modes together have unit RMS.
  amp: f32,
  /// Rotor coefficient of the ring and of the onset rotor.
  c: (f32, f32),
  c_onset: (f32, f32),
  bloom: f32,
}

/// Half-octave band of the dense mode floor.
#[derive(Clone, Debug)]
struct FloorBand {
  hz: f32,
  bp: [Biquad; FLOOR_ORDER],
  /// Envelope amplitude per unit strike (at mf).
  gain: f32,
  bloom: f32,
  /// Ring and onset envelopes (summed) and their per-sample decay factors.
  ring: f32,
  onset: f32,
  r: f32,
  r_onset: f32,
}

#[derive(Clone, Debug)]
struct RotorBlock {
  re: [f32; LANES],
  im: [f32; LANES],
  cr: [f32; LANES],
  ci: [f32; LANES],
  /// 2·mode for the ring rotor, 2·mode + 1 for the onset rotor.
  tag: [u32; LANES],
}

impl Default for RotorBlock {
  fn default() -> Self {
    Self {
      re: [0.0; LANES],
      im: [0.0; LANES],
      cr: [0.0; LANES],
      ci: [0.0; LANES],
      tag: [EMPTY; LANES],
    }
  }
}

#[derive(Clone, Debug)]
pub struct Cymbal {
  spec: CymbalSpec,
  sr: f32,
  modes: Vec<Mode>,
  blocks: Vec<RotorBlock>,
  floor: Vec<FloorBand>,
  noise: Noise,
  hp: Biquad,
  stick_env: f32,
  stick_coef: f32,
  sizzle_env: f32,
  sizzle_coef: f32,
  /// Phase wander per lane (every mode keeps its lane): cosine-interpolated
  /// random walks, from → to over one step, scaled by `wobble`.
  wob_from: [f32; LANES],
  wob_to: [f32; LANES],
  wob_t: f32,
  wob_inc: f32,
  level: f32,
}

/// Small deterministic PRNG (xorshift32) giving floats in 0..1.
struct Rng(u32);

impl Rng {
  fn new(seed: u32) -> Self {
    // Scramble so neighbouring seeds give unrelated sequences.
    let mut s = seed.wrapping_mul(0x9E37_79B9) ^ 0x85EB_CA6B;
    s ^= s >> 16;
    Self(s.max(1))
  }

  fn next(&mut self) -> f32 {
    let mut x = self.0;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    self.0 = x;
    (x >> 8) as f32 / 16_777_216.0
  }

  /// Roughly Gaussian in about −1..1 (sum of three uniforms).
  fn bell(&mut self) -> f32 {
    (self.next() + self.next() + self.next()) * (2.0 / 3.0) - 1.0
  }
}

/// Interpolate `(db, bloom, tau)` at `hz` in log-frequency.
fn shape(bands: &[CymbalBand], hz: f32) -> (f32, f32, f32) {
  let first = bands[0];
  if hz <= first.hz {
    return (first.db, first.bloom, first.tau);
  }
  for w in bands.windows(2) {
    let (a, b) = (w[0], w[1]);
    if hz <= b.hz {
      let t = (hz / a.hz).ln() / (b.hz / a.hz).ln();
      let mix = |x: f32, y: f32| x + (y - x) * t;
      return (mix(a.db, b.db), mix(a.bloom, b.bloom), mix(a.tau, b.tau));
    }
  }
  let last = bands[bands.len() - 1];
  (last.db, last.bloom, last.tau)
}

/// Per-sample decay factor for a T60 in seconds.
fn t60_coef(t60: f32, sr: f32) -> f32 {
  10f32.powf(-3.0 / (t60.max(0.01) * sr))
}

/// Per-sample decay factor of a ring time combined with an onset time
/// constant.
fn onset_coef(r: f32, tau: f32, sr: f32) -> f32 {
  r * (-1.0 / (tau.max(1e-3) * sr)).exp()
}

/// Output power of uniform white noise in −1..1 (variance 1/3) through
/// `FLOOR_ORDER` cascaded copies of `bp` (∫|H|² df on a log grid).
fn noise_power(bp: &Biquad, sr: f32) -> f32 {
  let steps = 1_000;
  let (lo, hi) = (10f32, sr * 0.5);
  let k = (hi / lo).ln() / steps as f32;
  let sum: f32 = (0..steps)
    .map(|i| {
      let f = lo * ((i as f32 + 0.5) * k).exp();
      let (re, im) = bp.response(f, sr);
      (re * re + im * im).powi(FLOOR_ORDER as i32) * f * k
    })
    .sum();
  (1.0 / 3.0) * 2.0 / sr * sum
}

fn rotor(r: f32, f: f32, sr: f32) -> (f32, f32) {
  let w = std::f32::consts::TAU * f / sr;
  (r * w.cos(), r * w.sin())
}

impl Cymbal {
  /// A silent cymbal; call `strike` to play it.
  pub fn new(spec: &CymbalSpec, sr: f32) -> Self {
    let hi = spec.hi.min(MAX_MODE_HZ).min(sr * 0.45);
    let slot = 100.0 / spec.density;
    let count = ((hi - spec.lo) / slot).max(0.0) as usize;
    let ring_t60 = |f: f32| spec.ring / (1.0 + (f / spec.ring_corner).powi(2));

    let mut rng = Rng::new(spec.seed);
    let mut modes = Vec::with_capacity(count);
    for k in 0..count {
      let f = spec.lo + (k as f32 + rng.next()) * slot;
      let (db, bloom, tau) = shape(spec.bands, f);
      let amp = 10f32.powf((db + spec.scatter_db * rng.bell()) / 20.0);
      let r = t60_coef(ring_t60(f) * (1.0 + RING_SCATTER * rng.bell()), sr);
      // The plate isn't perfectly round, so each mode is a split pair that
      // beats slowly (the shimmer; single clean lines sound glassy).
      let split = SPLIT_HZ.0 + (SPLIT_HZ.1 - SPLIT_HZ.0) * rng.next();
      let partner = 0.4 + 0.6 * rng.next();
      for (f, amp) in [(f, amp), (f + split, amp * partner)] {
        modes.push(Mode {
          f,
          amp,
          c: rotor(r, f, sr),
          c_onset: rotor(onset_coef(r, tau, sr), f, sr),
          bloom,
        });
      }
    }
    let power: f32 = modes.iter().map(|m| m.amp * m.amp * 0.5).sum();
    let norm = 1.0 / power.max(1e-12).sqrt();
    for m in &mut modes {
      m.amp *= norm;
    }

    // Floor bands: noise power per band = `floor_db` × the modes' power in
    // that band.
    let floor_lin = 10f32.powf(spec.floor_db / 10.0);
    let edge = 2f32.powf(0.25);
    let mut floor = Vec::new();
    let mut hz = spec.lo * edge;
    while hz / edge < hi {
      let p: f32 = modes
        .iter()
        .filter(|m| m.f >= hz / edge && m.f < hz * edge)
        .map(|m| m.amp * m.amp * 0.5)
        .sum();
      let bp = [Biquad::bandpass(hz, FLOOR_Q, sr); FLOOR_ORDER];
      let unit = noise_power(&bp[0], sr);
      let (_, bloom, tau) = shape(spec.bands, hz);
      let r = t60_coef(ring_t60(hz), sr);
      floor.push(FloorBand {
        hz,
        bp,
        gain: (floor_lin * p / unit).sqrt(),
        bloom,
        ring: 0.0,
        onset: 0.0,
        r,
        r_onset: onset_coef(r, tau, sr),
      });
      hz *= edge * edge;
    }

    Self {
      spec: *spec,
      sr,
      modes,
      blocks: Vec::new(),
      floor,
      noise: Noise::new(spec.seed),
      hp: Biquad::highpass(spec.noise_hz, 0.7, sr),
      stick_env: 0.0,
      stick_coef: (-1.0 / (spec.stick_tau.max(1e-4) * sr)).exp(),
      sizzle_env: 0.0,
      sizzle_coef: t60_coef(spec.sizzle_t60, sr),
      wob_from: [0.0; LANES],
      wob_to: [0.0; LANES],
      wob_t: 1.0,
      wob_inc: 1.0 / (WOBBLE_STEP * sr),
      level: 0.0,
    }
  }

  /// Hit the cymbal. `velocity` is 0..1 after the synth's velocity curve and
  /// scales the excitation; `hit` varies the strike from note to note (any
  /// value; the sample clock at note-on).
  pub fn strike(&mut self, velocity: f32, hit: u64) {
    let spec = &self.spec;
    let vel_ratio = (velocity.max(0.01) / MF_VELOCITY).sqrt();
    let corner = spec.brightness * vel_ratio;
    // Harder sticks excite the upper modes more, and drive the bloom harder
    // (the energy cascade is a nonlinearity).
    let tilt = |f: f32| {
      ((1.0 + (f / spec.brightness).powi(2)) / (1.0 + (f / corner).powi(2)))
        .sqrt()
    };
    let bloom = |b: f32| {
      if b > 0.0 {
        (b * vel_ratio.sqrt()).min(0.9)
      } else {
        b
      }
    };

    // Current state of every rotor, by tag.
    let mut state = vec![(0.0f32, 0.0f32); self.modes.len() * 2];
    for blk in &self.blocks {
      for j in 0..LANES {
        if blk.tag[j] != EMPTY {
          state[blk.tag[j] as usize] = (blk.re[j], blk.im[j]);
        }
      }
    }
    let mut rng = Rng::new(spec.seed ^ (hit as u32) ^ ((hit >> 32) as u32));
    let mut rotors = Vec::with_capacity(self.modes.len() * 2);
    for (k, m) in self.modes.iter().enumerate() {
      let a = velocity
        * m.amp
        * tilt(m.f)
        * 10f32.powf(HIT_SCATTER_DB * rng.bell() / 20.0);
      let (s, c) = (std::f32::consts::TAU * rng.next()).sin_cos();
      let (re, im) = state[2 * k];
      rotors.push((2 * k as u32, re + a * c, im + a * s, m.c));
      let b = bloom(m.bloom);
      let (re, im) = state[2 * k + 1];
      if b != 0.0 || re != 0.0 || im != 0.0 {
        rotors.push((
          2 * k as u32 + 1,
          re - b * a * c,
          im - b * a * s,
          m.c_onset,
        ));
      }
    }
    self.blocks = pack(&rotors);

    for band in &mut self.floor {
      let a = velocity * band.gain * tilt(band.hz);
      band.ring += a;
      band.onset -= bloom(band.bloom) * a;
    }
    self.stick_env += velocity * spec.stick * vel_ratio;
    self.sizzle_env += velocity * spec.sizzle * vel_ratio.min(1.5);
    self.level = 1.0;
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    self.wob_t += self.wob_inc;
    if self.wob_t >= 1.0 {
      self.wob_t -= 1.0;
      self.wob_from = self.wob_to;
      for w in &mut self.wob_to {
        *w = self.spec.wobble * self.noise.tick();
      }
    }
    let k = 0.5 - 0.5 * (std::f32::consts::PI * self.wob_t).cos();
    let rot: [(f32, f32); LANES] = std::array::from_fn(|j| {
      (self.wob_from[j] + (self.wob_to[j] - self.wob_from[j]) * k).sin_cos()
    });
    let mut out = step_blocks(&mut self.blocks, &rot);
    let white = self.noise.tick();
    for b in &mut self.floor {
      let y = b.bp.iter_mut().fold(white, |x, f| f.tick(x));
      out += y * (b.ring + b.onset);
      b.ring *= b.r;
      b.onset *= b.r_onset;
    }
    let env = self.stick_env + self.sizzle_env;
    if env > 1e-6 {
      out += self.hp.tick(white) * env;
      self.stick_env *= self.stick_coef;
      self.sizzle_env *= self.sizzle_coef;
    }
    let d = self.spec.drive;
    if d > 0.0 {
      out = (out * d).tanh() / d;
    }
    out
  }

  /// Stop the cymbal quickly (a hi-hat closing, a hand grabbing the edge).
  pub fn damp(&mut self) {
    let d = 10f32.powf(-3.0 / (CHOKE_T60 * self.sr));
    for blk in &mut self.blocks {
      for j in 0..LANES {
        blk.cr[j] *= d;
        blk.ci[j] *= d;
      }
    }
    for b in &mut self.floor {
      b.r *= d;
      b.r_onset *= d;
    }
    self.stick_coef *= d;
    self.sizzle_coef *= d;
  }

  /// Drop inaudible rotors and repack the rest. Call once per render block.
  pub fn cull(&mut self) {
    let floor: f32 = self.floor.iter().map(|b| (b.ring + b.onset).abs()).sum();
    self.level =
      cull_blocks(&mut self.blocks) + floor + self.stick_env + self.sizzle_env;
  }

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

/// Advance every rotor one sample and return the summed output, each lane's
/// rotors read at a phase offset θ given as `rot[lane]` = (sin θ, cos θ):
/// Im(z·e^{iθ}).
#[inline]
// One counter over all lane arrays keeps the loop trivially vectorizable.
#[allow(clippy::needless_range_loop)]
fn step_blocks(blocks: &mut [RotorBlock], rot: &[(f32, f32); LANES]) -> f32 {
  let s: [f32; LANES] = std::array::from_fn(|j| rot[j].0);
  let c: [f32; LANES] = std::array::from_fn(|j| rot[j].1);
  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] * c[j] + blk.re[j] * s[j];
    }
  }
  acc.iter().sum()
}

/// Lane of a rotor: fixed per mode (ring and onset rotor together), so its
/// phase wander stays continuous when blocks are repacked.
fn lane(tag: u32) -> usize {
  (tag / 2) as usize % LANES
}

/// Pack `(tag, re, im, coefficient)` rotors into lane blocks, each rotor in
/// its own lane.
fn pack(rotors: &[(u32, f32, f32, (f32, f32))]) -> Vec<RotorBlock> {
  let mut blocks: Vec<RotorBlock> = Vec::new();
  let mut fill = [0usize; LANES];
  for &(tag, re, im, (cr, ci)) in rotors {
    let j = lane(tag);
    if fill[j] == blocks.len() {
      blocks.push(RotorBlock::default());
    }
    let blk = &mut blocks[fill[j]];
    fill[j] += 1;
    blk.tag[j] = tag;
    blk.re[j] = re;
    blk.im[j] = im;
    blk.cr[j] = cr;
    blk.ci[j] = ci;
  }
  blocks
}

/// Drop rotors below `CULL_LEVEL` (and empty lanes), repack, and return the
/// summed magnitude of the rest.
fn cull_blocks(blocks: &mut Vec<RotorBlock>) -> f32 {
  let mut live = Vec::new();
  let mut level = 0.0;
  for blk in blocks.iter() {
    for j in 0..LANES {
      let mag = blk.re[j].hypot(blk.im[j]);
      if blk.tag[j] != EMPTY && mag > CULL_LEVEL {
        level += mag;
        live.push((blk.tag[j], blk.re[j], blk.im[j], (blk.cr[j], blk.ci[j])));
      }
    }
  }
  if live.len().div_ceil(LANES) < blocks.len() {
    let packed = pack(&live);
    if packed.len() < blocks.len() {
      *blocks = packed;
    }
  }
  level
}