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
use alloc::sync::Arc;
use core::sync::atomic::{AtomicU32, Ordering};

use crate::{frame, math::Float, Frame, Seek, Signal, Smoothed};

/// Amplifies a signal by a constant amount
///
/// Unlike [`Gain`], this can implement [`Seek`].
pub struct FixedGain<T: ?Sized> {
    gain: f32,
    inner: T,
}

impl<T> FixedGain<T> {
    /// Amplify `signal` by `db` decibels
    ///
    /// Decibels are perceptually linear. Negative values make the signal quieter.
    pub fn new(signal: T, db: f32) -> Self {
        Self {
            gain: 10.0f32.powf(db / 20.0),
            inner: signal,
        }
    }
}

impl<T: Signal + ?Sized> Signal for FixedGain<T>
where
    T::Frame: Frame,
{
    type Frame = T::Frame;

    fn sample(&mut self, interval: f32, out: &mut [T::Frame]) {
        self.inner.sample(interval, out);
        for x in out {
            *x = frame::scale(x, self.gain);
        }
    }

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

impl<T: Seek + ?Sized> Seek for FixedGain<T>
where
    T::Frame: Frame,
{
    fn seek(&mut self, seconds: f32) {
        self.inner.seek(seconds)
    }
}

/// Amplifies a signal dynamically
///
/// To implement a volume control, place a gain combinator near the end of your pipeline where the
/// input amplitude is initially in the range [0, 1] and pass decibels to [`GainControl::set_gain`],
/// mapping the maximum volume to 0 decibels, and the minimum to e.g. -60.
pub struct Gain<T: ?Sized> {
    shared: Arc<AtomicU32>,
    gain: Smoothed<f32>,
    inner: T,
}

impl<T> Gain<T> {
    /// Apply dynamic amplification to `signal`
    pub fn new(signal: T) -> (GainControl, Self) {
        let signal = Gain {
            shared: Arc::new(AtomicU32::new(1.0f32.to_bits())),
            gain: Smoothed::new(1.0),
            inner: signal,
        };
        let handle = GainControl(signal.shared.clone());
        (handle, signal)
    }

    /// Set the initial amplification to `db` decibels
    ///
    /// Perceptually linear. Negative values make the signal quieter.
    ///
    /// Equivalent to `self.set_amplitude_ratio(10.0f32.powf(db / 20.0))`.
    pub fn set_gain(&mut self, db: f32) {
        self.set_amplitude_ratio(10.0f32.powf(db / 20.0));
    }

    /// Set the initial amplitude scaling of the signal directly
    ///
    /// This is nonlinear in terms of both perception and power. Most users should prefer
    /// `set_gain`. Unlike `set_gain`, this method allows a signal to be completely zeroed out if
    /// needed, or even have its phase inverted with a negative factor.
    pub fn set_amplitude_ratio(&mut self, factor: f32) {
        self.shared.store(factor.to_bits(), Ordering::Relaxed);
        self.gain = Smoothed::new(factor);
    }
}

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

    #[allow(clippy::float_cmp)]
    fn sample(&mut self, interval: f32, out: &mut [T::Frame]) {
        self.inner.sample(interval, out);
        let shared = f32::from_bits(self.shared.load(Ordering::Relaxed));
        if self.gain.target() != &shared {
            self.gain.set(shared);
        }
        if self.gain.progress() == 1.0 {
            let g = self.gain.get();
            if g != 1.0 {
                for x in out {
                    *x = frame::scale(x, g);
                }
            }
            return;
        }
        for x in out {
            *x = frame::scale(x, self.gain.get());
            self.gain.advance(interval / SMOOTHING_PERIOD);
        }
    }

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

/// Thread-safe control for a [`Gain`] filter
pub struct GainControl(Arc<AtomicU32>);

impl GainControl {
    /// Get the current amplification in decibels
    pub fn gain(&self) -> f32 {
        20.0 * self.amplitude_ratio().log10()
    }

    /// Amplify the signal by `db` decibels
    ///
    /// Perceptually linear. Negative values make the signal quieter.
    ///
    /// Equivalent to `self.set_amplitude_ratio(10.0f32.powf(db / 20.0))`.
    pub fn set_gain(&mut self, db: f32) {
        self.set_amplitude_ratio(10.0f32.powf(db / 20.0));
    }

    /// Get the current amplitude scaling factor
    pub fn amplitude_ratio(&self) -> f32 {
        f32::from_bits(self.0.load(Ordering::Relaxed))
    }

    /// Scale the amplitude of the signal directly
    ///
    /// This is nonlinear in terms of both perception and power. Most users should prefer
    /// `set_gain`. Unlike `set_gain`, this method allows a signal to be completely zeroed out if
    /// needed, or even have its phase inverted with a negative factor.
    pub fn set_amplitude_ratio(&mut self, factor: f32) {
        self.0.store(factor.to_bits(), Ordering::Relaxed);
    }
}

/// Number of seconds over which to smooth a change in gain
const SMOOTHING_PERIOD: f32 = 0.1;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Constant;

    #[test]
    fn smoothing() {
        let (mut c, mut s) = Gain::new(Constant(1.0));
        let mut buf = [0.0; 6];
        c.set_amplitude_ratio(5.0);
        s.sample(0.025, &mut buf);
        assert_eq!(buf, [1.0, 2.0, 3.0, 4.0, 5.0, 5.0]);
        s.sample(0.025, &mut buf);
        assert_eq!(buf, [5.0; 6]);
    }
}