oximedia-effects 0.1.8

Professional audio effects suite for OxiMedia
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
//! Chorus effect implementation.
//!
//! Creates a rich, ensemble-like sound by mixing the dry signal with multiple
//! delayed and modulated copies (voices).
//!
//! ## Wavetable LFO
//!
//! [`WavetableChorus`] replaces the per-sample `sin()` call with a 1024-entry
//! wavetable lookup plus linear interpolation, reducing LFO CPU cost by 3–5×
//! on typical hardware.

use std::sync::OnceLock;

use crate::{
    utils::{FractionalDelayLine, InterpolationMode, Lfo, LfoWaveform},
    AudioEffect,
};

// ── Sine wavetable ────────────────────────────────────────────────────────────

/// Number of entries in the chorus sine wavetable (1024 = good balance of
/// accuracy vs memory footprint for LFO use at audio sample rates).
const WAVETABLE_SIZE: usize = 1024;

/// Global sine wavetable — initialised once and shared across all instances.
static SINE_TABLE: OnceLock<Box<[f32; WAVETABLE_SIZE]>> = OnceLock::new();

/// Return a reference to the global 1024-entry sine wavetable, initialising it
/// on first call.
fn get_sine_table() -> &'static [f32; WAVETABLE_SIZE] {
    SINE_TABLE.get_or_init(|| {
        let mut table = Box::new([0.0f32; WAVETABLE_SIZE]);
        for (i, entry) in table.iter_mut().enumerate() {
            *entry = (2.0 * std::f32::consts::PI * i as f32 / WAVETABLE_SIZE as f32).sin();
        }
        table
    })
}

/// Evaluate sine at a fractional phase in `[0, 1)` using the global wavetable
/// with linear interpolation between adjacent entries.
///
/// Maximum error vs `f32::sin` is < 0.003 (well within perceptual threshold for
/// LFO modulation).
fn wavetable_sin(phase: f32) -> f32 {
    let tbl = get_sine_table();
    // Map phase [0, 1) → fractional index [0, WAVETABLE_SIZE).
    let idx_f = phase.rem_euclid(1.0) * WAVETABLE_SIZE as f32;
    let i0 = idx_f as usize % WAVETABLE_SIZE;
    let i1 = (i0 + 1) % WAVETABLE_SIZE;
    let frac = idx_f.fract();
    tbl[i0] * (1.0 - frac) + tbl[i1] * frac
}

// ── WavetableChorus ───────────────────────────────────────────────────────────

/// Per-voice state for the wavetable chorus.
struct WtVoice {
    /// Fractional delay line.
    delay: FractionalDelayLine,
    /// Phase accumulator for this voice's LFO, in `[0, 1)`.
    phase: f32,
    /// Per-sample phase increment (`rate_hz / sample_rate`).
    phase_inc: f32,
    /// Voice index as `f32` (pre-computed to avoid cast in the hot path).
    index_f32: f32,
}

/// Chorus effect that drives its LFO via a wavetable instead of per-sample `sin()`.
///
/// This is a drop-in replacement for [`StereoChorus`] with identical sonic
/// characteristics but lower CPU cost for the LFO computation.
///
/// ## Example
///
/// ```ignore
/// use oximedia_effects::modulation::chorus::{WavetableChorus, ChorusConfig};
///
/// let config = ChorusConfig::default();
/// let mut chorus = WavetableChorus::new(config, 48_000.0);
/// let (l, r) = chorus.process_stereo_sample(0.5, 0.5);
/// ```
pub struct WavetableChorus {
    voices: Vec<WtVoice>,
    config: ChorusConfig,
    sample_rate: f32,
}

impl WavetableChorus {
    /// Create a new `WavetableChorus` from a [`ChorusConfig`].
    #[must_use]
    pub fn new(config: ChorusConfig, sample_rate: f32) -> Self {
        let n_voices = config.voices.clamp(MIN_VOICES, MAX_VOICES);
        let n_voices_f = n_voices as f32; // n_voices ≤ 8; exact in f32

        let max_delay_ms = config.delay_ms + config.depth_ms;
        // Convert ms→samples; max_delay_ms ≤ 70ms at default settings,
        // so the result is ≤ 48000 * 0.07 = 3360 — well within usize range.
        let max_delay_samples_f = (max_delay_ms * sample_rate / 1000.0).max(1.0);
        // Conversion is safe: value is small and non-negative.
        let max_delay_samples = max_delay_samples_f as usize;
        let phase_inc = config.rate / sample_rate;

        let voices: Vec<WtVoice> = (0..n_voices)
            .map(|i| {
                // i ≤ 7; exact in f32
                let index_f32 = i as f32;
                let initial_phase = index_f32 / n_voices_f;
                WtVoice {
                    delay: FractionalDelayLine::new(max_delay_samples, InterpolationMode::Linear),
                    phase: initial_phase,
                    phase_inc,
                    index_f32,
                }
            })
            .collect();

        Self {
            voices,
            config,
            sample_rate,
        }
    }

