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
//! A compression filter.

use oxcable::types::{AudioDevice, MessageReceiver, Sample, Time};
use oxcable::utils::helpers::decibel_to_ratio;
use oxcable::level_detector::LevelDetector;


/// Defines the messages that the Compressor supports.
#[derive(Clone, Copy, Debug)]
pub enum Message {
    /// Sets the compression threshold, in decibels.
    SetThreshold(f32),
    /// Sets the compression ratio.
    SetRatio(f32),
    /// Sets the output gian, in decibels.
    SetGain(f32)
}
pub use self::Message::*;


/// A compression filter.
///
/// Compression filters provide a soft limit on the maximum amplitude of
/// a signal. When a signal exceeds the threshold of the filter, it is partially
/// attenuated to bring it closer to the threshold.
///
/// The intensity of the attenuation is determined by the compression ratio.
/// A ratio of zero provides no attenuation. A ratio of 1 will hard limit the
/// signal to the threshold. Values in between will provide partial attenuation.
pub struct Compressor {
    level_detectors: Vec<LevelDetector>,
    num_channels: usize,
    threshold: f32,
    compression_ratio: f32,
    gain: f32
}

impl Compressor {
    /// Creates a new compressor.
    ///
    /// * The `threshold` specifies the decibel level at which compression begins.
    /// * The `compression_ratio` specifies the ratio of attenuation above the
    ///   threshold.
    /// * The `gain` (in decibels) will be applied to the signal after
    ///   compression.
    pub fn new(threshold: f32, compression_ratio: f32, gain: f32,
               num_channels: usize) -> Self {
        Compressor {
            level_detectors: vec![LevelDetector::default(); num_channels],
            num_channels: num_channels,
            threshold: decibel_to_ratio(threshold),
            compression_ratio: compression_ratio,
            gain: decibel_to_ratio(gain)
        }
    }
}

impl MessageReceiver for Compressor {
    type Msg = Message;
    fn handle_message(&mut self, msg: Message) {
        match msg {
            SetThreshold(threshold) => {
                self.threshold = decibel_to_ratio(threshold);
            },
            SetRatio(ratio) => {
                self.compression_ratio = ratio;
            }
            SetGain(gain) => {
                self.gain = decibel_to_ratio(gain);
            }
        }
    }
}

impl AudioDevice for Compressor {
    fn num_inputs(&self) -> usize {
        self.num_channels
    }

    fn num_outputs(&self) -> usize {
        self.num_channels
    }

    fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
        for (i,s) in inputs.iter().enumerate() {
            // Get the current signal level and use it to calculate the gain
            // correction
            let level = self.level_detectors[i].compute_next_level(*s);
            let compression = if level > self.threshold {
                self.compression_ratio*self.threshold/level +
                    1.0-self.compression_ratio
            } else {
                1.0
            };

            outputs[i] = self.gain*compression*s;
        }
    }
}