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
//! GM sound effects (programs 118–127).
//!
//! Each one is a small dedicated generator built around what makes the real
//! sound recognisable — usually its time structure rather than its
//! spectrum: the stutter of a bell clapper, the random density of a crowd's
//! claps, the blade-slap rate of a rotor, the slow swell of a wave. All
//! randomness is seeded by the key, so renders stay deterministic.

use crate::synth::filter::{FilterMode, Svf};
use crate::synth::waveguide::{Noise, Ramp, note_hz};
use std::f32::consts::TAU;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FxKind {
  /// Electronic tom: a sine sweeping down onto the note, plus a stick click.
  SynthDrum,
  /// Cymbal swell played backwards: metallic noise rising to an abrupt cut.
  ReverseCymbal,
  /// A fingertip sliding along a wound string: a pitched squeak.
  FretNoise,
  /// Breath through an open mouth: noise through broad vocal resonances.
  BreathNoise,
  /// Waves: slow swells of filtered noise breaking into foam.
  Seashore,
  /// Birdsong: bursts of fast frequency-swept chirps.
  BirdTweet,
  /// Electromechanical bell: a clapper hitting two bells, in rings.
  Telephone,
  /// Rotor blade slaps over turbine whine and engine rumble.
  Helicopter,
  /// A crowd: randomly timed, randomly coloured hand claps.
  Applause,
  /// A crack, a blast with a falling boom, and a reverberant tail.
  Gunshot,
}

const SILENT: f32 = 1e-4;
/// Number of claps that can sound at once.
const CLAPPERS: usize = 10;

#[derive(Clone, Debug)]
struct Clap {
  filter: Svf,
  env: f32,
}

/// A fingertip sliding along a wound guitar string — the quick "zwip" of a
/// hand shifting position.
///
/// The finger hits the winding's ridges at slide speed ÷ winding pitch —
/// at 0.2–0.5 m/s over a 0.25 mm winding, ~1–2 kHz — so the squeak is
/// pitched, and its pitch follows the hand: a fast glide up as the hand
/// accelerates, falling away as it stops, over about half a second.
/// What keeps it from sounding like a machine:
///
/// - **Two strings.** The finger usually crosses two wound strings, whose
///   windings differ, so two squeaks at different rates blur together.
/// - **Soft hits.** The fingertip rounds each ridge hit off (a low-pass that
///   tracks the hit rate), so it squeals rather than buzzes.
/// - **Stick–slip.** Finger pressure flutters, so the level jumps around
///   irregularly at tens of hertz, and each ridge is hit a little early or
///   late.
/// - **Scrape.** Friction noise, band-passed around the squeak's pitch.
///
/// The scraped string rings faintly underneath (a Karplus-Strong loop).
#[derive(Clone, Debug)]
struct Squeak {
  /// Gesture length (s) and peak ridge rate (Hz) of the first string.
  dur: f32,
  peak: f32,
  strings: [Ridge; 2],
  flutter: f32,
  flutter_a: f32,
  scrape: Svf,
  hp: Svf,
  lp: Svf,
  string: Vec<f32>,
  idx: usize,
  prev: f32,
}

/// One wound string under the finger.
#[derive(Clone, Copy, Debug)]
struct Ridge {
  /// Rate relative to the first string, and level.
  ratio: f32,
  mix: f32,
  phase: f32,
  jitter: f32,
  /// Fingertip rounding of the hits (one-pole state).
  soft: f32,
}

/// Ridge-hit rate at mf for key 60, Hz.
const SQUEAK_RATE: f32 = 1_800.0;
/// Per-trip loss of the string loop.
const SQUEAK_STRING_LOSS: f32 = 0.93;
/// Corner of the pressure flutter, Hz.
const SQUEAK_FLUTTER_HZ: f32 = 35.0;