    /// Set the LFO rate for all voices.
    pub fn set_rate(&mut self, rate: f32) {
        self.config.rate = rate.clamp(0.1, 10.0);
        let inc = self.config.rate / self.sample_rate;
        for v in &mut self.voices {
            v.phase_inc = inc;
        }
    }

    /// Process a mono sample and return the mono output.
    pub fn process_mono(&mut self, input: f32) -> f32 {
        let (l, _r) = self.process_stereo_sample(input, input);
        l
    }

    /// Process a stereo sample pair and return `(left, right)` output.
    pub fn process_stereo_sample(&mut self, input_l: f32, input_r: f32) -> (f32, f32) {
        let mut out_l = 0.0_f32;
        let mut out_r = 0.0_f32;
        let n = self.voices.len();
        // n ≤ 8; exact in f32
        let inv_n = if n == 0 { 1.0_f32 } else { 1.0 / n as f32 };
        let n_minus_one = if n <= 1 { 1.0_f32 } else { (n - 1) as f32 };

        for voice in &mut self.voices {
            // Wavetable LFO: phase [0,1) → unipolar [0,1) via (sin+1)/2.
            let lfo_bipolar = wavetable_sin(voice.phase);
            let lfo_uni = (lfo_bipolar + 1.0) * 0.5;

            // Advance phase with wrap.
            voice.phase = (voice.phase + voice.phase_inc).rem_euclid(1.0);

            // Compute modulated delay.
            let delay_ms = self.config.delay_ms + lfo_uni * self.config.depth_ms;
            let delay_samples = (delay_ms * self.sample_rate) / 1000.0;

            // Read from delay line then write input.
            let delayed = voice.delay.read(delay_samples);
            voice.delay.write((input_l + input_r) * 0.5);

            // Stereo pan: spread voices across [-spread, +spread].
            let pan_norm = voice.index_f32 / n_minus_one * 2.0 - 1.0;
            let pan = pan_norm * self.config.spread;
            let gain_l = if pan <= 0.0 { 1.0 } else { 1.0 - pan };
            let gain_r = if pan >= 0.0 { 1.0 } else { 1.0 + pan };

            out_l += delayed * gain_l * inv_n;
            out_r += delayed * gain_r * inv_n;
        }

        let out_l = out_l * self.config.wet + input_l * self.config.dry;
        let out_r = out_r * self.config.wet + input_r * self.config.dry;
        (out_l, out_r)
    }
}

impl AudioEffect for WavetableChorus {
    const EFFECT_ID: &'static str = "wavetable_chorus";

    fn process_sample(&mut self, input: f32) -> f32 {
        self.process_mono(input)
    }

    fn process_sample_stereo(&mut self, left: f32, right: f32) -> (f32, f32) {
        self.process_stereo_sample(left, right)
    }

    fn reset(&mut self) {
        for v in &mut self.voices {
            v.delay.clear();
            v.phase = 0.0;
        }
    }
}

/// Maximum number of chorus voices.
pub const MAX_VOICES: usize = 8;
/// Minimum number of chorus voices.
pub const MIN_VOICES: usize = 2;

/// Configuration for chorus effect.
#[derive(Debug, Clone)]
pub struct ChorusConfig {
    /// Number of voices (2-8).
    pub voices: usize,
    /// LFO rate in Hz (0.1 - 10.0).
    pub rate: f32,
    /// Modulation depth in milliseconds (0.0 - 20.0).
    pub depth_ms: f32,
    /// Base delay time in milliseconds (10.0 - 50.0).
    pub delay_ms: f32,
    /// Wet signal level (0.0 - 1.0).
    pub wet: f32,
    /// Dry signal level (0.0 - 1.0).
    pub dry: f32,
    /// Stereo spread (0.0 - 1.0).
    pub spread: f32,
    /// LFO waveform.
    pub waveform: LfoWaveform,
}

impl Default for ChorusConfig {
    fn default() -> Self {
        Self {
            voices: 4,
            rate: 0.5,
            depth_ms: 5.0,
            delay_ms: 25.0,
            wet: 0.5,
            dry: 0.5,
            spread: 0.8,
            waveform: LfoWaveform::Sine,
        }
    }
}

impl ChorusConfig {
    /// Create a subtle chorus preset (2 voices).
    #[must_use]
    pub fn subtle() -> Self {
        Self {
            voices: 2,
            rate: 0.3,
            depth_ms: 2.0,
            delay_ms: 20.0,
            wet: 0.3,
            dry: 0.7,
            spread: 0.5,
            waveform: LfoWaveform::Sine,
        }
    }

