naad 1.1.0

naad — Audio synthesis primitives: oscillators, filters, envelopes, modulation, wavetables, effects
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
//! ADSR envelope generator and multi-stage envelopes.
//!
//! Provides standard Attack-Decay-Sustain-Release envelopes with linear
//! segments, plus a flexible multi-stage envelope for arbitrary shapes.

use serde::{Deserialize, Serialize};

use crate::error::{NaadError, Result};

/// Envelope state machine stages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum EnvelopeState {
    /// Envelope is inactive (output = 0).
    Idle,
    /// Attack phase (rising from 0 to 1).
    Attack,
    /// Decay phase (falling from 1 to sustain level).
    Decay,
    /// Sustain phase (holding at sustain level).
    Sustain,
    /// Release phase (falling from current to 0).
    Release,
}

/// ADSR envelope generator with linear segments.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Adsr {
    /// Attack time in seconds.
    ///
    /// Note: modifying this directly bypasses validation. Use the constructor
    /// for guaranteed-valid values.
    pub attack_time: f32,
    /// Decay time in seconds.
    ///
    /// Note: modifying this directly bypasses validation. Use the constructor
    /// for guaranteed-valid values.
    pub decay_time: f32,
    /// Sustain level (0.0 to 1.0).
    ///
    /// Note: modifying this directly bypasses validation. Use the constructor
    /// for guaranteed-valid values.
    pub sustain_level: f32,
    /// Release time in seconds.
    ///
    /// Note: modifying this directly bypasses validation. Use the constructor
    /// for guaranteed-valid values.
    pub release_time: f32,
    /// Sample rate in Hz.
    sample_rate: f32,
    /// Current envelope state.
    state: EnvelopeState,
    /// Current output value.
    current_value: f32,
    /// Value at the start of the release phase.
    release_start_value: f32,
    /// Time spent in the current stage (in samples).
    stage_samples: f32,
}

impl Adsr {
    /// Create a new ADSR envelope.
    ///
    /// All times are in seconds. Sustain level is 0.0 to 1.0.
    ///
    /// # Errors
    ///
    /// Returns error if any time is negative or sustain is out of range.
    pub fn new(attack: f32, decay: f32, sustain: f32, release: f32) -> Result<Self> {
        Self::with_sample_rate(attack, decay, sustain, release, 44100.0)
    }

    /// Create a new ADSR envelope with an explicit sample rate.
    ///
    /// # Errors
    ///
    /// Returns error if any time is negative, sustain is out of range,
    /// or sample_rate is invalid.
    pub fn with_sample_rate(
        attack: f32,
        decay: f32,
        sustain: f32,
        release: f32,
        sample_rate: f32,
    ) -> Result<Self> {
        if attack < 0.0 {
            return Err(NaadError::InvalidParameter {
                name: "attack".to_string(),
                reason: "must be >= 0".to_string(),
            });
        }
        if decay < 0.0 {
            return Err(NaadError::InvalidParameter {
                name: "decay".to_string(),
                reason: "must be >= 0".to_string(),
            });
        }
        if !(0.0..=1.0).contains(&sustain) {
            return Err(NaadError::InvalidParameter {
                name: "sustain".to_string(),
                reason: "must be between 0.0 and 1.0".to_string(),
            });
        }
        if release < 0.0 {
            return Err(NaadError::InvalidParameter {
                name: "release".to_string(),
                reason: "must be >= 0".to_string(),
            });
        }
        if sample_rate <= 0.0 || !sample_rate.is_finite() {
            return Err(NaadError::InvalidSampleRate { sample_rate });
        }

        Ok(Self {
            attack_time: attack,
            decay_time: decay,
            sustain_level: sustain,
            release_time: release,
            sample_rate,
            state: EnvelopeState::Idle,
            current_value: 0.0,
            release_start_value: 0.0,
            stage_samples: 0.0,
        })
    }

    /// Returns the current envelope state.
    #[inline]
    #[must_use]
    pub fn state(&self) -> EnvelopeState {
        self.state
    }

