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
//! Different kinds of signal distortion.

use crate::{prelude::Signal, signal::PointwiseMapSgn, Map};

/// Infinite clipping distortion.
///
/// Maps positive values to `1.0`, negative values to `-1.0`.
#[derive(Clone, Copy, Debug, Default)]
pub struct InfClip;

impl Map<f64, f64> for InfClip {
    fn eval(&self, x: f64) -> f64 {
        x.signum()
    }
}

/// Applies [`InfClip`] distortion to a signal.
pub type InfClipping<S> = PointwiseMapSgn<S, InfClip>;

impl<S: Signal> InfClipping<S> {
    /// Initializes a new [`InfClipping`].
    pub fn new(sgn: S) -> Self {
        Self::new_pointwise(sgn, InfClip)
    }
}

/// Clipping distortion.
///
/// Clamps all values between `-threshold` and `threshold`, and normalizes.
#[derive(Clone, Copy, Debug)]
pub struct Clip {
    /// The threshold for clipping.
    pub threshold: f64,
}

impl Clip {
    /// Initializes a new [`Clip`] struct.
    pub fn new(threshold: f64) -> Self {
        Self { threshold }
    }
}

impl Default for Clip {
    fn default() -> Self {
        Self::new(1.0)
    }
}

impl Map<f64, f64> for Clip {
    fn eval(&self, x: f64) -> f64 {
        x.clamp(-self.threshold, self.threshold) / self.threshold
    }
}

/// Applies [`Clip`] distortion to a signal.
pub type Clipping<S> = PointwiseMapSgn<S, Clip>;

impl<S: Signal> Clipping<S> {
    /// Initializes a new [`Clipping`].
    pub fn new(sgn: S, threshold: f64) -> Self {
        Self::new_pointwise(sgn, Clip::new(threshold))
    }
}

/// Arctangent distortion.
///
/// Applies the function `tan⁻¹(shape * x)` to the input signal and normalizes.
#[derive(Clone, Copy, Debug)]
pub struct Atan {
    /// The shape of the distortion. Typically larger than `1.0`.
    pub shape: f64,
}

impl Atan {
    /// Initializes a new [`Atan`] struct.
    pub fn new(shape: f64) -> Self {
        Self { shape }
    }
}

impl Default for Atan {
    fn default() -> Self {
        Self::new(1.0)
    }
}

impl Map<f64, f64> for Atan {
    fn eval(&self, x: f64) -> f64 {
        (self.shape * x).atan() / std::f64::consts::FRAC_PI_2
    }
}

/// Applies [`Atan`] distortion to a signal.
pub type Arctangent<S> = PointwiseMapSgn<S, Atan>;

impl<S: Signal> Arctangent<S> {
    /// Initializes a new [`Arctangent`].
    pub fn new(sgn: S, shape: f64) -> Self {
        Self::new_pointwise(sgn, Atan::new(shape))
    }
}

// Todo: bitcrusher effect.