    /// Create a lush chorus preset (6 voices).
    #[must_use]
    pub fn lush() -> Self {
        Self {
            voices: 6,
            rate: 0.8,
            depth_ms: 8.0,
            delay_ms: 30.0,
            wet: 0.6,
            dry: 0.4,
            spread: 1.0,
            waveform: LfoWaveform::Sine,
        }
    }

    /// Create a vibrato-like chorus preset.
    #[must_use]
    pub fn vibrato() -> Self {
        Self {
            voices: 3,
            rate: 4.0,
            depth_ms: 3.0,
            delay_ms: 15.0,
            wet: 1.0,
            dry: 0.0,
            spread: 0.3,
            waveform: LfoWaveform::Triangle,
        }
    }
}

/// Stereo chorus effect.
pub struct StereoChorus {
    delay_lines: Vec<FractionalDelayLine>,
    lfos: Vec<Lfo>,
    config: ChorusConfig,
    sample_rate: f32,
}

impl StereoChorus {
    /// Create a new stereo chorus effect.
    #[must_use]
    pub fn new(config: ChorusConfig, sample_rate: f32) -> Self {
        let voices = config.voices.clamp(MIN_VOICES, MAX_VOICES);

        // Create delay lines (need enough for maximum delay + modulation)
        let max_delay_ms = config.delay_ms + config.depth_ms;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let max_delay_samples = ((max_delay_ms * sample_rate) / 1000.0) as usize;

        let delay_lines: Vec<FractionalDelayLine> = (0..voices)
            .map(|_| FractionalDelayLine::new(max_delay_samples.max(1), InterpolationMode::Linear))
            .collect();

        // Create LFOs with different phases for each voice
        let lfos: Vec<Lfo> = (0..voices)
            .map(|i| {
                let mut lfo = Lfo::new(config.rate, sample_rate, config.waveform);
                // Distribute phases evenly across voices
                #[allow(clippy::cast_precision_loss)]
                let phase = i as f32 / voices as f32;
                lfo.set_phase(phase);
                lfo
            })
            .collect();

        Self {
            delay_lines,
            lfos,
            config,
            sample_rate,
        }
    }

    /// Set chorus rate.
    pub fn set_rate(&mut self, rate: f32) {
        self.config.rate = rate.clamp(0.1, 10.0);
        for lfo in &mut self.lfos {
            lfo.set_frequency(self.config.rate);
        }
    }

    /// Set modulation depth.
    pub fn set_depth(&mut self, depth_ms: f32) {
        self.config.depth_ms = depth_ms.clamp(0.0, 20.0);
    }

    /// Set wet level.
    pub fn set_wet(&mut self, wet: f32) {
        self.config.wet = wet.clamp(0.0, 1.0);
    }

    /// Set dry level.
    pub fn set_dry(&mut self, dry: f32) {
        self.config.dry = dry.clamp(0.0, 1.0);
    }

    fn process_sample_internal(&mut self, input_l: f32, input_r: f32) -> (f32, f32) {
        let mut out_l = 0.0;
        let mut out_r = 0.0;

        #[allow(clippy::cast_precision_loss)]
        let num_voices = self.delay_lines.len() as f32;

        // Process each voice
        for (i, delay_line) in self.delay_lines.iter_mut().enumerate() {
            // Get modulation value
            let mod_value = self.lfos[i].next_unipolar(); // 0.0 - 1.0

            // Calculate delay time
            let delay_ms = self.config.delay_ms + mod_value * self.config.depth_ms;
            let delay_samples = (delay_ms * self.sample_rate) / 1000.0;

            // Read modulated delay
            let delayed = delay_line.read(delay_samples);

            // Write input to delay line
            delay_line.write((input_l + input_r) * 0.5);

            // Distribute voices across stereo field based on spread
            #[allow(clippy::cast_precision_loss)]
            let pan = ((i as f32 / num_voices) * 2.0 - 1.0) * self.config.spread;

            // Calculate stereo gains
            let left_gain = if pan <= 0.0 { 1.0 } else { 1.0 - pan };
            let right_gain = if pan >= 0.0 { 1.0 } else { 1.0 + pan };

            out_l += delayed * left_gain / num_voices;
            out_r += delayed * right_gain / num_voices;
        }

        // Mix wet and dry
        out_l = out_l * self.config.wet + input_l * self.config.dry;
        out_r = out_r * self.config.wet + input_r * self.config.dry;

        (out_l, out_r)
    }
}

impl AudioEffect for StereoChorus {
    const EFFECT_ID: &'static str = "stereo_chorus";

