devalang_wasm/engine/audio/effects/processors/
distortion.rs

1use crate::engine::audio::effects::processors::super_trait::EffectProcessor;
2
3#[derive(Debug, Clone)]
4pub struct DistortionProcessor {
5    amount: f32,
6    mix: f32,
7}
8
9impl DistortionProcessor {
10    pub fn new(amount: f32, mix: f32) -> Self {
11        Self {
12            amount: amount.clamp(0.0, 1.0),
13            mix: mix.clamp(0.0, 1.0),
14        }
15    }
16}
17
18impl Default for DistortionProcessor {
19    fn default() -> Self {
20        Self::new(0.5, 0.5)
21    }
22}
23
24impl EffectProcessor for DistortionProcessor {
25    fn process(&mut self, samples: &mut [f32], _sample_rate: u32) {
26        // Map amount -> drive factor for audible range
27        let drive = 1.0 + self.amount * 29.0; // 1x..30x
28        for sample in samples.iter_mut() {
29            let input = *sample;
30            let driven = input * drive;
31            let distorted = driven.tanh();
32            *sample = input * (1.0 - self.mix) + distorted * self.mix;
33        }
34    }
35
36    fn reset(&mut self) {
37        // No state to reset
38    }
39
40    fn name(&self) -> &str {
41        "Distortion"
42    }
43}