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
//! Percussion model for the GM drum map (everything but the cymbals).
//!
//! A struck or shaken object is built from up to four physically motivated
//! layers, each fitted to recordings (Logic Pro's Drum Kit Designer kit
//! pieces and percussion library, analysis only):
//!
//! - **Modes**: the body's vibration modes as decaying sinusoids at absolute
//!   frequencies (drum heads: inharmonic membrane modes; bars, blocks, bells:
//!   their own ratios). A head's tension rises with its displacement, so
//!   every mode starts sharp and glides down (`glide`, decaying with
//!   `glide_tau`, scaled by velocity). The stick or hand is a second-order
//!   low-pass on the mode levels whose corner (`hardness`) rises with
//!   velocity.
//! - **Noise**: band-limited noise with a delay, attack and decay, optionally
//!   repeated as a burst train (stick contact, snare wires, hand claps).
//! - **Particles**: collisions — impulses at a random or regular rate under an
//!   envelope — exciting a bank of resonators (shaker beads, tambourine
//!   jingles, guiro ridges, vibraslap teeth).
//! - **Tone**: a gliding, warbling oscillator through an optional drive
//!   (whistles, cuíca, scratch).
//!
//! Choking (mute groups, the closed hi-hat stopping an open one) damps every
//! layer with a short T60 via `damp`.

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

/// Velocity (after the synth's squared curve) treated as mezzo-forte.
const MF_VELOCITY: f32 = 0.4;
/// Mode coefficients are recomputed this often while gliding (samples).
const GLIDE_STEP: usize = 16;
/// T60 applied to everything when the sound is choked, seconds.
const CHOKE_T60: f32 = 0.06;

#[derive(Clone, Copy, Debug)]
pub struct PercMode {
  pub hz: f32,
  /// Level, dB (relative within the sound).
  pub db: f32,
  pub t60: f32,
  /// Start time, seconds (a bell tree's cups are struck in turn).
  pub delay: f32,
}

/// Band of noise: high-pass at `lo`, low-pass at `hi` (both 2nd order).
#[derive(Clone, Copy, Debug)]
pub struct PercNoise {
  pub lo: f32,
  pub hi: f32,
  pub db: f32,
  pub delay: f32,
  pub attack: f32,
  /// Time at full level before the decay, seconds.
  pub hold: f32,
  pub t60: f32,
  /// Number of envelope restarts (1 = a single hit) and their spacing (s);
  /// each restart is jittered by ±30% of the spacing.
  pub bursts: u8,
  pub spacing: f32,
  /// Level grows as (velocity / mf)^`vel` on top of the overall velocity
  /// gain: > 0 for layers that grow faster than the body (stick contact).
  pub vel: f32,
}

#[derive(Clone, Copy, Debug)]
pub struct Resonator {
  pub hz: f32,
  pub q: f32,
  pub db: f32,
}

#[derive(Clone, Copy, Debug)]
pub struct Particles {
  /// Collisions per second.
  pub rate: f32,
  /// 0 = random (Poisson) timing, 1 = perfectly regular (ridges, teeth).
  pub regular: f32,
  /// Envelope of the collision strength: delay, attack, hold, then T60.
  pub delay: f32,
  pub attack: f32,
  pub hold: f32,
  pub t60: f32,
  /// Random level scatter of each collision, 0..1.
  pub scatter: f32,
  /// T60 of each collision's noise grain, seconds; 0 = a single impulse.
  /// A grain stands for many small hits at once (a rattle of loose teeth).
  pub grain: f32,
  /// Splits `resonators` into this many equal groups (separate bells); each
  /// collision strikes one at random. 0 or 1: every collision drives all.
  pub groups: u8,
  /// Level of the raw collision added to the resonators' output (the metal
  /// click of a jingle), relative to the resonator gain.
  pub click: f32,
  pub resonators: &'static [Resonator],
  pub db: f32,
}

#[derive(Clone, Copy, Debug)]
pub struct PercTone {
  /// Frequency glides from `from` to `to` (Hz) with time constant `glide`.
  pub from: f32,
  pub to: f32,
  pub glide: f32,
  /// Warble: rate (Hz) and depth (fraction of frequency). `rough` > 0 makes
  /// the warble irregular (a whistle's pea).
  pub warble_hz: f32,
  pub warble: f32,
  pub rough: f32,
  /// `tanh` drive (0 = sine): adds harmonics.
  pub drive: f32,
  /// Optional band-pass formant on the tone (0 = none).
  pub formant: f32,
  pub formant_q: f32,
  pub attack: f32,
  pub hold: f32,
  pub t60: f32,
  pub db: f32,
}

