mecomp_analysis/
utils.rs

1use log::warn;
2use ndarray::{Array, Array1, Array2, arr1, s};
3use rustfft::FftPlanner;
4use rustfft::num_complex::Complex;
5use std::f32::consts::PI;
6
7use crate::Feature;
8
9#[must_use]
10#[inline]
11pub fn reflect_pad(array: &[f32], pad: usize) -> Vec<f32> {
12    debug_assert!(pad < array.len(), "Padding is too large");
13    let prefix = array[1..=pad].iter().rev().copied().collect::<Vec<f32>>();
14    let suffix = array[(array.len() - 2) - pad + 1..array.len() - 1]
15        .iter()
16        .rev()
17        .copied()
18        .collect::<Vec<f32>>();
19    let mut output = Vec::with_capacity(prefix.len() + array.len() + suffix.len());
20
21    output.extend(prefix);
22    output.extend(array);
23    output.extend(suffix);
24    output
25}
26
27#[must_use]
28#[allow(clippy::missing_inline_in_public_items)]
29pub fn stft(signal: &[f32], window_length: usize, hop_length: usize) -> Array2<f64> {
30    debug_assert!(
31        window_length.is_multiple_of(2),
32        "Window length must be even"
33    );
34    debug_assert!(window_length < signal.len(), "Signal is too short");
35    debug_assert!(hop_length < window_length, "Hop length is too large");
36    let half_window_length = window_length / 2;
37    // Take advantage of row-major order to have contiguous window for the
38    // `assign`, reversing the axes to have the expected shape at the end only.
39    let mut stft = Array2::zeros((signal.len().div_ceil(hop_length), half_window_length + 1));
40    let signal = reflect_pad(signal, half_window_length);
41
42    // Periodic, so window_size + 1
43    let mut hann_window = Array::zeros(window_length + 1);
44    #[allow(clippy::cast_precision_loss)]
45    for n in 0..window_length {
46        hann_window[[n]] =
47            0.5f32.mul_add(-f32::cos(2. * n as f32 * PI / (window_length as f32)), 0.5);
48    }
49    hann_window = hann_window.slice_move(s![0..window_length]);
50    let mut planner = FftPlanner::new();
51    let fft = planner.plan_fft_forward(window_length);
52
53    for (window, mut stft_col) in signal
54        .windows(window_length)
55        .step_by(hop_length)
56        .zip(stft.rows_mut())
57    {
58        let mut signal = (arr1(window) * &hann_window).mapv(|x| Complex::new(x, 0.));
59        if let Some(s) = signal.as_slice_mut() {
60            fft.process(s);
61        } else {
62            warn!("non-contiguous slice found for stft; expect slow performances.");
63            fft.process(&mut signal.to_vec());
64        }
65
66        stft_col.assign(
67            &signal
68                .slice(s![..=half_window_length])
69                .mapv(|x| f64::from(x.re.hypot(x.im))),
70        );
71    }
72    stft.permuted_axes((1, 0))
73}
74
75#[allow(clippy::cast_precision_loss)]
76pub(crate) fn mean<T: Clone + Into<f32>>(input: &[T]) -> f32 {
77    if input.is_empty() {
78        return 0.;
79    }
80    input.iter().map(|x| x.clone().into()).sum::<f32>() / input.len() as f32
81}
82
83pub(crate) trait Normalize {
84    const MAX_VALUE: Feature;
85    const MIN_VALUE: Feature;
86
87    fn normalize(&self, value: Feature) -> Feature {
88        2. * (value - Self::MIN_VALUE) / (Self::MAX_VALUE - Self::MIN_VALUE) - 1.
89    }
90}
91
92// Essentia algorithm
93// https://github.com/MTG/essentia/blob/master/src/algorithms/temporal/zerocrossingrate.cpp
94pub(crate) fn number_crossings(input: &[f32]) -> u32 {
95    if input.is_empty() {
96        return 0;
97    }
98
99    let mut crossings = 0;
100
101    let mut was_positive = input[0] > 0.;
102
103    for &sample in input {
104        let is_positive = sample > 0.;
105        if was_positive != is_positive {
106            crossings += 1;
107            was_positive = is_positive;
108        }
109    }
110
111    crossings
112}
113
114/// Only works for input of size 256 (or at least of size a multiple
115/// of 8), with values belonging to [0; 2^65].
116///
117/// This finely optimized geometric mean courtesy of
118/// Jacques-Henri Jourdan (<https://jhjourdan.mketjh.fr/>)
119#[must_use]
120#[allow(clippy::missing_inline_in_public_items)]
121pub fn geometric_mean(input: &[f32]) -> f32 {
122    debug_assert_eq!(input.len() % 8, 0, "Input size must be a multiple of 8");
123    if input.is_empty() {
124        return 0.;
125    }
126
127    let mut exponents: i32 = 0;
128    let mut mantissas: f64 = 1.;
129    for ch in input.chunks_exact(8) {
130        let mut m = (f64::from(ch[0]) * f64::from(ch[1])) * (f64::from(ch[2]) * f64::from(ch[3]));
131        m *= 3.273_390_607_896_142e150; // 2^500 : avoid underflows and denormals
132        m *= (f64::from(ch[4]) * f64::from(ch[5])) * (f64::from(ch[6]) * f64::from(ch[7]));
133        if m == 0. {
134            return 0.;
135        }
136        exponents += (m.to_bits() >> 52) as i32;
137        mantissas *= f64::from_bits((m.to_bits() & 0x000F_FFFF_FFFF_FFFF) | 0x3FF0_0000_0000_0000);
138    }
139
140    #[allow(clippy::cast_possible_truncation)]
141    let n = input.len() as u32;
142    #[allow(clippy::cast_possible_truncation)]
143    let result = (((mantissas.log2() + f64::from(exponents)) / f64::from(n) - (1023. + 500.) / 8.)
144        .exp2()) as f32;
145    result
146}
147
148pub(crate) fn hz_to_octs_inplace(
149    frequencies: &mut Array1<f64>,
150    tuning: f64,
151    bins_per_octave: u32,
152) -> &mut Array1<f64> {
153    let a440 = 440.0 * (tuning / f64::from(bins_per_octave)).exp2();
154
155    *frequencies /= a440 / 16.;
156    frequencies.mapv_inplace(f64::log2);
157    frequencies
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use crate::decoder::{Decoder as DecoderTrait, MecompDecoder as Decoder};
164    use ndarray::{Array, Array2, arr1};
165    use ndarray_npy::ReadNpyExt;
166    use std::{fs::File, path::Path};
167
168    #[test]
169    fn test_mean() {
170        let numbers = vec![0.0, 1.0, 2.0, 3.0, 4.0];
171        let mean = mean(&numbers);
172        assert!(f32::EPSILON > (2.0 - mean).abs(), "{mean} !~= 2.0");
173    }
174
175    #[test]
176    #[allow(clippy::too_many_lines)]
177    fn test_geometric_mean() {
178        let numbers = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0];
179        let mean = geometric_mean(&numbers);
180        assert!(f32::EPSILON > (0.0 - mean).abs(), "{mean} !~= 0.0");
181
182        let numbers = vec![4.0, 2.0, 1.0, 4.0, 2.0, 1.0, 2.0, 2.0];
183        let mean = geometric_mean(&numbers);
184        assert!(0.0001 > (2.0 - mean).abs(), "{mean} !~= 2.0");
185
186        // never going to happen, but just in case
187        let numbers = vec![256., 4.0, 2.0, 1.0, 4.0, 2.0, 1.0, 2.0];
188        let mean = geometric_mean(&numbers);
189        assert!(
190            0.0001 > (3.668_016_2 - mean).abs(),
191            "{mean} !~= {}",
192            3.668_016_172_818_685
193        );
194
195        let subnormal = vec![4.0, 2.0, 1.0, 4.0, 2.0, 1.0, 2.0, 1.0e-40_f32];
196        let mean = geometric_mean(&subnormal);
197        assert!(
198            0.0001 > (1.834_008e-5 - mean).abs(),
199            "{} !~= {}",
200            mean,
201            1.834_008_086_409_341_7e-5
202        );
203
204        let maximum = vec![2_f32.powi(65); 256];
205        let mean = geometric_mean(&maximum);
206        assert!(
207            0.0001 > (2_f32.powi(65) - mean.abs()),
208            "{} !~= {}",
209            mean,
210            2_f32.powi(65)
211        );
212
213        let input = [
214            0.024_454_033,
215            0.088_096_89,
216            0.445_543_62,
217            0.827_535_03,
218            0.158_220_93,
219            1.444_224_5,
220            3.697_138_5,
221            3.678_955_6,
222            1.598_157_2,
223            1.017_271_8,
224            1.443_609_6,
225            3.145_710_2,
226            2.764_110_8,
227            0.839_523_5,
228            0.248_968_29,
229            0.070_631_73,
230            0.355_419_4,
231            0.352_001_4,
232            0.797_365_1,
233            0.661_970_8,
234            0.784_104,
235            0.876_795_7,
236            0.287_382_66,
237            0.048_841_28,
238            0.322_706_5,
239            0.334_907_47,
240            0.185_888_75,
241            0.135_449_42,
242            0.140_177_46,
243            0.111_815_82,
244            0.152_631_61,
245            0.221_993_12,
246            0.056_798_387,
247            0.083_892_57,
248            0.070_009_65,
249            0.202_903_29,
250            0.370_717_38,
251            0.231_543_18,
252            0.023_348_59,
253            0.013_220_183,
254            0.035_887_096,
255            0.029_505_49,
256            0.090_338_57,
257            0.176_795_04,
258            0.081_421_87,
259            0.003_326_808_6,
260            0.012_269_007,
261            0.016_257_336,
262            0.027_027_424,
263            0.017_253_408,
264            0.017_230_038,
265            0.021_678_915,
266            0.018_645_158,
267            0.005_417_136,
268            0.006_650_174_5,
269            0.020_159_671,
270            0.026_623_515,
271            0.005_166_793_7,
272            0.016_880_387,
273            0.009_935_223_5,
274            0.011_079_361,
275            0.013_200_151,
276            0.005_320_572_3,
277            0.005_070_289_6,
278            0.008_130_498,
279            0.009_006_041,
280            0.003_602_499_8,
281            0.006_440_387_6,
282            0.004_656_151,
283            0.002_513_185_8,
284            0.003_084_559_7,
285            0.008_722_531,
286            0.017_871_628,
287            0.022_656_294,
288            0.017_539_924,
289            0.009_439_588_5,
290            0.003_085_72,
291            0.001_358_616_6,
292            0.002_746_787_2,
293            0.005_413_010_3,
294            0.004_140_312,
295            0.000_143_587_14,
296            0.001_371_840_8,
297            0.004_472_961,
298            0.003_769_122,
299            0.003_259_129_6,
300            0.003_637_24,
301            0.002_445_332_2,
302            0.000_590_368_93,
303            0.000_647_898_65,
304            0.001_745_297,
305            0.000_867_165_5,
306            0.002_156_236_2,
307            0.001_075_606_8,
308            0.002_009_199_5,
309            0.001_537_388_5,
310            0.000_984_620_4,
311            0.000_292_002_49,
312            0.000_921_162_4,
313            0.000_535_111_8,
314            0.001_491_276_5,
315            0.002_065_137_5,
316            0.000_661_122_26,
317            0.000_850_054_26,
318            0.001_900_590_1,
319            0.000_639_584_5,
320            0.002_262_803,
321            0.003_094_018_2,
322            0.002_089_161_7,
323            0.001_215_059,
324            0.001_311_408_4,
325            0.000_470_959,
326            0.000_665_480_7,
327            0.001_430_32,
328            0.001_791_889_3,
329            0.000_863_200_75,
330            0.000_560_445_5,
331            0.000_828_417_54,
332            0.000_669_453_9,
333            0.000_822_765,
334            0.000_616_575_8,
335            0.001_189_319,
336            0.000_730_024_5,
337            0.000_623_748_1,
338            0.001_207_644_4,
339            0.001_474_674_2,
340            0.002_033_916,
341            0.001_500_169_9,
342            0.000_520_51,
343            0.000_445_643_32,
344            0.000_558_462_75,
345            0.000_897_786_64,
346            0.000_805_247_05,
347            0.000_726_536_44,
348            0.000_673_052_6,
349            0.000_994_064_5,
350            0.001_109_393_7,
351            0.001_295_099_7,
352            0.000_982_682_2,
353            0.000_876_651_8,
354            0.001_654_928_7,
355            0.000_929_064_35,
356            0.000_291_306_23,
357            0.000_250_490_47,
358            0.000_228_488_02,
359            0.000_269_673_15,
360            0.000_237_375_09,
361            0.000_969_406_1,
362            0.001_063_811_8,
363            0.000_793_428_86,
364            0.000_590_835_06,
365            0.000_476_389_9,
366            0.000_951_664_1,
367            0.000_692_231_46,
368            0.000_557_113_7,
369            0.000_851_769_7,
370            0.001_071_027_7,
371            0.000_610_243_9,
372            0.000_746_876_23,
373            0.000_849_898_44,
374            0.000_495_806_2,
375            0.000_526_994,
376            0.000_215_249_22,
377            0.000_096_684_314,
378            0.000_654_554_4,
379            0.001_220_697_3,
380            0.001_210_358_3,
381            0.000_920_454_33,
382            0.000_924_843_5,
383            0.000_812_128_4,
384            0.000_239_532_56,
385            0.000_931_822_4,
386            0.001_043_966_3,
387            0.000_483_734_15,
388            0.000_298_952_22,
389            0.000_484_425_4,
390            0.000_666_829_5,
391            0.000_998_398_5,
392            0.000_860_489_7,
393            0.000_183_153_23,
394            0.000_309_180_8,
395            0.000_542_646_2,
396            0.001_040_391_5,
397            0.000_755_456_6,
398            0.000_284_601_7,
399            0.000_600_979_3,
400            0.000_765_056_9,
401            0.000_562_810_46,
402            0.000_346_616_55,
403            0.000_236_224_32,
404            0.000_598_710_6,
405            0.000_295_684_27,
406            0.000_386_978_06,
407            0.000_584_258,
408            0.000_567_097_6,
409            0.000_613_644_4,
410            0.000_564_549_3,
411            0.000_235_384_52,
412            0.000_285_574_6,
413            0.000_385_352_93,
414            0.000_431_935_65,
415            0.000_731_246_5,
416            0.000_603_072_8,
417            0.001_033_130_8,
418            0.001_195_216_2,
419            0.000_824_500_7,
420            0.000_422_183_63,
421            0.000_821_760_16,
422            0.001_132_246,
423            0.000_891_406_73,
424            0.000_635_158_8,
425            0.000_372_681_56,
426            0.000_230_35,
427            0.000_628_649_3,
428            0.000_806_159_9,
429            0.000_661_622_15,
430            0.000_227_139_01,
431            0.000_214_694_96,
432            0.000_665_457_7,
433            0.000_513_901,
434            0.000_391_766_78,
435            0.001_079_094_7,
436            0.000_735_363_7,
437            0.000_171_665_73,
438            0.000_439_648_87,
439            0.000_295_145_3,
440            0.000_177_047_08,
441            0.000_182_958_97,
442            0.000_926_536_04,
443            0.000_832_408_3,
444            0.000_804_168_4,
445            0.001_131_809_3,
446            0.001_187_149_6,
447            0.000_806_948_8,
448            0.000_628_624_75,
449            0.000_591_386_1,
450            0.000_472_182_3,
451            0.000_163_652_31,
452            0.000_177_876_57,
453            0.000_425_363_75,
454            0.000_573_699_3,
455            0.000_434_679_24,
456            0.000_090_282_94,
457            0.000_172_573_55,
458            0.000_501_957_4,
459            0.000_614_716_8,
460            0.000_216_780_5,
461            0.000_148_974_3,
462            0.000_055_081_473,
463            0.000_296_264_13,
464            0.000_378_055_67,
465            0.000_147_361_96,
466            0.000_262_513_64,
467            0.000_162_118_42,
468            0.000_185_347_7,
469            0.000_138_735_4,
470        ];
471        assert!(
472            0.000_000_01 > (0.002_575_059_7 - geometric_mean(&input)).abs(),
473            "{} !~= 0.0025750597",
474            geometric_mean(&input)
475        );
476    }
477
478    #[test]
479    fn test_hz_to_octs_inplace() {
480        let mut frequencies = arr1(&[32., 64., 128., 256.]);
481        let expected = arr1(&[0.168_640_29, 1.168_640_29, 2.168_640_29, 3.168_640_29]);
482
483        hz_to_octs_inplace(&mut frequencies, 0.5, 10)
484            .iter()
485            .zip(expected.iter())
486            .for_each(|(x, y)| assert!(0.0001 > (x - y).abs(), "{x} !~= {y}"));
487    }
488
489    #[test]
490    fn test_compute_stft() {
491        let file = File::open("data/librosa-stft.npy").unwrap();
492        let expected_stft = Array2::<f32>::read_npy(file).unwrap().mapv(f64::from);
493
494        let song = Decoder::new()
495            .unwrap()
496            .decode(Path::new("data/piano.flac"))
497            .unwrap();
498
499        let stft = stft(&song.samples, 2048, 512);
500
501        assert!(!stft.is_empty() && !expected_stft.is_empty(), "Empty STFT");
502        for (expected, actual) in expected_stft.iter().zip(stft.iter()) {
503            // NOTE: can't use relative error here due to division by zero
504            assert!(
505                0.0001 > (expected - actual).abs(),
506                "{expected} !~= {actual}"
507            );
508        }
509    }
510
511    #[test]
512    fn test_reflect_pad() {
513        let array = Array::range(0., 100_000., 1.);
514
515        let output = reflect_pad(array.as_slice().unwrap(), 3);
516        assert_eq!(&output[..4], &[3.0, 2.0, 1.0, 0.]);
517        assert_eq!(&output[3..100_003], array.to_vec());
518        assert_eq!(&output[100_003..100_006], &[99998.0, 99997.0, 99996.0]);
519    }
520}