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
use crate::{math::Float, Frame, Seek, Signal};

/// Smoothly maps a signal of any range into (-1, 1)
///
/// For each input sample `x`, outputs `x / (1 + |x|)`.
///
/// When many signals are combined with a [`Mixer`](crate::Mixer) or [`Spatial`](crate::Spatial), or
/// when spatial signals are very near by, audio can get arbitrarily loud. Because surprisingly loud
/// audio can be disruptive and even damaging, it can be useful to limit the output range, but
/// simple clamping introduces audible artifacts.
///
/// See also [`Tanh`](crate::Tanh), which distorts quiet sounds less, and loud sounds more.
pub struct Reinhard<T>(T);

impl<T> Reinhard<T> {
    /// Apply the Reinhard operator to `signal`
    pub fn new(signal: T) -> Self {
        Self(signal)
    }
}

impl<T: Signal> Signal for Reinhard<T>
where
    T::Frame: Frame,
{
    type Frame = T::Frame;

    fn sample(&mut self, interval: f32, out: &mut [T::Frame]) {
        self.0.sample(interval, out);
        for x in out {
            for channel in x.channels_mut() {
                *channel /= 1.0 + channel.abs();
            }
        }
    }

    fn is_finished(&self) -> bool {
        self.0.is_finished()
    }
}

impl<T> Seek for Reinhard<T>
where
    T: Signal + Seek,
    T::Frame: Frame,
{
    fn seek(&mut self, seconds: f32) {
        self.0.seek(seconds);
    }
}