oximedia-audio 0.1.4

Audio codec implementations 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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Chorus effect implementation.
//!
//! A chorus effect creates a thicker, richer sound by combining the original
//! signal with multiple delayed and modulated copies (voices). Each voice
//! has a slightly different delay time that varies with an LFO.

#![forbid(unsafe_code)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::too_many_arguments)]

use super::delay::{FractionalDelayLine, InterpolationMode};
use super::lfo::{Lfo, LfoWaveform, ParameterSmoother};

/// Maximum number of chorus voices.
pub const MAX_CHORUS_VOICES: usize = 8;

/// Minimum number of chorus voices.
pub const MIN_CHORUS_VOICES: usize = 2;

/// Default chorus delay in milliseconds.
const DEFAULT_DELAY_MS: f64 = 25.0;

/// Default chorus depth in milliseconds.
const DEFAULT_DEPTH_MS: f64 = 5.0;

/// Configuration for the chorus effect.
#[derive(Clone, Debug)]
pub struct ChorusConfig {
    /// Number of voices (2-8).
    pub voices: usize,
    /// LFO rate in Hz (0.1 to 10.0).
    pub rate: f64,
    /// Modulation depth in milliseconds (0.0 to 20.0).
    pub depth: f64,
    /// Base delay in milliseconds (10.0 to 50.0).
    pub delay: f64,
    /// Dry/wet mix (0.0 = dry only, 1.0 = wet only).
    pub mix: f64,
    /// Feedback amount (-0.9 to 0.9).
    pub feedback: f64,
    /// Stereo spread (0.0 = mono, 1.0 = maximum spread).
    pub spread: f64,
    /// LFO waveform.
    pub waveform: LfoWaveform,
}

impl Default for ChorusConfig {
    fn default() -> Self {
        Self {
            voices: 4,
            rate: 1.5,
            depth: DEFAULT_DEPTH_MS,
            delay: DEFAULT_DELAY_MS,
            mix: 0.5,
            feedback: 0.0,
            spread: 0.7,
            waveform: LfoWaveform::Sine,
        }
    }
}

impl ChorusConfig {
    /// Create a new chorus configuration.
    ///
    /// # Arguments
    ///
    /// * `voices` - Number of voices (2-8)
    /// * `rate` - LFO rate in Hz
    /// * `depth` - Modulation depth in milliseconds
    #[must_use]
    pub fn new(voices: usize, rate: f64, depth: f64) -> Self {
        Self {
            voices: voices.clamp(MIN_CHORUS_VOICES, MAX_CHORUS_VOICES),
            rate: rate.clamp(0.1, 10.0),
            depth: depth.clamp(0.0, 20.0),
            ..Default::default()
        }
    }

    /// Set the number of voices.
    #[must_use]
    pub fn with_voices(mut self, voices: usize) -> Self {
        self.voices = voices.clamp(MIN_CHORUS_VOICES, MAX_CHORUS_VOICES);
        self
    }

    /// Set the LFO rate.
    #[must_use]
    pub fn with_rate(mut self, rate: f64) -> Self {
        self.rate = rate.clamp(0.1, 10.0);
        self
    }

    /// Set the modulation depth.
    #[must_use]
    pub fn with_depth(mut self, depth: f64) -> Self {
        self.depth = depth.clamp(0.0, 20.0);
        self
    }

    /// Set the base delay.
    #[must_use]
    pub fn with_delay(mut self, delay: f64) -> Self {
        self.delay = delay.clamp(10.0, 50.0);
        self
    }

    /// Set the dry/wet mix.
    #[must_use]
    pub fn with_mix(mut self, mix: f64) -> Self {
        self.mix = mix.clamp(0.0, 1.0);
        self
    }

    /// Set the feedback amount.
    #[must_use]
    pub fn with_feedback(mut self, feedback: f64) -> Self {
        self.feedback = feedback.clamp(-0.9, 0.9);
        self
    }