    fn process_sample(&mut self, input: f32) -> f32 {
        let (left, _right) = self.process_sample_internal(input, input);
        left
    }

    fn process_sample_stereo(&mut self, left: f32, right: f32) -> (f32, f32) {
        self.process_sample_internal(left, right)
    }

    fn reset(&mut self) {
        for delay_line in &mut self.delay_lines {
            delay_line.clear();
        }
        for lfo in &mut self.lfos {
            lfo.reset();
        }
    }
}

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

    #[test]
    fn test_chorus_config() {
        let config = ChorusConfig::default();
        assert_eq!(config.voices, 4);
        assert_eq!(config.rate, 0.5);
    }

    #[test]
    fn test_chorus_presets() {
        let subtle = ChorusConfig::subtle();
        assert_eq!(subtle.voices, 2);

        let lush = ChorusConfig::lush();
        assert_eq!(lush.voices, 6);
    }

    #[test]
    fn test_chorus_process() {
        let config = ChorusConfig::default();
        let mut chorus = StereoChorus::new(config, 48000.0);

        let (out_l, out_r) = chorus.process_sample_stereo(1.0, 1.0);
        assert!(out_l.is_finite());
        assert!(out_r.is_finite());

        // Process more samples to verify LFO modulation
        for _ in 0..1000 {
            chorus.process_sample_stereo(0.1, 0.1);
        }
    }

    #[test]
    fn test_chorus_voices() {
        let config = ChorusConfig {
            voices: 3,
            ..Default::default()
        };
        let chorus = StereoChorus::new(config, 48000.0);
        assert_eq!(chorus.delay_lines.len(), 3);
        assert_eq!(chorus.lfos.len(), 3);
    }

    #[test]
    fn test_chorus_stereo_spread() {
        let config = ChorusConfig {
            spread: 1.0,
            ..Default::default()
        };
        let mut chorus = StereoChorus::new(config, 48000.0);

        let (out_l, out_r) = chorus.process_sample_stereo(1.0, 0.0);
        // With spread, left and right should be different
        assert!(out_l.is_finite());
        assert!(out_r.is_finite());
    }

    // ── Wavetable tests ───────────────────────────────────────────────────────

    #[test]
    fn test_wavetable_sin_accuracy() {
        // Verify max error vs f32::sin over 100 evenly-spaced phase values < 0.005.
        use std::f32::consts::PI;
        let mut max_err = 0.0f32;
        for i in 0..100_usize {
            let phase = i as f32 / 100.0; // [0, 1)
            let wt = wavetable_sin(phase);
            let exact = (2.0 * PI * phase).sin();
            let err = (wt - exact).abs();
            if err > max_err {
                max_err = err;
            }
        }
        assert!(
            max_err < 0.005,
            "wavetable_sin max error {max_err:.6} exceeds 0.005"
        );
    }

    #[test]
    fn test_chorus_wavetable_output() {
        // WavetableChorus with a sine LFO should produce output whose values
        // vary over time (non-zero variance) because the delay modulation causes
        // each output sample to be different.
        //
        // Use a short delay (5 ms base + 2 ms depth) so the delay line fills
        // quickly, giving non-zero wet output within the first ~400 samples.
        let config = ChorusConfig {
            voices: 4,
            rate: 5.0, // 5 Hz — fast enough to see variation in short test
            depth_ms: 2.0,
            delay_ms: 5.0, // short: 5 ms × 48 kHz = 240 samples to fill
            wet: 1.0,
            dry: 0.0,
            spread: 0.8,
            waveform: LfoWaveform::Sine,
        };
        let mut chorus = WavetableChorus::new(config, 48_000.0);

        // Feed a 440 Hz sine for 2048 samples. The delay line fills after ~340 samples,
        // and then the LFO modulation creates time-varying output.
        use std::f32::consts::TAU;
        let total = 2048_usize;
        let mut outputs = Vec::with_capacity(total);
        for i in 0..total {
            let s = (i as f32 * TAU * 440.0 / 48_000.0).sin() * 0.7;
            outputs.push(chorus.process_mono(s));
        }

        // All samples must be finite.
        for (i, &s) in outputs.iter().enumerate() {
            assert!(s.is_finite(), "non-finite output at sample {i}: {s}");
        }

        // After the delay line has filled (skip first 512 samples for warm-up),
        // compute variance to verify the LFO is modulating the delay.
        let warmed: &[f32] = &outputs[512..];
        let mean: f32 = warmed.iter().sum::<f32>() / warmed.len() as f32;
        let variance: f32 =
            warmed.iter().map(|&x| (x - mean) * (x - mean)).sum::<f32>() / warmed.len() as f32;
        assert!(
            variance > 1e-6,
            "WavetableChorus output should have non-zero variance after warm-up; got {variance}"
        );
    }
}