lib_jsl_dsp/discrete/spectral/
stft.rs1use super::welch::SpectralScaling;
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_ffts::RealFft;
8use ndarray::Array2;
9use num_complex::Complex;
10
11pub fn stft(x: &[f64], window: &[f64], hop: usize) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
15 let m = window.len();
16 if m == 0 || hop == 0 || hop > m {
17 return Err(ErrorsJSL::InvalidInputRange("Need a non-empty window and 0 < hop <= window length."));
18 }
19 if x.len() < m {
20 return Err(ErrorsJSL::InvalidInputRange("The signal is shorter than one frame."));
21 }
22 let frames = (x.len() - m) / hop + 1;
23 let mut fft = RealFft::new(m)?;
24 let mut out = Array2::zeros((frames, fft.spectrum_len()));
25 let mut frame = vec![0.0; m];
26 for t in 0..frames {
27 frame.iter_mut().zip(&x[t * hop..t * hop + m]).zip(window).for_each(|((f, v), w)| *f = v * w);
28 let spectrum = fft.forward(&frame)?;
29 out.row_mut(t).iter_mut().zip(spectrum).for_each(|(o, s)| *o = s);
30 }
31 Ok(out)
32}
33
34pub fn istft(frames: &Array2<Complex<f64>>, window: &[f64], hop: usize) -> Result<Vec<f64>, ErrorsJSL> {
38 let m = window.len();
39 if m == 0 || hop == 0 || frames.ncols() != m / 2 + 1 {
40 return Err(ErrorsJSL::InvalidInputRange("The frames do not match the window."));
41 }
42 let count = frames.nrows();
43 let length = if count == 0 { 0 } else { (count - 1) * hop + m };
44 let mut fft = RealFft::new(m)?;
45 let mut x = vec![0.0; length];
46 let mut weight = vec![0.0; length];
47 for t in 0..count {
48 let frame = fft.inverse(&frames.row(t).to_vec())?;
49 for i in 0..m {
50 x[t * hop + i] += window[i] * frame[i];
51 weight[t * hop + i] += window[i] * window[i];
52 }
53 }
54 x.iter_mut().zip(&weight).for_each(|(v, w)| if *w > 1e-12 { *v /= w } else { *v = 0.0 });
55 Ok(x)
56}
57
58#[derive(Debug, Clone)]
61pub struct Spectrogram {
62 pub power: Array2<f64>,
64 pub times: Vec<f64>,
66 pub frequencies: Vec<f64>,
67}
68
69pub fn spectrogram(x: &[f64], fs: f64, window: &[f64], hop: usize, scaling: SpectralScaling) -> Result<Spectrogram, ErrorsJSL> {
72 let s = stft(x, window, hop)?;
73 let m = window.len();
74 let scale = match scaling {
75 SpectralScaling::Density => 1.0 / (fs * window.iter().map(|w| w * w).sum::<f64>()),
76 SpectralScaling::Spectrum => 1.0 / window.iter().sum::<f64>().powi(2),
77 };
78 let bins = s.ncols();
79 let last_doubled = if m.is_multiple_of(2) { bins - 1 } else { bins };
80 let power = Array2::from_shape_fn(s.dim(), |(t, k)| s[[t, k]].norm_sqr() * scale * if k > 0 && k < last_doubled { 2.0 } else { 1.0 });
81 let times = (0..s.nrows()).map(|t| (t * hop) as f64 / fs + (m as f64 / 2.0) / fs).collect();
82 let frequencies = (0..bins).map(|k| k as f64 * fs / m as f64).collect();
83 Ok(Spectrogram { power, times, frequencies })
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89 use crate::discrete::windows::{WindowType, generate_window};
90 use std::f64::consts::TAU;
91
92 #[test]
93 fn istft_reconstructs_the_signal() {
94 let x: Vec<f64> = (0..2000).map(|i| (0.013 * i as f64).sin() + 0.3 * (0.21 * i as f64).cos() + ((i * 7) % 11) as f64 * 0.01).collect();
95 for (m, hop, kind) in [(256, 64, WindowType::Hann), (255, 100, WindowType::Hann), (64, 64, WindowType::Boxcar)] {
98 let w = generate_window(kind, m, false);
99 let s = stft(&x, &w, hop).unwrap();
100 let y = istft(&s, &w, hop).unwrap();
101 let worst = (m..y.len() - m).map(|i| (y[i] - x[i]).abs()).fold(0.0, f64::max);
103 assert!(worst < 1e-12, "m={m} hop={hop}: {worst}");
104 }
105 }
106
107 #[test]
108 fn spectrogram_tracks_a_linear_chirp() {
109 let fs = 8000.0;
110 let n = 16000;
111 let x: Vec<f64> = (0..n).map(|i| { let t = i as f64 / fs; (TAU * (500.0 * t + 500.0 * t * t)).cos() }).collect();
113 let w = generate_window(WindowType::Hann, 512, false);
114 let sg = spectrogram(&x, fs, &w, 128, SpectralScaling::Spectrum).unwrap();
115 for (t, &time) in sg.times.iter().enumerate().step_by(10) {
116 let row = sg.power.row(t);
117 let peak = (0..row.len()).max_by(|&i, &j| row[i].total_cmp(&row[j])).unwrap();
118 let expected = 500.0 + 1000.0 * time;
119 assert!((sg.frequencies[peak] - expected).abs() < 2.0 * fs / 512.0, "t={time}: {} vs {expected}", sg.frequencies[peak]);
120 }
121 assert!(stft(&x, &w, 0).is_err() && stft(&x[..10], &w, 1).is_err());
122 }
123}