Skip to main content

roxlap_audio/
synth.rs

1//! AU.2 — procedurally synthesized demo sounds (house pattern: no
2//! binary assets; the Doom demo synthesizes its GIFs, we synthesize
3//! our bleeps). Deterministic — the noise source is a fixed LCG — so
4//! buffers are testable byte-for-byte and identical across runs.
5//!
6//! Retro engine, retro bleeps: these read as programmer art on
7//! purpose. Real assets can replace them at the playback layer (the
8//! kira backend also accepts encoded files via its own loaders).
9
10/// A mono PCM buffer in `-1..=1` floats — the backend-agnostic sound
11/// asset the [`crate::AudioOut`] trait registers.
12#[derive(Debug, Clone, PartialEq)]
13pub struct SoundBuffer {
14    /// Samples per second.
15    pub sample_rate: u32,
16    /// Mono samples, `-1..=1`.
17    pub samples: Vec<f32>,
18}
19
20impl SoundBuffer {
21    /// Buffer duration in seconds.
22    #[must_use]
23    pub fn duration(&self) -> f32 {
24        #[allow(clippy::cast_precision_loss)]
25        let n = self.samples.len() as f32;
26        #[allow(clippy::cast_precision_loss)]
27        let sr = self.sample_rate as f32;
28        n / sr
29    }
30}
31
32/// Fixed-seed LCG noise in `-1..=1` (Numerical Recipes constants) —
33/// deterministic across runs and platforms.
34struct Lcg(u64);
35
36impl Lcg {
37    fn next(&mut self) -> f32 {
38        self.0 = self
39            .0
40            .wrapping_mul(6_364_136_223_846_793_005)
41            .wrapping_add(1_442_695_040_888_963_407);
42        // Top 24 bits → [-1, 1).
43        #[allow(clippy::cast_precision_loss)]
44        let v = ((self.0 >> 40) as f32) / 8_388_608.0;
45        v - 1.0
46    }
47}
48
49/// A plasma-shot transient: a sharp noise burst with a fast downward
50/// pitch sweep, ~120 ms.
51#[must_use]
52pub fn shot(sample_rate: u32) -> SoundBuffer {
53    let n = (sample_rate as usize * 120) / 1000;
54    let mut rng = Lcg(0x5EED_0001);
55    let mut samples = Vec::with_capacity(n);
56    #[allow(clippy::cast_precision_loss)]
57    let sr = sample_rate as f32;
58    let mut phase = 0.0f32;
59    for i in 0..n {
60        #[allow(clippy::cast_precision_loss)]
61        let t = i as f32 / sr;
62        // 1400 Hz → 300 Hz sweep under an exponential decay, plus a
63        // noise tail for the "crack".
64        let f = 1400.0 * (-t * 18.0).exp() + 300.0;
65        phase += std::f32::consts::TAU * f / sr;
66        let env = (-t * 30.0).exp();
67        let s = (phase.sin() * 0.7 + rng.next() * 0.3) * env;
68        samples.push(s.clamp(-1.0, 1.0));
69    }
70    SoundBuffer {
71        sample_rate,
72        samples,
73    }
74}
75
76/// An impact boom: a low sine thump plus a noise tail, ~500 ms —
77/// the carve explosion.
78#[must_use]
79pub fn impact(sample_rate: u32) -> SoundBuffer {
80    let n = (sample_rate as usize * 500) / 1000;
81    let mut rng = Lcg(0x5EED_0002);
82    let mut samples = Vec::with_capacity(n);
83    #[allow(clippy::cast_precision_loss)]
84    let sr = sample_rate as f32;
85    let mut phase = 0.0f32;
86    for i in 0..n {
87        #[allow(clippy::cast_precision_loss)]
88        let t = i as f32 / sr;
89        let f = 120.0 * (-t * 6.0).exp() + 45.0;
90        phase += std::f32::consts::TAU * f / sr;
91        let thump = phase.sin() * (-t * 7.0).exp();
92        let rumble = rng.next() * (-t * 4.0).exp() * 0.35;
93        samples.push((thump * 0.8 + rumble).clamp(-1.0, 1.0));
94    }
95    SoundBuffer {
96        sample_rate,
97        samples,
98    }
99}
100
101/// A crystal hum: a softly beating detuned sine pair, seamlessly
102/// loopable (both partials complete an integer number of cycles).
103#[must_use]
104pub fn hum(sample_rate: u32) -> SoundBuffer {
105    // Loop length 1 s ⇒ integer frequencies loop seamlessly. 220 Hz +
106    // 223 Hz beats at 3 Hz — a slow shimmer.
107    let n = sample_rate as usize;
108    let mut samples = Vec::with_capacity(n);
109    #[allow(clippy::cast_precision_loss)]
110    let sr = sample_rate as f32;
111    for i in 0..n {
112        #[allow(clippy::cast_precision_loss)]
113        let t = i as f32 / sr;
114        let a = (std::f32::consts::TAU * 220.0 * t).sin();
115        let b = (std::f32::consts::TAU * 223.0 * t).sin();
116        samples.push((a + b) * 0.25);
117    }
118    SoundBuffer {
119        sample_rate,
120        samples,
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    const SR: u32 = 44_100;
129
130    #[test]
131    fn buffers_have_expected_shapes() {
132        let s = shot(SR);
133        assert!((s.duration() - 0.12).abs() < 0.01);
134        let i = impact(SR);
135        assert!((i.duration() - 0.5).abs() < 0.01);
136        let h = hum(SR);
137        assert!((h.duration() - 1.0).abs() < 0.01);
138        for b in [&s, &i, &h] {
139            assert!(!b.samples.is_empty());
140            assert!(
141                b.samples.iter().all(|v| (-1.0..=1.0).contains(v)),
142                "samples stay in range"
143            );
144            assert!(
145                b.samples.iter().any(|v| v.abs() > 0.05),
146                "buffer is not silence"
147            );
148        }
149    }
150
151    #[test]
152    fn hum_loops_seamlessly() {
153        // Both partials are integer Hz over a 1 s buffer, so the loop
154        // wrap (last → first sample) continues the waveform: the jump
155        // must be no bigger than a typical adjacent-sample step.
156        let h = hum(SR);
157        let wrap = (h.samples[0] - h.samples[h.samples.len() - 1]).abs();
158        let step = (h.samples[1] - h.samples[0]).abs();
159        assert!(
160            wrap <= step * 2.0 + 1e-4,
161            "loop wrap jump {wrap} vs adjacent step {step}"
162        );
163    }
164
165    #[test]
166    fn deterministic() {
167        assert_eq!(shot(SR), shot(SR));
168        assert_eq!(impact(SR), impact(SR));
169        assert_eq!(hum(SR), hum(SR));
170    }
171}