impl Squeak {
  fn new(key: u8, velocity: f32, sr: f32) -> Self {
    let u = velocity.clamp(0.0, 1.0).sqrt();
    // Higher keys: faster slides (or finer windings); harder: faster.
    let peak =
      SQUEAK_RATE * 2f32.powf((key as f32 - 60.0) / 24.0) * (0.75 + 0.5 * u);
    // The wound strings are the low ones: an octave or two under the key.
    let string_hz = note_hz(key as f32 - 24.0).clamp(70.0, 200.0);
    let n = (sr / string_hz).round() as usize;
    let ridge = |ratio, mix| Ridge {
      ratio,
      mix,
      phase: 0.0,
      jitter: 1.0,
      soft: 0.0,
    };
    Self {
      dur: 0.55 - 0.2 * u,
      peak: peak.clamp(400.0, 5_000.0),
      strings: [ridge(1.0, 1.0), ridge(0.77, 0.6)],
      flutter: 0.0,
      flutter_a: (-std::f32::consts::TAU * SQUEAK_FLUTTER_HZ / sr).exp(),
      scrape: Svf::new(FilterMode::Band, sr, peak, 2.5),
      hp: Svf::new(FilterMode::High, sr, 500.0, 0.7),
      lp: Svf::new(FilterMode::Low, sr, 7_000.0, 0.7),
      string: vec![0.0; n.max(2)],
      idx: 0,
      prev: 0.0,
    }
  }

  #[inline]
  fn tick(&mut self, noise: &mut Noise, rng: &mut u32, t: f32, sr: f32) -> f32 {
    let mut rand = || {
      *rng = rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
      (*rng >> 8) as f32 / 16_777_216.0
    };
    // Hand speed over the gesture: a fast push, a slower stop.
    let x = t / self.dur;
    let v = if x < 1.0 {
      (std::f32::consts::PI * x.sqrt()).sin().max(0.0)
    } else {
      0.0
    };
    let rate = self.peak * (0.2 + 0.8 * v);
    let mut y = 0.0;
    if v > 0.0 {
      for r in self.strings.iter_mut() {
        let f = rate * r.ratio;
        r.phase += f / sr * r.jitter;
        let mut hit = 0.0;
        if r.phase >= 1.0 {
          r.phase -= 1.0;
          r.jitter = 0.9 + 0.2 * rand();
          hit = 0.5 + 0.5 * rand();
        }
        // The fingertip rounds each hit off just above the hit rate.
        let a = (-std::f32::consts::TAU * 1.5 * f / sr).exp();
        r.soft = a * r.soft + (1.0 - a) * hit;
        y += r.soft * r.mix;
      }
    }
    // Stick–slip: the pressure (and level) flutters irregularly.
    self.flutter =
      self.flutter_a * self.flutter + (1.0 - self.flutter_a) * noise.tick();
    let press = (1.0 + 6.0 * self.flutter).clamp(0.2, 1.8);
    if ((t * sr) as u32).is_multiple_of(16) {
      self.scrape.set(rate.max(300.0), 2.5);
    }
    let scrape = 0.6 * self.scrape.tick(noise.tick());
    let src = (8.0 * y + scrape) * v * press;
    let y = self.lp.tick(self.hp.tick(src));
    // The string, set ringing by the scrape.
    let back = self.string[self.idx];
    let s = y * 0.15 + back;
    let fed = 0.5 * (s + self.prev) * SQUEAK_STRING_LOSS;
    self.prev = s;
    self.string[self.idx] = fed;
    self.idx = (self.idx + 1) % self.string.len();
    0.4 * (y + 0.6 * back)
  }
}

#[derive(Clone, Debug)]
pub struct Fx {
  kind: FxKind,
  sr: f32,
  f0: f32,
  vel: f32,
  t: u32,
  gate: Ramp,
  release: f32,
  released: bool,
  noise: Noise,
  rng: u32,
  /// General-purpose state, used as each generator needs.
  f: [Svf; 3],
  phase: [f32; 4],
  env: [f32; 4],
  next: u32,
  count: u32,
  sweep: [f32; 3],
  claps: Vec<Clap>,
  squeak: Option<Box<Squeak>>,
  clap_idx: usize,
  /// The voice is done (one-shot generators).
  done: bool,
}