    /// Trigger the envelope (note on).
    pub fn gate_on(&mut self) {
        self.state = EnvelopeState::Attack;
        self.stage_samples = 0.0;
    }

    /// Release the envelope (note off).
    pub fn gate_off(&mut self) {
        if self.state != EnvelopeState::Idle {
            self.release_start_value = self.current_value;
            self.state = EnvelopeState::Release;
            self.stage_samples = 0.0;
        }
    }

    /// Generate the next envelope value.
    ///
    /// Returns a value between 0.0 and 1.0.
    #[inline]
    #[must_use]
    pub fn next_value(&mut self) -> f32 {
        let sr = self.sample_rate;
        match self.state {
            EnvelopeState::Idle => {
                self.current_value = 0.0;
            }
            EnvelopeState::Attack => {
                let attack_samples = self.attack_time * sr;
                if attack_samples <= 0.0 {
                    self.current_value = 1.0;
                    self.state = EnvelopeState::Decay;
                    self.stage_samples = 0.0;
                } else {
                    self.current_value = self.stage_samples / attack_samples;
                    self.stage_samples += 1.0;
                    if self.current_value >= 1.0 {
                        self.current_value = 1.0;
                        self.state = EnvelopeState::Decay;
                        self.stage_samples = 0.0;
                    }
                }
            }
            EnvelopeState::Decay => {
                let decay_samples = self.decay_time * sr;
                if decay_samples <= 0.0 {
                    self.current_value = self.sustain_level;
                    self.state = EnvelopeState::Sustain;
                } else {
                    let progress = self.stage_samples / decay_samples;
                    self.current_value = 1.0 + (self.sustain_level - 1.0) * progress;
                    self.stage_samples += 1.0;
                    if self.current_value <= self.sustain_level {
                        self.current_value = self.sustain_level;
                        self.state = EnvelopeState::Sustain;
                    }
                }
            }
            EnvelopeState::Sustain => {
                self.current_value = self.sustain_level;
            }
            EnvelopeState::Release => {
                let release_samples = self.release_time * sr;
                if release_samples <= 0.0 {
                    self.current_value = 0.0;
                    self.state = EnvelopeState::Idle;
                } else {
                    let progress = self.stage_samples / release_samples;
                    self.current_value = self.release_start_value * (1.0 - progress);
                    self.stage_samples += 1.0;
                    if self.current_value <= 0.0 {
                        self.current_value = 0.0;
                        self.state = EnvelopeState::Idle;
                    }
                }
            }
        }

        self.current_value
    }

    /// Check if the envelope is active (not idle).
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.state != EnvelopeState::Idle
    }
}

/// A single segment in a multi-stage envelope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvelopeSegment {
    /// Target level for this segment (0.0 to 1.0).
    pub target: f32,
    /// Duration in seconds.
    pub duration: f32,
}

/// Multi-stage envelope with arbitrary segments.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiStageEnvelope {
    /// The segments of the envelope.
    pub segments: Vec<EnvelopeSegment>,
    /// Sample rate in Hz.
    sample_rate: f32,
    /// Current segment index.
    current_segment: usize,
    /// Current output value.
    current_value: f32,
    /// Start value of current segment.
    segment_start_value: f32,
    /// Time spent in current segment (in samples).
    stage_samples: f32,
    /// Whether the envelope is active.
    active: bool,
}

impl MultiStageEnvelope {
    /// Create a new multi-stage envelope (defaults to 44100 Hz sample rate).
    ///
    /// # Errors
    ///
    /// Returns error if segments is empty.
    pub fn new(segments: Vec<EnvelopeSegment>) -> Result<Self> {
        Self::with_sample_rate(segments, 44100.0)
    }

    /// Create a new multi-stage envelope with an explicit sample rate.
    ///
    /// # Errors
    ///
    /// Returns error if segments is empty or sample_rate is invalid.
    pub fn with_sample_rate(segments: Vec<EnvelopeSegment>, sample_rate: f32) -> Result<Self> {
        if segments.is_empty() {
            return Err(NaadError::InvalidParameter {
                name: "segments".to_string(),
                reason: "must have at least one segment".to_string(),
            });
        }
        if sample_rate <= 0.0 || !sample_rate.is_finite() {
            return Err(NaadError::InvalidSampleRate { sample_rate });
        }

        Ok(Self {
            segments,
            sample_rate,
            current_segment: 0,
            current_value: 0.0,
            segment_start_value: 0.0,
            stage_samples: 0.0,
            active: false,
        })
    }

