helena 0.1.0

Core types and component interfaces for helena, a latent data-to-waveform generation platform.
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
//! Analytic acoustic probes: typed, fingerprintable capability targets.
//!
//! A maximum-fidelity *overfit proof* asks: can the model represent nuanced,
//! layered acoustics — oscillating harmonies, vibrating melodies, rhythmic
//! beats, vocalic resonance — at once? To make that question answerable, the
//! target must have *known structure*. A [`Probe`] is that target: a stack
//! of analytic [`Stratum`] layers rendered deterministically to [`Pcm`],
//! serializable and therefore fingerprintable (a capability experiment's
//! target is reproducible from its descriptor, NFR-010).
//!
//! **The superposition contract.** A probe's render is *bit-exactly* the
//! left-fold sum of its layers' solo renders
//! ([`Probe::render_layer`]): the cumulative effect is not an emergent hope
//! but an algebraic identity, so per-stratum fidelity diagnostics can
//! decompose a reconstruction against each layer's exact reference. Gains
//! are the caller's mix; rendering never normalizes (normalization would
//! break the identity).
//!
//! Each stratum is one contrast of the island: the harmonic stack and its
//! vibrato are the sustained interior, the beat train the breaking rhythm,
//! the vowel formants the voiced resonance, and the seeded wash the sea —
//! vast, textural, and exactly reproducible.

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::seams::ClipDuration;
use crate::signal::{ChannelLayout, Pcm};
use crate::time::SampleRate;

/// Sinusoidal frequency modulation of a stratum's fundamental — the
/// "vibrating melody" axis.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Vibrato {
    /// Modulation rate in Hz (how fast the pitch waves).
    pub rate_hz: f32,
    /// Peak deviation of the fundamental in Hz (how far it waves).
    pub depth_hz: f32,
}

/// One partial of a harmonic stack.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Partial {
    /// Harmonic number (1 = fundamental).
    pub harmonic: u32,
    /// Linear amplitude.
    pub amplitude: f32,
}

/// One vocal-tract resonance of a vowel stratum.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Formant {
    /// Resonance center in Hz.
    pub center_hz: f32,
    /// Resonance bandwidth in Hz (full width at half maximum).
    pub bandwidth_hz: f32,
    /// Linear gain at the center.
    pub gain: f32,
}

/// One analytic layer of a probe.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Stratum {
    /// Oscillating harmonies: a stack of partials over a fundamental,
    /// optionally frequency-modulated ([`Vibrato`]).
    Harmonics {
        /// Fundamental frequency in Hz.
        f0_hz: f32,
        /// The stack, as (harmonic number, amplitude) pairs.
        partials: Vec<Partial>,
        /// Optional pitch modulation.
        vibrato: Option<Vibrato>,
    },
    /// Rhythmic beats: exponentially decaying sine clicks on a tempo grid.
    Beats {
        /// Tempo in beats per minute.
        tempo_bpm: f32,
        /// Click carrier frequency in Hz.
        carrier_hz: f32,
        /// Click energy decay time constant in seconds.
        decay_seconds: f32,
    },
    /// Vocalic resonance: a voiced source whose partial amplitudes are
    /// shaped by formant resonances (additive source–filter, no IIR state,
    /// spectrally exact for diagnostics).
    Vowel {
        /// Voicing fundamental in Hz.
        f0_hz: f32,
        /// The vocal-tract resonances.
        formants: Vec<Formant>,
    },
    /// The sea: a seeded, uniformly distributed noise wash — textural
    /// contrast, exactly reproducible from its seed.
    Wash {
        /// Deterministic noise seed.
        seed: u64,
        /// Linear amplitude.
        amplitude: f32,
    },
}

