Skip to main content

alpha2_audio/
gain.rs

1use crate::{ProcessCtx, Processor, StateBlob, StateError};
2
3/// Stateless linear amplitude multiplier.
4#[derive(Copy, Clone, Debug, PartialEq)]
5pub struct Gain {
6    gain: f32,
7}
8
9impl Gain {
10    /// Creates a gain processor. Non-finite values are normalized to silence.
11    #[must_use]
12    pub fn new(gain: f32) -> Self {
13        Self {
14            gain: if gain.is_finite() { gain } else { 0.0 },
15        }
16    }
17
18    /// Replaces the linear amplitude multiplier.
19    pub fn set_gain(&mut self, gain: f32) {
20        self.gain = if gain.is_finite() { gain } else { 0.0 };
21    }
22}
23
24impl Processor for Gain {
25    fn prepare(&mut self, _sample_rate: u32, _max_block: usize) {}
26
27    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
28        for channel in 0..inputs.len().min(outputs.len()) {
29            for (source, target) in inputs[channel].iter().zip(outputs[channel].iter_mut()) {
30                *target = *source * self.gain;
31            }
32        }
33    }
34
35    fn reset(&mut self) {}
36
37    fn save_state(&self) -> StateBlob {
38        StateBlob::new(Vec::new())
39    }
40
41    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
42        if state.as_bytes().is_empty() {
43            Ok(())
44        } else {
45            Err(StateError::Mismatch)
46        }
47    }
48}