    /// Set the stereo spread.
    #[must_use]
    pub fn with_spread(mut self, spread: f64) -> Self {
        self.spread = spread.clamp(0.0, 1.0);
        self
    }

    /// Set the LFO waveform.
    #[must_use]
    pub fn with_waveform(mut self, waveform: LfoWaveform) -> Self {
        self.waveform = waveform;
        self
    }

    /// Create a subtle chorus preset.
    #[must_use]
    pub fn subtle() -> Self {
        Self {
            voices: 2,
            rate: 0.8,
            depth: 3.0,
            delay: 20.0,
            mix: 0.3,
            feedback: 0.1,
            spread: 0.5,
            waveform: LfoWaveform::Sine,
        }
    }

    /// Create a lush chorus preset.
    #[must_use]
    pub fn lush() -> Self {
        Self {
            voices: 6,
            rate: 1.2,
            depth: 7.0,
            delay: 25.0,
            mix: 0.6,
            feedback: 0.2,
            spread: 0.8,
            waveform: LfoWaveform::Sine,
        }
    }

    /// Create a vibrato preset (deep modulation, no dry signal).
    #[must_use]
    pub fn vibrato() -> Self {
        Self {
            voices: 1,
            rate: 5.0,
            depth: 10.0,
            delay: 15.0,
            mix: 1.0,
            feedback: 0.0,
            spread: 0.0,
            waveform: LfoWaveform::Sine,
        }
    }
}

/// Single chorus voice.
struct ChorusVoice {
    /// Fractional delay line.
    delay_line: FractionalDelayLine,
    /// LFO for modulation.
    lfo: Lfo,
}

impl ChorusVoice {
    /// Create a new chorus voice.
    fn new(sample_rate: f64, rate: f64, phase_offset: f64, waveform: LfoWaveform) -> Self {
        let max_delay_ms = 100.0;
        let mut lfo = Lfo::new(rate, sample_rate, waveform);
        lfo.set_phase(phase_offset);

        Self {
            delay_line: FractionalDelayLine::new(
                max_delay_ms,
                sample_rate,
                InterpolationMode::Linear,
            ),
            lfo,
        }
    }

    /// Process one sample through the voice.
    fn process(&mut self, input: f64, base_delay: f64, depth: f64, feedback: f64) -> f64 {
        let lfo_value = self.lfo.next();
        let modulated_delay = base_delay + lfo_value * depth;
        self.delay_line
            .process_with_feedback(input, modulated_delay, feedback)
    }

    /// Reset the voice.
    fn reset(&mut self) {
        self.delay_line.reset();
        self.lfo.reset();
    }
}

/// Mono chorus effect processor.
pub struct MonoChorus {
    /// Configuration.
    config: ChorusConfig,
    /// Chorus voices.
    voices: Vec<ChorusVoice>,
    /// Sample rate.
    sample_rate: f64,
    /// Base delay in samples.
    base_delay_samples: f64,
    /// Depth in samples.
    depth_samples: f64,
    /// Mix smoother.
    mix_smoother: ParameterSmoother,
}

impl MonoChorus {
    /// Create a new mono chorus effect.
    ///
    /// # Arguments
    ///
    /// * `config` - Chorus configuration
    /// * `sample_rate` - Sample rate in Hz
    #[must_use]
    pub fn new(config: ChorusConfig, sample_rate: f64) -> Self {
        let mut voices = Vec::with_capacity(config.voices);

        for i in 0..config.voices {
            let phase_offset = i as f64 / config.voices as f64;
            voices.push(ChorusVoice::new(
                sample_rate,
                config.rate,
                phase_offset,
                config.waveform,
            ));
        }

        let base_delay_samples = config.delay * 0.001 * sample_rate;
        let depth_samples = config.depth * 0.001 * sample_rate;

        Self {
            voices,
            base_delay_samples,
            depth_samples,
            mix_smoother: ParameterSmoother::new(config.mix, 10.0, sample_rate),
            sample_rate,
            config,
        }
    }

