bevy_seedling 0.8.0

A sprouting integration of the Firewheel audio engine
Documentation
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Limiter with configurable lookahead, attack and release.

use core::f32;
use std::num::NonZeroU32;

use bevy_ecs::component::Component;
use firewheel::{
    Volume,
    channel_config::{ChannelConfig, NonZeroChannelCount},
    diff::{Diff, Patch},
    dsp::filter::smoothing_filter::{SmoothingFilter, SmoothingFilterCoeff},
    event::ProcEvents,
    node::{
        AudioNode, AudioNodeInfo, AudioNodeProcessor, ConstructProcessorContext, NodeError,
        ProcBuffers, ProcExtra, ProcInfo, ProcStreamCtx, ProcessStatus,
    },
};

// Settle at 1% offset
const SETTLE_RATIO: f32 = 0.01;

/// The configuration for an [`AsymmetricalSmoothedParam`]
#[derive(Debug, Clone, Copy, PartialEq)]
struct AsymmetricalSmootherConfig {
    /// The amount of smoothing in seconds when the target is higher than the current value
    pub smooth_secs_up: f32,
    /// The amount of smoothing in seconds when the target is lower than the current value
    pub smooth_secs_down: f32,
}

/// A helper struct to smooth an f32 parameter, allowing different rates for up and down.
#[derive(Debug, Clone)]
struct AsymmetricalSmoothedParam {
    target_value: f32,
    target_times_a_up: f32,
    target_times_a_down: f32,
    filter: SmoothingFilter,
    coeff_up: SmoothingFilterCoeff,
    coeff_down: SmoothingFilterCoeff,
    smooth_secs_up: f32,
    smooth_secs_down: f32,
}

impl AsymmetricalSmoothedParam {
    /// Construct a new smoothed f32 parameter with the given configuration.
    pub fn new(value: f32, config: AsymmetricalSmootherConfig, sample_rate: NonZeroU32) -> Self {
        assert!(config.smooth_secs_up > 0.0);
        assert!(config.smooth_secs_down > 0.0);

        let coeff_up = SmoothingFilterCoeff::new(sample_rate, config.smooth_secs_up, SETTLE_RATIO);
        let coeff_down =
            SmoothingFilterCoeff::new(sample_rate, config.smooth_secs_down, SETTLE_RATIO);

        Self {
            target_value: value,
            target_times_a_up: value * coeff_up.a0,
            target_times_a_down: value * coeff_down.a0,
            filter: SmoothingFilter::new(value),
            coeff_up,
            coeff_down,
            smooth_secs_up: config.smooth_secs_up,
            smooth_secs_down: config.smooth_secs_down,
        }
    }

    /// The target value of the parameter.
    pub fn target_value(&self) -> f32 {
        self.target_value
    }

    /// Set the target value of the parameter.
    pub fn set_value(&mut self, value: f32) {
        self.target_value = value;
        self.target_times_a_up = value * self.coeff_up.a0;
        self.target_times_a_down = value * self.coeff_down.a0;
    }

    /// Set the smooth rate when the target value is higher than the current value.
    pub fn set_smooth_secs_up(&mut self, sample_rate: NonZeroU32, smooth_secs_up: f32) {
        let coeff_up = SmoothingFilterCoeff::new(sample_rate, smooth_secs_up, SETTLE_RATIO);
        self.smooth_secs_up = smooth_secs_up;
        self.coeff_up = coeff_up;
    }

    /// Set the smooth rate when the target value is lower than the current value.
    pub fn set_smooth_secs_down(&mut self, sample_rate: NonZeroU32, smooth_secs_down: f32) {
        let coeff_down = SmoothingFilterCoeff::new(sample_rate, smooth_secs_down, SETTLE_RATIO);
        self.smooth_secs_down = smooth_secs_down;
        self.coeff_down = coeff_down;
    }

    /// Return the next smoothed value.
    #[inline(always)]
    pub fn next_smoothed(&mut self) -> f32 {
        // Branchless alternation between up and down.
        let signum = (self.target_value() - self.filter.z1).signum();
        let less_factor = signum.max(0.);
        let more_factor = (-signum).max(0.);

        debug_assert!(less_factor == 1. || more_factor == 1.);

        let target_times_a =
            less_factor * self.target_times_a_up + more_factor * self.target_times_a_down;
        let coeff_b1 = less_factor * self.coeff_up.b1 + more_factor * self.coeff_down.b1;
        self.filter.process_sample_a(target_times_a, coeff_b1)
    }