impl Stratum {
    /// Validate the stratum's rate-independent invariants.
    fn validate(&self) -> Result<()> {
        let positive = |value: f32, what: &str| -> Result<()> {
            if value.is_finite() && value > 0.0 {
                Ok(())
            } else {
                Err(Error::validation(format!(
                    "probe {what} must be finite and positive, got {value}"
                )))
            }
        };
        let non_negative = |value: f32, what: &str| -> Result<()> {
            if value.is_finite() && value >= 0.0 {
                Ok(())
            } else {
                Err(Error::validation(format!(
                    "probe {what} must be finite and non-negative, got {value}"
                )))
            }
        };
        match self {
            Stratum::Harmonics {
                f0_hz,
                partials,
                vibrato,
            } => {
                positive(*f0_hz, "harmonic f0")?;
                if partials.is_empty() {
                    return Err(Error::validation("a harmonic stack needs ≥ 1 partial"));
                }
                for partial in partials {
                    if partial.harmonic == 0 {
                        return Err(Error::validation("harmonic numbers start at 1"));
                    }
                    non_negative(partial.amplitude, "partial amplitude")?;
                }
                if let Some(v) = vibrato {
                    positive(v.rate_hz, "vibrato rate")?;
                    non_negative(v.depth_hz, "vibrato depth")?;
                    if v.depth_hz >= *f0_hz {
                        return Err(Error::validation(
                            "vibrato depth must stay below f0 (frequency must stay positive)",
                        ));
                    }
                }
                Ok(())
            }
            Stratum::Beats {
                tempo_bpm,
                carrier_hz,
                decay_seconds,
            } => {
                positive(*tempo_bpm, "tempo")?;
                positive(*carrier_hz, "beat carrier")?;
                positive(*decay_seconds, "beat decay")
            }
            Stratum::Vowel { f0_hz, formants } => {
                positive(*f0_hz, "vowel f0")?;
                if formants.is_empty() {
                    return Err(Error::validation("a vowel needs ≥ 1 formant"));
                }
                for formant in formants {
                    positive(formant.center_hz, "formant center")?;
                    positive(formant.bandwidth_hz, "formant bandwidth")?;
                    non_negative(formant.gain, "formant gain")?;
                }
                Ok(())
            }
            Stratum::Wash { amplitude, .. } => non_negative(*amplitude, "wash amplitude"),
        }
    }

    /// The highest frequency this stratum emits, for the render-time Nyquist
    /// check (vibrato excursion included).
    fn max_frequency(&self) -> f32 {
        match self {
            Stratum::Harmonics {
                f0_hz,
                partials,
                vibrato,
            } => {
                let top = partials.iter().map(|p| p.harmonic).max().unwrap_or(1) as f32;
                let excursion = vibrato.map_or(0.0, |v| v.depth_hz);
                top * (f0_hz + excursion)
            }
            Stratum::Beats { carrier_hz, .. } => *carrier_hz,
            // Vowel partials above Nyquist are skipped at render; the
            // constraint is on the fundamental itself.
            Stratum::Vowel { f0_hz, .. } => *f0_hz,
            Stratum::Wash { .. } => 0.0,
        }
    }

