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
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 {
SetThreshold(f32),
SetGain(f32)
}
pub use self::Message::*;
pub struct Limiter {
level_detectors: Vec<LevelDetector>,
num_channels: usize,
threshold: f32,
gain: f32
}
impl Limiter {
pub fn new(threshold: f32, gain: f32, num_channels: usize) -> Self {
Limiter {
level_detectors: vec![LevelDetector::default(); num_channels],
num_channels: num_channels,
threshold: decibel_to_ratio(threshold),
gain: decibel_to_ratio(gain)
}
}
}
impl MessageReceiver for Limiter {
type Msg = Message;
fn handle_message(&mut self, msg: Message) {
match msg {
SetThreshold(threshold) => {
self.threshold = decibel_to_ratio(threshold);
},
SetGain(gain) => {
self.gain = decibel_to_ratio(gain);
}
}
}
}
impl AudioDevice for Limiter {
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);
let limit = if level > self.threshold {
self.threshold / level
} else {
1.0
};
outputs[i] = self.gain*limit*s;
}
}
}