    /// Update the sample rate.
    pub fn update_sample_rate(&mut self, sample_rate: NonZeroU32) {
        self.coeff_up = SmoothingFilterCoeff::new(sample_rate, self.smooth_secs_up, SETTLE_RATIO);
        self.coeff_down =
            SmoothingFilterCoeff::new(sample_rate, self.smooth_secs_down, SETTLE_RATIO);
        self.target_times_a_up = self.target_value() * self.coeff_up.a0;
        self.target_times_a_down = self.target_value() * self.coeff_down.a0;
    }
}

/// Buffer to incrementally calculate a maximum value of a buffer with the minimum number of comparisons.
#[derive(Debug, Clone)]
struct IncrementalMax {
    // First item is unused for convenience. Buffer length is rounded up to an even number.
    buffer: Box<[f32]>,
    length: usize,
    leaf_offset: usize,
}

impl IncrementalMax {
    #[inline]
    fn get_index(&self, i: usize) -> usize {
        self.leaf_offset + i
    }

    /// Create a new [`IncrementalMax`].
    pub fn new(length: usize) -> Self {
        let leaf_offset = length.next_power_of_two();
        Self {
            buffer: vec![0.; leaf_offset + length + (length & 1)].into(),
            length,
            leaf_offset,
        }
    }

    /// The length of the internal buffer.
    #[inline]
    // `is_empty` doesn't make sense for this type, the length should always be >0
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.length
    }

    /// Get the maximum of the values in the buffer.
    #[inline]
    pub fn max(&self) -> f32 {
        self.buffer[1]
    }

    /// Set a value at the given index.
    pub fn set(&mut self, index: usize, value: f32) {
        let mut i = self.get_index(index);

        self.buffer[i] = value;

        while i > 1 {
            let max = self.buffer[i].max(self.buffer[i ^ 1]);
            i >>= 1;
            self.buffer[i] = max;
        }
    }
}

/// Configuration for a [`LimiterNode`].
#[derive(Debug, Clone, Component, PartialEq)]
#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
pub struct LimiterConfig {
    /// The limiter lookahead.
    ///
    /// This is how much latency will be introduced in order to ensure that the
    /// limiter will reduce volume in time for high peaks to be reduced.
    ///
    /// By default, it will set the lookahead to the same as the `attack` of the limiter.
    pub lookahead: Option<f32>,
    /// How much extra headroom to add.
    ///
    /// The intended target volume will be unity gain minus this.
    ///
    /// By default, no headroom is added.
    pub headroom: Volume,
    /// How many channels to take as input/return as output.
    ///
    /// By default, this is stereo.
    pub channels: NonZeroChannelCount,
}

impl Default for LimiterConfig {
    fn default() -> Self {
        Self {
            lookahead: None,
            headroom: Volume::Decibels(0.),
            channels: NonZeroChannelCount::STEREO,
        }
    }
}

/// A limiter node with lookahead.
///
/// By default the lookahead will be set to `attack`, see [`LimiterConfig`] to see how to
/// set lookahead to something else.
#[derive(Diff, Patch, Debug, Clone, Component)]
#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
pub struct LimiterNode {
    /// How long it takes to react to increases in volume, in seconds.
    ///
    /// By default, this is 0.05s.
    pub attack: f32,
    /// How long it takes to react to decreases in volume, in seconds.
    ///
    /// By default, this is 0.2s.
    pub release: f32,
}

impl LimiterNode {
    /// Create a new [`LimiterNode`].
    pub fn new(attack: f32, release: f32) -> Self {
        Self { attack, release }
    }
}

impl Default for LimiterNode {
    fn default() -> Self {
        Self::new(0.05, 0.2)
    }
}

/// Look-ahead limiter.
struct Limiter {
    lookahead: f32,
    headroom: Volume,
    sample_rate: NonZeroU32,
    reducer: IncrementalMax,
    follower: AsymmetricalSmoothedParam,
    buffer: Box<[f32]>,
    num_channels: u32,
    max_buffer_length: NonZeroU32,
    index: usize,
}

impl AudioNode for LimiterNode {
    type Configuration = LimiterConfig;