    /// Render `len` mono samples at `rate` into a fresh f32 buffer.
    /// Deterministic: phase accumulation and noise generation are seeded,
    /// order-fixed f64 arithmetic.
    fn render(&self, rate: SampleRate, len: usize) -> Vec<f32> {
        let sr = f64::from(rate.get());
        let mut out = vec![0.0f32; len];
        match self {
            Stratum::Harmonics {
                f0_hz,
                partials,
                vibrato,
            } => {
                let f0 = f64::from(*f0_hz);
                let mut phases = vec![0.0f64; partials.len()];
                for (n, sample) in out.iter_mut().enumerate() {
                    let t = n as f64 / sr;
                    let dev = vibrato.map_or(0.0, |v| {
                        f64::from(v.depth_hz)
                            * (std::f64::consts::TAU * f64::from(v.rate_hz) * t).sin()
                    });
                    let mut acc = 0.0f64;
                    for (partial, phase) in partials.iter().zip(phases.iter_mut()) {
                        acc += f64::from(partial.amplitude) * phase.sin();
                        *phase +=
                            std::f64::consts::TAU * f64::from(partial.harmonic) * (f0 + dev) / sr;
                    }
                    *sample = acc as f32;
                }
            }
            Stratum::Beats {
                tempo_bpm,
                carrier_hz,
                decay_seconds,
            } => {
                let period = 60.0 / f64::from(*tempo_bpm);
                for (n, sample) in out.iter_mut().enumerate() {
                    let t = n as f64 / sr;
                    // Time since the most recent beat: with decay well under
                    // the period, one click is audible at a time.
                    let t_rel = t - (t / period).floor() * period;
                    let envelope = (-t_rel / f64::from(*decay_seconds)).exp();
                    *sample = (envelope
                        * (std::f64::consts::TAU * f64::from(*carrier_hz) * t_rel).sin())
                        as f32;
                }
            }
            Stratum::Vowel { f0_hz, formants } => {
                let f0 = f64::from(*f0_hz);
                let nyquist = sr / 2.0;
                // Voiced source with 1/k tilt, partial amplitudes shaped by
                // Lorentzian resonances — the spectral envelope is exact, so
                // a diagnostic can read formants straight off the partials.
                let mut stack = Vec::new();
                let mut k = 1u32;
                while f64::from(k) * f0 < nyquist {
                    let freq = f64::from(k) * f0;
                    let mut amp = 0.0f64;
                    for formant in formants {
                        let half = f64::from(formant.bandwidth_hz) / 2.0;
                        let detune = (freq - f64::from(formant.center_hz)) / half;
                        amp += f64::from(formant.gain) / (1.0 + detune * detune);
                    }
                    stack.push((freq, amp / f64::from(k)));
                    k += 1;
                }
                let mut phases = vec![0.0f64; stack.len()];
                for sample in out.iter_mut() {
                    let mut acc = 0.0f64;
                    for ((freq, amp), phase) in stack.iter().zip(phases.iter_mut()) {
                        acc += amp * phase.sin();
                        *phase += std::f64::consts::TAU * freq / sr;
                    }
                    *sample = acc as f32;
                }
            }
            Stratum::Wash { seed, amplitude } => {
                let mut state = *seed;
                for sample in out.iter_mut() {
                    // SplitMix64: tiny, seedable, dependency-free.
                    state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
                    let mut z = state;
                    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
                    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
                    z ^= z >> 31;
                    let unit = (z >> 11) as f64 / (1u64 << 53) as f64; // [0, 1)
                    *sample = (f64::from(*amplitude) * (2.0 * unit - 1.0)) as f32;
                }
            }
        }
        out
    }
}

/// One layer of a probe: a stratum at a mix gain.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layer {
    stratum: Stratum,
    gain: f32,
}

impl Layer {
    /// A stratum at a finite, non-negative mix gain.
    pub fn new(stratum: Stratum, gain: f32) -> Result<Self> {
        if !(gain.is_finite() && gain >= 0.0) {
            return Err(Error::validation(format!(
                "layer gain must be finite and non-negative, got {gain}"
            )));
        }
        stratum.validate()?;
        Ok(Self { stratum, gain })
    }

    /// The layer's stratum.
    pub fn stratum(&self) -> &Stratum {
        &self.stratum
    }

    /// The layer's mix gain.
    pub fn gain(&self) -> f32 {
        self.gain
    }
}

/// A layered analytic target for fidelity experiments.
///
/// Invariants (enforced at construction and re-proven on deserialization):
/// at least one layer, every layer validated. Rendering demands every
/// stratum's top frequency clear Nyquist at the chosen rate.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "ProbeRepr")]
pub struct Probe {
    layers: Vec<Layer>,
}