#[derive(Clone, Copy, Debug)]
pub struct PercSpec {
  pub modes: &'static [PercMode],
  /// Initial pitch excess of the modes (fraction, at mf) and its decay time
  /// constant (s).
  pub glide: f32,
  pub glide_tau: f32,
  /// Corner of the mallet low-pass on the mode levels at mf (Hz).
  pub hardness: f32,
  /// Level of the modes, dB.
  pub modes_db: f32,
  pub noise: &'static [PercNoise],
  pub particles: Option<Particles>,
  pub tone: Option<PercTone>,
  /// `tanh` drive on the summed output (0 = clean).
  pub drive: f32,
  /// Output gain so the patch gains stay in a common range.
  pub gain: f32,
}

impl PercSpec {
  /// An empty spec to build from with struct-update syntax.
  pub const EMPTY: PercSpec = PercSpec {
    modes: &[],
    glide: 0.0,
    glide_tau: 0.05,
    hardness: 20_000.0,
    modes_db: 0.0,
    noise: &[],
    particles: None,
    tone: None,
    drive: 0.0,
    gain: 1.0,
  };
}

#[derive(Clone, Debug)]
struct NoiseLayer {
  hp: Biquad,
  lp: Biquad,
  amp: f32,
  /// Sample index of each envelope restart.
  starts: Vec<u32>,
  attack: f32,
  hold: u32,
  held: u32,
  decay: f32,
  env: f32,
  rising: bool,
}

#[derive(Clone, Debug)]
struct ParticleLayer {
  spec: Particles,
  res: Vec<(Biquad, f32)>,
  /// 4th-order high-pass an octave below the lowest resonator: a band-pass
  /// biquad's 6 dB/oct skirt lets each click's low end through as a thump.
  hp: [Biquad; 2],
  amp: f32,
  /// Samples until the next collision.
  next: f32,
  period: f32,
  env: f32,
  /// Current grain level and its per-sample decay.
  grain: f32,
  grain_coef: f32,
  /// Resonator group struck by the current collision.
  group: usize,
}

#[derive(Clone, Debug)]
struct ToneLayer {
  spec: PercTone,
  phase: f32,
  wphase: f32,
  wtarget: f32,
  wvalue: f32,
  formant: Option<Biquad>,
  amp: f32,
}

#[derive(Clone, Debug)]
pub struct Perc {
  // Modes; `pending` holds (start sample, index, re, im) of delayed ones.
  pending: Vec<(u32, usize, f32, f32)>,
  re: Vec<f32>,
  im: Vec<f32>,
  w0: Vec<f32>,
  r: Vec<f32>,
  cr: Vec<f32>,
  ci: Vec<f32>,
  glide: f32,
  glide_coef: f32,
  noise: Vec<NoiseLayer>,
  particles: Option<ParticleLayer>,
  tone: Option<ToneLayer>,
  white: Noise,
  rng: u32,
  drive: f32,
  gain: f32,
  t: u32,
  sr: f32,
  /// Extra per-sample decay once choked (1 = not choked).
  choke: f32,
  choke_gain: f32,
  level: f32,
}

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

fn t60_coef(t60: f32, sr: f32) -> f32 {
  10f32.powf(-3.0 / (t60.max(1e-4) * sr))
}

