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
use oxcable::types::{AudioDevice, MessageReceiver, Sample, Time};
use oxcable::utils::helpers::decibel_to_ratio;
use oxcable::level_detector::LevelDetector;
#[derive(Clone, Copy, Debug)]
pub enum Message {
SetOnThreshold(f32),
SetOffThreshold(f32),
SetGain(f32)
}
pub use self::Message::*;
pub struct NoiseGate {
level_detectors: Vec<LevelDetector>,
active: bool,
num_channels: usize,
on_threshold: f32,
off_threshold: f32,
gain: f32
}
impl NoiseGate {
pub fn new(on_threshold: f32, off_threshold: f32, gain: f32,
num_channels: usize) -> Self {
NoiseGate {
level_detectors: vec![LevelDetector::default(); num_channels],
active: false,
num_channels: num_channels,
on_threshold: decibel_to_ratio(on_threshold),
off_threshold: decibel_to_ratio(off_threshold),
gain: decibel_to_ratio(gain)
}
}
}
impl MessageReceiver for NoiseGate {
type Msg = Message;
fn handle_message(&mut self, msg: Message) {
match msg {
SetOnThreshold(threshold) => {
self.on_threshold = decibel_to_ratio(threshold);
},
SetOffThreshold(threshold) => {
self.off_threshold = decibel_to_ratio(threshold);
},
SetGain(gain) => {
self.gain = decibel_to_ratio(gain);
}
}
}
}
impl AudioDevice for NoiseGate {
fn num_inputs(&self) -> usize {
self.num_channels
}
fn num_outputs(&self) -> usize {
self.num_channels
}
fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
for (i,s) in inputs.iter().enumerate() {
let level = self.level_detectors[i].compute_next_level(*s);
if self.active && level < self.off_threshold {
self.active = false;
} else if !self.active && level > self.on_threshold {
self.active = true;
}
outputs[i] = if self.active { self.gain*s } else { 0.0 };
}
}
}