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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
MIT License
Copyright (c) 2023 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//! An easy to use and fast `no_std` library (with `alloc`) to get the frequency
//! spectrum of a digital signal (e.g. audio) using FFT.
//!
//! ## Getting started
//! If you are unsure what to pick, start here. The
//! [`samples_fft_to_spectrum()`] function is the entry into the library. The
//! following configuration works for most cases: take a block of samples, apply
//! a Hann window, and divide the result by the number of samples.
//!
//! ```rust
//! use spectrum_analyzer::scaling::divide_by_N;
//! use spectrum_analyzer::windows::hann_window;
//! use spectrum_analyzer::{FrequencyLimit, samples_fft_to_spectrum};
//!
//! // your samples; the length must be a power of two
//! let samples = vec![0.0; 2048];
//!
//! let windowed = hann_window(&samples);
//! let spectrum = samples_fft_to_spectrum(
//! &windowed,
//! 44100,
//! FrequencyLimit::All,
//! Some(÷_by_N),
//! )
//! .unwrap();
//!
//! // the loudest frequency in the block
//! let (frequency, value) = spectrum.max();
//! ```
//!
//! ### How many samples?
//! More samples mean a finer frequency resolution (`sample_rate / N`), but
//! they also cover a longer time span, so the spectrum reacts more slowly to
//! changes. At 44100 Hz, 2048 samples (~46 ms, ~22 Hz per bin) are a good
//! starting point, 4096 if you need to tell close frequencies apart.
//!
//! ### What next?
//! * [`windows`]: which window function to apply
//! * [`scaling`]: which scaling to apply
//! * [`samples_fft_to_spectrum`]: what the resulting values mean
//! * [`FrequencySpectrum`]: what you can read from the result, e.g.
//! [`FrequencySpectrum::max`] for the loudest frequency,
//! [`FrequencySpectrum::freq_val_closest`] for one specific frequency, or
//! [`FrequencySpectrum::data`] to iterate over all of them
//!
//! ## Examples
//! ### Scaling via dynamic closure
//! ```rust
//! use spectrum_analyzer::{samples_fft_to_spectrum, FrequencyLimit};
//! // get data from audio source, ideally in range `-1.0..=1.0`
//! let samples = vec![0.0, 1.1, 5.5, -5.5];
//! let res = samples_fft_to_spectrum(
//! &samples,
//! 44100,
//! FrequencyLimit::All,
//! // Create your scaling function as closure on the fly as needed.
//! Some(&|val, info| val - info.min),
//! );
//! ```
//! ### Scaling via static function
//! ```rust
//! use spectrum_analyzer::{samples_fft_to_spectrum, FrequencyLimit};
//! use spectrum_analyzer::scaling::divide_by_N;
//! // get data from audio source, ideally in range `-1.0..=1.0`
//! let samples = vec![0.0, 1.1, 5.5, -5.5];
//! let res = samples_fft_to_spectrum(
//! &samples,
//! 44100,
//! FrequencyLimit::All,
//! // Use one of the provided scaling functions. Here, we make the
//! // values independent of the number of samples.
//! Some(÷_by_N),
//! );
//! ```
// now allow a few rules which are denied by the above statement
// --> they are ridiculous and not necessary
extern crate std;
// `vec!` is only used in tests; `alloc` itself is used throughout.
extern crate alloc;
pub use crate;
pub use crateFrequencyLimit;
pub use crateFrequencyLimitError;
pub use crateFrequencySpectrum;
use crateSpectrumAnalyzerError;
use crate;
use crateSpectrumScalingFunction;
use Vec;
// test module for large "integration"-like tests
/// Takes an array of samples (length must be a power of 2, such as 2048),
/// applies an FFT, and returns all frequencies with their magnitude.
///
/// If a scaling function was used, the magnitude is scaled/normalized
/// accordingly.
///
/// ## Meaning of the frequency values
/// Without a scaling function, each value is the plain magnitude of the FFT
/// result. Think of it as "how much of this frequency is in the samples",
/// but not in absolute units:
///
/// * The values grow with the number of samples: twice the samples, twice
/// the value.
/// * A window function (e.g. Hann) shrinks all values by a constant factor,
/// its coherent gain (see [`windows`]).
/// * A frequency that falls between two bins reads a bit lower than one that
/// sits exactly on a bin.
///
/// To compare spectra of different lengths, use [`scaling::divide_by_N`].
/// For the actual amplitude of a sine wave, see the details below.
///
/// ### Details
/// Each value is `sqrt(re*re + im*im)` of the corresponding FFT result,
/// optionally scaled, and relates to the input as follows:
///
/// * A sine wave with amplitude `A` on a bin frequency shows up as
/// `A * N / 2`, `N` being the number of samples. The DC (0 Hz) and Nyquist
/// bins show `A * N` instead, because they have no mirror bin.
/// * A window multiplies each sample by its coefficient before the FFT. The
/// average coefficient is the coherent gain, e.g. `0.5` for Hann, and every
/// value in the spectrum shrinks by that factor.
/// * A frequency between two bins leaks into its neighbors, so its peak reads
/// lower: up to `36%` lower without a window and `15%` with a Hann window.
///
/// So to get the amplitude of a sine wave from a one-sided spectrum: divide by
/// N and multiply by 2, because the FFT splits the sine wave's amplitude
/// between its positive- and negative-frequency bins. Do not multiply by 2 for
/// the DC and Nyquist bins, which have no separate mirror bin. Finally, divide
/// by the window's coherent gain. This gives the amplitude of the individual
/// sine wave components that make up the input signal.
///
/// ## Parameters
/// * `samples` Raw audio samples, normalized to `[-1.0; 1.0]`, which is what
/// audio APIs typically deliver. Other scales work too, as the FFT is
/// linear and the values simply scale with the input, but the normalized
/// range keeps the magnitudes small: very large samples can push a
/// magnitude out of the range of [`f32`].
/// You should apply a window function (like Hann) on the data first.
/// The final frequency resolution (spacing between two bins) is
/// `sample_rate / N`, e.g. `44100/16384 == 2.69Hz`, i.e. more samples =>
/// better accuracy/frequency resolution. The amount of samples must
/// be a power of 2. If you don't have enough data, provide zeroes.
/// * `sampling_rate` The used sampling_rate in Hertz, e.g. `44100`. It must
/// not be zero, as every frequency of the spectrum derives from it.
/// * `frequency_limit` The [`FrequencyLimit`].
/// * `scaling_fn` See [`SpectrumScalingFunction`] for details.
///
/// ## Panics
/// Everything this function can check about its input is reported as an
/// error. What is left is the magnitude of a frequency leaving the range of
/// [`f32`], which needs samples far outside the range described above: with
/// normalized samples, a magnitude never exceeds the number of samples.
///
/// ## Examples
/// ### Scaling via dynamic closure
/// ```rust
/// use spectrum_analyzer::{samples_fft_to_spectrum, FrequencyLimit};
/// // get data from audio source, ideally in range `-1.0..=1.0`
/// let samples = vec![0.0, 1.1, 5.5, -5.5];
/// let res = samples_fft_to_spectrum(
/// &samples,
/// 44100,
/// FrequencyLimit::All,
/// // Create your scaling function as closure on the fly as needed.
/// Some(&|val, info| val - info.min),
/// );
/// ```
/// ### Scaling via static function
/// ```rust
/// use spectrum_analyzer::{samples_fft_to_spectrum, FrequencyLimit};
/// use spectrum_analyzer::scaling::divide_by_N;
/// // get data from audio source, ideally in range `-1.0..=1.0`
/// let samples = vec![0.0, 1.1, 5.5, -5.5];
/// let res = samples_fft_to_spectrum(
/// &samples,
/// 44100,
/// FrequencyLimit::All,
/// // Use one of the provided scaling functions. Here, we make the
/// // values independent of the number of samples.
/// Some(÷_by_N),
/// );
/// Transforms the FFT result into a [`FrequencySpectrum`] by calculating the
/// corresponding frequency of each FFT result (frequency bin) and optionally
/// scales each value.
///
/// ## Parameters
/// * `samples_len` Number of input samples.
/// * `fft_result` FFT result, i.e. frequency bins.
/// * `sampling_rate` Sampling rate of the input samples, e.g. `44100 [Hz]`.
/// * `frequency_limit` Possibly the bounds of [`FrequencyLimit`] the caller is
/// interested in.
/// * `scaling_fn` Optional scaling function to modify each frequency value
/// (FFT result). See [`SpectrumScalingFunction`] for details.
/// Calculate the frequency resolution of the FFT. It is determined by the
/// sampling rate in Hertz and N, the number of samples given into the FFT.
///
/// With the frequency resolution, we can determine the corresponding frequency
/// of each index (frequency bin) in the FFT result buffer.
///
/// ## Parameters
/// * `samples_len` Number of samples put into the FFT
/// * `sampling_rate` sampling_rate, e.g. `44100 [Hz]`
///
/// ## Return value
/// Frequency resolution in Hertz.
///
/// ## More info
/// * <https://www.researchgate.net/post/How-can-I-define-the-frequency-resolution-in-FFT-And-what-is-the-difference-on-interpreting-the-results-between-high-and-low-frequency-resolution>
/// * <https://stackoverflow.com/questions/4364823/>
/// Maps a [`Complex32`] to its magnitude as `f32`. This is done by calculating
/// `sqrt(re*re + im*im)`. This is required to convert the complex FFT results
/// back to real values.
///
/// ## Parameters
/// * `val` A single value from the FFT output buffer of type [`Complex32`].
///
/// ## Panics
/// If the magnitude leaves the range of [`f32`], which needs samples far
/// outside the range this library expects.