impl Perc {
  /// `velocity` is 0..1 after the synth's velocity curve; `seed` varies the
  /// random parts from hit to hit (the sample clock at note-on).
  pub fn new(spec: &PercSpec, velocity: f32, seed: u64, sr: f32) -> Self {
    let vel_ratio = (velocity.max(0.01) / MF_VELOCITY).sqrt();
    let corner = spec.hardness * vel_ratio;
    let mut rng = (seed as u32 ^ (seed >> 32) as u32)
      .wrapping_mul(0x9E37_79B9)
      .max(1);
    let mut next = move || {
      rng ^= rng << 13;
      rng ^= rng >> 17;
      rng ^= rng << 5;
      (rng >> 8) as f32 / 16_777_216.0
    };

    let nyq = sr * 0.45;
    let (mut re, mut im, mut w0, mut r) = (vec![], vec![], vec![], vec![]);
    let mut pending = Vec::new();
    for m in spec.modes.iter().filter(|m| m.hz < nyq) {
      // Mallet low-pass, normalised to mf.
      let tilt = ((1.0 + (m.hz / spec.hardness).powi(2))
        / (1.0 + (m.hz / corner).powi(2)))
      .sqrt();
      let a = db(m.db + spec.modes_db) * tilt;
      // Low modes start in sine phase (a clean push); higher ones at a random
      // phase, as the stick excites them.
      let ph = if m.hz < 300.0 {
        0.0
      } else {
        std::f32::consts::TAU * next()
      };
      if m.delay > 0.0 {
        pending.push((
          (m.delay * sr) as u32,
          re.len(),
          a * ph.cos(),
          a * ph.sin(),
        ));
        re.push(0.0);
        im.push(0.0);
      } else {
        re.push(a * ph.cos());
        im.push(a * ph.sin());
      }
      w0.push(std::f32::consts::TAU * m.hz / sr);
      r.push(t60_coef(m.t60, sr));
    }
    let n = re.len();

    let noise = spec
      .noise
      .iter()
      .map(|ns| {
        let mut starts = Vec::with_capacity(ns.bursts.max(1) as usize);
        let mut t = ns.delay;
        for _ in 0..ns.bursts.max(1) {
          starts.push((t * sr) as u32);
          t += ns.spacing * (0.7 + 0.6 * next());
        }
        NoiseLayer {
          hp: Biquad::highpass(ns.lo.max(10.0), 0.707, sr),
          lp: Biquad::lowpass(ns.hi.min(nyq), 0.707, sr),
          amp: db(ns.db) * vel_ratio.powf(ns.vel * 2.0),
          starts,
          attack: 1.0 / (ns.attack.max(1e-4) * sr),
          hold: (ns.hold * sr) as u32,
          held: 0,
          decay: t60_coef(ns.t60, sr),
          env: 0.0,
          rising: false,
        }
      })
      .collect();

    let particles = spec.particles.map(|p| ParticleLayer {
      spec: p,
      res: p
        .resonators
        .iter()
        .map(|rz| (Biquad::bandpass(rz.hz, rz.q, sr), db(rz.db)))
        .collect(),
      hp: {
        let lo = p.resonators.iter().map(|r| r.hz).fold(f32::MAX, f32::min);
        let hz = (lo * 0.5).clamp(20.0, sr * 0.4);
        [
          Biquad::highpass(hz, 0.54, sr),
          Biquad::highpass(hz, 1.31, sr),
        ]
      },
      amp: db(p.db),
      next: p.delay * sr,
      period: sr / p.rate.max(0.1),
      env: 0.0,
      grain: 0.0,
      group: 0,
      grain_coef: if p.grain > 0.0 {
        t60_coef(p.grain, sr)
      } else {
        0.0
      },
    });

    let tone = spec.tone.map(|t| ToneLayer {
      spec: t,
      phase: 0.0,
      wphase: 0.0,
      wtarget: 0.0,
      wvalue: 0.0,
      formant: (t.formant > 0.0)
        .then(|| Biquad::bandpass(t.formant, t.formant_q, sr)),
      amp: db(t.db),
    });

    let mut p = Self {
      pending,
      re,
      im,
      w0,
      r,
      cr: vec![0.0; n],
      ci: vec![0.0; n],
      glide: spec.glide * vel_ratio,
      glide_coef: (-(GLIDE_STEP as f32) / (spec.glide_tau.max(1e-3) * sr))
        .exp(),
      noise,
      particles,
      tone,
      white: Noise::new(seed as u32 ^ 0x5EED),
      rng: (seed as u32).wrapping_mul(747_796_405).max(1),
      drive: spec.drive,
      gain: spec.gain,
      t: 0,
      sr,
      choke: 1.0,
      choke_gain: 1.0,
      level: 1.0,
    };
    p.retune();
    p
  }

  fn retune(&mut self) {
    let g = 1.0 + self.glide;
    for k in 0..self.re.len() {
      let w = self.w0[k] * g;
      self.cr[k] = self.r[k] * w.cos();
      self.ci[k] = self.r[k] * w.sin();
    }
  }

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

