summaryrefslogtreecommitdiff
path: root/src/synth/noise.rs
blob: 765d17e917f414b18081df436e5d5ff74d471e2a (plain)
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
use super::{
    FactoryParameters, GenBox, GenFactoryError, Generator, GeneratorFactory, Parameters, Rate,
    SampleBuffer,
};
use std::mem;

use ::rand::{Rng, SeedableRng, XorShiftRng};

#[derive(Debug)]
pub struct Noise {
    pub rng: XorShiftRng,
    pub buf: SampleBuffer,
}

impl Generator for Noise {
    fn eval<'a>(&'a mut self, _params: &Parameters) -> &'a SampleBuffer {
        self.buf.rate = Rate::Sample;

        for i in 0..self.buf.len() {
            self.buf[i] = self.rng.next_f32();
        }

        &self.buf
    }
    fn buffer(&self) -> &SampleBuffer {
        &self.buf
    }
    fn set_buffer(&mut self, buf: SampleBuffer) -> SampleBuffer {
        mem::replace(&mut self.buf, buf)
    }
}

pub struct NoiseFactory;

impl GeneratorFactory for NoiseFactory {
    fn new(&self, params: &mut FactoryParameters) -> Result<GenBox, GenFactoryError> {
        Ok(Box::new(Noise {
            rng: XorShiftRng::from_seed(::rand::random()),
            buf: SampleBuffer::new(params.env.default_buffer_size),
        }))
    }
}

pub static Factory: NoiseFactory = NoiseFactory;