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
use crate::context::{AsBaseAudioContext, AudioContextRegistration, AudioParamId};
use crate::param::{AudioParam, AudioParamOptions};
use crate::render::{AudioParamValues, AudioProcessor, AudioRenderQuantum};
use crate::SampleRate;
use super::{AudioNode, ChannelConfig, ChannelConfigOptions};
pub struct GainOptions {
pub gain: f32,
pub channel_config: ChannelConfigOptions,
}
impl Default for GainOptions {
fn default() -> Self {
Self {
gain: 1.,
channel_config: ChannelConfigOptions::default(),
}
}
}
pub struct GainNode {
registration: AudioContextRegistration,
channel_config: ChannelConfig,
gain: AudioParam,
}
impl AudioNode for GainNode {
fn registration(&self) -> &AudioContextRegistration {
&self.registration
}
fn channel_config_raw(&self) -> &ChannelConfig {
&self.channel_config
}
fn number_of_inputs(&self) -> u32 {
1
}
fn number_of_outputs(&self) -> u32 {
1
}
}
impl GainNode {
pub fn new<C: AsBaseAudioContext>(context: &C, options: GainOptions) -> Self {
context.base().register(move |registration| {
let param_opts = AudioParamOptions {
min_value: f32::MIN,
max_value: f32::MAX,
default_value: 1.,
automation_rate: crate::param::AutomationRate::A,
};
let (param, proc) = context
.base()
.create_audio_param(param_opts, registration.id());
param.set_value_at_time(options.gain, 0.);
let render = GainRenderer { gain: proc };
let node = GainNode {
registration,
channel_config: options.channel_config.into(),
gain: param,
};
(node, Box::new(render))
})
}
pub fn gain(&self) -> &AudioParam {
&self.gain
}
}
struct GainRenderer {
gain: AudioParamId,
}
impl AudioProcessor for GainRenderer {
fn process(
&mut self,
inputs: &[AudioRenderQuantum],
outputs: &mut [AudioRenderQuantum],
params: AudioParamValues,
_timestamp: f64,
_sample_rate: SampleRate,
) -> bool {
let input = &inputs[0];
let output = &mut outputs[0];
let gain_values = params.get(&self.gain);
*output = input.clone();
output.modify_channels(|channel| {
channel
.iter_mut()
.zip(gain_values.iter())
.for_each(|(value, g)| *value *= g)
});
false
}
}