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
//   Copyright 2019 Waver Contributors
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

//! A module for wave types and iterators.

use core::{
    f32::consts::PI,
    fmt,
    iter::{IntoIterator, Iterator},
};
use libm::sinf;

/// A structure that represent a sinusoidal wave.
///
/// The default value for a wave values is 0.0 except for the amplitude weight
/// which is 1.0 (100% of available amplitude).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Wave {
    /// The sampling rate of this wave.
    pub sample_rate: f32,

    /// The frequency of this wave.
    pub frequency: f32,

    /// The phase of this wave.
    pub phase: f32,

    /// The amplitude as a percentage [0.0 - 1.0].
    pub amplitude: f32,
}

impl Wave {
    /// An infinite iterator for the Wave structure.
    ///
    /// The iterator will produce an infinite number of wave samples at the
    /// specified sampling rate and frequency.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::vec::Vec;
    /// use waver::Wave;
    ///
    /// let wave = Wave { sample_rate: 10000.0, frequency: 2000.0, ..Default::default() };
    /// let res: Vec<f32> = wave.iter().take(10).collect();
    /// ```
    pub fn iter(&self) -> WaveIterator {
        WaveIterator {
            inner: self,
            index: 0.0,
        }
    }
}

impl<'a> IntoIterator for &'a Wave {
    type Item = f32;
    type IntoIter = WaveIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        WaveIterator {
            inner: self,
            index: 0.0,
        }
    }
}

impl Default for Wave {
    fn default() -> Self {
        Self {
            sample_rate: 0.0,
            frequency: 0.0,
            phase: 0.0,
            amplitude: 1.0,
        }
    }
}

impl fmt::Display for Wave {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "<Freq: {}Hz, Ampl: {}, Sampling Freq: {}Hz>",
            self.frequency, self.amplitude, self.sample_rate
        )
    }
}

/// Iterator for Wave structure.
#[derive(Debug, Clone)]
pub struct WaveIterator<'a> {
    inner: &'a Wave,
    index: f32,
}

impl<'a> WaveIterator<'a> {
    /// Post-increment the index of the iterator.
    #[inline]
    fn index_inc(&mut self) -> f32 {
        let idx = self.index;
        // The index cycles after 1s of samples.
        self.index = (self.index % self.inner.sample_rate) + 1.0;

        idx
    }
}

impl<'a> Iterator for WaveIterator<'a> {
    type Item = f32;

    fn next(&mut self) -> Option<Self::Item> {
        let t = self.index_inc() / self.inner.sample_rate;

        Some(self.inner.amplitude * sinf(2.0 * PI * t * self.inner.frequency + self.inner.phase))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec::Vec;

    #[test]
    fn test_wave_default() {
        let wave: Wave = Default::default();

        assert_eq!(
            wave,
            Wave {
                sample_rate: 0.0,
                frequency: 0.0,
                phase: 0.0,
                amplitude: 1.0
            }
        );
    }

    #[test]
    fn test_wave_iteration() {
        let wave = Wave {
            sample_rate: 500.0,
            frequency: 130.0,
            ..Default::default()
        };
        let res: Vec<f32> = wave.iter().take(1001).collect();

        // It must start from the point of origin.
        assert_eq!(res[0], 0.0);

        // The 2s of samples must match exactly.
        assert_eq!(&res[1..501], &res[501..]);
    }

    #[test]
    fn test_wave_phase_shift() {
        let wave = Wave {
            sample_rate: 500.0,
            frequency: 120.0,
            phase: PI / 2.0,
            ..Default::default()
        };
        let res: Vec<f32> = wave.iter().take(5).collect();

        // A cosine wave is a sine wave with a phase shift of Pi / 2.
        assert_eq!(res[0], 1.0);
    }
}