use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rate {
Rate8k,
Rate16k,
}
impl Rate {
pub const fn sample_rate(self) -> usize {
match self {
Self::Rate8k => 8000,
Self::Rate16k => 16000,
}
}
pub const fn window_samples(self) -> usize {
match self {
Self::Rate8k => 32,
Self::Rate16k => 64,
}
}
pub const fn margin_windows(self) -> usize {
75
}
pub const fn margin_samples(self) -> usize {
self.margin_windows() * self.window_samples()
}
pub const fn padding_samples(self) -> usize {
match self {
Self::Rate8k => 2560,
Self::Rate16k => 5120,
}
}
pub const fn align_fft_len(self) -> usize {
match self {
Self::Rate8k => 512,
Self::Rate16k => 1024,
}
}
pub const fn min_input_samples(self) -> usize {
match self {
Self::Rate8k => 2000,
Self::Rate16k => 4000,
}
}
pub const fn frame_len(self) -> usize {
match self {
Self::Rate8k => 256,
Self::Rate16k => 512,
}
}
pub const fn frame_hop(self) -> usize {
match self {
Self::Rate8k => 128,
Self::Rate16k => 256,
}
}
pub const fn num_bands(self) -> usize {
match self {
Self::Rate8k => 42,
Self::Rate16k => 49,
}
}
pub const fn num_power_bins(self) -> usize {
self.frame_len() / 2
}
pub const fn pitch_power_scale(self) -> f64 {
match self {
Self::Rate8k => 2.764_344e-5,
Self::Rate16k => 6.910_853e-6,
}
}
pub const fn loudness_scale(self) -> f64 {
1.866_055e-1
}
}
pub const RATE_8K: Rate = Rate::Rate8k;
pub const RATE_16K: Rate = Rate::Rate16k;
pub const SAMPLE_RATE_HZ: usize = RATE_8K.sample_rate();
pub const WINDOW_SAMPLES: usize = RATE_8K.window_samples();
pub const MARGIN_WINDOWS: usize = RATE_8K.margin_windows();
pub const MARGIN_SAMPLES: usize = RATE_8K.margin_samples();
pub const PADDING_SAMPLES: usize = RATE_8K.padding_samples();
pub const ALIGN_FFT_LEN: usize = RATE_8K.align_fft_len();
pub const MIN_INPUT_SAMPLES: usize = RATE_8K.min_input_samples();
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PesqError {
SignalTooShort { samples: usize },
NoUtterancesFound,
}
impl fmt::Display for PesqError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SignalTooShort { samples } => {
write!(
f,
"input has {samples} samples, which is below the minimum of \
f/4 samples (250 ms) at the operating sample rate"
)
}
Self::NoUtterancesFound => {
write!(f, "no utterance found in the input signals")
}
}
}
}
impl std::error::Error for PesqError {}
#[derive(Debug, Clone, PartialEq)]
pub struct SignalBuffer {
pub samples: Vec<f32>,
pub nominal_len: usize,
pub input_len: usize,
pub rate: Rate,
}
impl SignalBuffer {
pub fn from_pcm(pcm: &[i16]) -> Result<Self, PesqError> {
Self::from_pcm_at(pcm, RATE_8K)
}
pub fn from_pcm_at(pcm: &[i16], rate: Rate) -> Result<Self, PesqError> {
let l = pcm.len();
if l < rate.min_input_samples() {
return Err(PesqError::SignalTooShort { samples: l });
}
let margin = rate.margin_samples();
let nominal_len = l + 2 * margin;
let mut samples = vec![0.0f32; nominal_len + rate.padding_samples()];
for (i, &sample) in pcm.iter().enumerate() {
samples[margin + i] = f32::from(sample);
}
Ok(Self {
samples,
nominal_len,
input_len: l,
rate,
})
}
pub const fn signal_start(&self) -> usize {
self.rate.margin_samples()
}
pub fn signal_end(&self) -> usize {
self.rate.margin_samples() + self.input_len
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct VadData {
pub window_count: usize,
pub energy: Vec<f32>,
pub log_vad: Vec<f32>,
pub threshold: f32,
pub signal_level: f32,
pub noise_level: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Utterance {
pub start_window: usize,
pub end_window: usize,
pub coarse_delay: i32,
pub fine_delay: i32,
pub confidence: f32,
pub split_frame: Option<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameRange {
pub start: usize,
pub stop: usize,
pub skip_start: usize,
pub skip_end: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_input_is_rejected() {
let err = SignalBuffer::from_pcm(&[0i16; MIN_INPUT_SAMPLES - 1]).unwrap_err();
assert_eq!(
err,
PesqError::SignalTooShort {
samples: MIN_INPUT_SAMPLES - 1
}
);
}
#[test]
fn buffer_layout_matches_spec_1_2_step_6() {
let pcm: Vec<i16> = (0..4000).map(|i| (i % 1000) as i16).collect();
let signal = SignalBuffer::from_pcm(&pcm).unwrap();
assert_eq!(signal.input_len, 4000);
assert_eq!(signal.nominal_len, 4000 + 2 * MARGIN_SAMPLES);
assert_eq!(
signal.samples.len(),
4000 + 2 * MARGIN_SAMPLES + PADDING_SAMPLES
);
assert!(signal.samples[..MARGIN_SAMPLES].iter().all(|&s| s == 0.0));
assert!(
signal.samples[signal.signal_end()..]
.iter()
.all(|&s| s == 0.0)
);
assert_eq!(signal.samples[MARGIN_SAMPLES], 0.0);
assert_eq!(signal.samples[signal.signal_end() - 1], 999.0);
}
#[test]
fn errors_display_without_panicking() {
let err = PesqError::SignalTooShort { samples: 100 };
assert!(err.to_string().contains("100"));
assert!(!PesqError::NoUtterancesFound.to_string().is_empty());
}
}