Skip to main content

firefly_audio/
modulators.rs

1//! A collection of modulators.
2
3use crate::SAMPLE_DURATION;
4use micromath::F32Ext;
5
6/// An audio node parameter modulator.
7///
8/// Includes both [envelopes] and [LFOs].
9///
10/// All modulators produce value between 0 and 1.
11/// The range of the modulated parameter value is adjusted via
12/// `low` and `high` args of [`Node::modulate`][crate::Node::modulate].
13///
14/// [envelopes]: https://en.wikipedia.org/wiki/Envelope_(music)
15/// [LFOs]: https://en.wikipedia.org/wiki/Low-frequency_oscillation
16pub trait Modulator: Send {
17    /// Get the modulator value at the given time (in samples).
18    ///
19    /// The value is guaranteed to be in the range from 0 to 1 (inclusive).
20    ///
21    /// The time usually increases. It can go down if it wraps, which happens only
22    /// if the audio plays for a very long time. Or it can be intentionally reset to 0.
23    ///
24    /// The time value is not sequential: 8 might be followed by 200.
25    fn get(&self, now: u32) -> f32;
26}
27
28/// Emit first value before the given moment and the second value after.
29///
30/// For oscillating between two values, use [`Pulse`] instead.
31pub struct Hold {
32    time: u32,
33}
34
35impl Hold {
36    #[must_use]
37    pub const fn new(time: u32) -> Self {
38        Self { time }
39    }
40}
41
42impl Modulator for Hold {
43    fn get(&self, now: u32) -> f32 {
44        if now < self.time { 0. } else { 1. }
45    }
46}
47
48/// Linearly ramp up (or cut down) from one value to another on the given time interval.
49pub struct Linear {
50    start_at: u32,
51    end_at: u32,
52}
53
54impl Linear {
55    #[must_use]
56    pub const fn new(start_at: u32, end_at: u32) -> Self {
57        Self { start_at, end_at }
58    }
59}
60
61impl Modulator for Linear {
62    fn get(&self, now: u32) -> f32 {
63        if now <= self.start_at {
64            return 0.;
65        }
66        if now >= self.end_at {
67            return 1.;
68        }
69        let duration = self.end_at.saturating_sub(self.start_at);
70        if duration == 0 {
71            return 1.;
72        }
73        let elapsed = now - self.start_at;
74        elapsed as f32 / duration as f32
75    }
76}
77
78/// Sine wave low-frequency oscillator.
79pub struct Sine {
80    s: f32,
81}
82
83impl Sine {
84    #[must_use]
85    pub const fn new(freq: f32) -> Self {
86        let s = core::f32::consts::TAU * freq * SAMPLE_DURATION;
87        Self { s }
88    }
89}
90
91impl Modulator for Sine {
92    #[expect(clippy::manual_midpoint)]
93    fn get(&self, now: u32) -> f32 {
94        let s = F32Ext::sin(self.s * now as f32);
95        (s + 1.) / 2.
96    }
97}
98
99/// Pulse wave low-frequency oscillator.
100///
101/// Pulse wave is a slight generalization of square wave where the duty cycle
102/// (the ratio of time between pulse and the wave period) can be configured.
103///
104/// For switching from one value to another only once, use [`Hold`] instead.
105pub struct Pulse {
106    period: u32,
107    pulse_t: u32,
108}
109
110impl Pulse {
111    #[must_use]
112    pub const fn new(v1_t: u32, v2_t: u32) -> Self {
113        Self {
114            period: v1_t + v2_t,
115            pulse_t: v1_t,
116        }
117    }
118
119    #[must_use]
120    pub const fn new_square(period: u32) -> Self {
121        Self {
122            period,
123            pulse_t: period / 2,
124        }
125    }
126}
127
128impl Modulator for Pulse {
129    fn get(&self, now: u32) -> f32 {
130        let step = now % self.period;
131        if step < self.pulse_t { 0. } else { 1. }
132    }
133}
134
135/// Triangle wave low-frequency oscillator.
136///
137/// The period of up and down cycle can be configured independently
138/// allowing for assymetric wave. With both equal, it is the classic [triangle wave].
139/// With the down period zero, it is a [sawtooth wave].
140///
141/// [triangle wave]: https://en.wikipedia.org/wiki/Triangle_wave
142/// [sawtooth wave]: https://en.wikipedia.org/wiki/Sawtooth_wave
143pub struct Triangle {
144    t1: u32,
145    t2: u32,
146}
147
148impl Triangle {
149    #[must_use]
150    pub const fn new(t1: u32, t2: u32) -> Self {
151        Self { t1, t2 }
152    }
153
154    #[must_use]
155    pub const fn new_symmetric(period: u32) -> Self {
156        Self {
157            t1: period / 2,
158            t2: period / 2,
159        }
160    }
161
162    #[must_use]
163    pub const fn new_sawtooth(period: u32) -> Self {
164        Self { t1: period, t2: 0 }
165    }
166}
167
168impl Modulator for Triangle {
169    fn get(&self, now: u32) -> f32 {
170        let step = now % (self.t1 + self.t2);
171        if step < self.t1 {
172            step as f32 / self.t1 as f32
173        } else {
174            1. - (step - self.t1) as f32 / self.t2 as f32
175        }
176    }
177}
178
179/// Attack-decay-sustain-release ([ADSR]) envelope.
180///
181/// The output:
182///
183/// 1. jumps from 0 to 1 during `attack`,
184/// 2. then goes to `attack_level` during `decay`,
185/// 3. holds it for `sustain`,
186/// 4. and goes back to 0 during `release`.
187///
188/// An equivalent of chaining 4 [`Linear`] modulators.
189///
190/// [ADSR]: https://en.wikipedia.org/wiki/Envelope_(music)#ADSR
191pub struct Adsr {
192    attack: u32,
193    decay: u32,
194    sustain: u32,
195    sustain_level: f32,
196    release: u32,
197}
198
199impl Adsr {
200    #[must_use]
201    pub const fn new(
202        attack: u32,
203        decay: u32,
204        sustain: u32,
205        sustain_level: f32,
206        release: u32,
207    ) -> Self {
208        Self {
209            attack,
210            decay,
211            sustain,
212            sustain_level,
213            release,
214        }
215    }
216}
217
218impl Modulator for Adsr {
219    fn get(&self, now: u32) -> f32 {
220        if now <= self.attack {
221            // Going up to 1.
222            now as f32 / self.attack as f32
223        } else if now <= self.decay {
224            // Going down from 1 to sustain_level.
225            let ratio = (self.decay - now) as f32 / (self.decay - self.attack) as f32;
226            (1. - self.sustain_level).mul_add(ratio, self.sustain_level)
227        } else if now <= self.sustain {
228            // Keeping sustain level until release.
229            self.sustain_level
230        } else if now <= self.release {
231            // Going down from sustain_level to 0.
232            let ratio = (self.release - now) as f32 / (self.release - self.sustain) as f32;
233            self.sustain_level * ratio
234        } else {
235            // Keeping zero forever.
236            0.
237        }
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    #![allow(clippy::float_cmp)]
244    use super::*;
245
246    fn assert_close(a: f32, b: f32) {
247        let diff = a - b;
248        assert!(diff < 0.00001, "{a} != {b}");
249        assert!(diff > -0.00001, "{a} != {b}");
250    }
251
252    #[test]
253    fn switch() {
254        let lfo = Hold::new(10);
255        assert_eq!(lfo.get(0), 0.);
256        assert_eq!(lfo.get(6), 0.);
257        assert_eq!(lfo.get(9), 0.);
258
259        assert_eq!(lfo.get(10), 1.);
260        assert_eq!(lfo.get(11), 1.);
261        assert_eq!(lfo.get(12), 1.);
262        assert_eq!(lfo.get(21), 1.);
263        assert_eq!(lfo.get(100), 1.);
264    }
265
266    #[test]
267    fn ramp_up() {
268        let lfo = Linear::new(10, 20);
269        assert_eq!(lfo.get(0), 0.);
270        assert_eq!(lfo.get(8), 0.);
271        assert_eq!(lfo.get(10), 0.);
272
273        assert_eq!(lfo.get(20), 1.);
274        assert_eq!(lfo.get(23), 1.);
275        assert_eq!(lfo.get(100), 1.);
276
277        assert_eq!(lfo.get(13), 0.3);
278        assert_eq!(lfo.get(15), 0.5);
279        assert_eq!(lfo.get(17), 0.7);
280    }
281
282    #[test]
283    fn sine() {
284        const R: u32 = 44_100; // sample rate
285        let lfo = Sine::new(1.);
286        assert_eq!(lfo.get(0), 0.5);
287        assert!(lfo.get(1) > 0.);
288        assert_eq!(lfo.get(R / 4), 1.);
289        assert_close(lfo.get(R / 2), 0.5);
290        assert!(lfo.get(R / 2 + 1) < 0.5);
291        assert_eq!(lfo.get(R * 3 / 4), 0.);
292        assert_close(lfo.get(R), 0.5);
293    }
294
295    #[test]
296    fn pulse() {
297        let lfo = Pulse::new(5, 5);
298        assert_eq!(lfo.get(0), 0.);
299        assert_eq!(lfo.get(1), 0.);
300        assert_eq!(lfo.get(4), 0.);
301
302        assert_eq!(lfo.get(5), 1.);
303        assert_eq!(lfo.get(6), 1.);
304        assert_eq!(lfo.get(9), 1.);
305
306        assert_eq!(lfo.get(10), 0.);
307        assert_eq!(lfo.get(11), 0.);
308        assert_eq!(lfo.get(12), 0.);
309        assert_eq!(lfo.get(14), 0.);
310
311        assert_eq!(lfo.get(15), 1.);
312        assert_eq!(lfo.get(16), 1.);
313    }
314
315    #[test]
316    fn triangle() {
317        let lfo = Triangle::new(5, 5);
318        assert_eq!(lfo.get(0), 0.);
319        assert_eq!(lfo.get(3), 0.6);
320        assert_eq!(lfo.get(5), 1.);
321        assert_eq!(lfo.get(7), 0.6);
322        assert_eq!(lfo.get(10), 0.);
323    }
324
325    #[test]
326    fn adsr() {
327        let lfo = Adsr::new(10, 20, 30, 0.5, 40);
328        assert_eq!(lfo.get(0), 0.);
329        assert_eq!(lfo.get(5), 0.5);
330        assert_eq!(lfo.get(10), 1.);
331        assert_eq!(lfo.get(15), 0.75);
332        assert_eq!(lfo.get(20), 0.5);
333        assert_eq!(lfo.get(21), 0.5);
334        assert_eq!(lfo.get(30), 0.5);
335        assert_eq!(lfo.get(35), 0.25);
336        assert_eq!(lfo.get(40), 0.);
337        assert_eq!(lfo.get(41), 0.);
338        assert_eq!(lfo.get(50), 0.);
339    }
340}