1#![allow(clippy::cast_precision_loss)]
2
3use crate::{ProcessCtx, Processor, StateBlob, StateError};
4
5#[derive(Copy, Clone, Debug, PartialEq)]
7pub struct EnvelopeFollower {
8 attack_ms: f32,
9 release_ms: f32,
10 attack: f32,
11 release: f32,
12 value: f32,
13}
14
15impl EnvelopeFollower {
16 #[must_use]
19 pub fn new(attack_ms: f32, release_ms: f32) -> Self {
20 Self {
21 attack_ms: positive(attack_ms, 5.0),
22 release_ms: positive(release_ms, 100.0),
23 attack: 0.0,
24 release: 0.0,
25 value: 0.0,
26 }
27 }
28 pub fn prepare(&mut self, sample_rate: u32) {
30 let rate = sample_rate.max(1) as f32;
31 self.attack = libm::expf(-1.0 / (self.attack_ms * 0.001 * rate));
32 self.release = libm::expf(-1.0 / (self.release_ms * 0.001 * rate));
33 }
34 pub fn next(&mut self, sample: f32) -> f32 {
36 if !self.value.is_finite() {
37 self.value = 0.0;
38 }
39 let peak = finite_or_zero(sample).abs();
40 let coefficient = if peak > self.value {
41 self.attack
42 } else {
43 self.release
44 };
45 self.value = coefficient * self.value + (1.0 - coefficient) * peak;
46 if self.value.abs() < 1.0e-30 {
47 self.value = 0.0;
48 }
49 self.value
50 }
51 pub fn reset(&mut self) {
53 self.value = 0.0;
54 }
55}
56
57#[derive(Clone, Debug)]
64pub struct Ducker {
65 follower: EnvelopeFollower,
66 threshold: f32,
67 depth_db: f32,
68 depth: f32,
69 bypass: bool,
70 ramp: Option<DuckRamp>,
71}
72
73#[derive(Clone, Copy, Debug)]
74struct DuckRamp {
75 from: [f32; 2],
76 change: [f32; 2],
77 phase: usize,
78}
79
80impl DuckRamp {
81 fn at(&self, frame: usize) -> [f32; 2] {
82 let progress = crate::control::progress(self.phase, frame);
83 [
84 self.from[0] + self.change[0] * progress,
85 self.from[1] + self.change[1] * progress,
86 ]
87 }
88}
89
90impl Ducker {
91 #[must_use]
96 pub fn new(threshold: f32, depth_db: f32, attack_ms: f32, release_ms: f32) -> Self {
97 Self {
98 follower: EnvelopeFollower::new(attack_ms, release_ms),
99 threshold: positive(threshold, 0.1),
100 depth_db,
101 depth: depth_gain(depth_db),
102 bypass: false,
103 ramp: None,
104 }
105 }
106 pub fn set_bypass(&mut self, bypass: bool) {
108 self.bypass = bypass;
109 }
110}
111
112impl Ducker {
113 fn run(
114 &mut self,
115 inputs: &[&[f32]],
116 outputs: &mut [&mut [f32]],
117 threshold_and_depth_at_frame: impl Fn(usize) -> [f32; 2],
118 ) -> usize {
119 let channels = outputs.len().min(inputs.len() / 2).min(2);
120 let frames = outputs
121 .iter()
122 .take(channels)
123 .map(|v| v.len())
124 .chain(inputs.iter().take(channels * 2).map(|v| v.len()))
125 .min()
126 .unwrap_or(0);
127 for frame in 0..frames {
128 let [threshold, depth] = threshold_and_depth_at_frame(frame);
129 let sidechain = inputs[channels..channels * 2]
130 .iter()
131 .map(|channel| channel[frame].abs())
132 .fold(0.0_f32, f32::max);
133 let envelope = self.follower.next(sidechain);
134 let mix = ((envelope - threshold) / threshold.max(1.0e-9)).clamp(0.0, 1.0);
135 let gain = if self.bypass {
136 1.0
137 } else {
138 1.0 + (depth - 1.0) * mix
139 };
140 for channel in 0..channels {
141 outputs[channel][frame] = finite_or_zero(inputs[channel][frame]) * gain;
142 }
143 }
144 frames
145 }
146}
147
148impl Processor for Ducker {
149 fn inputs_per_output(&self) -> usize {
151 2
152 }
153
154 fn history_samples(&self) -> u32 {
155 crate::processor::settling_samples(f64::from(
156 self.follower.attack.max(self.follower.release),
157 ))
158 }
159
160 fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
161 self.follower.prepare(sample_rate);
162 }
163
164 fn control_params(&self) -> usize {
166 2
167 }
168
169 fn control(&mut self, span: &crate::ControlSpan<'_>) {
170 let (&[threshold, depth_db], &[next_threshold, next_depth_db]) = (span.from, span.to)
171 else {
172 return;
173 };
174 let threshold = positive(threshold, 0.1);
175 let depth = if depth_db.to_bits() == self.depth_db.to_bits() {
176 self.depth
177 } else {
178 depth_gain(depth_db)
179 };
180 if span.is_steady() {
181 (self.threshold, self.depth_db, self.depth) = (threshold, depth_db, depth);
182 self.ramp = None;
183 return;
184 }
185 let next = [positive(next_threshold, 0.1), depth_gain(next_depth_db)];
186 self.ramp = Some(DuckRamp {
187 from: [threshold, depth],
188 change: [next[0] - threshold, next[1] - depth],
189 phase: span.phase,
190 });
191 }
192 fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
193 match self.ramp {
194 None => {
195 let steady = [self.threshold, self.depth];
196 self.run(inputs, outputs, |_| steady);
197 }
198 Some(ramp) => {
199 let frames = self.run(inputs, outputs, |frame| ramp.at(frame));
200 self.ramp = Some(DuckRamp {
201 phase: ramp.phase.saturating_add(frames),
202 ..ramp
203 });
204 }
205 }
206 }
207 fn reset(&mut self) {
208 self.follower.reset();
209 }
210 fn save_state(&self) -> StateBlob {
211 StateBlob::new(self.follower.value.to_le_bytes().to_vec())
212 }
213 fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
214 let bytes = <[u8; 4]>::try_from(state.as_bytes()).map_err(|_| StateError::Mismatch)?;
215 let value = f32::from_le_bytes(bytes);
216 if !value.is_finite() || value < 0.0 {
217 return Err(StateError::Invalid);
218 }
219 self.follower.value = value;
220 Ok(())
221 }
222}
223
224fn depth_gain(depth_db: f32) -> f32 {
225 libm::powf(10.0, -depth_db.abs().min(96.0) / 20.0)
226}
227
228fn finite_or_zero(value: f32) -> f32 {
229 if value.is_finite() { value } else { 0.0 }
230}
231
232fn positive(value: f32, fallback: f32) -> f32 {
233 if value.is_finite() && value > 0.0 {
234 value
235 } else {
236 fallback
237 }
238}