impl Fx {
  pub fn new(kind: FxKind, key: u8, velocity: f32, sr: f32) -> Self {
    let f0 = note_hz(key as f32);
    let (attack, release) = match kind {
      FxKind::SynthDrum | FxKind::Gunshot | FxKind::FretNoise => (0.0005, 0.3),
      FxKind::ReverseCymbal => (0.0005, 0.08),
      FxKind::BreathNoise => (0.15, 0.3),
      FxKind::Seashore => (0.8, 1.5),
      FxKind::BirdTweet => (0.001, 0.05),
      FxKind::Telephone => (0.001, 0.15),
      FxKind::Helicopter => (0.4, 1.0),
      FxKind::Applause => (0.3, 1.0),
    };
    let mut gate = Ramp::new();
    gate.go(1.0, attack, sr);
    let svf = |m, c, r| Svf::new(m, sr, c, r);
    use FilterMode::*;
    let f = match kind {
      FxKind::SynthDrum => [
        svf(Band, 3_000.0, 1.0),
        svf(Low, 200.0, 0.7),
        svf(Low, 200.0, 0.7),
      ],
      FxKind::ReverseCymbal => [
        svf(High, 6_000.0, 0.8),
        svf(Band, 9_000.0, 0.8),
        svf(High, 3_000.0, 0.7),
      ],
      // (The squeak has its own filters.)
      FxKind::FretNoise => [
        svf(Low, 10_000.0, 0.7),
        svf(Low, 10_000.0, 0.7),
        svf(Low, 10_000.0, 0.7),
      ],
      FxKind::BreathNoise => {
        let s = 2f32.powf((key as f32 - 60.0) / 48.0);
        [
          svf(Band, 600.0 * s, 2.0),
          svf(Band, 1_500.0 * s, 3.0),
          svf(Band, 2_600.0 * s, 3.0),
        ]
      }
      FxKind::Seashore => [
        svf(Low, 400.0, 0.7),
        svf(High, 3_000.0, 0.7),
        svf(Low, 8_000.0, 0.7),
      ],
      FxKind::BirdTweet => [
        svf(Low, 10_000.0, 0.7),
        svf(Low, 10_000.0, 0.7),
        svf(Low, 10_000.0, 0.7),
      ],
      FxKind::Telephone => [
        svf(High, 300.0, 0.7),
        svf(Low, 9_000.0, 0.7),
        svf(Low, 9_000.0, 0.7),
      ],
      FxKind::Helicopter => [
        svf(Low, 700.0, 1.2),
        svf(Low, 250.0, 0.9),
        svf(Band, 120.0, 2.0),
      ],
      FxKind::Applause => [
        svf(Low, 1_200.0, 0.7),
        svf(High, 200.0, 0.7),
        svf(Low, 9_000.0, 0.7),
      ],
      FxKind::Gunshot => [
        svf(Low, 2_000.0, 0.8),
        svf(Low, 700.0, 0.7),
        svf(High, 1_500.0, 0.7),
      ],
    };
    let claps = if kind == FxKind::Applause {
      (0..CLAPPERS)
        .map(|_| Clap {
          filter: svf(Band, 1_500.0, 1.5),
          env: 0.0,
        })
        .collect()
    } else {
      Vec::new()
    };
    let mut env = [0.0; 4];
    if kind == FxKind::Gunshot {
      env = [1.0, 1.0, 1.0, 0.0];
    } else if kind == FxKind::SynthDrum {
      env = [1.0, 1.0, 0.0, 0.0];
    }
    Self {
      kind,
      sr,
      f0,
      vel: velocity.clamp(0.0, 1.0).sqrt(),
      t: 0,
      gate,
      release,
      released: false,
      noise: Noise::new(0x510E_527F ^ (key as u32) << 9),
      rng: 0x9B05_688C ^ (key as u32).wrapping_mul(0x9E37_79B9),
      f,
      phase: [0.0; 4],
      env,
      next: 0,
      count: 0,
      sweep: [0.0; 3],
      claps,
      squeak: (kind == FxKind::FretNoise)
        .then(|| Box::new(Squeak::new(key, velocity, sr))),
      clap_idx: 0,
      done: false,
    }
  }

  pub fn release(&mut self) {
    if !self.released {
      self.released = true;
      self.gate.go(0.0, self.release, self.sr);
    }
  }

  pub fn is_silent(&self) -> bool {
    self.done || (self.released && self.gate.value < SILENT)
  }

  /// Uniform random in 0..1.
  fn rand(&mut self) -> f32 {
    self.rng = self.rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
    (self.rng >> 8) as f32 / 16_777_216.0
  }

