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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use audio_garbage_collector::{make_shared, Shared};
use std::marker::PhantomData;
use std::ops::Mul;
use audio_processor_traits::simple_processor::SimpleAudioProcessor;
use audio_processor_traits::{AtomicF32, Float};
pub struct GainProcessorHandle {
gain: AtomicF32,
}
impl GainProcessorHandle {
fn new(gain: impl Into<f32>) -> Self {
Self {
gain: AtomicF32::new(gain.into()),
}
}
pub fn set_gain(&self, gain: impl Into<f32>) {
self.gain.set(gain.into());
}
pub fn gain(&self) -> f32 {
self.gain.get()
}
}
pub struct GainProcessor<SampleType> {
handle: Shared<GainProcessorHandle>,
phantom: PhantomData<SampleType>,
}
impl<SampleType> Default for GainProcessor<SampleType> {
fn default() -> Self {
Self::new(1.0)
}
}
impl<SampleType> GainProcessor<SampleType> {
pub fn new(gain: impl Into<f32>) -> Self {
Self::new_with_handle(make_shared(GainProcessorHandle::new(gain)))
}
pub fn new_with_handle(handle: Shared<GainProcessorHandle>) -> Self {
Self {
handle,
phantom: PhantomData::default(),
}
}
pub fn set_gain(&self, gain: impl Into<f32>) {
self.handle.set_gain(gain)
}
pub fn gain(&self) -> f32 {
self.handle.gain()
}
}
impl<SampleType> SimpleAudioProcessor for GainProcessor<SampleType>
where
SampleType: Float + Send + Sync + Mul<Output = SampleType>,
{
type SampleType = SampleType;
fn s_process(&mut self, sample: SampleType) -> SampleType {
SampleType::from(self.gain()).unwrap() * sample
}
}
#[cfg(test)]
mod test {
use audio_processor_testing_helpers::assert_f_eq;
use audio_processor_traits::simple_processor;
use audio_processor_traits::InterleavedAudioBuffer;
use super::*;
#[test]
fn test_gain_does_its_thing() {
let mut gain = GainProcessor::new(0.8);
let mut samples = [1., 1., 1., 1., 1., 1.];
let mut input = InterleavedAudioBuffer::new(1, &mut samples);
simple_processor::process_buffer(&mut gain, &mut input);
for sample in samples {
assert_f_eq!(sample, 0.8);
}
}
#[test]
fn test_gain_can_be_changed() {
let mut gain = GainProcessor::default();
gain.set_gain(0.8);
let mut samples = [1., 1., 1., 1., 1., 1.];
let mut input = InterleavedAudioBuffer::new(1, &mut samples);
simple_processor::process_buffer(&mut gain, &mut input);
for sample in samples {
assert_f_eq!(sample, 0.8);
}
}
}