    /// Set the configuration.
    pub fn set_config(&mut self, config: ChorusConfig) {
        if config.voices != self.config.voices {
            self.voices.clear();
            for i in 0..config.voices {
                let phase_offset = i as f64 / config.voices as f64;
                self.voices.push(ChorusVoice::new(
                    self.sample_rate,
                    config.rate,
                    phase_offset,
                    config.waveform,
                ));
            }
        } else {
            for voice in &mut self.voices {
                voice.lfo.set_rate(config.rate);
                voice.lfo.set_waveform(config.waveform);
            }
        }

        self.base_delay_samples = config.delay * 0.001 * self.sample_rate;
        self.depth_samples = config.depth * 0.001 * self.sample_rate;
        self.mix_smoother.set_target(config.mix);
        self.config = config;
    }

    /// Get the current configuration.
    #[must_use]
    pub fn config(&self) -> &ChorusConfig {
        &self.config
    }

    /// Process a single sample.
    pub fn process_sample(&mut self, input: f64) -> f64 {
        let mut wet = 0.0;
        let num_voices = self.voices.len() as f64;

        for voice in &mut self.voices {
            wet += voice.process(
                input,
                self.base_delay_samples,
                self.depth_samples,
                self.config.feedback,
            ) / num_voices;
        }

        let mix = self.mix_smoother.next();
        input * (1.0 - mix) + wet * mix
    }

    /// Process a buffer of samples.
    ///
    /// # Arguments
    ///
    /// * `samples` - Input/output sample buffer
    pub fn process(&mut self, samples: &mut [f64]) {
        for sample in samples.iter_mut() {
            *sample = self.process_sample(*sample);
        }
    }

    /// Set the wet/dry mix (0.0 = fully dry, 1.0 = fully wet).
    ///
    /// This provides a convenient way to adjust the mix at runtime
    /// without rebuilding the entire configuration.
    pub fn set_mix(&mut self, mix: f64) {
        let clamped = mix.clamp(0.0, 1.0);
        self.config.mix = clamped;
        self.mix_smoother.set_target(clamped);
    }

    /// Get the current wet/dry mix value.
    #[must_use]
    pub fn mix(&self) -> f64 {
        self.config.mix
    }

    /// Reset the effect state.
    pub fn reset(&mut self) {
        for voice in &mut self.voices {
            voice.reset();
        }
        self.mix_smoother.reset(self.config.mix);
    }
}

/// Stereo chorus effect processor.
pub struct StereoChorus {
    /// Configuration.
    config: ChorusConfig,
    /// Left channel voices.
    left_voices: Vec<ChorusVoice>,
    /// Right channel voices.
    right_voices: Vec<ChorusVoice>,
    /// Sample rate.
    sample_rate: f64,
    /// Base delay in samples.
    base_delay_samples: f64,
    /// Depth in samples.
    depth_samples: f64,
    /// Mix smoother.
    mix_smoother: ParameterSmoother,
}

impl StereoChorus {
    /// Create a new stereo chorus effect.
    ///
    /// # Arguments
    ///
    /// * `config` - Chorus configuration
    /// * `sample_rate` - Sample rate in Hz
    #[must_use]
    pub fn new(config: ChorusConfig, sample_rate: f64) -> Self {
        let mut left_voices = Vec::with_capacity(config.voices);
        let mut right_voices = Vec::with_capacity(config.voices);

        for i in 0..config.voices {
            let phase_offset = i as f64 / config.voices as f64;

            left_voices.push(ChorusVoice::new(
                sample_rate,
                config.rate,
                phase_offset,
                config.waveform,
            ));

            right_voices.push(ChorusVoice::new(
                sample_rate,
                config.rate,
                phase_offset + 0.5,
                config.waveform,
            ));
        }

        let base_delay_samples = config.delay * 0.001 * sample_rate;
        let depth_samples = config.depth * 0.001 * sample_rate;

        Self {
            left_voices,
            right_voices,
            base_delay_samples,
            depth_samples,
            mix_smoother: ParameterSmoother::new(config.mix, 10.0, sample_rate),
            sample_rate,
            config,
        }
    }