    /// Start the envelope.
    pub fn trigger(&mut self) {
        self.current_segment = 0;
        self.current_value = 0.0;
        self.segment_start_value = 0.0;
        self.stage_samples = 0.0;
        self.active = true;
    }

    /// Generate the next envelope value.
    #[inline]
    #[must_use]
    pub fn next_value(&mut self) -> f32 {
        if !self.active {
            return 0.0;
        }

        if self.current_segment >= self.segments.len() {
            self.active = false;
            return 0.0;
        }

        let seg = &self.segments[self.current_segment];
        let seg_samples = seg.duration * self.sample_rate;

        if seg_samples <= 0.0 {
            self.current_value = seg.target;
            self.segment_start_value = self.current_value;
            self.current_segment += 1;
            self.stage_samples = 0.0;
        } else {
            let progress = (self.stage_samples / seg_samples).min(1.0);
            self.current_value =
                self.segment_start_value + (seg.target - self.segment_start_value) * progress;
            self.stage_samples += 1.0;

            if self.stage_samples >= seg_samples {
                self.current_value = seg.target;
                self.segment_start_value = self.current_value;
                self.current_segment += 1;
                self.stage_samples = 0.0;
            }
        }

        self.current_value
    }

    /// Check if the envelope is active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.active
    }
}

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

    #[test]
    fn test_adsr_basic() {
        let mut env = Adsr::new(0.01, 0.01, 0.5, 0.01).unwrap();
        assert!(!env.is_active());
        env.gate_on();
        assert!(env.is_active());
    }

    #[test]
    fn test_adsr_sustain_holds() {
        let mut env = Adsr::new(0.001, 0.001, 0.7, 0.01).unwrap();
        env.gate_on();
        // Run through attack + decay
        for _ in 0..1000 {
            let _ = env.next_value();
        }
        // Should be at sustain level
        let val = env.next_value();
        assert!(
            (val - 0.7).abs() < 0.01,
            "sustain should hold at 0.7, got {val}"
        );
    }

    #[test]
    fn test_adsr_release_to_zero() {
        let mut env = Adsr::new(0.0, 0.0, 1.0, 0.01).unwrap();
        env.gate_on();
        let _ = env.next_value();
        env.gate_off();
        for _ in 0..2000 {
            let _ = env.next_value();
        }
        assert!(!env.is_active());
    }

    #[test]
    fn test_invalid_params() {
        assert!(Adsr::new(-1.0, 0.0, 0.5, 0.0).is_err());
        assert!(Adsr::new(0.0, 0.0, 1.5, 0.0).is_err());
        assert!(Adsr::new(0.0, 0.0, -0.1, 0.0).is_err());
    }

    #[test]
    fn test_multi_stage() {
        let segments = vec![
            EnvelopeSegment {
                target: 1.0,
                duration: 0.01,
            },
            EnvelopeSegment {
                target: 0.5,
                duration: 0.01,
            },
            EnvelopeSegment {
                target: 0.0,
                duration: 0.01,
            },
        ];
        let mut env = MultiStageEnvelope::new(segments).unwrap();
        env.trigger();
        assert!(env.is_active());
        for _ in 0..5000 {
            let _ = env.next_value();
        }
        assert!(!env.is_active());
    }

    #[test]
    fn test_serde_roundtrip() {
        let env = Adsr::new(0.01, 0.1, 0.5, 0.2).unwrap();
        let json = serde_json::to_string(&env).unwrap();
        let back: Adsr = serde_json::from_str(&json).unwrap();
        assert!((env.attack_time - back.attack_time).abs() < f32::EPSILON);
        assert!((env.sustain_level - back.sustain_level).abs() < f32::EPSILON);
    }
}