  /// Seconds since note-on.
  fn time(&self) -> f32 {
    self.t as f32 / self.sr
  }

  fn decay(t60: f32, sr: f32) -> f32 {
    10f32.powf(-3.0 / (t60 * sr))
  }

  #[inline]
  fn osc(phase: &mut f32, hz: f32, sr: f32) -> f32 {
    *phase += hz / sr;
    if *phase >= 1.0 {
      *phase -= 1.0;
    }
    (TAU * *phase).sin()
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    let g = self.gate.tick();
    let sr = self.sr;
    let t = self.time();
    let s = match self.kind {
      FxKind::SynthDrum => {
        // Pitch falls from an octave and a half above onto the note.
        let hz = self.f0 * (1.0 + 1.8 * (-t / 0.05).exp());
        let tone = Self::osc(&mut self.phase[0], hz, sr) * self.env[0];
        self.env[0] *=
          Self::decay(0.7 * (261.6 / self.f0).powf(0.3).clamp(0.4, 2.0), sr);
        let click = self.f[0].tick(self.noise.tick()) * self.env[1];
        self.env[1] *= Self::decay(0.025, sr);
        if self.env[0] < SILENT {
          self.done = true;
        }
        0.8 * tone + 0.6 * click
      }
      FxKind::ReverseCymbal => {
        // Inharmonic square-wave cluster (a metal plate's dense partials)
        // and noise, swelling exponentially to a cut at `PEAK` s.
        const PEAK: f32 = 1.8;
        const RATIOS: [f32; 6] = [1.0, 1.483, 1.932, 2.546, 2.630, 3.897];
        let base = 300.0 * (self.f0 / 261.6).powf(0.25);
        let mut metal = 0.0;
        for (i, r) in RATIOS.iter().enumerate() {
          let p = (t * base * r).fract();
          metal += if p < 0.5 { 1.0 } else { -1.0 } * (1.0 - 0.1 * i as f32);
        }
        let n = self.noise.tick();
        let x = self.f[0].tick(0.3 * metal / 6.0 + 0.7 * n);
        let x = x + 0.4 * self.f[1].tick(n);
        let env = if t < PEAK {
          ((t - PEAK) / 0.45).exp()
        } else {
          self.env[0] = if self.env[0] == 0.0 {
            1.0
          } else {
            self.env[0] * Self::decay(0.12, sr)
          };
          if self.env[0] < SILENT {
            self.done = true;
          }
          self.env[0]
        };
        1.4 * x * env
      }
      FxKind::FretNoise => {
        let sq = self.squeak.as_mut().expect("fret noise has a squeak");
        let x = sq.tick(&mut self.noise, &mut self.rng, t, sr);
        if t > sq.dur + 1.5 {
          self.done = true;
        }
        x
      }
      FxKind::BreathNoise => {
        let n = self.noise.tick();
        // Slow unsteadiness of the airflow.
        let wobble = 1.0 + 0.25 * Self::osc(&mut self.phase[0], 0.7, sr);
        let x = 0.8 * self.f[0].tick(n)
          + 0.6 * self.f[1].tick(n)
          + 0.35 * self.f[2].tick(n);
        x * wobble
      }
      FxKind::Seashore => {
        // One wave every 6–10 s: a swell for ~35 % of it, then the break
        // and a long retreating hiss.
        if self.t >= self.next {
          self.count = self.t;
          let period = 6.0 + 4.0 * self.rand();
          self.sweep[0] = period;
          self.sweep[1] = 0.6 + 0.4 * self.rand(); // size
          self.next = self.t + (period * sr) as u32;
        }
        let tw = (self.t - self.count) as f32 / sr;
        let peak = 0.35 * self.sweep[0];
        let w = if tw < peak {
          (tw / peak).powi(2)
        } else {
          (-(tw - peak) / (0.22 * self.sweep[0])).exp()
        } * self.sweep[1];
        if self.t.is_multiple_of(32) {
          self.f[0].set(250.0 + 3_500.0 * w, 0.7);
        }
        let n = self.noise.tick();
        let body = self.f[0].tick(n) * (0.15 + w);
        // Foam fizz after the break.
        let foam = if tw > peak { w } else { 0.0 };
        let fizz = self.f[1].tick(n) * foam * 0.5;
        0.9 * (body + fizz)
      }
      FxKind::BirdTweet => {
        // Phrases of 3–7 chirps ~90 ms apart, then a pause.
        if self.t >= self.next {
          if self.count == 0 {
            self.count = 3 + (self.rand() * 5.0) as u32;
          }
          self.count -= 1;
          let len = 0.04 + 0.05 * self.rand();
          self.sweep = [0.0, len, if self.rand() < 0.7 { 1.0 } else { -1.0 }];
          let gap = if self.count == 0 {
            0.25 + 0.5 * self.rand()
          } else {
            0.07 + 0.04 * self.rand()
          };
          self.next = self.t + ((len + gap) * sr) as u32;
          self.env[0] = 0.6 + 0.4 * self.rand();
        }
        let fc = (self.f0 * 16.0).clamp(1_500.0, 9_000.0);
        let (age, len, dir) = (self.sweep[0], self.sweep[1], self.sweep[2]);
        self.sweep[0] += 1.0 / sr;
        if age < len {
          let x = age / len;
          // Downward (or upward) sweep over most of an octave, with a fast
          // warble on top.
          let hz = fc
            * 2f32.powf(dir * (0.6 - 0.9 * x))
            * (1.0 + 0.04 * Self::osc(&mut self.phase[1], 45.0, sr));
          let win = (std::f32::consts::PI * x).sin().powi(2);
          Self::osc(&mut self.phase[0], hz, sr) * win * self.env[0]
        } else {
          0.0
        }
      }
      FxKind::Telephone => {
        // Rings of 0.4 s on, 0.2 off, 0.4 on, 2 off; while ringing a
        // clapper alternates between two small bells 20 times a second.
        const PATTERN: f32 = 3.0;
        let c = t % PATTERN;
        let ringing = c < 0.4 || (0.6..1.0).contains(&c);
        if ringing && self.t >= self.next {
          self.next = self.t + (sr / 20.0) as u32;
          self.count ^= 1;
          let b = self.count as usize;
          self.env[b] = 1.0;
        }
        let base = (self.f0 * 4.0).clamp(500.0, 4_000.0);
        let k = Self::decay(0.25, sr);
        let mut x = 0.0;
        for b in 0..2 {
          let fb = base * if b == 0 { 1.0 } else { 1.19 };
          // Small bell: hum, prime and a couple of upper partials.
          x += self.env[b]
            * (Self::osc(&mut self.phase[b * 2], fb, sr)
              + 0.5 * (TAU * self.phase[b * 2] * 2.76).sin()
              + 0.25 * (TAU * self.phase[b * 2] * 5.40).sin());
          self.env[b] *= k;
        }
        0.45 * self.f[0].tick(x)
      }
      FxKind::Helicopter => {
        // Blade passes at ~13 Hz (transposed gently by key).
        let rate = 13.0 * 2f32.powf((12.0 * (self.f0 / 261.6).log2()) / 36.0);
        let p = self.phase[0];
        self.phase[0] = (p + rate / sr).fract();
        if self.phase[0] < p {
          self.env[0] = 1.0;
          self.env[1] = 1.0;
        }
        let n = self.noise.tick();
        let slap = self.f[0].tick(n) * self.env[0];
        self.env[0] *= Self::decay(0.06, sr);
        let thump = Self::osc(&mut self.phase[1], 55.0, sr) * self.env[1];
        self.env[1] *= Self::decay(0.09, sr);
        let rumble = self.f[1].tick(n) * 0.6;
        let whine = 0.04
          * (Self::osc(&mut self.phase[2], 1_420.0, sr)
            + 0.5 * Self::osc(&mut self.phase[3], 2_870.0, sr));
        1.2 * slap + 0.8 * thump + rumble + whine
      }
      FxKind::Applause => {
        // Claps arrive at random; louder applause is denser.
        let density = 40.0 + 220.0 * self.vel;
        if self.rand() < density / sr {
          let centre = 700.0 * 2f32.powf(2.0 * self.rand());
          let amp = 0.4 + 0.6 * self.rand();
          let i = self.clap_idx;
          self.clap_idx = (i + 1) % CLAPPERS;
          let c = &mut self.claps[i];
          c.filter
            .set(centre, 1.2 + self.rng as f32 / u32::MAX as f32);
          c.env = amp;
        }
        let k = Self::decay(0.035, sr);
        let mut x = 0.0;
        for c in self.claps.iter_mut() {
          if c.env > 1e-4 {
            let n = self.noise.tick();
            x += c.filter.tick(n) * c.env;
            c.env *= k;
          }
        }
        let wash = 0.15 * self.f[0].tick(self.noise.tick());
        1.4 * self.f[1].tick(x + wash)
      }
      FxKind::Gunshot => {
        let n = self.noise.tick();
        let crack = n * self.env[0];
        self.env[0] *= Self::decay(0.008, sr);
        let blast = self.f[0].tick(n) * self.env[1];
        self.env[1] *= Self::decay(0.3, sr);
        let hz = 40.0 + 60.0 * (-t / 0.04).exp();
        let boom = Self::osc(&mut self.phase[0], hz, sr) * self.env[2];
        self.env[2] *= Self::decay(0.4, sr);
        let tail = self.f[1].tick(n) * 0.18 * (-t / 0.35).exp();
        if t > 3.0 {
          self.done = true;
        }
        0.8 * crack + 1.2 * blast + 0.9 * boom + tail
      }
    };
    self.t = self.t.saturating_add(1);
    s * g
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  const ALL: [FxKind; 10] = [
    FxKind::SynthDrum,
    FxKind::ReverseCymbal,
    FxKind::FretNoise,
    FxKind::BreathNoise,
    FxKind::Seashore,
    FxKind::BirdTweet,
    FxKind::Telephone,
    FxKind::Helicopter,
    FxKind::Applause,
    FxKind::Gunshot,
  ];

  /// Period (samples) of the strongest repetition in `x` between `lo` and
  /// `hi` samples.
  fn period(x: &[f32], lo: usize, hi: usize) -> usize {
    (lo..=hi)
      .max_by(|&a, &b| {
        let ac =
          |l: usize| (0..x.len() - l).map(|i| x[i] * x[i + l]).sum::<f32>();
        ac(a).total_cmp(&ac(b))
      })
      .unwrap()
  }

  /// The squeak is pitched by the ridge-hit rate: around a kilohertz or two,
  /// rising while the hand speeds up.
  #[test]
  fn fret_squeak_is_pitched_and_rises() {
    let sr = 44_100.0;
    let mut fx = Fx::new(FxKind::FretNoise, 60, 0.5, sr);
    let x: Vec<f32> = (0..(0.5 * sr) as usize).map(|_| fx.tick()).collect();
    let dur = fx.squeak.as_ref().unwrap().dur;
    let win = |c: f32| {
      let i = (c * dur * sr) as usize;
      &x[i.saturating_sub(300)..i + 300]
    };
    let (lo, hi) = ((sr / 4_000.0) as usize, (sr / 300.0) as usize);
    let early = sr / period(win(0.05), lo, hi) as f32;
    let top = sr / period(win(0.25), lo, hi) as f32;
    assert!((800.0..3_500.0).contains(&top), "peak squeak at {top} Hz");
    assert!(top > 1.3 * early, "no rise: {early} → {top} Hz");
  }

  #[test]
  fn every_effect_sounds_and_stops() {
    let sr = 44_100.0;
    for kind in ALL {
      let mut fx = Fx::new(kind, 60, 0.5, sr);
      let x: Vec<f32> = (0..(3.0 * sr) as usize).map(|_| fx.tick()).collect();
      let rms = (x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).sqrt();
      let peak = x.iter().fold(0f32, |m, v| m.max(v.abs()));
      assert!(x.iter().all(|v| v.is_finite()), "{kind:?}: not finite");
      assert!(rms > 0.01, "{kind:?}: too quiet ({rms})");
      assert!(peak < 3.0, "{kind:?}: peak {peak}");
      fx.release();
      for _ in 0..(5.0 * sr) as usize {
        fx.tick();
      }
      assert!(fx.is_silent(), "{kind:?}: still sounding");
    }
  }
}