  /// Stop the sound quickly (mute groups, hi-hat choke).
  pub fn damp(&mut self) {
    self.choke = t60_coef(CHOKE_T60, self.sr);
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    let t = self.t;
    self.t = t.wrapping_add(1);
    if self.glide > 1e-5 && (t as usize).is_multiple_of(GLIDE_STEP) {
      self.glide *= self.glide_coef;
      self.retune();
    }
    if !self.pending.is_empty() {
      for &(start, k, a, b) in &self.pending {
        if start == t {
          self.re[k] = a;
          self.im[k] = b;
        }
      }
      self.pending.retain(|p| p.0 > t);
    }
    let mut out = 0.0;
    for k in 0..self.re.len() {
      let (r, i) = (self.re[k], self.im[k]);
      self.re[k] = r * self.cr[k] - i * self.ci[k];
      self.im[k] = r * self.ci[k] + i * self.cr[k];
      out += self.im[k];
    }

    let white = self.white.tick();
    for ns in &mut self.noise {
      if ns.starts.contains(&t) {
        ns.rising = true;
      }
      if ns.rising {
        ns.env += ns.attack;
        if ns.env >= 1.0 {
          ns.env = 1.0;
          ns.rising = false;
          ns.held = ns.hold;
        }
      } else if ns.held > 0 {
        ns.held -= 1;
      } else {
        ns.env *= ns.decay;
      }
      if ns.env > 1e-6 {
        out += ns.lp.tick(ns.hp.tick(white)) * ns.env * ns.amp;
      }
    }

    if let Some(mut p) = self.particles.take() {
      let s = &p.spec;
      let tsec = t as f32 / self.sr;
      let since = tsec - s.delay;
      p.env = if since < 0.0 {
        0.0
      } else if since < s.attack {
        since / s.attack.max(1e-4)
      } else if since < s.attack + s.hold {
        1.0
      } else {
        10f32.powf(-3.0 * (since - s.attack - s.hold) / s.t60.max(1e-3))
      };
      let mut x = 0.0;
      p.next -= 1.0;
      if p.next <= 0.0 {
        let jitter = 1.0 - s.regular;
        // Exponential gaps (Poisson) blended with a fixed period.
        let u = self.rand().max(1e-6);
        let gap = p.period * (s.regular + jitter * -u.ln());
        p.next += gap.max(1.0);
        let lvl = 1.0 - s.scatter * self.rand();
        let sign = if self.rand() < 0.5 { -1.0 } else { 1.0 };
        if s.groups > 1 {
          p.group = ((self.rand() * s.groups as f32) as usize)
            .min(s.groups as usize - 1);
        }
        x = sign * lvl * p.env;
        if s.grain > 0.0 {
          p.grain += lvl * p.env;
          x = 0.0;
        }
      }
      if p.grain > 1e-6 {
        x += p.grain * white;
        p.grain *= p.grain_coef;
      }
      let mut y = x * s.click;
      let per = p.res.len().div_ceil(s.groups.max(1) as usize).max(1);
      for (k, (bq, g)) in p.res.iter_mut().enumerate() {
        let drive = if s.groups <= 1 || k / per == p.group {
          x
        } else {
          0.0
        };
        y += bq.tick(drive) * *g;
      }
      let [h0, h1] = &mut p.hp;
      y = h1.tick(h0.tick(y));
      out += y * p.amp;
      self.particles = Some(p);
    }

    if let Some(tn) = &mut self.tone {
      let s = tn.spec;
      let tsec = t as f32 / self.sr;
      let f = s.to + (s.from - s.to) * (-tsec / s.glide.max(1e-3)).exp();
      // Warble: a smooth random walk (rough) blended with a sine.
      tn.wphase += s.warble_hz / self.sr;
      if tn.wphase >= 1.0 {
        tn.wphase -= 1.0;
        tn.wtarget = white;
      }
      tn.wvalue += (tn.wtarget - tn.wvalue) * (s.warble_hz * 6.0 / self.sr);
      let sine = (std::f32::consts::TAU * tn.wphase).sin();
      let wob = (1.0 - s.rough) * sine + s.rough * tn.wvalue;
      tn.phase += f * (1.0 + s.warble * wob) / self.sr;
      tn.phase -= tn.phase.floor();
      let mut y = (std::f32::consts::TAU * tn.phase).sin();
      if s.drive > 0.0 {
        y = (y * (1.0 + s.drive)).tanh();
      }
      if let Some(bp) = &mut tn.formant {
        y = bp.tick(y);
      }
      let env = if tsec < s.attack {
        tsec / s.attack.max(1e-4)
      } else if tsec < s.attack + s.hold {
        1.0
      } else {
        10f32.powf(-3.0 * (tsec - s.attack - s.hold) / s.t60.max(1e-3))
      };
      out += y * env * tn.amp;
    }

    if self.drive > 0.0 {
      out = (out * self.drive).tanh() / self.drive;
    }
    if self.choke < 1.0 {
      self.choke_gain *= self.choke;
    }
    out * self.gain * self.choke_gain
  }

  /// Track the level for idle detection. Call once per render block.
  pub fn update_level(&mut self) {
    let modes: f32 = self
      .re
      .iter()
      .zip(&self.im)
      .map(|(r, i)| r.abs() + i.abs())
      .sum();
    let noise: f32 = self.noise.iter().map(|n| n.env * n.amp).sum();
    let pending = self
      .noise
      .iter()
      .any(|n| n.starts.iter().any(|&s| s >= self.t));
    let part = self.particles.as_ref().map_or(0.0, |p| {
      // Still waiting for, or rising through, the attack.
      let rising = self.t < ((p.spec.delay + p.spec.attack) * self.sr) as u32;
      if rising { 1.0 } else { p.env }
    });
    let tone = self.tone.as_ref().map_or(0.0, |tn| {
      let s = tn.spec;
      let tsec = self.t as f32 / self.sr;
      if tsec < s.attack + s.hold {
        1.0
      } else {
        10f32.powf(-3.0 * (tsec - s.attack - s.hold) / s.t60.max(1e-3))
      }
    });
    let pending = pending || !self.pending.is_empty();
    self.level =
      (modes + noise + part + tone + if pending { 1.0 } else { 0.0 })
        * self.choke_gain;
  }

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