crates/format/audio/src/mel.rs 2.9 KiB 87 lines Raw
1 //! The mel filterbank over one frame.2 //!3 //! A model front end asks for the same band layout that it was trained with:4 //! triangular filters that are equally spaced on the mel scale, from 0 Hz to5 //! Nyquist. The bank is computed instead of stored because the bin count and6 //! the rate belong to the call, not to this crate.7 8 use crate::AudioError;9 use crate::pcm::MAX_RATE;10 use crate::pcm::MIN_RATE;11 12 /// The HTK mel scale: 2595 multiplies the decade of the linear part.13 const MEL_SCALE: f64 = 2595.0;14 15 /// The HTK break at 700 Hz, where the scale becomes logarithmic.16 const MEL_BREAK_HZ: f64 = 700.0;17 18 /// The Nyquist frequency is half the sample rate.19 const NYQUIST_DIVISOR: f64 = 2.0;20 21 /// The mel filterbank over `bins` frequency bins at `rate`, `filters` filters,22 /// 0 Hz to Nyquist, the HTK formula. The output is row-major [filters][bins].23 pub fn filterbank(rate: u32, bins: usize, filters: usize) -> Result<Vec<f32>, AudioError> {24     if !(MIN_RATE..=MAX_RATE).contains(&rate) {25         return Err(AudioError::Rate);26     }27     // A bank of zero filters has no rows, and a single bin cannot span DC and28     // Nyquist. Both are a shape error rather than an empty answer.29     if filters == 0 || bins < 2 {30         return Err(AudioError::Shape);31     }32 33     let nyquist = f64::from(rate) / NYQUIST_DIVISOR;34     let low = hz_to_mel(0.0);35     let high = hz_to_mel(nyquist);36     let step = (high - low) / (filters + 1) as f64;37     let mut edges = Vec::with_capacity(filters + 2);38     for index in 0..filters + 2 {39         edges.push(mel_to_hz(low + step * index as f64));40     }41 42     let mut bank = vec![0.0; filters * bins];43     for (row, points) in edges.windows(3).enumerate() {44         let left = points[0];45         let center = points[1];46         let right = points[2];47         let start = row * bins;48         for (bin, slot) in bank[start..start + bins].iter_mut().enumerate() {49             let hz = bin as f64 * nyquist / (bins - 1) as f64;50             let weight = if hz <= left || hz >= right {51                 0.052             } else if hz <= center {53                 (hz - left) / (center - left)54             } else {55                 (right - hz) / (right - center)56             };57             *slot = weight as f32;58         }59     }60     Ok(bank)61 }62 63 /// One frame of a magnitude spectrum to `filters` mel energies.64 pub fn energies(bank: &[f32], filters: usize, bins: usize, power: &[f32]) -> Vec<f32> {65     let mut out = vec![0.0; filters];66     if bins == 0 {67         return out;68     }69     for (slot, row) in out.iter_mut().zip(bank.chunks_exact(bins)) {70         *slot = row71             .iter()72             .zip(power)73             .map(|(weight, value)| weight * value)74             .sum();75     }76     out77 }78 79 /// The HTK mel of a frequency in Hz.80 fn hz_to_mel(hz: f64) -> f64 {81     MEL_SCALE * (1.0 + hz / MEL_BREAK_HZ).log10()82 }83 84 /// The frequency in Hz of an HTK mel.85 fn mel_to_hz(mel: f64) -> f64 {86     MEL_BREAK_HZ * (10.0_f64.powf(mel / MEL_SCALE) - 1.0)87 }