impl Probe {
    /// Stack layers into a probe.
    pub fn new(layers: Vec<Layer>) -> Result<Self> {
        if layers.is_empty() {
            return Err(Error::validation("a probe needs at least one layer"));
        }
        Ok(Self { layers })
    }

    /// The layers, in mix order.
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }

    /// Render one layer solo — the per-stratum reference a fidelity
    /// diagnostic decomposes against. Mono at `rate` for `duration`.
    pub fn render_layer(
        &self,
        index: usize,
        rate: SampleRate,
        duration: ClipDuration,
    ) -> Result<Pcm> {
        let layer = self.layers.get(index).ok_or_else(|| {
            Error::validation(format!(
                "probe has {} layers; no layer {index}",
                self.layers.len()
            ))
        })?;
        self.check_nyquist(rate)?;
        let len = samples_for(rate, duration);
        let mut buffer = layer.stratum.render(rate, len);
        for sample in &mut buffer {
            *sample *= layer.gain;
        }
        Pcm::new(rate, ChannelLayout::Mono, buffer)
    }

    /// Render the full stack.
    ///
    /// **Superposition contract**: this is bit-exactly the left-fold sum of
    /// [`render_layer`](Self::render_layer) over all layers — verified by
    /// this module's tests, relied on by per-stratum diagnostics.
    pub fn render(&self, rate: SampleRate, duration: ClipDuration) -> Result<Pcm> {
        self.check_nyquist(rate)?;
        let len = samples_for(rate, duration);
        let mut mix = vec![0.0f32; len];
        for layer in &self.layers {
            let buffer = layer.stratum.render(rate, len);
            for (out, sample) in mix.iter_mut().zip(buffer) {
                *out += layer.gain * sample;
            }
        }
        Pcm::new(rate, ChannelLayout::Mono, mix)
    }

    fn check_nyquist(&self, rate: SampleRate) -> Result<()> {
        let nyquist = f64::from(rate.get()) / 2.0;
        for (i, layer) in self.layers.iter().enumerate() {
            let top = f64::from(layer.stratum.max_frequency());
            if top >= nyquist {
                return Err(Error::validation(format!(
                    "layer {i} reaches {top} Hz, at or above Nyquist ({nyquist} Hz) for {rate}"
                )));
            }
        }
        Ok(())
    }
}

fn samples_for(rate: SampleRate, duration: ClipDuration) -> usize {
    (f64::from(duration.seconds()) * f64::from(rate.get())).round() as usize
}

/// Wire form, routed back through the validating constructors so a
/// hand-written probe descriptor with an illegal stratum fails closed.
#[derive(Deserialize)]
struct ProbeRepr {
    layers: Vec<LayerRepr>,
}

#[derive(Deserialize)]
struct LayerRepr {
    stratum: Stratum,
    gain: f32,
}

impl TryFrom<ProbeRepr> for Probe {
    type Error = Error;

