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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * Copyright (C) Simon Werner, 2022.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

use std::f32;
#[cfg(feature = "png")]
use std::path::Path;

use crate::errors::SonogramError;
use crate::window_fn;
use crate::SpecCompute;

type WindowFn = fn(usize, usize) -> f32;

///
/// A builder struct that will output a spectrogram creator when complete.
/// This builder will require the height and width of the final spectrogram,
/// at a minimum.  However you can load data from a .wav file, or directly
/// from a Vec<i16> memory object.
///
/// # Example
///
/// ```Rust
///   let mut spectrograph = SpecOptionsBuilder::new(512, 128)
///     .set_window_fn(utility::blackman_harris)
///     .load_data_from_file(&std::path::Path::new("test.wav"))?
///     .build();
/// ```
///
pub struct SpecOptionsBuilder {
    // Inputs
    data: Vec<f32>,                    // Our time-domain data (audio samples)
    sample_rate: u32,                  // The sample rate of the wav data
    channel: u16,                      // The audio channel
    scale_factor: Option<f32>,         // How much to scale the sample amplitude by
    do_normalise: bool,                // Normalise the samples to between -1.0...1.0
    downsample_divisor: Option<usize>, // Downsample the samples by a given amount

    // FFT info
    num_bins: usize,     // The number of FFT bins
    step_size: usize,    // How far to step between each window function
    window_fn: WindowFn, // The windowing function to use.
}

impl SpecOptionsBuilder {
    /// Create a new SpecOptionsBuilder.  The final height and width of
    /// the spectrogram must be supplied.  Before the `build` function
    /// can be called a `load_data_from_*` function needs to be called.
    ///
    /// # Arguments
    ///  
    ///  * `num_bins` - Number of bins in the discrete fourier transform (FFT)
    ///
    pub fn new(num_bins: usize) -> Self {
        SpecOptionsBuilder {
            data: vec![],
            sample_rate: 11025,
            channel: 1,
            scale_factor: None,
            do_normalise: false,
            downsample_divisor: None,
            num_bins,
            window_fn: window_fn::rectangular,
            step_size: num_bins,
        }
    }

    /// Load a .wav file to memory and use that file as the input.
    ///
    /// # Arguments
    ///
    ///  * `fname` - The path to the file.
    ///
    #[cfg(feature = "hound")]
    pub fn load_data_from_file(self, fname: &Path) -> Result<Self, SonogramError> {
        let mut reader = hound::WavReader::open(fname)?;

        // Can only handle 16 bit data
        // TODO: Add more data here
        if 16 != reader.spec().bits_per_sample {
            return Err(SonogramError::InvalidCodec);
        }

        if self.channel > reader.spec().channels {
            return Err(SonogramError::InvalidChannel);
        }

        let data: Vec<i16> = {
            let first_sample = self.channel as usize - 1;
            let step_size = reader.spec().channels as usize;
            let mut s = reader.samples();

            // TODO: replace this with .advanced_by in the future
            for _ in 0..first_sample {
                s.next();
            }

            s.step_by(step_size).map(|x| x.unwrap()).collect()
        };
        let sample_rate = reader.spec().sample_rate;

        Ok(self.load_data_from_memory(data, sample_rate))
    }

    /// Load data directly from memory - i16 version.
    ///
    /// # Arguments
    ///
    ///  * `data` - The raw wavform data that will be converted to a spectrogram.
    ///  * `sample_rate` - The sample rate, in Hz, of the data.
    ///
    pub fn load_data_from_memory(mut self, data: Vec<i16>, sample_rate: u32) -> Self {
        self.data = data.iter().map(|&x| x as f32 / (i16::MAX as f32)).collect();
        self.sample_rate = sample_rate;
        self
    }

    /// Load data directly from memory - f32 version.
    ///
    /// # Arguments
    ///
    ///  * `data` - The raw wavform data that will be converted to a spectrogram.
    ///             Samples must be in the range -1.0 to 1.0.
    ///  * `sample_rate` - The sample rate, in Hz, of the data.
    ///
    pub fn load_data_from_memory_f32(mut self, data: Vec<f32>, sample_rate: u32) -> Self {
        self.data = data;
        self.sample_rate = sample_rate;
        self
    }

    ///
    /// Down sample the data by the given divisor.  This is a cheap way of
    /// improving the performance of the FFT.
    ///
    /// # Arguments
    ///
    ///  * `divisor` - How much to reduce the data by.
    ///
    pub fn downsample(mut self, divisor: usize) -> Self {
        self.downsample_divisor = Some(divisor);
        self
    }

    ///
    /// Set the audio channel to use when importing a WAV file.
    /// By default this is 1.
    ///
    pub fn channel(mut self, channel: u16) -> Self {
        self.channel = channel;
        self
    }

    ///
    /// Normalise all the sample values to range from -1.0 to 1.0.
    ///
    pub fn normalise(mut self) -> Self {
        self.do_normalise = true;
        self
    }

    ///
    /// Scale the sample data by the given amount.
    ///
    pub fn scale(mut self, scale_factor: f32) -> Self {
        self.scale_factor = Some(scale_factor);
        self
    }

    /// A window function describes the type of window to use during the
    /// DFT (discrete fourier transform).  See
    /// (here)[https://en.wikipedia.org/wiki/Window_function] for more details.
    ///
    /// # Arguments
    ///
    ///  * `window` - The window function to be used.
    ///
    pub fn set_window_fn(mut self, window_fn: WindowFn) -> Self {
        self.window_fn = window_fn;
        self
    }

    ///
    /// This is the step size (as the number of samples) between each
    /// application of the window function.  A smaller step size may
    /// increase the smoothness of the sample, but take more time.  The default
    /// step size, if not set, is the same as the number of FFT bins.  This
    /// there is no overlap between windows and it most cases will suit your
    /// needs.
    ///
    pub fn set_step_size(mut self, step_size: usize) -> Self {
        self.step_size = step_size;
        self
    }

    ///
    /// The final method to be called.  This will create an instance of
    /// [Spectrograph].
    ///
    pub fn build(mut self) -> Result<SpecCompute, SonogramError> {
        if self.data.is_empty() {
            // SpecOptionsBuilder requires data to be loaded
            return Err(SonogramError::IncompleteData);
        }

        if self.channel == 0 {
            // The channel must be an integer 1 or greater
            return Err(SonogramError::InvalidChannel);
        }

        //
        // Do downsample
        //

        if let Some(divisor) = self.downsample_divisor {
            if divisor == 0 {
                return Err(SonogramError::InvalidDivisor);
            }

            if divisor > 1 {
                for (j, i) in (0..self.data.len() - divisor).step_by(divisor).enumerate() {
                    let sum: f32 = self.data[i..i + divisor].iter().fold(0.0, |mut sum, &val| {
                        sum += val;
                        sum
                    });
                    let avg = sum / (divisor as f32);

                    self.data[j] = avg;
                }
                self.data.resize(self.data.len() / divisor, 0.0);
                self.sample_rate /= divisor as u32;
            }
        }

        //
        // Normalise
        //

        if self.do_normalise {
            let max = self
                .data
                .iter()
                .reduce(|max, x| if x > max { x } else { max })
                .unwrap();

            let norm = 1.0 / max;
            for x in self.data.iter_mut() {
                *x *= norm;
            }
        }

        //
        // Apply the scale factor
        //

        if let Some(scale_factor) = self.scale_factor {
            for x in self.data.iter_mut() {
                *x *= scale_factor;
            }
        }

        Ok(SpecCompute::new(
            self.num_bins,
            self.step_size,
            self.data,
            self.window_fn,
        ))
    }
}