    /// Set the configuration.
    pub fn set_config(&mut self, config: ChorusConfig) {
        if config.voices != self.config.voices {
            self.left_voices.clear();
            self.right_voices.clear();

            for i in 0..config.voices {
                let phase_offset = i as f64 / config.voices as f64;

                self.left_voices.push(ChorusVoice::new(
                    self.sample_rate,
                    config.rate,
                    phase_offset,
                    config.waveform,
                ));

                self.right_voices.push(ChorusVoice::new(
                    self.sample_rate,
                    config.rate,
                    phase_offset + 0.5,
                    config.waveform,
                ));
            }
        } else {
            for voice in self
                .left_voices
                .iter_mut()
                .chain(self.right_voices.iter_mut())
            {
                voice.lfo.set_rate(config.rate);
                voice.lfo.set_waveform(config.waveform);
            }
        }

        self.base_delay_samples = config.delay * 0.001 * self.sample_rate;
        self.depth_samples = config.depth * 0.001 * self.sample_rate;
        self.mix_smoother.set_target(config.mix);
        self.config = config;
    }

    /// Get the current configuration.
    #[must_use]
    pub fn config(&self) -> &ChorusConfig {
        &self.config
    }

    /// Process stereo samples (interleaved).
    ///
    /// # Arguments
    ///
    /// * `samples` - Interleaved stereo input/output buffer
    /// * `num_frames` - Number of sample frames
    pub fn process_interleaved(&mut self, samples: &mut [f64], num_frames: usize) {
        for i in 0..num_frames {
            let left_idx = i * 2;
            let right_idx = i * 2 + 1;

            if left_idx >= samples.len() || right_idx >= samples.len() {
                break;
            }

            let (left_out, right_out) = self.process_frame(samples[left_idx], samples[right_idx]);

            samples[left_idx] = left_out;
            samples[right_idx] = right_out;
        }
    }

    /// Process stereo samples (planar).
    ///
    /// # Arguments
    ///
    /// * `left` - Left channel input/output buffer
    /// * `right` - Right channel input/output buffer
    pub fn process_planar(&mut self, left: &mut [f64], right: &mut [f64]) {
        let num_samples = left.len().min(right.len());

        for i in 0..num_samples {
            let (left_out, right_out) = self.process_frame(left[i], right[i]);
            left[i] = left_out;
            right[i] = right_out;
        }
    }

    /// Process a single stereo frame.
    fn process_frame(&mut self, left_in: f64, right_in: f64) -> (f64, f64) {
        let mut left_wet = 0.0;
        let mut right_wet = 0.0;
        let num_voices = self.left_voices.len() as f64;

        for voice in &mut self.left_voices {
            left_wet += voice.process(
                left_in,
                self.base_delay_samples,
                self.depth_samples,
                self.config.feedback,
            ) / num_voices;
        }

        for voice in &mut self.right_voices {
            right_wet += voice.process(
                right_in,
                self.base_delay_samples,
                self.depth_samples,
                self.config.feedback,
            ) / num_voices;
        }

        let mix = self.mix_smoother.next();
        let left_out = left_in * (1.0 - mix) + left_wet * mix;
        let right_out = right_in * (1.0 - mix) + right_wet * mix;

        (left_out, right_out)
    }

    /// Set the wet/dry mix (0.0 = fully dry, 1.0 = fully wet).
    pub fn set_mix(&mut self, mix: f64) {
        let clamped = mix.clamp(0.0, 1.0);
        self.config.mix = clamped;
        self.mix_smoother.set_target(clamped);
    }

    /// Get the current wet/dry mix value.
    #[must_use]
    pub fn mix(&self) -> f64 {
        self.config.mix
    }

    /// Reset the effect state.
    pub fn reset(&mut self) {
        for voice in self
            .left_voices
            .iter_mut()
            .chain(self.right_voices.iter_mut())
        {
            voice.reset();
        }
        self.mix_smoother.reset(self.config.mix);
    }
}