    fn try_from(repr: ProbeRepr) -> Result<Self> {
        Probe::new(
            repr.layers
                .into_iter()
                .map(|layer| Layer::new(layer.stratum, layer.gain))
                .collect::<Result<Vec<_>>>()?,
        )
    }
}

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

    fn rate() -> SampleRate {
        SampleRate::try_from(16_000).unwrap()
    }

    fn secs(s: f32) -> ClipDuration {
        ClipDuration::new(s).unwrap()
    }

    fn island() -> Probe {
        Probe::new(vec![
            Layer::new(
                Stratum::Harmonics {
                    f0_hz: 220.0,
                    partials: vec![
                        Partial {
                            harmonic: 1,
                            amplitude: 1.0,
                        },
                        Partial {
                            harmonic: 3,
                            amplitude: 0.4,
                        },
                    ],
                    vibrato: Some(Vibrato {
                        rate_hz: 5.0,
                        depth_hz: 6.0,
                    }),
                },
                0.5,
            )
            .unwrap(),
            Layer::new(
                Stratum::Beats {
                    tempo_bpm: 120.0,
                    carrier_hz: 1_000.0,
                    decay_seconds: 0.03,
                },
                0.3,
            )
            .unwrap(),
            Layer::new(
                Stratum::Vowel {
                    f0_hz: 110.0,
                    formants: vec![
                        Formant {
                            center_hz: 700.0,
                            bandwidth_hz: 110.0,
                            gain: 1.0,
                        },
                        Formant {
                            center_hz: 1_220.0,
                            bandwidth_hz: 120.0,
                            gain: 0.5,
                        },
                    ],
                },
                0.4,
            )
            .unwrap(),
            Layer::new(
                Stratum::Wash {
                    seed: 7,
                    amplitude: 1.0,
                },
                0.05,
            )
            .unwrap(),
        ])
        .unwrap()
    }

    /// Correlate against a probe frequency — a one-bin DFT, enough to read
    /// spectral structure off a rendered probe.
    fn energy_at(pcm: &Pcm, freq: f64) -> f64 {
        let sr = f64::from(pcm.rate().get());
        let (mut re, mut im) = (0.0f64, 0.0f64);
        for (n, &x) in pcm.samples().iter().enumerate() {
            let phase = std::f64::consts::TAU * freq * n as f64 / sr;
            re += f64::from(x) * phase.cos();
            im -= f64::from(x) * phase.sin();
        }
        (re * re + im * im).sqrt() / pcm.samples().len() as f64
    }

    #[test]
    fn superposition_is_bit_exact() {
        let probe = island();
        let mix = probe.render(rate(), secs(0.25)).unwrap();
        let mut fold = vec![0.0f32; mix.samples().len()];
        for i in 0..probe.layers().len() {
            let solo = probe.render_layer(i, rate(), secs(0.25)).unwrap();
            for (acc, s) in fold.iter_mut().zip(solo.samples()) {
                *acc += *s;
            }
        }
        assert_eq!(mix.samples(), fold.as_slice());
    }

    #[test]
    fn renders_are_deterministic_and_fingerprintable() {
        let probe = island();
        let a = probe.render(rate(), secs(0.1)).unwrap();
        let b = probe.render(rate(), secs(0.1)).unwrap();
        assert_eq!(a, b);
        crate::laws::fingerprint_stable(&probe).unwrap();

        // Distinct wash seeds are distinct seas.
        let sea = |seed| {
            Probe::new(vec![
                Layer::new(
                    Stratum::Wash {
                        seed,
                        amplitude: 1.0,
                    },
                    1.0,
                )
                .unwrap(),
            ])
            .unwrap()
            .render(rate(), secs(0.05))
            .unwrap()
        };
        assert_ne!(sea(1), sea(2));
    }

    #[test]
    fn harmonics_land_on_their_partials() {
        let probe = Probe::new(vec![
            Layer::new(
                Stratum::Harmonics {
                    f0_hz: 440.0,
                    partials: vec![
                        Partial {
                            harmonic: 1,
                            amplitude: 1.0,
                        },
                        Partial {
                            harmonic: 2,
                            amplitude: 0.5,
                        },
                    ],
                    vibrato: None,
                },
                1.0,
            )
            .unwrap(),
        ])
        .unwrap();
        let pcm = probe.render(rate(), secs(0.5)).unwrap();
        assert!(energy_at(&pcm, 440.0) > 10.0 * energy_at(&pcm, 617.0));
        assert!(energy_at(&pcm, 880.0) > 10.0 * energy_at(&pcm, 617.0));
    }

    #[test]
    fn vibrato_spreads_the_line() {
        let stack = |vibrato| {
            Probe::new(vec![
                Layer::new(
                    Stratum::Harmonics {
                        f0_hz: 440.0,
                        partials: vec![Partial {
                            harmonic: 1,
                            amplitude: 1.0,
                        }],
                        vibrato,
                    },
                    1.0,
                )
                .unwrap(),
            ])
            .unwrap()
            .render(rate(), secs(0.5))
            .unwrap()
        };
        let plain = stack(None);
        let waved = stack(Some(Vibrato {
            rate_hz: 6.0,
            depth_hz: 15.0,
        }));
        assert_ne!(plain, waved);
        // Modulation moves energy off the exact carrier line.
        assert!(energy_at(&waved, 440.0) < energy_at(&plain, 440.0));
    }

    #[test]
    fn beats_decay_between_onsets() {
        let probe = Probe::new(vec![
            Layer::new(
                Stratum::Beats {
                    tempo_bpm: 120.0, // 0.5 s period
                    carrier_hz: 1_000.0,
                    decay_seconds: 0.02,
                },
                1.0,
            )
            .unwrap(),
        ])
        .unwrap();
        let pcm = probe.render(rate(), secs(1.0)).unwrap();
        let sr = pcm.rate().get() as usize;
        let rms = |from: usize, to: usize| {
            let window = &pcm.samples()[from..to];
            (window
                .iter()
                .map(|x| f64::from(*x) * f64::from(*x))
                .sum::<f64>()
                / window.len() as f64)
                .sqrt()
        };
        // Attack of the second beat vs the tail of the first.
        let attack = rms(sr / 2, sr / 2 + sr / 100);
        let tail = rms(sr * 2 / 5, sr * 2 / 5 + sr / 100);
        assert!(attack > 5.0 * tail, "attack {attack} vs tail {tail}");
    }

    #[test]
    fn vowel_partials_follow_the_formants() {
        let probe = Probe::new(vec![
            Layer::new(
                Stratum::Vowel {
                    f0_hz: 100.0,
                    formants: vec![Formant {
                        center_hz: 700.0,
                        bandwidth_hz: 100.0,
                        gain: 1.0,
                    }],
                },
                1.0,
            )
            .unwrap(),
        ])
        .unwrap();
        let pcm = probe.render(rate(), secs(0.5)).unwrap();
        // The partial at the formant (700 Hz = 7·f0) dominates a distant one
        // (3 kHz = 30·f0) by far more than the 1/k source tilt explains.
        assert!(energy_at(&pcm, 700.0) > 10.0 * energy_at(&pcm, 3_000.0));
    }

    #[test]
    fn construction_and_render_fail_closed() {
        assert!(Probe::new(vec![]).is_err());
        assert!(
            Layer::new(
                Stratum::Harmonics {
                    f0_hz: 0.0,
                    partials: vec![],
                    vibrato: None
                },
                1.0
            )
            .is_err()
        );
        assert!(
            Layer::new(
                Stratum::Wash {
                    seed: 0,
                    amplitude: -1.0
                },
                1.0
            )
            .is_err()
        );
        assert!(
            Layer::new(
                Stratum::Wash {
                    seed: 0,
                    amplitude: 0.0
                },
                f32::NAN
            )
            .is_err()
        );

        // A 9 kHz carrier cannot render at 16 kHz.
        let hot = Probe::new(vec![
            Layer::new(
                Stratum::Beats {
                    tempo_bpm: 60.0,
                    carrier_hz: 9_000.0,
                    decay_seconds: 0.01,
                },
                1.0,
            )
            .unwrap(),
        ])
        .unwrap();
        assert!(hot.render(rate(), secs(0.1)).is_err());
    }

    #[test]
    fn serde_round_trips_and_re_proves_invariants() {
        let probe = island();
        let json = serde_json::to_string(&probe).unwrap();
        assert_eq!(serde_json::from_str::<Probe>(&json).unwrap(), probe);

        // A hand-edited descriptor with an illegal gain fails closed.
        let bad = json.replace(r#""gain":0.5"#, r#""gain":-0.5"#);
        assert!(serde_json::from_str::<Probe>(&bad).is_err());
    }
}