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
use dasp_frame::Frame;
use dasp_sample::Sample;
use ops::f32::powf32;
#[cfg(feature = "peak")]
pub use self::peak::Peak;
mod ops;
#[cfg(feature = "peak")]
mod peak;
#[cfg(feature = "rms")]
mod rms;
#[derive(Clone, Debug)]
pub struct Detector<F, D>
where
F: Frame,
D: Detect<F>,
{
last_env_frame: D::Output,
attack_gain: f32,
release_gain: f32,
detect: D,
}
pub trait Detect<F>
where
F: Frame,
{
type Output: Frame<NumChannels = F::NumChannels>;
fn detect(&mut self, frame: F) -> Self::Output;
}
fn calc_gain(n_frames: f32) -> f32 {
if n_frames == 0.0 {
0.0
} else {
powf32(core::f32::consts::E, -1.0 / n_frames)
}
}
impl<F, D> Detector<F, D>
where
F: Frame,
D: Detect<F>,
{
pub fn new(detect: D, attack_frames: f32, release_frames: f32) -> Self {
Detector {
last_env_frame: D::Output::EQUILIBRIUM,
attack_gain: calc_gain(attack_frames),
release_gain: calc_gain(release_frames),
detect: detect,
}
}
pub fn set_attack_frames(&mut self, frames: f32) {
self.attack_gain = calc_gain(frames);
}
pub fn set_release_frames(&mut self, frames: f32) {
self.release_gain = calc_gain(frames);
}
pub fn next(&mut self, frame: F) -> D::Output {
let Detector {
attack_gain,
release_gain,
ref mut detect,
ref mut last_env_frame,
} = *self;
let detected_frame = detect.detect(frame);
let new_env_frame = last_env_frame.zip_map(detected_frame, |l, d| {
let gain = if l < d { attack_gain } else { release_gain };
let diff = l.add_amp(-d.to_signed_sample());
d.add_amp(diff.mul_amp(gain.to_sample()).to_sample())
});
*last_env_frame = new_env_frame;
new_env_frame
}
}