    fn info(
        &self,
        config: &Self::Configuration,
    ) -> Result<firewheel::node::AudioNodeInfo, NodeError> {
        Ok(AudioNodeInfo::new()
            .debug_name("limiter")
            .channel_config(ChannelConfig {
                num_inputs: config.channels.get(),
                num_outputs: config.channels.get(),
            }))
    }

    fn construct_processor(
        &self,
        config: &Self::Configuration,
        cx: ConstructProcessorContext,
    ) -> Result<impl AudioNodeProcessor, NodeError> {
        Ok(Limiter::new(
            cx.stream_info.sample_rate,
            config.lookahead.unwrap_or(self.attack),
            self.attack,
            self.release,
            config.headroom,
            config.channels.get().get(),
            cx.stream_info.max_block_frames,
        ))
    }
}

fn reducer_buf_size(sample_rate: NonZeroU32, lookahead: f32) -> usize {
    (sample_rate.get() as f32 * lookahead).round().max(1.) as usize
}

impl Limiter {
    fn advance(&mut self) {
        self.index = (self.index + 1) % self.reducer.len();
    }

    fn new(
        sample_rate: NonZeroU32,
        lookahead: f32,
        attack: f32,
        release: f32,
        headroom: Volume,
        num_channels: u32,
        max_buffer_length: NonZeroU32,
    ) -> Self {
        let follower = AsymmetricalSmoothedParam::new(
            1.,
            AsymmetricalSmootherConfig {
                smooth_secs_up: attack,
                smooth_secs_down: release,
            },
            sample_rate,
        );
        let reducer = IncrementalMax::new(reducer_buf_size(sample_rate, lookahead));
        let buffer = vec![0.; reducer.len() * num_channels as usize].into();

        Limiter {
            // Updated when given a new stream
            sample_rate,
            buffer,
            num_channels,
            max_buffer_length,
            reducer,
            index: 0,

            // Static
            lookahead,
            headroom,
            follower,
        }
    }
}

impl AudioNodeProcessor for Limiter {
    fn events(&mut self, _info: &ProcInfo, events: &mut ProcEvents, _extra: &mut ProcExtra) {
        for patch in events.drain_patches::<LimiterNode>() {
            match patch {
                LimiterNodePatch::Attack(atk) => {
                    self.follower.set_smooth_secs_up(self.sample_rate, atk);
                }
                LimiterNodePatch::Release(rel) => {
                    self.follower.set_smooth_secs_down(self.sample_rate, rel);
                }
            }
        }
    }

    fn process(
        &mut self,
        proc_info: &ProcInfo,
        buffers: ProcBuffers,
        _: &mut ProcExtra,
    ) -> ProcessStatus {
        if proc_info
            .in_silence_mask
            .all_channels_silent(buffers.inputs.len())
            && self.buffer.iter().all(|s| *s == 0.)
        {
            return ProcessStatus::ClearAllOutputs;
        }

        let frame_size = proc_info.frames;

        for i in 0..frame_size {
            let amplitude = buffers
                .inputs
                .iter()
                .map(|input| input[i])
                .filter(|x| x.is_finite())
                .fold(0f32, |amp, x| amp.max(x.abs()));

            self.reducer.set(self.index, amplitude);
            let max = self.reducer.max();

            self.follower.set_value(max * self.headroom.amp());

            let limit = self.follower.next_smoothed().max(1.);

            for ((current_chan, out_chan), input_chan) in self
                .buffer
                .chunks_exact_mut(self.num_channels as usize)
                .nth(self.index)
                .unwrap()
                .iter_mut()
                .zip(&mut *buffers.outputs)
                .zip(buffers.inputs)
            {
                out_chan[i] = *current_chan / limit;
                *current_chan = input_chan[i];
            }

            self.advance();
        }

        ProcessStatus::OutputsModified
    }

    fn new_stream(&mut self, stream_info: &firewheel::StreamInfo, _: &mut ProcStreamCtx) {
        self.index = 0;
        self.sample_rate = stream_info.sample_rate;
        self.max_buffer_length = stream_info.max_block_frames;

        self.reducer =
            IncrementalMax::new(reducer_buf_size(stream_info.sample_rate, self.lookahead));

        self.follower.update_sample_rate(stream_info.sample_rate);

        let new_buffer_size = self.reducer.len() * self.num_channels as usize;

        if self.buffer.len() == new_buffer_size {
            self.buffer.fill(0.);
        } else {
            self.buffer = vec![0.; new_buffer_size].into();
        }
    }
}