Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This book is the learning guide of the Rust crate audio_samples: fourteen chapters on speech and audio signal processing, from sampling and quantisation to pitch, MFCCs, dynamics processing and perceptual coding.

Each chapter has the same structure:

  1. Concept: the theory, with every symbol and its unit defined.
  2. With the library: the audio_samples calls that compute it.
  3. How it works: the same result derived from first principles in a few lines of plain code and checked against the library.
  4. Ask the library to explain: the educational feature’s explanations of a configuration (formulas, derived numbers, warnings).
  5. Exercises with worked answers, common pitfalls, references and links to the API documentation.

How the book relates to the crate

The chapters are the Markdown files in documentation/guide/ of the repository. The same files are compiled into the API documentation as the audio_samples::guide module, where every code block is a doctest: the numbers stated in the text are asserted by the code next to them, and the test suite fails if the library stops producing them.

The figures are computed by the library as well. A small program in book/figures/ makes the same calls with the same parameters as the chapter, asserts the same numbers, and draws the result. A figure therefore shows the values the chapter’s code computes, not an independent illustration.

Code blocks hide their setup lines; the eye icon on a block shows them. Links on item names (for example resample) go to the API documentation on docs.rs.

Running the code

Every chapter has a lab, examples/tutorial_NN_<topic>.rs, which runs the chapter’s computations and prints the results:

cargo run --release --example tutorial_01_sampling_aliasing --features educational,full_no_plotting

To use the snippets in a crate of your own, see Guide index and setup for the dependencies and their versions. Lecturers considering the crate for a course should read For instructors.

Prerequisites

The chapters assume calculus, complex numbers and basic linear algebra. They do not assume prior signal processing: chapter 1 starts from sampling, and later chapters refer back to earlier ones where they build on them. Some Rust is needed to read the code; the API calls are explained where they are used.

01. Sampling and aliasing

A digital audio signal is a sequence of samples taken at a fixed rate: 8 kHz for narrow-band telephone speech, 16 kHz for wide-band speech and most speech recognisers, 44.1 or 48 kHz for music. The sample rate determines which frequencies the samples can represent. Frequencies above that limit are not removed by sampling: they appear in the sampled signal as lower frequencies. This chapter shows where they appear, why, and how to prevent it.

Concept

Sampling reads an analogue signal every seconds:

where is the analogue signal (amplitude in units of full scale) at time in seconds, is the integer sample index, is the sampling period in seconds and is the sample rate in Hz (samples per second).

Why aliasing happens. For any integer ,

because the extra phase is a whole number of turns. Here is a tone frequency in Hz. Since is even, gives the same samples too, so the tones , and are indistinguishable once sampled (up to a reversal of phase for the family: a sine comes back with its sign flipped).

Nyquist frequency and the sampling theorem. The highest frequency that is represented unambiguously is the Nyquist frequency

in Hz. If contains no energy at or above , it is recovered exactly from its samples by sinc interpolation (Whittaker-Shannon):

where is a dimensionless time offset in sampling periods.

Folding formula. A tone at Hz appears after sampling at

where is the alias frequency in Hz (always between 0 and ) and is the nearest integer multiple of the sample rate. Equivalently, the frequency axis is folded at , , , , …, which maps every frequency into .

Alias frequency of a tone sampled at 16 kHz, from topics::aliasing every 250 Hz. The frequency axis folds at multiples of the 8 kHz Nyquist frequency; an 11 kHz tone appears at 5 kHz.
Figure 1.1. Alias frequency of a tone sampled at 16 kHz, from topics::aliasing every 250 Hz. The frequency axis folds at multiples of the 8 kHz Nyquist frequency; an 11 kHz tone appears at 5 kHz.

Aliasing occurs in three places:

  • acquisition: an analogue anti-aliasing filter must remove energy above before the converter samples;
  • downsampling: keeping every -th sample is sampling again at , so content between the new and old Nyquist frequencies must be filtered out first;
  • synthesis: a waveform with jumps (a hard square wave) has harmonics at every odd multiple of its fundamental , with amplitudes for peak amplitude . Computing it sample by sample samples those harmonics too, and the ones above fold back as inharmonic tones.

With the library

Generate an 11 kHz tone at 48 kHz, then reduce it to 16 kHz (new Nyquist frequency 8 kHz) in two ways: naively, by keeping every third sample (written by hand below), and with the library’s resampler at each of its three quality tiers. The folding formula predicts Hz.

use audio_samples::educational::topics;
use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{AudioSamples, AudioTransforms, nzu, resample, sample_rate, sine_wave};
use std::time::Duration;

// The library's folding calculation.
let doc = topics::aliasing(11_000.0, 16_000.0);
assert_eq!(doc.quantity("Alias frequency").unwrap().value, 5_000.0);

// 250 ms of an 11 kHz tone, amplitude 0.5, at 48 kHz: 12 000 samples.
let hi = sine_wave::<f64>(11_000.0, Duration::from_millis(250), sample_rate!(48000), 0.5);

// Naive decimation: keep every third sample. 4000 samples at 16 kHz.
let naive: Vec<f64> = hi.as_slice().unwrap().iter().step_by(3).copied().collect();
let naive = AudioSamples::new_mono(ndarray::Array1::from(naive), sample_rate!(16000)).unwrap();

// A 4000-point DFT of 4000 samples at 16 kHz has 4 Hz bins.
let spec = naive.rfft(nzu!(4000)).unwrap();
let row = spec.row(0);
let peak = (0..row.len()).max_by(|&a, &b| row[a].total_cmp(&row[b])).unwrap();
assert_eq!(peak as f64 * 4.0, 5_000.0); // the alias, exactly where predicted
// A bin-centred sine of amplitude A gives |X| = A N / 2 = 1000: full strength.
assert!((row[peak] - 1000.0).abs() < 1e-6);

// Every resampler tier low-pass filters below 8 kHz before it decimates.
// Measure what is left at 5 kHz in the steady state: the middle 100 ms of
// the output (samples 1200..2800) holds exactly 500 periods of 5 kHz, so one
// DFT bin gives its amplitude, compared with the 0.5 the naive decimator
// delivers there.
let db = |v: f64| 20.0 * v.log10();
let amplitude = |x: &[f64], f: f64| {
    let (re, im) = x.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
        let ph = 2.0 * std::f64::consts::PI * f * n as f64 / 16_000.0;
        (re + v * ph.cos(), im - v * ph.sin())
    });
    2.0 * (re * re + im * im).sqrt() / x.len() as f64
};
let mut steady_db = Vec::new();
for q in [ResamplingQuality::Fast, ResamplingQuality::Medium, ResamplingQuality::High] {
    let y = resample(&hi, sample_rate!(16000), q).unwrap();
    assert_eq!(y.samples_per_channel().get(), 4_000);
    steady_db.push(db(amplitude(&y.as_slice().unwrap()[1_200..2_800], 5_000.0) / 0.5));
}
println!("steady-state alias, Fast/Medium/High: {steady_db:.1?} dB");
// Gone: for this 1 : 3 ratio the resampler works block by block in the
// frequency domain and drops everything above the new Nyquist frequency
// instead of folding the filter's stopband back, so what is left is f64
// round-off, more than 180 dB down.
assert!(steady_db.iter().all(|&d| d < -180.0));

// Over the whole 250 ms the residue is larger, and not because of aliasing:
// the tone starts and stops abruptly, and those edges are broadband clicks
// that the filter passes below 8 kHz. For High, the 5 kHz bin of the full
// output is 78.4 dB below the naive alias, and the largest bin anywhere
// (7652 Hz, in the filter's transition band between 0.913 x 8 kHz = 7304 Hz
// and 8 kHz) only 74.5 dB below it.
let high = resample(&hi, sample_rate!(16000), ResamplingQuality::High).unwrap();
let high_spec = high.rfft(nzu!(4000)).unwrap();
let hrow = high_spec.row(0);
let bin_5k_db = db(row[peak] / hrow[1250]);
let top = (0..hrow.len()).max_by(|&a, &b| hrow[a].total_cmp(&hrow[b])).unwrap();
let largest_db = db(row[peak] / hrow[top]);
println!("5 kHz bin {bin_5k_db:.1} dB, largest bin {largest_db:.1} dB at {} Hz", top * 4);
assert!((bin_5k_db - 78.4).abs() < 0.1);
assert_eq!(top * 4, 7_652);
assert!(top * 4 > 7_304 && top * 4 < 8_000);
assert!((largest_db - 74.5).abs() < 0.1);
// The click is visible in the samples: the first 50 output samples reach 0.12,
// while the middle of the output is below 1e-7.
let hs = high.as_slice().unwrap();
let max_abs = |x: &[f64]| x.iter().fold(0.0f64, |m, v| m.max(v.abs()));
assert!((max_abs(&hs[..50]) - 0.12).abs() < 0.005);
assert!(max_abs(&hs[1_200..2_800]) < 1e-7);

The naive version did not remove the tone; it moved it to 5 kHz at full strength, where it is indistinguishable from a genuine 5 kHz component. Every tier of the resampler removes it instead: in the steady state the residue is more than 180 dB down, floating-point round-off, for every tier (for this 1 : 3 ratio the resampler drops everything above the new Nyquist frequency in the frequency domain, so its filter’s stopband does not fold back). Measure over the whole signal and High’s figure drops to 78.4 dB at 5 kHz (74.5 dB for the largest bin, at 7652 Hz): the residue there is the broadband click of a tone switched on and off abruptly, not aliasing. Always measure rejection away from the ends of a test signal, as chapter 07 does.

The same applies when a waveform is synthesised. A naive square wave (square_wave) switches between ; the band-limited version (square_wave_bandlimited) adds only the odd harmonics below . With Hz and kHz, one second holds exactly 700 periods, so every harmonic and every alias falls on an integer-Hz bin of a 16 000-point DFT, and the power that is not at an odd harmonic of 700 Hz can be summed directly:

use audio_samples::utils::generation::{square_wave, square_wave_bandlimited};
use audio_samples::{AudioTransforms, nzu, sample_rate};
use std::time::Duration;

let one_s = Duration::from_secs(1);
let naive = square_wave::<f64>(700.0, one_s, sample_rate!(16000), 1.0);
let clean = square_wave_bandlimited::<f64>(700.0, one_s, sample_rate!(16000), 1.0);
let s_naive = naive.rfft(nzu!(16000)).unwrap().row(0).to_vec(); // 1 Hz bins
let s_clean = clean.rfft(nzu!(16000)).unwrap().row(0).to_vec();

let odd_harmonic = |k: usize| k.is_multiple_of(700) && (k / 700) % 2 == 1;
let stray_db = |s: &[f64]| {
    let total: f64 = s.iter().map(|m| m * m).sum();
    let stray: f64 = s.iter().enumerate()
        .filter(|(k, _)| !odd_harmonic(*k))
        .map(|(_, m)| m * m).sum();
    10.0 * (stray / total).log10()
};
// About 3.3 % of the naive wave's power is aliased (-14.77 dB) ...
assert!((stray_db(&s_naive) + 14.77).abs() < 0.01);
// ... and essentially none of the band-limited wave's.
assert!(stray_db(&s_clean) < -200.0);

// The 13th harmonic (9100 Hz) is the first above 8 kHz: it folds to 6900 Hz,
// close to its ideal level of 1/13 of the fundamental (-22.3 dB).
let rel_db = 20.0 * (s_naive[6900] / s_naive[700]).log10();
assert!((rel_db - 20.0 * (1.0f64 / 13.0).log10()).abs() < 0.3);
assert!(s_clean[6900] / s_clean[700] < 1e-9);
Spectra of a 700 Hz square wave at 16 kHz, relative to the fundamental. The naive wave (top) has aliased harmonics between the true odd harmonics, such as the 13th folded to 6900 Hz and the 21st to 1300 Hz; the band-limited wave (bottom) has only the odd harmonics up to 7700 Hz.
Figure 1.2. Spectra of a 700 Hz square wave at 16 kHz, relative to the fundamental. The naive wave (top) has aliased harmonics between the true odd harmonics, such as the 13th folded to 6900 Hz and the 21st to 1300 Hz; the band-limited wave (bottom) has only the odd harmonics up to 7700 Hz.

How it works

The folding formula is one line of code. Check it against the library over a sweep of frequencies, and check the identity behind it: the samples of an 11 kHz sine at 16 kHz are exactly those of a 5 kHz sine with inverted sign, because .

An 11 kHz sine (blue) sampled at 16 kHz. The samples (dots, from sine_wave) lie exactly on a 5 kHz sine with inverted sign (orange): after sampling the two tones cannot be told apart.
Figure 1.3. An 11 kHz sine (blue) sampled at 16 kHz. The samples (dots, from sine_wave) lie exactly on a 5 kHz sine with inverted sign (orange): after sampling the two tones cannot be told apart.
use audio_samples::educational::topics;
use std::f64::consts::PI;

fn fold(f: f64, fs: f64) -> f64 {
    (f - (f / fs).round() * fs).abs()
}

// Every 250 Hz from 0 to 50 kHz at 16 kHz agrees with the library exactly
// (both are a handful of exact operations on multiples of 250).
for i in 0..=200 {
    let f = 250.0 * f64::from(i);
    let lib = topics::aliasing(f, 16_000.0).quantity("Alias frequency").unwrap().value;
    assert_eq!(fold(f, 16_000.0), lib);
    assert!(lib <= 8_000.0);
}

// Identical samples, sign inverted. Tolerance: sin of arguments up to ~2e4 rad
// in f64 carries ~1e-12 of rounding.
let fs = 16_000.0;
for n in 0..1000 {
    let t = f64::from(n) / fs;
    let a = (2.0 * PI * 11_000.0 * t).sin();
    let b = -(2.0 * PI * 5_000.0 * t).sin();
    assert!((a - b).abs() < 1e-9);
}

The sampling theorem says a band-limited signal can be recovered between its samples. Reconstruct a 1 kHz tone sampled at 8 kHz halfway between two samples with a (truncated) sinc sum:

use std::f64::consts::PI;

let fs = 8_000.0;
let f = 1_000.0;
let x: Vec<f64> = (0..8000).map(|n| (2.0 * PI * f * n as f64 / fs).sin()).collect();
let sinc = |u: f64| if u == 0.0 { 1.0 } else { (PI * u).sin() / (PI * u) };

// Evaluate at t = 4000.5 T, in the middle of the 1 s block.
let u0 = 4000.5;
let estimate: f64 = x.iter().enumerate().map(|(n, &v)| v * sinc(u0 - n as f64)).sum();
let truth = (2.0 * PI * f * u0 / fs).sin();
// The sum is truncated to 8000 terms; the neglected tails decay like 1/(pi u),
// so an error of order 1e-4 is expected.
assert!((estimate - truth).abs() < 1e-3);

Ask the library to explain

topics::sampling and topics::aliasing return an ExplainDoc with the formulas, the numbers for your case, a table of tones that share the same samples, and a warning when a tone is above the Nyquist frequency.

use audio_samples::educational::{WarningLevel, topics};

let s = topics::sampling(16_000.0);
assert_eq!(s.quantity("Nyquist frequency").unwrap().value, 8_000.0);
assert_eq!(s.quantity("Sampling period").unwrap().value, 0.0625); // ms
// 8 kHz is below the 20 kHz limit of hearing: an informational note.
assert!(s.has_warning(WarningLevel::Info));

let a = topics::aliasing(25_000.0, 16_000.0);
assert_eq!(a.quantity("Alias frequency").unwrap().value, 7_000.0);
assert!(a.has_warning(WarningLevel::Caution));
assert!(a.has_warning_containing("will alias to 7000 Hz"));
println!("{a}"); // formulas, symbols, the table of look-alike tones, the warning

Exercises

  1. A telephone line samples at 8 kHz. A 7.5 kHz whistle leaks in before the converter. At what frequency does it appear after sampling?
  2. You halve the rate of a 44.1 kHz recording by keeping every second sample. It contains a 15 kHz tone. Predict its alias frequency, then measure it.
  3. In the naive 700 Hz square wave above, there is energy at 1300 Hz, which is not a harmonic of 700 Hz. Which harmonic folded there?

Answers

use audio_samples::utils::generation::{square_wave, square_wave_bandlimited};
use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate, sine_wave};
use std::time::Duration;

fn fold(f: f64, fs: f64) -> f64 {
    (f - (f / fs).round() * fs).abs()
}

// 1. |7500 - 1 * 8000| = 500 Hz.
assert_eq!(fold(7_500.0, 8_000.0), 500.0);

// 2. New rate 22 050 Hz: |15000 - 22050| = 7050 Hz. Measure: 0.2 s at 44.1 kHz
//    is 8820 samples; keeping every second leaves 4410 samples at 22 050 Hz,
//    so a 4410-point DFT has 5 Hz bins and 7050 Hz is bin 1410.
assert_eq!(fold(15_000.0, 22_050.0), 7_050.0);
let x = sine_wave::<f64>(15_000.0, Duration::from_millis(200), sample_rate!(44100), 1.0);
let dec: Vec<f64> = x.as_slice().unwrap().iter().step_by(2).copied().collect();
assert_eq!(dec.len(), 4410);
let dec = AudioSamples::new_mono(ndarray::Array1::from(dec), sample_rate!(22050)).unwrap();
let mag = dec.rfft(nzu!(4410)).unwrap().row(0).to_vec();
let peak = (0..mag.len()).max_by(|&a, &b| mag[a].total_cmp(&mag[b])).unwrap();
assert_eq!(peak as f64 * 5.0, 7_050.0);

// 3. Search the odd harmonics h whose alias is 1300 Hz: the 21st (14 700 Hz,
//    folded about 16 kHz). The band-limited wave stops at the 11th harmonic
//    (7700 Hz), so it has nothing at 1300 Hz.
let h = (1..200).step_by(2).find(|&h| fold(700.0 * f64::from(h), 16_000.0) == 1_300.0);
assert_eq!(h, Some(21));
let one_s = Duration::from_secs(1);
let naive = square_wave::<f64>(700.0, one_s, sample_rate!(16000), 1.0)
    .rfft(nzu!(16000)).unwrap().row(0).to_vec();
let clean = square_wave_bandlimited::<f64>(700.0, one_s, sample_rate!(16000), 1.0)
    .rfft(nzu!(16000)).unwrap().row(0).to_vec();
assert!(naive[1300] / naive[700] > 1e-3);  // clearly present
assert!(clean[1300] / clean[700] < 1e-9);  // absent

Common pitfalls

  • Keeping every -th sample is not resampling: it aliases. Every ResamplingQuality filters first, but the default, Fast, uses a short filter whose pass band ends at 0.8 times the new Nyquist frequency; use Medium or High when the top of the band matters (chapter 07).
  • square_wave, sawtooth_wave and triangle_wave are naive and alias; use the *_bandlimited versions for test signals.
  • A tone exactly at is ambiguous: a sine sampled there at zero phase is all zeros.
  • An alias may come back with inverted phase (the 11 kHz example above returns as at 5 kHz).
  • rfft returns magnitudes and needs n_fft at least the signal length (chapter 03).

References

  • C. E. Shannon, “Communication in the presence of noise”, Proceedings of the IRE 37(1), 10-21, 1949.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010. Chapter 4 covers sampling, aliasing and reconstruction.

See also

02. Quantisation and dither

Sampling (chapter 01) makes time discrete; quantisation makes amplitude discrete. A 16-bit file can store only 65 536 different values, so every sample is rounded, and the rounding error behaves like added noise. The level of that noise, and whether it is heard as noise or as distortion, determine how many bits a recording needs and how to reduce bit depth without damaging quiet passages such as a fading voice or a reverb tail.

Concept

Uniform quantisation maps a sample on the normalised scale to an integer code and back. This crate uses an asymmetric mapping (see conversions) so that both and are reachable and the integer round trip is exact:

where is the word length in bits, is clamped to and rounds half away from zero. Converting back divides by the same factors. The step size (one least-significant bit, LSB, in units of full scale) is therefore

For : and , a difference of 0.003 %.

Quantisation noise. If the signal is large and varied compared with one step, the rounding error is spread uniformly over one step, , so its power is

in units of full scale squared, where is the quantised value.

Levels in dB. This guide quotes powers in dB re 1, i.e. relative to full scale squared ( of a mean square, so 0 dB is the power of a full-scale DC level or square wave), and RMS levels as of the RMS in dBFS with the same reference, so a full-scale sine (power ) is at dBFS. The AES17 standard instead defines 0 dBFS as the RMS of a full-scale sine, so AES17 figures are 3.01 dB higher. A level read from the largest absolute sample is called dBFS peak: a sine of amplitude 0.1 is at dBFS peak and dBFS RMS.

SQNR of a full-scale sine. A sine of amplitude 1 has power . With :

Each extra bit adds about 6 dB. A signal peaking dB below full scale loses dB of SQNR.

Dither. For a quiet signal only a few steps tall, the error is not uniform noise: it is a deterministic function of the signal, so it repeats with the signal and appears as harmonics (distortion). TPDF dither adds, before rounding, a random value where are independent and uniform on ; has a triangular density on and power . The total error power becomes

i.e. dB more noise, but the error’s mean and variance no longer depend on the signal: the distortion is replaced by a steady hiss. This crate applies no dither anywhere, so the chapter implements it.

With the library

The crate’s convention, its step sizes and the SQNR at 16 bits through the i16 conversion (to_format), measured with comparison::snr:

use audio_samples::educational::topics;
use audio_samples::utils::comparison::snr;
use audio_samples::{AudioSamples, AudioTypeConversion, sample_rate, sine_wave};
use ndarray::array;
use std::time::Duration;

// The asymmetric mapping: -1 -> -32768, +1 -> 32767.
let edge = AudioSamples::new_mono(array![-1.0f64, -0.5, 0.0, 0.5, 1.0], sample_rate!(16000)).unwrap();
let codes = edge.to_format::<i16>();
assert_eq!(codes.as_slice().unwrap(), &[-32768, -16384, 0, 16384, 32767]);

let doc = topics::quantisation(16);
assert_eq!(doc.quantity("Quantisation levels").unwrap().value, 65_536.0);
assert_eq!(doc.quantity("Step size (negative half)").unwrap().value, 1.0 / 32768.0);
assert!((doc.quantity("Step size (positive half)").unwrap().value - 1.0 / 32767.0).abs() < 1e-18);

// Full-scale 997 Hz sine at 48 kHz, 1 s, rounded to i16 and back.
let fs = sample_rate!(48000);
let x = sine_wave::<f64>(997.0, Duration::from_secs(1), fs, 1.0);
let back = x.to_format::<i16>().to_format::<f64>();
let err: Vec<f64> = back.as_slice().unwrap().iter()
    .zip(x.as_slice().unwrap()).map(|(q, v)| q - v).collect();
let err = AudioSamples::new_mono(ndarray::Array1::from(err), fs).unwrap();
let measured = snr(&x, &err).unwrap();
let predicted = doc.quantity("SQNR (full-scale sine)").unwrap().value;
assert!((predicted - 98.09).abs() < 0.01);
assert!((measured - predicted).abs() < 0.05); // measured: 98.10 dB

The quiet case: a 997 Hz sine of amplitude 2.5 LSB at 16 kHz, rounded to i16 with and without TPDF dither. The dither is built from the crate’s white_noise, which is uniform on , so :

use audio_samples::{AudioSamples, AudioTransforms, AudioTypeConversion, nzu, sample_rate,
                    sine_wave, white_noise};
use std::time::Duration;

let fs = sample_rate!(16000);
let one_s = Duration::from_secs(1);
let lsb = 1.0 / 32768.0;
let x = sine_wave::<f64>(997.0, one_s, fs, 2.5 * lsb);
let xs = x.as_slice().unwrap().to_vec();

let u1 = white_noise::<f64>(one_s, fs, lsb / 2.0, Some(1));
let u2 = white_noise::<f64>(one_s, fs, lsb / 2.0, Some(2));
let dither: Vec<f64> = u1.as_slice().unwrap().iter()
    .zip(u2.as_slice().unwrap()).map(|(a, b)| a + b).collect();

let to_i16_and_back = |v: Vec<f64>| -> Vec<f64> {
    AudioSamples::new_mono(ndarray::Array1::from(v), fs).unwrap()
        .to_format::<i16>().to_format::<f64>().as_slice().unwrap().to_vec()
};
let plain = to_i16_and_back(xs.clone());
let dith = to_i16_and_back(xs.iter().zip(&dither).map(|(a, d)| a + d).collect());
let e_plain: Vec<f64> = plain.iter().zip(&xs).map(|(y, v)| y - v).collect();
let e_dith: Vec<f64> = dith.iter().zip(&xs).map(|(y, v)| y - v).collect();

let power = |v: &[f64]| v.iter().map(|a| a * a).sum::<f64>() / v.len() as f64;
// Dithered error power is Δ²/4 = 3 x (Δ²/12). Measured: 3.02 x, against
// 1.23 x without dither (a deterministic error need not be uniform).
assert!((power(&e_dith) / (lsb * lsb / 12.0) - 3.0).abs() < 0.1);
assert!((power(&e_plain) / (lsb * lsb / 12.0) - 1.23).abs() < 0.01);

// Distortion: the error's 3rd-harmonic bin (2991 Hz) against its mean bin power.
let spur_db = |e: &[f64]| {
    let a = AudioSamples::new_mono(ndarray::Array1::from(e.to_vec()), fs).unwrap();
    let m = a.rfft(nzu!(16000)).unwrap().row(0).to_vec(); // 1 Hz bins
    let mean = m.iter().map(|v| v * v).sum::<f64>() / m.len() as f64;
    10.0 * (m[2991] * m[2991] / mean).log10()
};
assert!(spur_db(&e_plain) > 30.0); // measured +31.9 dB: a clear harmonic
assert!(spur_db(&e_dith) < 3.0);   // measured -4.5 dB: noise only

// Correlation between error and signal: -0.516 undithered, about 0 dithered.
let corr = |e: &[f64]| {
    let num: f64 = e.iter().zip(&xs).map(|(a, b)| a * b).sum();
    num / ((power(e) * power(&xs)).sqrt() * xs.len() as f64)
};
assert!(corr(&e_plain) < -0.5);
assert!(corr(&e_dith).abs() < 0.03);
Top: a 997 Hz sine of amplitude 2.5 LSB at 16 kHz (blue) and its value after to_format::<i16>() (orange steps). Bottom: the rounding error, which stays within half a step but repeats with the signal.
Figure 2.1. Top: a 997 Hz sine of amplitude 2.5 LSB at 16 kHz (blue) and its value after to_format::<i16>() (orange steps). Bottom: the rounding error, which stays within half a step but repeats with the signal.

Dither raised the error power to (from without dither, so by a factor of about 2.45 here), and the result is still better: the undithered error has a correlation of about with the signal and is concentrated at harmonics of 997 Hz, which is heard as distortion, while the dithered error has a flat spectrum with no harmonics.

Spectra of the quantisation error of the 2.5 LSB sine, each bin relative to the mean bin power. Without dither (top) the error is concentrated at harmonics of 997 Hz, such as the 3rd at 2991 Hz; with TPDF dither (bottom) it is flat noise.
Figure 2.2. Spectra of the quantisation error of the 2.5 LSB sine, each bin relative to the mean bin power. Without dither (top) the error is concentrated at harmonics of 997 Hz, such as the 3rd at 2991 Hz; with TPDF dither (bottom) it is flat noise.

How it works

Write the requantiser in plain Rust with the same convention, check that it is bit-identical to the crate’s 16-bit and 8-bit (u8, offset binary) round trips, then measure SQNR at several word lengths against .

use audio_samples::{AudioTypeConversion, sample_rate, sine_wave};
use std::time::Duration;

fn requantise(x: f64, b: u32) -> f64 {
    let half = 2f64.powi(b as i32 - 1);
    let x = x.clamp(-1.0, 1.0);
    if x < 0.0 { (x * half).round() / half } else { (x * (half - 1.0)).round() / (half - 1.0) }
}

let x = sine_wave::<f64>(997.0, Duration::from_secs(1), sample_rate!(48000), 1.0);
let xs = x.as_slice().unwrap();

// Same as the crate, sample for sample (to the last bit, up to division rounding).
let via_i16 = x.to_format::<i16>().to_format::<f64>();
let via_u8 = x.to_format::<u8>().to_format::<f64>();
for ((&v, &a), &b) in xs.iter().zip(via_i16.as_slice().unwrap()).zip(via_u8.as_slice().unwrap()) {
    assert!((a - requantise(v, 16)).abs() < 1e-15);
    assert!((b - requantise(v, 8)).abs() < 1e-15);
}

let p_signal = xs.iter().map(|v| v * v).sum::<f64>() / xs.len() as f64;
// (bits, measured SQNR in dB to 0.01, as printed by the lab)
for (b, expected) in [(4u32, 25.62), (8, 49.98), (12, 74.03), (16, 98.10)] {
    let p_err = xs.iter().map(|&v| (requantise(v, b) - v).powi(2)).sum::<f64>() / xs.len() as f64;
    let sqnr = 10.0 * (p_signal / p_err).log10();
    assert!((sqnr - expected).abs() < 0.01);
    // The rule of thumb: within 0.25 dB at 4 and 8 bits (the error is less
    // uniform when the steps are coarse), within 0.05 dB from 12 bits up.
    let rule = 6.02 * f64::from(b) + 1.76;
    assert!((sqnr - rule).abs() < if b >= 12 { 0.05 } else { 0.25 });
}

// Effect of the asymmetry at 16 bits: the steps differ by a factor
// 32768/32767 (0.003 %); averaging the two halves' noise powers:
let eps = 32768.0f64 / 32767.0 - 1.0;
assert!((eps - 3.05e-5).abs() < 1e-7);
let noise_ratio = (1.0 + (1.0 + eps).powi(2)) / 2.0;
assert!((noise_ratio - 1.0 - 3.05e-5).abs() < 1e-7);
assert!(10.0 * noise_ratio.log10() < 1.4e-4); // about 0.0001 dB

The asymmetric steps have a negligible effect: at 16 bits the positive-half step is larger by a factor , which changes the noise power by about (0.0001 dB), as the last lines check.

Ask the library to explain

topics::quantisation states the convention, the step sizes, the noise level, the SQNR and the SQNR with TPDF dither:

use audio_samples::educational::topics;

let doc = topics::quantisation(16);
let sqnr = doc.quantity("SQNR (full-scale sine)").unwrap().value;
let rule = doc.quantity("Rule of thumb").unwrap().value;
let dithered = doc.quantity("SQNR with TPDF dither").unwrap().value;
assert!((sqnr - 98.09).abs() < 0.01 && (rule - 98.09).abs() < 0.01);
assert!((sqnr - dithered - 4.77).abs() < 0.01); // 10 log10 3
// Noise power Δ²/12 in dB re 1 (full scale squared) ...
let noise = doc.quantity("Noise level").unwrap().value;
assert!((noise - (-101.10)).abs() < 0.01);
// ... which is -98.09 dBFS in the AES17 convention (full-scale sine = 0 dBFS),
// 3.01 dB higher. In AES17 terms SQNR = -(noise level in dBFS).
let aes17 = doc.quantity("Noise level (AES17 dBFS)").unwrap().value;
assert!((aes17 - (-98.09)).abs() < 0.01);
assert!((aes17 - noise - 10.0 * 2f64.log10()).abs() < 1e-9);
assert!((sqnr + aes17).abs() < 1e-9);
assert!(doc.has_warning_containing("i16"));
println!("{doc}");

Exercises

  1. How many bits are needed for an SQNR of at least 90 dB on a full-scale sine? Predict from the rule, then confirm by measurement at that word length and one bit fewer.
  2. A sine peaks at dBFS peak (amplitude 0.1) and is stored as i16. Predict its SQNR, then measure it.
  3. Predict how much TPDF dither lowers the SQNR of a loud sine (amplitude 0.9) quantised to 8 bits, and measure it.

Answers

use audio_samples::utils::comparison::snr;
use audio_samples::{AudioSamples, AudioTypeConversion, sample_rate, sine_wave, white_noise};
use std::time::Duration;

fn requantise(x: f64, b: u32) -> f64 {
    let half = 2f64.powi(b as i32 - 1);
    let x = x.clamp(-1.0, 1.0);
    if x < 0.0 { (x * half).round() / half } else { (x * (half - 1.0)).round() / (half - 1.0) }
}
fn sqnr(x: &[f64], y: &[f64]) -> f64 {
    let ps: f64 = x.iter().map(|v| v * v).sum();
    let pn: f64 = x.iter().zip(y).map(|(a, b)| (b - a).powi(2)).sum();
    10.0 * (ps / pn).log10()
}
let one_s = Duration::from_secs(1);
let fs = sample_rate!(48000);

// 1. b >= (90 - 1.76) / 6.02 = 14.66, so 15 bits.
let b = ((90.0 - 1.76) / 6.02f64).ceil() as u32;
assert_eq!(b, 15);
let x = sine_wave::<f64>(997.0, one_s, fs, 1.0);
let xs = x.as_slice().unwrap();
let at = |b: u32| sqnr(xs, &xs.iter().map(|&v| requantise(v, b)).collect::<Vec<_>>());
assert!(at(15) >= 90.0 && at(14) < 90.0);

// 2. 98.09 - 20 = 78.09 dB.
let quiet = sine_wave::<f64>(997.0, one_s, fs, 0.1);
let back = quiet.to_format::<i16>().to_format::<f64>();
let err: Vec<f64> = back.as_slice().unwrap().iter()
    .zip(quiet.as_slice().unwrap()).map(|(q, v)| q - v).collect();
let err = AudioSamples::new_mono(ndarray::Array1::from(err), fs).unwrap();
let measured = snr(&quiet, &err).unwrap();
assert!((measured - 78.09).abs() < 0.1);
// Its levels: -20 dBFS peak, -23.01 dBFS RMS (whole periods: 997 in 1 s).
let q = quiet.as_slice().unwrap();
let peak_db = 20.0 * q.iter().fold(0.0f64, |a, v| a.max(v.abs())).log10();
let rms_db = 10.0 * (q.iter().map(|v| v * v).sum::<f64>() / q.len() as f64).log10();
assert!((peak_db + 20.0).abs() < 0.01 && (rms_db + 23.01).abs() < 0.01);

// 3. 10 log10(3) = 4.77 dB. One step at 8 bits is 1/128.
let lsb = 1.0 / 128.0;
let loud = sine_wave::<f64>(997.0, one_s, fs, 0.9);
let ls = loud.as_slice().unwrap();
let u1 = white_noise::<f64>(one_s, fs, lsb / 2.0, Some(11));
let u2 = white_noise::<f64>(one_s, fs, lsb / 2.0, Some(12));
let plain: Vec<f64> = ls.iter().map(|&v| requantise(v, 8)).collect();
let dith: Vec<f64> = ls.iter().zip(u1.as_slice().unwrap()).zip(u2.as_slice().unwrap())
    .map(|((&v, a), b)| requantise(v + a + b, 8)).collect();
let penalty = sqnr(ls, &plain) - sqnr(ls, &dith);
// Random dither over 48 000 samples: the noise power estimate is good to ~1 %.
assert!((penalty - 10.0 * 3f64.log10()).abs() < 0.2);

Common pitfalls

  • The crate maps integers to floats asymmetrically (divide by below zero, by above). Many other audio libraries divide by on both sides, so their positive samples differ from this crate’s by up to about .
  • Signed integer-to-integer narrowing (for example i32 to i16) shifts bits: it truncates towards (a LSB bias) rather than rounding. Conversions to u8 are the exception: they rescale and round to nearest. Convert through f64 to round in every case.
  • No conversion applies dither; add it before reducing the bit depth of quiet material.
  • dB is for a full-scale sine. Speech peaks well below full scale and has a high crest factor; its SQNR is much lower.
  • white_noise is uniform, not Gaussian: amplitude gives RMS .

References

  • B. Widrow and I. Kollár, Quantization Noise: Roundoff Error in Digital Computation, Signal Processing, Control, and Communications, Cambridge University Press, 2008.
  • S. P. Lipshitz, R. A. Wannamaker and J. Vanderkooy, “Quantization and dither: a theoretical survey”, Journal of the Audio Engineering Society 40(5), 355-375, 1992.
  • AES17, AES standard method for digital audio engineering: measurement of digital audio equipment, Audio Engineering Society (the definition of dBFS as the RMS of a full-scale sine).

See also

03. The DFT, windows and leakage

The discrete Fourier transform (DFT) converts a block of samples into amplitudes and phases at evenly spaced frequencies. Most of the later chapters of this guide (spectrograms, mel features, pitch, filtering by FFT) build on it. This chapter covers exactly what it returns, why a pure tone often spreads over many bins (leakage), and what a window can and cannot do about that.

Concept

Definition. For a block of samples , :

where is the integer bin index, and is a complex number in the units of (here: full scale) times samples. The exponent is negative and there is no factor.

Bin frequencies. Bin is at

where is the sample rate in Hz and the bin spacing in Hz. For real , , so only bins carry information; this crate returns exactly those .

A tone on a bin. For with , (real; at or it is ); for , . With a window applied first, the peak becomes .

Leakage. The DFT treats the block as one period of a periodic signal. If the tone does not complete a whole number of cycles in the block, the implied periodic signal has a jump at the block edge, and the energy spreads over all bins. Multiplying by a window that tapers to zero removes the jump, at the cost of a wider main lobe. A window is summarised by:

where the coherent gain CG (dimensionless) scales the peak of a bin-centred tone relative to no window, and the equivalent noise bandwidth ENBW (in bins) is the bandwidth of broadband noise each bin collects. Two more figures are read off the window’s spectrum (with in bins): the scalloping loss in dB, the worst-case peak drop for a tone halfway between bins, and the peak side-lobe level (PSL), the highest lobe outside the main lobe in dB relative to .

This crate’s WindowType::Hanning is the symmetric Hann window

(denominator , so ), not the periodic one (denominator ) that many analysis tools use by default for spectra.

Zero padding (appending zeros before the DFT) samples the same spectrum on a finer grid. It does not narrow the main lobe; only a longer stretch of signal does.

With the library

fft returns the complex non-negative-frequency bins, rfft their magnitudes (real numbers, not complex values):

use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate};
use num_complex::Complex;
use std::f64::consts::PI;

// 64 samples: 0.25 (DC) + sin at bin 4 + 0.5 cos at bin 9.
let x: Vec<f64> = (0..64).map(|i| {
    let t = i as f64 / 64.0;
    0.25 + (2.0 * PI * 4.0 * t).sin() + 0.5 * (2.0 * PI * 9.0 * t).cos()
}).collect();
let audio = AudioSamples::new_mono(ndarray::Array1::from(x), sample_rate!(16000)).unwrap();

let spec = audio.fft(nzu!(64)).unwrap();
assert_eq!(spec.ncols(), 33); // N/2 + 1
let close = |a: Complex<f64>, b: Complex<f64>| (a - b).norm() < 1e-9;
assert!(close(spec[[0, 0]], Complex::new(16.0, 0.0)));   // N x 0.25
assert!(close(spec[[0, 4]], Complex::new(0.0, -32.0)));  // -j A N / 2: negative exponent
assert!(close(spec[[0, 9]], Complex::new(16.0, 0.0)));   // 0.5 N / 2

let mags = audio.rfft(nzu!(64)).unwrap();
assert!((mags[[0, 4]] - 32.0).abs() < 1e-9); // a real number: |X[4]|

Measuring leakage: at kHz and , Hz, so 1000 Hz is bin 32 and 1015.625 Hz is bin 32.5, the worst case. Window the tone with apply_window_f64 and the coefficients from spectrograms::make_window:

use audio_samples::{AudioProcessing, AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{WindowType, make_window};
use std::time::Duration;

let spectrum = |f: f64, wt: WindowType| -> Vec<f64> {
    let w = make_window::<f64>(wt, nzu!(512));
    sine_wave::<f64>(f, Duration::from_millis(32), sample_rate!(16000), 1.0) // 512 samples
        .apply_window_f64(&w).unwrap()
        .rfft(nzu!(512)).unwrap().row(0).to_vec()
};
let db = |r: f64| 20.0 * r.log10();
let peak = |s: &[f64]| s.iter().copied().fold(0.0, f64::max);

// Rectangular (no window): the peak drops by 3.86 dB off-bin, and 19.5 bins
// away the leakage is 34 dB down.
let (on, off) = (spectrum(1000.0, WindowType::Rectangular), spectrum(1015.625, WindowType::Rectangular));
assert!((db(peak(&on) / peak(&off)) - 3.86).abs() < 0.01);
assert!((db(off[52] / peak(&off)) + 34.0).abs() < 0.1);

// Hann: the peak drops by 1.42 dB, and 19.5 bins away the leakage is 86 dB down.
let (on, off) = (spectrum(1000.0, WindowType::Hanning), spectrum(1015.625, WindowType::Hanning));
assert!((db(peak(&on) / peak(&off)) - 1.42).abs() < 0.01);
assert!((db(off[52] / peak(&off)) + 86.0).abs() < 0.1);

(The rectangular drop of 3.86 dB is slightly less than the window’s 3.92 dB scalloping loss because a real sine also has a negative-frequency image whose leakage adds to the bins near the peak.)

Spectra of a 512-sample tone at 16 kHz (bins 31.25 Hz apart), relative to the bin-centred peak. At 1000 Hz (bin 32, blue) the tone falls on one bin; at 1015.625 Hz (bin 32.5, orange) it leaks into every bin. At bin 52 the leakage is 34 dB below the peak without a window and 86 dB below with a Hann window.
Figure 3.1. Spectra of a 512-sample tone at 16 kHz (bins 31.25 Hz apart), relative to the bin-centred peak. At 1000 Hz (bin 32, blue) the tone falls on one bin; at 1015.625 Hz (bin 32.5, orange) it leaks into every bin. At bin 52 the leakage is 34 dB below the peak without a window and 86 dB below with a Hann window.

Zero padding versus a longer signal: two tones 20 Hz apart, Hann window.

use audio_samples::{AudioProcessing, AudioSamples, AudioTransforms, sample_rate, sine_wave};
use spectrograms::{WindowType, make_window};
use std::num::NonZeroUsize;
use std::time::Duration;

let peaks_near_1khz = |dur: Duration, n_fft: usize| -> usize {
    let a = sine_wave::<f64>(1000.0, dur, sample_rate!(16000), 1.0);
    let b = sine_wave::<f64>(1020.0, dur, sample_rate!(16000), 1.0);
    let v: Vec<f64> = a.as_slice().unwrap().iter().zip(b.as_slice().unwrap()).map(|(p, q)| p + q).collect();
    let w = make_window::<f64>(WindowType::Hanning, NonZeroUsize::new(v.len()).unwrap());
    let m = AudioSamples::new_mono(ndarray::Array1::from(v), sample_rate!(16000)).unwrap()
        .apply_window_f64(&w).unwrap()
        .rfft(NonZeroUsize::new(n_fft).unwrap()).unwrap().row(0).to_vec();
    let bin = 16_000.0 / n_fft as f64;
    let (lo, hi) = ((900.0 / bin) as usize, (1120.0 / bin) as usize);
    let top = m[lo..hi].iter().copied().fold(0.0, f64::max);
    (lo..hi).filter(|&i| m[i] > m[i - 1] && m[i] >= m[i + 1] && m[i] > 0.5 * top).count()
};
assert_eq!(peaks_near_1khz(Duration::from_millis(32), 512), 1);   // 512 samples
assert_eq!(peaks_near_1khz(Duration::from_millis(32), 8192), 1);  // zero-padded: still 1
assert_eq!(peaks_near_1khz(Duration::from_millis(256), 8192), 2); // 4096 samples: resolved
Two tones at 1000 and 1020 Hz, Hann window, each spectrum scaled to its maximum. 512 samples give one peak, and zero-padding them to 8192 points only draws the same peak more smoothly; 4096 samples resolve both tones.
Figure 3.2. Two tones at 1000 and 1020 Hz, Hann window, each spectrum scaled to its maximum. 512 samples give one peak, and zero-padding them to 8192 points only draws the same peak more smoothly; 4096 samples resolve both tones.

How it works

The code below re-derives three results: the DFT itself, the symmetric-Hann figures in closed form, and the rectangular window’s scalloping loss.

use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate};
use audio_samples::educational::topics;
use num_complex::Complex;
use spectrograms::{WindowType, make_window};
use std::f64::consts::PI;

// 1. The DFT as a double loop, against the library's FFT.
let x: Vec<f64> = (0..64).map(|i| ((i * 7 % 13) as f64 - 6.0) / 6.0).collect();
let naive: Vec<Complex<f64>> = (0..=32).map(|k| {
    x.iter().enumerate()
        .map(|(n, &v)| Complex::from_polar(v, -2.0 * PI * (k * n) as f64 / 64.0))
        .sum()
}).collect();
let lib = AudioSamples::new_mono(ndarray::Array1::from(x), sample_rate!(16000)).unwrap()
    .fft(nzu!(64)).unwrap();
// 64-term sums of O(1) values: rounding of order 1e-14.
for k in 0..=32 {
    assert!((lib[[0, k]] - naive[k]).norm() < 1e-12);
}

// 2. Symmetric Hann: sum w = (N-1)/2 and sum w^2 = 3(N-1)/8, so
//    CG = (N-1)/(2N) and ENBW = 1.5 N/(N-1). For N = 512: 0.4990 and 1.5029.
let n = 512.0;
let w = make_window::<f64>(WindowType::Hanning, nzu!(512));
let cg = w.iter().sum::<f64>() / n;
let enbw = n * w.iter().map(|v| v * v).sum::<f64>() / w.iter().sum::<f64>().powi(2);
assert!((cg - (n - 1.0) / (2.0 * n)).abs() < 1e-12);
assert!((enbw - 1.5 * n / (n - 1.0)).abs() < 1e-12);
assert!((cg - 0.4990).abs() < 1e-4 && (enbw - 1.5029).abs() < 1e-4);
assert_eq!(w[0], 0.0);                       // symmetric: zero at both ends,
assert!(w[511].abs() < 1e-15);
assert!((w[256] - 0.999991).abs() < 1e-6);   // and no sample exactly at 1.0

// The library's explainer measures the same numbers from the coefficients.
let doc = topics::window(&WindowType::Hanning, 512, 16_000.0);
assert!((doc.quantity("Coherent gain").unwrap().value - cg).abs() < 1e-12);
assert!((doc.quantity("Equivalent noise bandwidth").unwrap().value - enbw).abs() < 1e-12);

// 3. Rectangular window: |W(f)| = |sin(pi f) / sin(pi f / N)|, so half a bin
//    off, |W(1/2)/W(0)| = 1 / (N sin(pi / 2N)), i.e. 3.92 dB.
let ratio: f64 = 1.0 / (n * (PI / (2.0 * n)).sin());
let loss = -20.0 * ratio.log10();
assert!((loss - 3.92).abs() < 0.01);
let rect = topics::window(&WindowType::Rectangular, 512, 16_000.0);
assert!((rect.quantity("Scalloping loss").unwrap().value - loss).abs() < 0.01);

Ask the library to explain

topics::dft explains bin spacing and the mirror symmetry; topics::window and WindowType::explain_with measure the window figures from the actual coefficients the STFT uses:

use audio_samples::educational::{Explain, ExplainContext, topics};
use spectrograms::WindowType;

let dft = topics::dft(512, 16_000.0);
assert_eq!(dft.quantity("Bin spacing").unwrap().value, 31.25);
assert_eq!(dft.quantity("Non-redundant bins").unwrap().value, 257.0);

// (window, coherent gain, ENBW in bins, peak side-lobe level in dB), N = 512
for (wt, cg, enbw, psl) in [
    (WindowType::Rectangular, 1.0, 1.0, -13.26),
    (WindowType::Hanning, 0.4990, 1.5029, -31.47),
    (WindowType::Hamming, 0.5391, 1.3647, -42.67),
    (WindowType::Blackman, 0.4192, 1.7301, -58.11),
] {
    let doc = wt.explain_with(&ExplainContext::new().with_n_fft(512).with_sample_rate(16_000.0));
    assert!((doc.quantity("Coherent gain").unwrap().value - cg).abs() < 1e-4);
    assert!((doc.quantity("Equivalent noise bandwidth").unwrap().value - enbw).abs() < 1e-4);
    assert!((doc.quantity("Peak side-lobe level").unwrap().value - psl).abs() < 0.01);
}
let hann = WindowType::Hanning.explain_with(&ExplainContext::new().with_n_fft(512));
assert!(hann.has_warning_containing("symmetric"));
println!("{hann}");

The table shows the standard trade-off: lower side lobes (less leakage from loud components into quiet ones) come with a wider main lobe and more noise per bin.

Top: the four windows for N = 512. Bottom: their spectra (zero-padded 16 times), relative to the peak, against the offset from the tone in bins. Lower side lobes come with a wider main lobe. The peak side-lobe levels in the legend are those the explainer reports.
Figure 3.3. Top: the four windows for N = 512. Bottom: their spectra (zero-padded 16 times), relative to the peak, against the offset from the tone in bins. Lower side lobes come with a wider main lobe. The peak side-lobe levels in the legend are those the explainer reports.

Exercises

  1. At kHz with , which bin is nearest to 440 Hz, and what is its centre frequency? Check that a Hann-windowed 440 Hz tone peaks there.
  2. A sine of amplitude 0.5 lies exactly on a bin, Hann window, . Predict at the peak, then measure.
  3. With a Hann window (main lobe about 2 bins wide at dB), what is the smallest that should separate two tones 10 Hz apart at 16 kHz? Check that a power of two above it separates 1000 Hz and 1010 Hz, and that does not.

Answers

use audio_samples::{AudioProcessing, AudioSamples, AudioTransforms, sample_rate, sine_wave};
use spectrograms::{WindowType, make_window};
use std::num::NonZeroUsize;
use std::time::Duration;

let nz = |n: usize| NonZeroUsize::new(n).unwrap();
let hann_mag = |v: Vec<f64>, fs: u32, n_fft: usize| -> Vec<f64> {
    let w = make_window::<f64>(WindowType::Hanning, nz(v.len()));
    AudioSamples::new_mono(ndarray::Array1::from(v), std::num::NonZeroU32::new(fs).unwrap()).unwrap()
        .apply_window_f64(&w).unwrap().rfft(nz(n_fft)).unwrap().row(0).to_vec()
};
let argmax = |m: &[f64]| (0..m.len()).max_by(|&a, &b| m[a].total_cmp(&m[b])).unwrap();

// 1. k = round(440 * 4096 / 44100) = round(40.87) = 41, at 41 * 44100 / 4096 = 441.43 Hz.
let k = (440.0f64 * 4096.0 / 44_100.0).round() as usize;
assert_eq!(k, 41);
assert!((k as f64 * 44_100.0 / 4096.0 - 441.43).abs() < 0.01);
let tone: Vec<f64> = (0..4096).map(|n| (2.0 * std::f64::consts::PI * 440.0 * n as f64 / 44_100.0).sin()).collect();
assert_eq!(argmax(&hann_mag(tone, 44_100, 4096)), 41);

// 2. A * sum(w) / 2 = 0.5 * 511.5 / 2 = 127.875 (sum of a symmetric Hann is (N-1)/2).
let x = sine_wave::<f64>(1000.0, Duration::from_millis(64), sample_rate!(16000), 0.5); // bin 64
let m = hann_mag(x.as_slice().unwrap().to_vec(), 16_000, 1024);
// The tone's negative-frequency image leaks a little into bin 64: allow 1e-3.
assert!((m[64] - 127.875).abs() < 1e-3);

// 3. -6 dB main-lobe width, about 2 fs / N for Hann, <= 10 Hz  =>  N >= 3200;
//    the next power of two is 4096.
let n_min = 2.0 * 16_000.0 / 10.0;
assert_eq!(n_min, 3200.0);
let count = |n: usize| -> usize {
    let v: Vec<f64> = (0..n).map(|i| {
        let t = i as f64 / 16_000.0;
        (2.0 * std::f64::consts::PI * 1000.0 * t).sin() + (2.0 * std::f64::consts::PI * 1010.0 * t).sin()
    }).collect();
    let m = hann_mag(v, 16_000, n);
    let bin = 16_000.0 / n as f64;
    let (lo, hi) = ((950.0 / bin) as usize, (1060.0 / bin) as usize);
    let top = m[lo..hi].iter().copied().fold(0.0, f64::max);
    (lo..hi).filter(|&i| m[i] > m[i - 1] && m[i] >= m[i + 1] && m[i] > 0.5 * top).count()
};
assert_eq!(count(4096), 2);
assert_eq!(count(1024), 1);

Common pitfalls

  • rfft returns magnitudes, not complex values; use fft for phase.
  • Neither transform normalises: a full-scale bin-centred sine gives , not 1 or 0.5. Divide by to read amplitudes.
  • n_fft must be at least the signal length (shorter signals are zero-padded; longer ones are an error, not truncated).
  • WindowType::Hanning is the symmetric Hann; many analysis tools default to the periodic one. Values differ by a fraction of a percent; pass a periodic window through WindowType::Custom when you need it.
  • Zero padding interpolates the spectrum onto a finer grid; it does not improve resolution.

References

  • F. J. Harris, “On the use of windows for harmonic analysis with the discrete Fourier transform”, Proceedings of the IEEE 66(1), 51-83, 1978. The source of the window figures (coherent gain, ENBW, scalloping loss, side-lobe level) used here.
  • J. W. Cooley and J. W. Tukey, “An algorithm for the machine calculation of complex Fourier series”, Mathematics of Computation 19(90), 297-301, 1965.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010.

See also

04. STFT and spectrograms

Speech and music change over time: a vowel lasts tens of milliseconds, a plosive burst a few. One DFT of a whole utterance (chapter 03) combines all of these into one spectrum. The short-time Fourier transform (STFT) takes a DFT of short, overlapping, windowed frames instead, giving frequency content as a function of time: the spectrogram. This chapter defines exactly how the crate frames the signal, why fine time and fine frequency resolution cannot be had at once, how the transform is inverted, and what the dB scale of a spectrogram means.

Concept

Definition (as implemented). With frame length (and FFT size) , hop and window :

where is the frame index, the bin index, the padding in samples and outside the signal. With centre = true, , so frame is centred on sample ; with centre = false, and frame starts at sample . The window is the symmetric Hann of chapter 03.

Number of frames for a signal of samples:

Resolution. Bins are Hz apart and frames seconds apart, with the sample rate in Hz. The actual time resolution, however, is set by the window length , and the actual frequency resolution by the window’s main lobe (about for Hann at dB). Their product is fixed by the window shape: halving one doubles the other. A smaller hop gives more frames, not sharper ones.

Inverse (weighted overlap-add). Inverse-DFT each frame to , multiply by the window again and overlap-add, dividing by the summed squared windows:

This is exact wherever the denominator is non-zero, for any window and hop, provided the STFT has not been modified. Two overlap conditions apply. NOLA (nonzero overlap-add): the summed squared windows are never zero, which is the only condition the inverse above requires. COLA (constant overlap-add): the plain summed windows are the same constant for every , which plain overlap-add without the division needs. WOLA works even for windows that are not COLA. If the STFT is modified before inversion (masking, a phase vocoder), the frames are no longer consistent and the same formula gives the least-squares estimate of Griffin and Lim (1984) rather than an exact inverse. With centring, the output has samples.

Spectrogram scales. Power (no division by ), magnitude , and decibels

in dB re 1 (an absolute reference), where floor is the LogParams value in dB. LogParams::new(-80.0) clamps at power ; it is not a floor relative to the peak (80 dB below it), and a loud bin can be far above 0 dB. A log-frequency spectrogram resamples the bins onto log-spaced frequencies; a mel spectrogram sums power through triangular filters on the Slaney mel scale (chapter 10).

With the library

use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate, white_noise};
use spectrograms::{StftParams, WindowType};
use std::time::Duration;

let x = white_noise::<f64>(Duration::from_secs(1), sample_rate!(16000), 0.5, Some(7));
let l = x.samples_per_channel().get(); // 16 000
let frames = |n: usize, h: usize, centre: bool| {
    let p = if centre { n / 2 } else { 0 };
    1 + (l + 2 * p - n) / h
};

let params = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, true).unwrap();
let st = x.stft(&params).unwrap();
assert_eq!(st.data.nrows(), 257);                 // N/2 + 1 bins
assert_eq!(st.data.ncols(), frames(512, 128, true));
assert_eq!(st.data.ncols(), 126);

let no_centre = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, false).unwrap();
assert_eq!(x.stft(&no_centre).unwrap().data.ncols(), 122);

// Inverse: 125 * 128 + 512 - 512 = 16 000 samples, equal to the input to round-off.
let y = AudioSamples::<f64>::istft(st).unwrap();
assert_eq!(y.samples_per_channel().get(), 16_000);
let err = x.as_slice().unwrap().iter().zip(y.as_slice().unwrap())
    .map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
assert!(err < 1e-12); // measured: about 3e-16

Measuring the trade-off: two tones 50 Hz apart, and a click, analysed with a 16 ms and a 128 ms window (hop 2 ms in both):

use audio_samples::utils::generation::impulse;
use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{StftParams, WindowType};
use std::num::NonZeroUsize;
use std::time::Duration;

let half_s = Duration::from_millis(500);
let a = sine_wave::<f64>(1000.0, half_s, sample_rate!(16000), 0.5);
let b = sine_wave::<f64>(1050.0, half_s, sample_rate!(16000), 0.5);
let tones: Vec<f64> = a.as_slice().unwrap().iter().zip(b.as_slice().unwrap()).map(|(p, q)| p + q).collect();
let tones = AudioSamples::new_mono(ndarray::Array1::from(tones), sample_rate!(16000)).unwrap();
let click = impulse::<f64>(half_s, sample_rate!(16000), 1.0, 0.25);

let analyse = |n: usize| -> (usize, f64) {
    let p = StftParams::new(NonZeroUsize::new(n).unwrap(), nzu!(32), WindowType::Hanning, true).unwrap();
    // Frequency: summed magnitude per bin; count peaks between 800 and 1250 Hz.
    let s = tones.stft(&p).unwrap();
    let avg: Vec<f64> = (0..s.data.nrows()).map(|k| s.data.row(k).iter().map(|c| c.norm()).sum()).collect();
    let bin = 16_000.0 / n as f64;
    let (lo, hi) = ((800.0 / bin) as usize, (1250.0 / bin) as usize);
    let top = avg[lo..hi].iter().copied().fold(0.0, f64::max);
    let peaks = (lo..hi).filter(|&i| avg[i] > avg[i - 1] && avg[i] >= avg[i + 1] && avg[i] > 0.5 * top).count();
    // Time: frames where the click's energy exceeds half its maximum, in ms.
    let c = click.stft(&p).unwrap();
    let e: Vec<f64> = (0..c.data.ncols()).map(|j| c.data.column(j).iter().map(|v| v.norm_sqr()).sum()).collect();
    let emax = e.iter().copied().fold(0.0, f64::max);
    let spread_ms = e.iter().filter(|&&v| v > 0.5 * emax).count() as f64 * 2.0;
    (peaks, spread_ms)
};
let (peaks_short, spread_short) = analyse(256);   // 16 ms window, Δf = 62.5 Hz
let (peaks_long, spread_long) = analyse(2048);    // 128 ms window, Δf = 7.8 Hz
assert_eq!((peaks_short, peaks_long), (1, 2));    // only the long window resolves 50 Hz
assert_eq!((spread_short, spread_long), (6.0, 46.0)); // ... and spreads the click 8x wider
The chapter's trade-off measurement, hop 2 ms. Top: summed STFT magnitude of two tones at 1000 and 1050 Hz; only the 128 ms window (N = 2048) separates them. Bottom: frame energy of a click at 250 ms; it stays above half its maximum for 6 ms with the 16 ms window (N = 256) and 46 ms with the 128 ms window.
Figure 4.1. The chapter's trade-off measurement, hop 2 ms. Top: summed STFT magnitude of two tones at 1000 and 1050 Hz; only the 128 ms window (N = 2048) separates them. Bottom: frame energy of a click at 250 ms; it stays above half its maximum for 6 ms with the 16 ms window (N = 256) and 46 ms with the 128 ms window.

Spectrogram types and the absolute dB floor. A full-scale 1 kHz sine is bin-centred for at 16 kHz (bin 32), so its peak power is and its dB value is dB re 1: above 0 dB.

use audio_samples::utils::generation::silence;
use audio_samples::{AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{LogHzParams, LogParams, MelParams, SpectrogramParams, StftParams, WindowType};
use std::time::Duration;

let sine = sine_wave::<f64>(1000.0, Duration::from_millis(500), sample_rate!(16000), 1.0);
let stft = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, true).unwrap();
let sp = SpectrogramParams::new(stft, 16_000.0).unwrap();
let floor = LogParams::new(-80.0).unwrap();

let lin = sine.linear_db_spectrogram(&sp, &floor).unwrap();
let loghz = sine.loghz_power_spectrogram(&sp, &LogHzParams::new(nzu!(64), 80.0, 8000.0).unwrap()).unwrap();
let mel = sine.mel_power_spectrogram(&sp, &MelParams::new(nzu!(40), 0.0, 8000.0).unwrap()).unwrap();
assert_eq!((lin.data().nrows(), loghz.data().nrows(), mel.data().nrows()), (257, 64, 40));

let peak_db = lin.data().iter().copied().fold(f64::MIN, f64::max);
assert!((peak_db - 42.13).abs() < 0.01);

// Silence is exactly at the floor: -80 dB re 1, whatever else is in the file.
let quiet = silence::<f64>(Duration::from_millis(250), sample_rate!(16000));
let q = quiet.linear_db_spectrogram(&sp, &floor).unwrap();
assert!(q.data().iter().all(|&v| (v + 80.0).abs() < 1e-9));

// The mel band with the most energy is the one centred nearest 1 kHz (1031 Hz).
// (frequencies() is correct here because the range is 0 Hz to Nyquist.)
let f = mel.frequencies();
let best = (0..40).max_by(|&i, &j| mel.data().row(i).sum().total_cmp(&mel.data().row(j).sum())).unwrap();
assert!((f[best] - 1031.0).abs() < 1.0);
A 2 s linear chirp from 100 Hz to 7.9 kHz at 16 kHz (amplitude 0.5). Top: linear_db_spectrogram with N = 512, H = 128 and a -80 dB floor, in dB re 1. Bottom: mel_power_spectrogram with 40 bands, in dB; the mel scale spends more bands on low frequencies, so the line bends.
Figure 4.2. A 2 s linear chirp from 100 Hz to 7.9 kHz at 16 kHz (amplitude 0.5). Top: linear_db_spectrogram with N = 512, H = 128 and a -80 dB floor, in dB re 1. Bottom: mel_power_spectrogram with 40 bands, in dB; the mel scale spends more bands on low frequencies, so the line bends.

How it works

Rebuild one frame from the definition (pad, slice, window, DFT), check the power spectrogram is , and measure the overlap-add sums that istft relies on:

use audio_samples::educational::Explain;
use audio_samples::{AudioTransforms, nzu, sample_rate, white_noise};
use num_complex::Complex;
use spectrograms::{SpectrogramParams, StftParams, WindowType};
use std::f64::consts::PI;
use std::time::Duration;

let x = white_noise::<f64>(Duration::from_millis(250), sample_rate!(16000), 0.5, Some(3));
let xs = x.as_slice().unwrap();
let (n, h, m) = (512usize, 128usize, 10usize);
let params = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, true).unwrap();
let st = x.stft(&params).unwrap();

// Symmetric Hann, denominator N - 1.
let w: Vec<f64> = (0..n).map(|i| 0.5 - 0.5 * (2.0 * PI * i as f64 / (n - 1) as f64).cos()).collect();
// Frame m covers padded samples mH .. mH + N, i.e. original samples mH - N/2 ...
let frame: Vec<f64> = (0..n).map(|i| {
    let idx = (m * h + i) as isize - (n / 2) as isize;
    if idx >= 0 && (idx as usize) < xs.len() { xs[idx as usize] * w[i] } else { 0.0 }
}).collect();
for k in [0, 1, 37, 128, 256] {
    let xk: Complex<f64> = frame.iter().enumerate()
        .map(|(i, &v)| Complex::from_polar(v, -2.0 * PI * ((k * i) % n) as f64 / n as f64)).sum();
    // 512-term sums of O(0.5) values: rounding of order 1e-13.
    assert!((xk - st.data[[k, m]]).norm() < 1e-10);
}

// Power spectrogram = |X|^2, element by element.
let sp = SpectrogramParams::new(params.clone(), 16_000.0).unwrap();
let pow = x.linear_power_spectrogram(&sp).unwrap();
assert!((pow.data()[[37, m]] - st.data[[37, m]].norm_sqr()).abs() < 1e-9);

// Overlap-add sums in the steady state (away from the ends).
let sum_w: Vec<f64> = (0..h).map(|r| (0..n / h).map(|q| w[r + q * h]).sum()).collect();
let sum_w2: Vec<f64> = (0..h).map(|r| (0..n / h).map(|q| w[r + q * h].powi(2)).sum()).collect();
let mean = sum_w.iter().sum::<f64>() / h as f64;
let (lo, hi) = sum_w.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v)));
let ripple = (hi - lo) / mean;
// The symmetric Hann at 75 % overlap is *almost* COLA (sum ~ 2), not exactly.
assert!((mean - 2.0).abs() < 0.01 && ripple > 0.0 && ripple < 0.01);
// NOLA holds with a wide margin, so istft is exact regardless.
assert!(sum_w2.iter().copied().fold(f64::MAX, f64::min) > 1.0);
let doc = params.explain();
assert!((doc.quantity("Overlap-add ripple").unwrap().value - ripple).abs() < 1e-6);

Ask the library to explain

StftParams implements Explain. Through a signal (ExplainFor) it receives the sample rate and length; given the expected pitch range as well, it warns when the window is too short for the lowest expected f0:

use audio_samples::educational::{Explain, ExplainContext, ExplainFor, WarningLevel};
use audio_samples::{nzu, sample_rate, sine_wave};
use spectrograms::{StftParams, WindowType};
use std::num::NonZeroUsize;
use std::time::Duration;

let speech_like = sine_wave::<f64>(120.0, Duration::from_secs(1), sample_rate!(16000), 0.5);
let params = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, true).unwrap();
let doc = speech_like.explain(&params);
assert_eq!(doc.quantity("Frequency resolution").unwrap().value, 31.25); // Hz
assert_eq!(doc.quantity("Frame period").unwrap().value, 8.0);           // ms
assert_eq!(doc.quantity("Frames").unwrap().value, 126.0);

// f0 between 80 and 400 Hz: two periods of 80 Hz last 25 ms.
for (n, short, coarse) in [(1024, false, false), (256, true, false), (128, true, true)] {
    let p = StftParams::new(NonZeroUsize::new(n).unwrap(), NonZeroUsize::new(n / 4).unwrap(),
                            WindowType::Hanning, true).unwrap();
    let ctx = ExplainContext::for_audio(&speech_like).with_f0_range(80.0, 400.0);
    let d = p.explain_with(&ctx);
    // 16 ms (N = 256) and 8 ms (N = 128) windows are shorter than 25 ms ...
    assert_eq!(d.has_warning_containing("shorter than two periods"), short);
    // ... and at N = 128 the 125 Hz bins are coarser than 80 Hz.
    assert_eq!(d.has_warning_containing("coarser than the lowest expected f0"), coarse);
    assert_eq!(d.has_warning(WarningLevel::Caution), short || coarse);
}
println!("{doc}");

Exercises

  1. How many frames does stft produce for 2.5 s of audio at 22.05 kHz with , and centring? Predict, then check.
  2. At 16 kHz, one frame is required every 10 ms. Choose , then the smallest power-of-two for each of two requirements: (a) a bin spacing of at most 20 Hz; (b) a Hann main lobe ( dB width about , the actual resolution) of at most 20 Hz. Confirm (a) with the explainer.
  3. A signal is 0.5 s of a full-scale 1 kHz sine followed by 0.5 s of silence. With LogParams::new(-100.0), what value do the bins of the last frame take, and how far below the spectrogram’s peak is that?

Answers

use audio_samples::educational::ExplainContext;
use audio_samples::educational::Explain;
use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{LogParams, SpectrogramParams, StftParams, WindowType};
use std::time::Duration;

// 1. L = 55 125; 1 + floor((55 125 + 2*1024 - 2048) / 512) = 1 + 107 = 108.
let l = 55_125usize;
assert_eq!(1 + (l + 2 * 1024 - 2048) / 512, 108);
let x = sine_wave::<f64>(440.0, Duration::from_millis(2500), sample_rate!(22050), 0.5);
assert_eq!(x.samples_per_channel().get(), l);
let p = StftParams::new(nzu!(2048), nzu!(512), WindowType::Hanning, true).unwrap();
assert_eq!(x.stft(&p).unwrap().data.ncols(), 108);

// 2. H = 0.010 * 16 000 = 160.
//    (a) bin spacing: N >= 16 000 / 20 = 800, next power of two 1024.
//    (b) main lobe:   2 * 16 000 / N <= 20, so N >= 1600, next power of two 2048.
let h = (0.010f64 * 16_000.0) as usize;
let n = ((16_000.0f64 / 20.0).ceil() as usize).next_power_of_two();
let n_lobe = ((2.0 * 16_000.0f64 / 20.0).ceil() as usize).next_power_of_two();
assert_eq!((h, n, n_lobe), (160, 1024, 2048));
let p = StftParams::new(nzu!(1024), nzu!(160), WindowType::Hanning, true).unwrap();
let d = p.explain_with(&ExplainContext::new().with_sample_rate(16_000.0));
assert_eq!(d.quantity("Frame period").unwrap().value, 10.0);
assert_eq!(d.quantity("Frequency resolution").unwrap().value, 15.625); // bin spacing
// (b) The explainer's measured -6 dB main-lobe width: too wide at N = 1024,
//     narrow enough at N = 2048 (about 2 bins in both cases).
let lobe = |n: usize| {
    let p = StftParams::new(std::num::NonZeroUsize::new(n).unwrap(), nzu!(160), WindowType::Hanning, true).unwrap();
    p.explain_with(&ExplainContext::new().with_sample_rate(16_000.0))
        .quantity("Main-lobe width (-6 dB)").unwrap().value
};
assert!(lobe(1024) > 20.0 && lobe(2048) <= 20.0);

// 3. -100 dB re 1, which is 100 + 42.13 = 142.13 dB below the peak.
let mut v = sine_wave::<f64>(1000.0, Duration::from_millis(500), sample_rate!(16000), 1.0)
    .as_slice().unwrap().to_vec();
v.extend(std::iter::repeat_n(0.0, 8000));
let a = AudioSamples::new_mono(ndarray::Array1::from(v), sample_rate!(16000)).unwrap();
let p = StftParams::new(nzu!(512), nzu!(128), WindowType::Hanning, true).unwrap();
let sp = SpectrogramParams::new(p, 16_000.0).unwrap();
let s = a.linear_db_spectrogram(&sp, &LogParams::new(-100.0).unwrap()).unwrap();
let last = s.data().ncols() - 1;
assert!(s.data().column(last).iter().all(|&db| (db + 100.0).abs() < 1e-9));
let peak = s.data().iter().copied().fold(f64::MIN, f64::max);
assert!((s.data()[[0, last]] - peak + 142.13).abs() < 0.01);

Common pitfalls

  • Centring pads with zeros. Tools that pad by reflection give different first and last frames.
  • The window is the symmetric Hann; many tools use the periodic one by default. Values differ slightly unless both use the same window.
  • dB values are re 1 with an absolute floor; there is no top_db. Subtract the maximum to get “dB below peak”.
  • Power is with no or window normalisation: a full-scale sine reads about dB at , and the number grows with .
  • istft can return up to samples fewer than the input; trim or pad.
  • A smaller hop does not improve resolution; only (and the window shape) sets it.

References

  • J. B. Allen and L. R. Rabiner, “A unified approach to short-time Fourier analysis and synthesis”, Proceedings of the IEEE 65(11), 1558-1564, 1977.
  • D. W. Griffin and J. S. Lim, “Signal estimation from modified short-time Fourier transform”, IEEE Transactions on Acoustics, Speech, and Signal Processing 32(2), 236-243, 1984.
  • F. J. Harris, “On the use of windows for harmonic analysis with the discrete Fourier transform”, Proceedings of the IEEE 66(1), 51-83, 1978.
  • B. McFee et al., “librosa: audio and music signal analysis in Python”, Proceedings of the 14th Python in Science Conference, 2015.

See also

05. Convolution and FIR filters

A finite impulse response (FIR) filter replaces each sample by a weighted sum of the most recent input samples. This operation, convolution, smooths noisy envelopes, removes hum, band-limits a signal before downsampling, simulates a room from its impulse response, and implements the pre-emphasis step of every speech front end. This chapter defines convolution precisely, shows the two output lengths the crate returns, and connects a filter’s taps to its frequency response and delay, ending with a low-pass filter designed from scratch.

Concept

Convolution. For an input of samples and taps , :

where is the output sample index, the tap index, the number of taps and outside the signal. The full convolution has samples (). The valid part, where every term of the sum uses a real input sample, has samples ().

Impulse response. Feeding the unit impulse (1 at , 0 elsewhere) returns : the taps are the impulse response.

Frequency response. A complex exponential at angular frequency (radians per sample, in Hz, the sample rate in Hz) is multiplied by

where (as in chapter 03; no formula in this chapter uses as an index). A sine of amplitude at the input therefore has amplitude at the output, shifted by the phase . For the -tap moving average this sums to the Dirichlet kernel

with nulls at every multiple of Hz (except 0).

Linear phase and group delay. The group delay

is the delay in samples of a narrow-band signal at . If the taps are symmetric, , the phase is exactly (plus jumps of where changes sign), so every frequency is delayed by the same samples and waveform shapes are preserved. Antisymmetric taps, , give the same constant delay with an extra phase shift. Other asymmetric taps delay different frequencies by different amounts.

The four linear-phase types combine the symmetry with the parity of . Each symmetry forces zeros of at (DC) or (Nyquist), which rules out some filter shapes:

TypeTapsLength Forced zerosCannot be
Isymmetricoddnone(any shape is possible)
IIsymmetriceven (Nyquist)high-pass, band-stop
IIIantisymmetricodd and low-pass, high-pass
IVantisymmetriceven (DC)low-pass

Types III and IV are used for differentiators and Hilbert transformers.

Windowed-sinc design. The ideal low-pass with cutoff Hz has the infinitely long impulse response , with . Truncate it to taps centred on , multiply by a window (Hamming here) to reduce the ripple that truncation causes, and scale so that (unit gain at DC):

where is the normalising constant. The response passes through about 0.5 ( dB) at , and the transition band narrows as grows. A Hamming design gives a stop-band attenuation of about 53 dB whatever is (the lab finds its first stop-band lobe at dB); do not confuse this with the Hamming window’s own peak side lobe, dB (chapter 03).

Impulse response of the chapter's 63-tap Hamming windowed-sinc low-pass (2 kHz cutoff at 16 kHz), obtained by convolving a unit impulse with convolve. The taps are symmetric about tap 31, the group delay that topics::fir reports.
Figure 5.1. Impulse response of the chapter's 63-tap Hamming windowed-sinc low-pass (2 kHz cutoff at 16 kHz), obtained by convolving a unit impulse with convolve. The taps are symmetric about tap 31, the group delay that topics::fir reports.

With the library

AudioTransforms::convolve returns the full convolution; AudioProcessing::apply_filter returns the valid part.

use audio_samples::educational::topics;
use audio_samples::{AudioProcessing, AudioSamples, AudioTransforms, sample_rate};
use non_empty_slice::NonEmptySlice;

let mono = |v: Vec<f64>| AudioSamples::new_mono(ndarray::Array1::from(v), sample_rate!(16000)).unwrap();
let x: Vec<f64> = (0..1000).map(|n| (0.05 * n as f64).sin()).collect();
let h = vec![1.0 / 31.0; 31]; // 31-tap moving average

let full = mono(x.clone()).convolve(&mono(h.clone())).unwrap();
let valid = mono(x.clone()).apply_filter(NonEmptySlice::new(&h).unwrap()).unwrap();
assert_eq!(full.samples_per_channel().get(), 1030);  // N + M - 1
assert_eq!(valid.samples_per_channel().get(), 970);  // N - M + 1
// The valid part is the full convolution from index M - 1 to N - 1.
let (f, v) = (full.as_slice().unwrap(), valid.as_slice().unwrap());
assert!(f[30..1000].iter().zip(v).all(|(a, b)| (a - b).abs() < 1e-12));

// An impulse as input returns the taps.
let mut delta = vec![0.0; 64];
delta[0] = 1.0;
let ir = mono(delta).convolve(&mono(h.clone())).unwrap();
assert!(ir.as_slice().unwrap()[..31].iter().zip(&h).all(|(a, b)| (a - b).abs() < 1e-12));

// The explainer classifies the taps and reports their delay.
let doc = topics::fir(&h, 16_000.0);
assert_eq!(doc.quantity("Group delay").unwrap().value, 15.0); // (31 - 1) / 2
assert!((doc.quantity("DC gain").unwrap().value - 1.0).abs() < 1e-12);

The moving-average response, measured by filtering sines. One second of output ( samples) holds a whole number of cycles of each test tone, so projecting the output on and recovers its amplitude exactly:

use audio_samples::{AudioProcessing, AudioSamples};
use non_empty_slice::NonEmptySlice;
use std::f64::consts::PI;

fn measured_gain(h: &[f64], f: f64, fs: f64) -> f64 {
    let len = fs as usize + h.len() - 1; // so the valid output is exactly fs samples
    let x: Vec<f64> = (0..len).map(|n| (2.0 * PI * f * n as f64 / fs).sin()).collect();
    let sr = std::num::NonZeroU32::new(fs as u32).unwrap();
    let y = AudioSamples::new_mono(ndarray::Array1::from(x), sr).unwrap()
        .apply_filter(NonEmptySlice::new(h).unwrap()).unwrap();
    let (mut s, mut c) = (0.0, 0.0);
    for (i, &v) in y.as_slice().unwrap().iter().enumerate() {
        let phi = 2.0 * PI * f * i as f64 / fs;
        s += v * phi.sin();
        c += v * phi.cos();
    }
    2.0 / fs * (s * s + c * c).sqrt()
}

let ma = vec![1.0 / 8.0; 8];
let fs = 8_000.0;
for (f, expected) in [(250.0, 0.901764), (500.0, 0.640729), (750.0, 0.304489), (1500.0, 0.224994)] {
    let u = PI * f / fs;
    let dirichlet = ((8.0 * u).sin() / (8.0 * u.sin())).abs();
    let measured = measured_gain(&ma, f, fs);
    assert!((measured - dirichlet).abs() < 1e-9); // exact up to rounding
    assert!((measured - expected).abs() < 1e-6);
}
// Nulls at multiples of fs / M = 1000 Hz.
for f in [1000.0, 2000.0, 3000.0] {
    assert!(measured_gain(&ma, f, fs) < 1e-9);
}

How it works

The convolution sum, a group-delay calculation, and the delay seen in the time domain, all for a 63-tap windowed-sinc low-pass ( kHz, kHz) designed here, since the crate has no FIR designer:

use audio_samples::{AudioProcessing, AudioSamples, sample_rate};
use non_empty_slice::NonEmptySlice;
use num_complex::Complex;
use spectrograms::{WindowType, make_window};
use std::f64::consts::PI;
use std::num::NonZeroUsize;

fn windowed_sinc(m: usize, fc: f64, fs: f64) -> Vec<f64> {
    let w = make_window::<f64>(WindowType::Hamming, NonZeroUsize::new(m).unwrap());
    let wc = 2.0 * fc / fs;
    let centre = (m - 1) as f64 / 2.0;
    let mut h: Vec<f64> = (0..m).map(|n| {
        let t = n as f64 - centre;
        let sinc = if t == 0.0 { 1.0 } else { (PI * wc * t).sin() / (PI * wc * t) };
        wc * sinc * w[n]
    }).collect();
    let dc: f64 = h.iter().sum();
    h.iter_mut().for_each(|v| *v /= dc);
    h
}
fn convolve_full(x: &[f64], h: &[f64]) -> Vec<f64> {
    let mut y = vec![0.0; x.len() + h.len() - 1];
    for (n, yn) in y.iter_mut().enumerate() {
        for (j, &hj) in h.iter().enumerate() {
            if n >= j && n - j < x.len() { *yn += hj * x[n - j]; }
        }
    }
    y
}
fn group_delay(h: &[f64], omega: f64) -> f64 {
    let num: Complex<f64> = h.iter().enumerate()
        .map(|(j, &c)| Complex::from_polar(j as f64 * c, -omega * j as f64)).sum();
    let den: Complex<f64> = h.iter().enumerate()
        .map(|(j, &c)| Complex::from_polar(c, -omega * j as f64)).sum();
    (num / den).re
}

let lp = windowed_sinc(63, 2000.0, 16_000.0);
assert!((0..31).all(|j| (lp[j] - lp[62 - j]).abs() < 1e-15)); // symmetric (to rounding)

// Direct sum versus apply_filter: the same numbers up to the last bits of
// rounding (below 160 taps apply_filter also sums directly, in another order).
let x: Vec<f64> = (0..1000).map(|n| (0.05 * n as f64).sin() + 0.3 * (0.71 * n as f64).cos()).collect();
let full = convolve_full(&x, &lp);
let y = AudioSamples::new_mono(ndarray::Array1::from(x), sample_rate!(16000)).unwrap()
    .apply_filter(NonEmptySlice::new(&lp).unwrap()).unwrap();
assert!(full[62..1000].iter().zip(y.as_slice().unwrap()).all(|(a, b)| (a - b).abs() < 1e-12));

// Linear phase: 31 samples of delay at every passband frequency ...
for f in [100.0, 500.0, 1000.0, 1500.0] {
    assert!((group_delay(&lp, 2.0 * PI * f / 16_000.0) - 31.0).abs() < 1e-9);
}
// ... but not for asymmetric taps: 0.7 samples at DC, 0.25 at Nyquist.
let skew = [0.5, 0.3, 0.2];
assert!((group_delay(&skew, 0.0) - 0.7).abs() < 1e-12);
assert!((group_delay(&skew, PI) - 0.25).abs() < 1e-12);

// Measured with a delayed impulse: impulse at n = 100 -> peak at 100 + 31.
let mut d = vec![0.0; 400];
d[100] = 1.0;
let resp = convolve_full(&d, &lp);
let peak = (0..resp.len()).max_by(|&a, &b| resp[a].total_cmp(&resp[b])).unwrap();
assert_eq!(peak, 131);
// apply_filter's output index i is time i + M - 1, so the same peak is at 131 - 62.
let yv = AudioSamples::new_mono(ndarray::Array1::from(d), sample_rate!(16000)).unwrap()
    .apply_filter(NonEmptySlice::new(&lp).unwrap()).unwrap();
let yv = yv.as_slice().unwrap();
assert_eq!((0..yv.len()).max_by(|&a, &b| yv[a].total_cmp(&yv[b])).unwrap(), 69);

// And with a smooth pulse: its centroid moves by exactly (M - 1)/2 = 31.
let pulse: Vec<f64> = (0..400).map(|n| (-((n as f64 - 150.0) / 12.0).powi(2) / 2.0).exp()).collect();
let centroid = |v: &[f64]| v.iter().enumerate().map(|(n, a)| n as f64 * a).sum::<f64>() / v.iter().sum::<f64>();
assert!((centroid(&convolve_full(&pulse, &lp)) - centroid(&pulse) - 31.0).abs() < 1e-9);

// The magnitude response, evaluated from the taps (the DTFT).
let gain = |f: f64| -> f64 {
    let om = 2.0 * PI * f / 16_000.0;
    lp.iter().enumerate().map(|(j, &c)| Complex::from_polar(c, -om * j as f64)).sum::<Complex<f64>>().norm()
};
let db = |g: f64| 20.0 * g.log10();
for f in [500.0, 1000.0, 1500.0] {
    assert!(db(gain(f)).abs() < 0.05);      // pass band flat to 0.05 dB (max 0.03 dB)
}
assert!((gain(2000.0) - 0.5005).abs() < 1e-4); // -6.01 dB at the cutoff
for f in [3000.0, 4000.0, 6000.0] {
    assert!(db(gain(f)) < -59.0);           // stop band below -59 dB from 3 kHz
}
A Gaussian pulse filtered by the 63-tap low-pass. The full convolution (convolve) has the same shape, delayed by exactly (M - 1)/2 = 31 samples; apply_filter returns its valid part, which starts at index M - 1 = 62.
Figure 5.2. A Gaussian pulse filtered by the 63-tap low-pass. The full convolution (convolve) has the same shape, delayed by exactly (M - 1)/2 = 31 samples; apply_filter returns its valid part, which starts at index M - 1 = 62.
Magnitude responses measured by filtering sines with apply_filter (dots) against the responses computed from the taps (lines). Top: the 63-tap low-pass, -6 dB at its 2 kHz cutoff and below -59 dB from 3 kHz. Bottom: the 8-tap moving average at 8 kHz, which follows the Dirichlet kernel with nulls at multiples of 1 kHz.
Figure 5.3. Magnitude responses measured by filtering sines with apply_filter (dots) against the responses computed from the taps (lines). Top: the 63-tap low-pass, -6 dB at its 2 kHz cutoff and below -59 dB from 3 kHz. Bottom: the 8-tap moving average at 8 kHz, which follows the Dirichlet kernel with nulls at multiples of 1 kHz.

Long filters are computed differently: from 160 taps up, apply_filter convolves by FFT. The lab checks that a 201-tap design agrees with the direct sum to better than .

Ask the library to explain

topics::fir classifies the taps (linear-phase types I-IV), reports the group delay, DC and Nyquist gains and a small response table, and notes when apply_filter will use FFT convolution:

use audio_samples::educational::topics;

let ma = topics::fir(&[0.2; 5], 16_000.0);
assert_eq!(ma.quantity("Taps").unwrap().value, 5.0);
assert_eq!(ma.quantity("Group delay").unwrap().value, 2.0);                         // samples
assert!((ma.quantity("Group delay (time)").unwrap().value - 0.125).abs() < 1e-12); // ms
assert!(ma.has_warning_containing("type I"));

// Even length and symmetric: type II, forced zero at Nyquist.
let t2 = topics::fir(&[0.25; 4], 16_000.0);
assert!(t2.has_warning_containing("type II"));
assert!(t2.quantity("Nyquist gain").unwrap().value.abs() < 1e-12);

// Asymmetric taps: no constant group delay, only its value at DC.
let skew = topics::fir(&[0.5, 0.3, 0.2], 16_000.0);
assert!(skew.quantity("Group delay").is_none());
assert!((skew.quantity("Group delay at DC").unwrap().value - 0.7).abs() < 1e-12);

// Antisymmetric taps: type III (odd length) and type IV (even length, zero at DC).
assert!(topics::fir(&[1.0, 0.0, -1.0], 16_000.0).has_warning_containing("type III"));
let t4 = topics::fir(&[1.0, -1.0], 16_000.0);
assert!(t4.has_warning_containing("type IV") && t4.quantity("DC gain").unwrap().value == 0.0);

let long = topics::fir(&[1.0 / 200.0; 200], 16_000.0);
assert!(long.has_warning_containing("FFT convolution"));
println!("{ma}");

Exercises

  1. Where are the nulls of a 5-tap moving average at kHz? Check two of them by filtering sines.
  2. 1 s of 16 kHz audio is low-pass filtered with the 63-tap filter above using apply_filter. How many output samples are there, and which input sample is output sample aligned with? Check with a 100 Hz sine.
  3. Spectral inversion: turns the low-pass into a high-pass. Predict its gain at DC, at the 2 kHz cutoff and at 6 kHz, then measure.

Answers

use audio_samples::educational::topics;
use audio_samples::{AudioProcessing, AudioSamples};
use non_empty_slice::NonEmptySlice;
use num_complex::Complex;
use spectrograms::{WindowType, make_window};
use std::f64::consts::PI;
use std::num::NonZeroUsize;

fn windowed_sinc(m: usize, fc: f64, fs: f64) -> Vec<f64> {
    let w = make_window::<f64>(WindowType::Hamming, NonZeroUsize::new(m).unwrap());
    let wc = 2.0 * fc / fs;
    let centre = (m - 1) as f64 / 2.0;
    let mut h: Vec<f64> = (0..m).map(|n| {
        let t = n as f64 - centre;
        let sinc = if t == 0.0 { 1.0 } else { (PI * wc * t).sin() / (PI * wc * t) };
        wc * sinc * w[n]
    }).collect();
    let dc: f64 = h.iter().sum();
    h.iter_mut().for_each(|v| *v /= dc);
    h
}
fn filter(x: Vec<f64>, h: &[f64], fs: u32) -> Vec<f64> {
    let sr = std::num::NonZeroU32::new(fs).unwrap();
    AudioSamples::new_mono(ndarray::Array1::from(x), sr).unwrap()
        .apply_filter(NonEmptySlice::new(h).unwrap()).unwrap().as_slice().unwrap().to_vec()
}
let sine = |f: f64, fs: f64, len: usize| -> Vec<f64> {
    (0..len).map(|n| (2.0 * PI * f * n as f64 / fs).sin()).collect()
};
let gain = |h: &[f64], f: f64, fs: f64| -> f64 {
    let om = 2.0 * PI * f / fs;
    h.iter().enumerate().map(|(j, &c)| Complex::from_polar(c, -om * j as f64)).sum::<Complex<f64>>().norm()
};

// 1. Multiples of fs / M = 2000 Hz: 2000 and 4000 Hz (below Nyquist).
let ma = [0.2; 5];
for f in [2000.0, 4000.0] {
    let y = filter(sine(f, 10_000.0, 10_004), &ma, 10_000); // 10 000 outputs
    assert!(y.iter().map(|v| v.abs()).fold(0.0, f64::max) < 1e-12);
}
assert!(gain(&ma, 1000.0, 10_000.0) > 0.5); // but not in between

// 2. 16 000 - 62 = 15 938 samples. Output i is the causal output at time
//    i + 62, which lags the input by 31: so y[i] lines up with x[i + 31].
let lp = windowed_sinc(63, 2000.0, 16_000.0);
let x = sine(100.0, 16_000.0, 16_000);
let y = filter(x.clone(), &lp, 16_000);
assert_eq!(y.len(), 15_938);
// At 100 Hz the gain is 1.0012 (pass-band ripple), so the aligned samples
// agree to about 1.2e-3 of the amplitude.
assert!((gain(&lp, 100.0, 16_000.0) - 1.0012).abs() < 1e-4);
assert!(y.iter().enumerate().all(|(i, v)| (v - x[i + 31]).abs() < 2e-3));

// 3. DC: 1 - 1 = 0. Cutoff: |1 - 0.5| = 0.5 (both terms share the same linear
//    phase, so the magnitudes subtract). 6 kHz: 1 - (almost 0) = 1.
let mut hp: Vec<f64> = lp.iter().map(|v| -v).collect();
hp[31] += 1.0;
assert!(gain(&hp, 0.0, 16_000.0) < 1e-12);
assert!((gain(&hp, 2000.0, 16_000.0) - 0.5).abs() < 0.01);
assert!((gain(&hp, 6000.0, 16_000.0) - 1.0).abs() < 1e-3);
let doc = topics::fir(&hp, 16_000.0);
assert!(doc.has_warning_containing("type I") && doc.quantity("Group delay").unwrap().value == 31.0);

Common pitfalls

  • apply_filter returns the valid part: samples shorter, and output belongs to input time . It is not delay-compensated; a linear-phase filter still lags by on top. convolve returns the full convolution.
  • For integer sample types, apply_filter interprets the taps on the normalised scale too (an i16 tap of 16384 means about 0.5); filter a float signal to avoid this.
  • convolve needs both signals mono and of the same sample type.
  • Even-length symmetric filters (type II) always have a zero at Nyquist and cannot be high-pass; spectral inversion needs an odd length.
  • A windowed sinc is dB (not dB) at its design cutoff.
  • A causal filter routine that returns one output per input sample gives more samples at the start than apply_filter. Drop its first samples before comparing.

References

  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010. Linear-phase FIR types and window design.
  • F. J. Harris, “On the use of windows for harmonic analysis with the discrete Fourier transform”, Proceedings of the IEEE 66(1), 51-83, 1978.

See also

06. IIR filters: design, poles, zeros and stability

A telephone channel band-limits speech, a notch filter removes 50 Hz mains hum, a de-emphasis filter undoes the pre-emphasis of chapter 08 after synthesis: all are recursive (infinite impulse response, IIR) filters. (Pre-emphasis itself, , has no feedback: it is an FIR filter.) IIR filters achieve a steep roll-off with few coefficients, but their output is fed back into their input, so they can ring, distort phase and become unstable. This chapter designs a Butterworth filter the way the library does, finds its poles, checks stability and the frequency response numerically, and ends the “With the library” section with a 50 Hz hum notch.

Concept

Difference equation. An IIR filter computes each output sample from the current and past inputs and past outputs:

where and are the input and output samples (dimensionless), are the feed-forward coefficients, the feedback coefficients (with ), and , the numerator and denominator orders.

Transfer function. Taking the z-transform turns delays into powers of :

where is a complex variable. The roots of are the zeros and the roots of are the poles. The frequency response is on the unit circle, with , where is the frequency in Hz and the sample rate in Hz.

Stability. A causal filter is bounded-input bounded-output stable if and only if every pole satisfies (the poles of in lowest terms, after cancelling any factor common to and ). A pole at radius contributes a term to the impulse response, so the closer is to 1, the longer the filter rings.

Butterworth prototype. The analogue Butterworth low-pass of order has the maximally flat magnitude

where is the analogue angular frequency in rad/s and the cutoff in rad/s. At the power is halved: dB. Its poles lie on a circle of radius in the left half of the s-plane:

Bilinear transform with pre-warping. The digital filter is obtained by substituting

where is a positive constant (rad/s). The usual choice is ; the library designs with normalised to 2 (so ), and every choice of gives the same once the cutoff is pre-warped. The substitution maps the whole axis onto the unit circle, with , so frequencies are compressed near Nyquist. To place the digital cutoff exactly at (Hz) the analogue cutoff is pre-warped:

Each analogue pole maps to , and the zeros at map to (Nyquist). Combining the two formulas gives a closed form for the digital Butterworth magnitude:

Second-order sections (SOS). A high-order is numerically ill-conditioned: small coefficient errors move the poles a long way. The library therefore factors into a cascade of biquads,

where is the number of sections and each row is stored as a row [b0, b1, b2, a0, a1, a2] with a0 = 1.

Chebyshev type I gives a steeper roll-off than Butterworth at the cost of ripple in the pass band. Its analogue magnitude is

where is the pass-band ripple in dB, the (dimensionless) ripple factor and the Chebyshev polynomial of order : for , which oscillates between and , and for , which grows like . So the pass band ripples between 0 and dB, and at () the gain is dB rather than dB. At DC, is for even (gain dB) and 0 for odd (gain 0 dB). As for the Butterworth, the bilinear transform with pre-warping turns into .

Zero-phase filtering. Running the filter forwards and then backwards (filtfilt) gives the overall response with zero phase: no delay, twice the attenuation in dB (so dB at a Butterworth cutoff), and a non-causal filter (it needs the whole signal).

The library’s design pipeline (src/operations/iir_design.rs) runs these steps in order: analogue prototype → frequency transform (lp2lp_zpk and its high-pass and band variants) → bilinear_zpk → zpk2sos, and tests/filter_reference.rs checks its coefficients and responses against golden reference fixtures.

With the library

Design a 4th-order Butterworth low-pass at 1 kHz for 16 kHz audio, inspect the sections, and measure the response with IirFilterDesign::frequency_response.

use audio_samples::nzu;
use audio_samples::operations::types::IirFilterDesign;
use std::f64::consts::PI;

let (fs, fc) = (16_000.0, 1_000.0);
let design = IirFilterDesign::butterworth_lowpass(nzu!(4), fc);
let sos = design.sos_coefficients(fs).unwrap();
assert_eq!(sos.len(), 2); // N = 4 -> two biquads

let probes = [0.0, fc, 2.0 * fc, 4.0 * fc];
let (mag, _phase) = design.frequency_response(&probes, fs).unwrap();
let db: Vec<f64> = mag.iter().map(|m| 20.0 * m.log10()).collect();
// 0 dB at DC and -3.0103 dB at the cutoff (1e-4 dB allows for rounding).
assert!(db[0].abs() < 1e-9);
assert!((db[1] + 3.0103).abs() < 1e-4);
// One octave up the filter is 25.5 dB down, two octaves up 56.1 dB down.
assert!((db[2] + 25.5).abs() < 0.05);
assert!((db[3] + 56.1).abs() < 0.05);

// The closed-form digital Butterworth magnitude matches to 1e-12.
for (&f, &m) in probes.iter().zip(&mag) {
    let r = (PI * f / fs).tan() / (PI * fc / fs).tan();
    assert!((m - 1.0 / (1.0 + r.powi(8)).sqrt()).abs() < 1e-12);
}

One octave above the cutoff the digital filter attenuates more (25.5 dB) than the analogue prototype ( dB), because the bilinear transform compresses the frequency axis towards Nyquist.

Magnitude responses from IirFilterDesign::frequency_response at 16 kHz, cutoff 1 kHz. Both Butterworth filters are -3.01 dB at the cutoff; at 2 kHz the 4th order is 25.5 dB down, the 8th order 51.0 dB and the 4th-order Chebyshev I (1 dB ripple) 35.5 dB. The lower panel enlarges the pass band, where the Chebyshev ripples between 0 and -1 dB.
Figure 6.1. Magnitude responses from IirFilterDesign::frequency_response at 16 kHz, cutoff 1 kHz. Both Butterworth filters are -3.01 dB at the cutoff; at 2 kHz the 4th order is 25.5 dB down, the 8th order 51.0 dB and the 4th-order Chebyshev I (1 dB ripple) 35.5 dB. The lower panel enlarges the pass band, where the Chebyshev ripples between 0 and -1 dB.

Apply it to a signal with AudioIirFiltering::apply_iir_filter (causal) or AudioIirFiltering::filtfilt (zero phase). For a 1 kHz tone the causal filter attenuates by 3.01 dB and shifts the tone by half a period, 8 samples (a 4th-order Butterworth has of phase at its cutoff); filtfilt attenuates by 6.02 dB and does not delay. Half a period is the phase delay . The group delay of chapter 05, the delay of the envelope of a narrow-band signal, is larger there: 9.66 samples. The two differ because IIR phase is not linear in frequency.

use audio_samples::operations::types::IirFilterDesign;
use audio_samples::{AudioIirFiltering, nzu, sample_rate, sine_wave};
use std::time::Duration;

let design = IirFilterDesign::butterworth_lowpass(nzu!(4), 1_000.0);
let tone = sine_wave::<f64>(1_000.0, Duration::from_millis(500), sample_rate!(16000), 1.0);
let once = tone.apply_iir_filter(&design).unwrap();
let twice = tone.filtfilt(&design).unwrap();
let (t, o, w) = (
    tone.as_slice().unwrap(),
    once.as_slice().unwrap(),
    twice.as_slice().unwrap(),
);

// Measure the middle of the signal, away from start-up and end transients.
let mid = 2_000..6_000;
let amp_db = |v: &[f64]| 20.0 * v[mid.clone()].iter().fold(0.0f64, |a, x| a.max(x.abs())).log10();
let corr = |v: &[f64], lag: usize| -> f64 { mid.clone().map(|n| v[n] * t[n - lag]).sum() };
let lag = |v: &[f64]| (0..16).max_by(|&a, &b| corr(v, a).total_cmp(&corr(v, b))).unwrap();

// Peak-picking a sampled sine can miss the true peak by 1 - cos(pi fc/fs)
// = 1.9 % (0.17 dB), so 0.2 dB is the tolerance.
assert!((amp_db(o) + 3.01).abs() < 0.2);
assert!((amp_db(w) + 6.02).abs() < 0.2);
assert_eq!(lag(o), 8); // half of the 16-sample period: -180 degrees
assert_eq!(lag(w), 0); // zero phase

// Group delay at 1 kHz, -d(arg H)/d(omega), by a central difference on the
// design's response. The ratio H(f + d) / H(f - d) avoids phase wrapping;
// a 0.01 Hz step makes the difference error negligible (< 1e-6 samples).
let (fs, d) = (16_000.0, 0.01);
let (m, ph) = design.frequency_response(&[1_000.0 - d, 1_000.0 + d], fs).unwrap();
let h = |i: usize| num_complex::Complex64::from_polar(m[i], ph[i]);
let group_delay = -(h(1) / h(0)).arg() / (2.0 * std::f64::consts::PI * 2.0 * d / fs);
assert!((group_delay - 9.66).abs() < 0.01); // samples, versus a phase delay of 8
Phase response (top) and delay (bottom) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, from IirFilterDesign::frequency_response. At the cutoff the phase is -180 degrees, a phase delay of 8 samples, while the group delay there is 9.66 samples: IIR phase is not linear in frequency.
Figure 6.2. Phase response (top) and delay (bottom) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, from IirFilterDesign::frequency_response. At the cutoff the phase is -180 degrees, a phase delay of 8 samples, while the group delay there is 9.66 samples: IIR phase is not linear in frequency.

A 50 Hz hum notch. Mains hum is a narrow-band tone; removing it requires a filter with a zero exactly on the unit circle at and poles just inside it at the same angle, so that the gain returns to unity within a few hertz of . That is the band-stop biquad of the RBJ Audio EQ Cookbook (Bristow-Johnson), available as EqBand::band_stop:

where is the notch frequency in Hz and (dimensionless) is divided by the dB bandwidth in Hz. The poles have radius , and the closer is to 1, the narrower the notch and the longer it takes to settle (time constant about samples).

use audio_samples::operations::types::EqBand;
use audio_samples::{AudioParametricEq, AudioSamples, sample_rate, sine_wave};
use num_complex::Complex64;
use std::f64::consts::PI;
use std::time::Duration;

let (fs, f0, q) = (16_000.0, 50.0, 10.0);

// The cookbook coefficients, evaluated on the unit circle.
let w0 = 2.0 * PI * f0 / fs;
let alpha = w0.sin() / (2.0 * q);
let (b, a) = ([1.0, -2.0 * w0.cos(), 1.0], [1.0 + alpha, -2.0 * w0.cos(), 1.0 - alpha]);
let gain = |f: f64| {
    let z1 = Complex64::from_polar(1.0, -2.0 * PI * f / fs); // z^-1
    ((b[0] + b[1] * z1 + b[2] * z1 * z1) / (a[0] + a[1] * z1 + a[2] * z1 * z1)).norm()
};
// An exact zero: |H(f0)| is 0 up to rounding (a 1e-16 numerator divided by a
// denominator of only 2 alpha sin(w0) = 4e-5, hence 1e-9).
assert!(gain(f0) < 1e-9);
// The -3 dB edges (|H|^2 = 1/2), found by bisection on each side of f0.
let edge = |mut lo: f64, mut hi: f64, rising: bool| {
    for _ in 0..60 {
        let mid = 0.5 * (lo + hi);
        if (gain(mid).powi(2) < 0.5) == rising { lo = mid } else { hi = mid }
    }
    0.5 * (lo + hi)
};
let bandwidth = edge(f0, 2.0 * f0, true) - edge(1.0, f0, false);
assert!((bandwidth - f0 / q).abs() < 0.01); // 5 Hz wide, as Q = 10 specifies
let r = ((1.0 - alpha) / (1.0 + alpha)).sqrt();
assert!((1.0 / (1.0 - r) - 1019.0).abs() < 1.0); // about 1019 samples = 64 ms to settle

// Apply it to 50 Hz hum plus a 1 kHz tone (in place of speech), 2 s long.
let dur = Duration::from_secs(2);
let hum = sine_wave::<f64>(50.0, dur, sample_rate!(16000), 0.5);
let tone = sine_wave::<f64>(1_000.0, dur, sample_rate!(16000), 0.5);
let mix: Vec<f64> = hum.as_slice().unwrap().iter().zip(tone.as_slice().unwrap()).map(|(p, q)| p + q).collect();
let mix = AudioSamples::new_mono(ndarray::Array1::from(mix), sample_rate!(16000)).unwrap();
let out = mix.apply_eq_band(&EqBand::band_stop(f0, q)).unwrap();

// Measure in the second half, after the notch has settled (16 time constants).
// 16 000 samples hold whole periods of both tones, so one DFT bin each is exact.
let tail = &out.as_slice().unwrap()[16_000..];
let amplitude = |f: f64| {
    let (re, im) = tail.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
        let ph = 2.0 * PI * f * n as f64 / fs;
        (re + v * ph.cos(), im - v * ph.sin())
    });
    2.0 * (re * re + im * im).sqrt() / tail.len() as f64
};
let hum_db = 20.0 * (amplitude(50.0) / 0.5).log10();
let tone_db = 20.0 * (amplitude(1_000.0) / 0.5).log10();
// Measured: the hum is 160.5 dB down (what is left is the start-up
// transient, still decaying), the tone loses 0.0001 dB.
assert!(hum_db < -150.0);
assert!(tone_db.abs() < 1e-3);

Once settled, the notch removes the hum by more than 150 dB (160.5 dB here) and leaves the 1 kHz tone unchanged to within 0.001 dB. A peaking cut (EqBand::peak with a negative gain) has no zero on the unit circle, so it attenuates 50 Hz only by the specified gain.

The 50 Hz notch (EqBand::band_stop, Q = 10) at 16 kHz: response from eq_frequency_response, -3 dB edges 5 Hz apart. Dots: levels measured on hum plus a 1 kHz tone filtered with apply_eq_band; the hum is 160 dB down (below the axis) and the tone is unchanged.
Figure 6.3. The 50 Hz notch (EqBand::band_stop, Q = 10) at 16 kHz: response from eq_frequency_response, -3 dB edges 5 Hz apart. Dots: levels measured on hum plus a 1 kHz tone filtered with apply_eq_band; the hum is 160 dB down (below the axis) and the tone is unchanged.

How it works

The code below builds the same filter from the formulas in the Concept section alone: place the analogue poles on a circle, pre-warp, apply the bilinear map, fix the gain so that , and compare with the library’s poles (the roots of each section’s denominator) and response.

use audio_samples::nzu;
use audio_samples::operations::types::IirFilterDesign;
use num_complex::Complex64;
use std::f64::consts::PI;

let (fs, fc, order) = (16_000.0, 1_000.0, 4usize);

// 1. Analogue poles, pre-warped cutoff, bilinear map (K = 2 fs).
let k = 2.0 * fs;
let omega_c = k * (PI * fc / fs).tan();
let n = order as f64;
let poles: Vec<Complex64> = (0..order)
    .map(|i| {
        let s = Complex64::from_polar(omega_c, PI * (2.0 * i as f64 + n + 1.0) / (2.0 * n));
        (k + s) / (k - s)
    })
    .collect();
// 2. Zeros all at z = -1; choose the gain g so that H(1) = g 2^N / prod(1 - p) = 1.
let gain = poles.iter().map(|p| 1.0 - p).product::<Complex64>().re / 2f64.powi(order as i32);

// 3. The library's poles: roots of a0 z^2 + a1 z + a2 for every section.
let sos = IirFilterDesign::butterworth_lowpass(nzu!(4), fc).sos_coefficients(fs).unwrap();
let lib_poles: Vec<Complex64> = sos
    .iter()
    .flat_map(|s| {
        let d = Complex64::new(s[4] * s[4] - 4.0 * s[3] * s[5], 0.0).sqrt();
        [(-s[4] + d) / (2.0 * s[3]), (-s[4] - d) / (2.0 * s[3])]
    })
    .collect();
for p in &poles {
    // Every pole is inside the unit circle ...
    assert!(p.norm() < 1.0);
    // ... and matches a library pole. Both come from a few dozen flops on
    // O(1) numbers, so 1e-12 is a loose bound on rounding.
    assert!(lib_poles.iter().any(|q| (p - q).norm() < 1e-12));
}
// The overall gain is the product of the sections' b0.
let lib_gain: f64 = sos.iter().map(|s| s[0]).product();
assert!((gain - lib_gain).abs() / lib_gain < 1e-10);

// 4. Evaluate H(e^{jw}) = g (z+1)^N / prod(z - p) and compare.
let design = IirFilterDesign::butterworth_lowpass(nzu!(4), fc);
for f in [100.0, 1_000.0, 3_000.0, 7_000.0] {
    let z = Complex64::from_polar(1.0, 2.0 * PI * f / fs);
    let h = gain * (z + 1.0).powu(order as u32) / poles.iter().map(|p| z - p).product::<Complex64>();
    let (m, _) = design.frequency_response(&[f], fs).unwrap();
    assert!((h.norm() - m[0]).abs() < 1e-12);
}
Poles (crosses) and zeros (circle) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, computed from its sos_coefficients. All four zeros are at z = -1 (Nyquist); the poles lie inside the unit circle, the largest at radius 0.8629.
Figure 6.4. Poles (crosses) and zeros (circle) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, computed from its sos_coefficients. All four zeros are at z = -1 (Nyquist); the poles lie inside the unit circle, the largest at radius 0.8629.

The difference equation itself is a five-term loop per section. Running it on an impulse reproduces the library’s filtered output to within rounding:

use audio_samples::operations::types::IirFilterDesign;
use audio_samples::{AudioIirFiltering, impulse, nzu, sample_rate};
use std::time::Duration;

let design = IirFilterDesign::butterworth_lowpass(nzu!(4), 1_000.0);
let sos = design.sos_coefficients(16_000.0).unwrap();
let x = impulse::<f64>(Duration::from_millis(20), sample_rate!(16000), 1.0, 0.0);
let lib = x.apply_iir_filter(&design).unwrap();

// Direct form I: y[n] = b0 x[n] + b1 x[n-1] + b2 x[n-2] - a1 y[n-1] - a2 y[n-2].
let mut y = x.as_slice().unwrap().to_vec();
for s in &sos {
    let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);
    for v in &mut y {
        let yn = (s[0] * *v + s[1] * x1 + s[2] * x2 - s[4] * y1 - s[5] * y2) / s[3];
        (x2, x1, y2, y1) = (x1, *v, y1, yn);
        *v = yn;
    }
}
// The library uses a different (transposed) form, so the rounding differs
// slightly; 1e-12 is far below anything audible.
let err = y.iter().zip(lib.as_slice().unwrap()).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
assert!(err < 1e-12);
// The impulse response sums to the DC gain, 1 (it has decayed within 20 ms).
assert!((y.iter().sum::<f64>() - 1.0).abs() < 1e-6);

Ask the library to explain

IirFilterDesign implements Explain. Explaining it through a signal supplies the sample rate, so the explainer can design the filter, tabulate the poles and zeros of every section, and measure the gain at the cutoff.

use audio_samples::educational::ExplainFor;
use audio_samples::operations::types::IirFilterDesign;
use audio_samples::{nzu, sample_rate, sine_wave};
use std::time::Duration;

let audio = sine_wave::<f64>(440.0, Duration::from_millis(50), sample_rate!(16000), 0.5);
let doc = audio.explain(&IirFilterDesign::butterworth_lowpass(nzu!(4), 1_000.0));
println!("{doc}");
assert_eq!(doc.quantity("Sections").unwrap().value, 2.0);
assert!((doc.quantity("Measured gain at the cutoff").unwrap().value + 3.0103).abs() < 1e-3);
// Largest pole radius 0.862856 (the pair nearest the cutoff).
assert!((doc.quantity("Largest pole radius").unwrap().value - 0.862856).abs() < 1e-6);

// A low cutoff relative to fs moves the poles towards z = 1. At 10 Hz with
// order 8 the stability margin drops below 1e-3 and the explainer warns.
let doc = audio.explain(&IirFilterDesign::butterworth_lowpass(nzu!(8), 10.0));
let margin = doc.quantity("Stability margin").unwrap().value;
assert!(margin > 0.0 && margin < 1e-3);
assert!(doc.has_warning_containing("very sensitive to rounding"));

Exercises

  1. Higher order, same cutoff gain. Predict the gain of an 8th-order Butterworth low-pass (1 kHz, 16 kHz) at 1 kHz and at 2 kHz, then check with frequency_response.
  2. Chebyshev versus Butterworth. For a 4th-order Chebyshev I low-pass with 1 dB ripple at 1 kHz (16 kHz), use the Chebyshev magnitude formula of the Concept section to predict the gain at 1 kHz, the largest and smallest gain between 0 and 1 kHz, and the attenuation at 2 kHz. Compare the attenuation at 2 kHz with the Butterworth’s.
  3. Zeros of a high-pass. The low-pass zeros are at (Nyquist). Predict where the zeros of a 4th-order Butterworth high-pass lie, then find them from sos_coefficients.
  4. filtfilt doubles the decibels. Predict the attenuation of a 2 kHz tone by filtfilt with the 4th-order, 1 kHz Butterworth, then measure it.

Answers

  1. The cutoff gain is dB for every order (this is the definition of ). At 2 kHz the closed form gives dB of attenuation, about twice the 4th-order figure.
use audio_samples::nzu;
use audio_samples::operations::types::IirFilterDesign;
use std::f64::consts::PI;

let (fs, fc) = (16_000.0, 1_000.0);
let (mag, _) = IirFilterDesign::butterworth_lowpass(nzu!(8), fc)
    .frequency_response(&[fc, 2.0 * fc], fs)
    .unwrap();
assert!((20.0 * mag[0].log10() + 3.0103).abs() < 1e-4);
let ratio = (PI * 2.0 * fc / fs).tan() / (PI * fc / fs).tan(); // 2.0824
let predicted = -10.0 * (1.0 + ratio.powi(16)).log10();
assert!((20.0 * mag[1].log10() - predicted).abs() < 1e-9);
assert!((predicted + 51.0).abs() < 0.05);
  1. At the Chebyshev gain is dB. With an even order the gain at DC is also dB () and the ripple peaks () reach 0 dB. At 2 kHz, , and , so the attenuation is dB, 10 dB more than the Butterworth’s 25.5 dB.
use audio_samples::nzu;
use audio_samples::operations::types::{FilterResponse, IirFilterDesign};

let cheb = IirFilterDesign::chebyshev_i(FilterResponse::LowPass, nzu!(4), 1_000.0, 1.0);
let grid: Vec<f64> = (0..=1000).map(|i| i as f64).collect(); // 0..1000 Hz, 1 Hz steps
let (m, _) = cheb.frequency_response(&grid, 16_000.0).unwrap();
let db: Vec<f64> = m.iter().map(|v| 20.0 * v.log10()).collect();
assert!((db[1000] + 1.0).abs() < 1e-6); // -1 dB at fc
assert!((db[0] + 1.0).abs() < 1e-6); // -1 dB at DC (even order)
let max = db.iter().cloned().fold(f64::MIN, f64::max);
assert!(max.abs() < 1e-3); // ripple peaks reach 0 dB (to the 1 Hz grid)
// The formula's prediction at 2 kHz, and the measurement.
let x = (std::f64::consts::PI / 8.0).tan() / (std::f64::consts::PI / 16.0).tan();
let t4 = (4.0 * x.acosh()).cosh();
let eps2 = 10f64.powf(0.1) - 1.0;
let predicted = 10.0 * (1.0 + eps2 * t4 * t4).log10();
assert!((x - 2.0824).abs() < 1e-4 && (t4 - 116.7).abs() < 0.05 && (eps2 - 0.2589).abs() < 1e-4);
assert!((predicted - 35.5).abs() < 0.05);
let (m2, _) = cheb.frequency_response(&[2_000.0], 16_000.0).unwrap();
assert!((20.0 * m2[0].log10() + predicted).abs() < 1e-6); // the design obeys the formula
  1. A high-pass must block DC, so its zeros move to (all four of them); the bilinear transform maps the analogue zeros at there.
use audio_samples::nzu;
use audio_samples::operations::types::IirFilterDesign;

let sos = IirFilterDesign::butterworth_highpass(nzu!(4), 1_000.0).sos_coefficients(16_000.0).unwrap();
let mut zeros = 0;
for s in &sos {
    // b0 z^2 + b1 z + b2 = b0 (z - 1)^2 means b1 = -2 b0 and b2 = b0.
    assert!((s[1] + 2.0 * s[0]).abs() < 1e-12 && (s[2] - s[0]).abs() < 1e-12);
    zeros += 2;
}
assert_eq!(zeros, 4);
  1. The forward pass attenuates by 25.5 dB and so does the backward pass: 51.0 dB in total ().
use audio_samples::operations::types::IirFilterDesign;
use audio_samples::{AudioIirFiltering, nzu, sample_rate, sine_wave};
use std::time::Duration;

let design = IirFilterDesign::butterworth_lowpass(nzu!(4), 1_000.0);
let tone = sine_wave::<f64>(2_000.0, Duration::from_millis(500), sample_rate!(16000), 1.0);
let out = tone.filtfilt(&design).unwrap();
let peak = out.as_slice().unwrap()[2_000..6_000].iter().fold(0.0f64, |a, x| a.max(x.abs()));
// 2 kHz is 8 samples per period, so the sampled peak can miss the true
// peak by 1 - cos(pi/8) = 7.6 % (0.69 dB) unless a sample falls on it; the
// tone starts at phase 0, so samples fall on the peaks and 0.1 dB is enough.
assert!((20.0 * peak.log10() + 51.0).abs() < 0.1);

Common pitfalls

  • Cutoff conventions. Here the cutoff is the dB point for Butterworth, the point for Chebyshev I and the start of the stop band for Chebyshev II. Some textbooks quote the Chebyshev dB frequency instead.
  • Frequencies are in Hz. Some design routines expect the cutoff as a fraction of Nyquist; this library always takes Hz and a sample rate.
  • Never cascade a high-order filter as one polynomial. Use the SOS rows. Each row is [b0, b1, b2, a0, a1, a2] with the overall gain folded into the sections; tools that keep a separate gain g normalise differently.
  • filtfilt doubles the attenuation in dB and is non-causal; use it for offline analysis, not real-time processing.
  • Low cutoffs at high sample rates put poles close to , which causes long ringing and sensitivity to rounding. Decimate first, or lower the order.
  • The trait method AudioIirFiltering::frequency_response is deprecated (it returns a flat response); use IirFilterDesign::frequency_response or SosFilter::frequency_response.

References

  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010. The bilinear transform, Butterworth and Chebyshev design.
  • R. Bristow-Johnson, Cookbook formulae for audio equalizer biquad filter coefficients (the “Audio EQ Cookbook”). The notch (band-stop) biquad used above.
  • P. Virtanen et al., “SciPy 1.0: fundamental algorithms for scientific computing in Python”, Nature Methods 17, 261-272, 2020. Describes the iirfilter design pipeline (prototype, frequency transform, bilinear transform, second-order sections) used in this chapter.

See also

07. Resampling

Speech models are trained at 16 kHz, CDs are 44.1 kHz, video is 48 kHz: most audio pipelines convert sample rates at some stage. Without adequate filtering, downsampling folds high frequencies back into the band as aliases and upsampling leaves spectral images. This chapter measures both effects on the library’s three quality tiers, compares them with naive decimation, and rebuilds a windowed-sinc decimator by hand.

Concept

Ratio. Converting from to (both in Hz) has ratio

(dimensionless). The output can only represent frequencies below its Nyquist frequency .

Downsampling and aliasing. Keeping every -th sample () is sampling the signal again at . A component at Hz above reappears at

where is the integer that brings into (chapter 01). Once folded it is indistinguishable from real content, so a resampler must low-pass filter before decimating, with a cutoff at or below .

Upsampling and imaging. Raising the rate by () can be modelled as inserting zeros between samples (which leaves copies, images, of the spectrum at ) followed by a low-pass interpolation filter that removes them.

Ideal band-limited interpolation. A band-limited signal is fully described by its samples, and its value at any time (seconds) is

A practical resampler truncates and windows the sinc, and scales it so that its cutoff is (slightly less, to leave room for the transition band). The same formula then performs both interpolation and anti-aliasing.

Linear interpolation uses a triangular kernel instead of a sinc. For integer upsampling by it equals zero-stuffing followed by the FIR , whose gain at frequency (Hz) is

where the combines two factors: zero-stuffing scales the wanted (baseband) component by , and the kernel’s DC gain of restores it, so with the kernel’s response and . is not flat in the pass band and not zero at the images.

Alias (or image) rejection is the level of the unwanted component relative to the input component that produced it:

where is a sinusoid’s amplitude. 0 dB means no rejection.

The library’s tiers (ResamplingQuality). Every tier except Fast upsampling is a Kaiser-windowed sinc low-pass whose cut-off is set relative to the lower Nyquist frequency ; the stop band starts at :

  • Fast (the default): when downsampling, a short filter with its pass band to and 70 dB of stop-band attenuation; when upsampling, linear interpolation (no anti-imaging filter).
  • Medium: pass band to , 100 dB.
  • High: pass band to , 125 dB.

The filter is computed in the buffer’s float type: f32 for f32, i16, I24 and u8 buffers, f64 for f64 and i32 ones.

Level after converting a 48 kHz tone to 16 kHz with resample, measured at the frequency at which it appears, for each ResamplingQuality. Below 8 kHz this is the pass band (Fast rolls off first); above 8 kHz it is the residue of the alias, more than 180 dB down (round-off): for 1 : 3 the resampler drops everything above 8 kHz.
Figure 7.1. Level after converting a 48 kHz tone to 16 kHz with resample, measured at the frequency at which it appears, for each ResamplingQuality. Below 8 kHz this is the pass band (Fast rolls off first); above 8 kHz it is the residue of the alias, more than 180 dB down (round-off): for 1 : 3 the resampler drops everything above 8 kHz.

Time alignment. Output sample is the band-limited reconstruction of the input at the exact input position : the sinc is centred on that position, so the filter is symmetric (linear phase) and adds no delay. Input before the start and after the end counts as zeros, and the output has exactly samples for input samples. The streaming StreamingResampler holds back the filter’s look-ahead and emits the same samples as the whole-buffer resample, chunk by chunk.

With the library

Mix a 1 kHz tone (to keep) with a 10 kHz tone (to remove), both at amplitude 0.5, and convert 48 kHz to 16 kHz by naive decimation (keep every third sample, written by hand) and with each tier. The folding formula puts the 10 kHz alias at Hz. Measure each component with one DFT bin over 1600 output samples (whole periods of both 1 kHz and 6 kHz, so there is no leakage), and measure the time shift of the output from the phase of the 1 kHz tone.

use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{AudioSamples, resample, sample_rate, sine_wave};
use non_empty_slice::NonEmptyVec;
use std::f64::consts::PI;
use std::time::Duration;

/// DFT bin of the component at f Hz (one bin; exact for whole periods).
fn bin(x: &[f64], f: f64, fs: f64) -> (f64, f64) {
    x.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
        let ph = 2.0 * PI * f * n as f64 / fs;
        (re + v * ph.cos(), im - v * ph.sin())
    })
}
fn amplitude(x: &[f64], f: f64, fs: f64) -> f64 {
    let (re, im) = bin(x, f, fs);
    2.0 * (re * re + im * im).sqrt() / x.len() as f64
}
fn phase(x: &[f64], f: f64, fs: f64) -> f64 {
    let (re, im) = bin(x, f, fs);
    im.atan2(re)
}

let dur = Duration::from_millis(250);
let a = sine_wave::<f64>(1_000.0, dur, sample_rate!(48000), 0.5);
let b = sine_wave::<f64>(10_000.0, dur, sample_rate!(48000), 0.5);
let x: Vec<f64> = a.as_slice().unwrap().iter().zip(b.as_slice().unwrap()).map(|(p, q)| p + q).collect();
let input: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x.clone()).unwrap(), sample_rate!(48000));

let mid = 1_200..2_800; // middle 100 ms of the 16 kHz output
let db = |v: f64| 20.0 * v.log10();
let ideal: Vec<f64> = (0..4_000).map(|n| 0.5 * (2.0 * PI * 1_000.0 * n as f64 / 16_000.0).sin()).collect();
let ideal_phase = phase(&ideal[mid.clone()], 1_000.0, 16_000.0);

// Naive decimation: the alias is at full level, 0 dB.
let naive: Vec<f64> = x.iter().step_by(3).copied().collect();
assert!(db(amplitude(&naive[mid.clone()], 6_000.0, 16_000.0) / 0.5).abs() < 1e-9);

let mut results = Vec::new();
for q in [ResamplingQuality::Fast, ResamplingQuality::Medium, ResamplingQuality::High] {
    let y = resample(&input, sample_rate!(16000), q).unwrap();
    assert_eq!(y.samples_per_channel().get(), 4_000); // ceil(12000 / 3)
    let y = y.as_slice().unwrap();
    let pass_db = db(amplitude(&y[mid.clone()], 1_000.0, 16_000.0) / 0.5);
    let alias_db = db(amplitude(&y[mid.clone()], 6_000.0, 16_000.0) / 0.5);
    // Shift in output frames: phase difference / (2 pi f / fs).
    let shift = (phase(&y[mid.clone()], 1_000.0, 16_000.0) - ideal_phase) / (2.0 * PI / 16.0);
    results.push((pass_db, alias_db, shift));
}
// Every tier passes 1 kHz unchanged (better than 0.001 dB) ...
assert!(results.iter().all(|(p, _, _)| p.abs() < 1e-3));
// ... removes the alias: for this 1 : 3 ratio the resampler drops everything
// above the new Nyquist frequency in the frequency domain, so what is left is
// f64 round-off, more than 180 dB down ...
assert!(results.iter().all(|&(_, a, _)| a < -180.0));
// ... and adds no delay: the shift is zero to rounding error.
assert!(results.iter().all(|(_, _, s)| s.abs() < 1e-9));
A 1 kHz plus 10 kHz mix converted from 48 kHz to 16 kHz, spectra of the middle 100 ms. Keeping every third sample (top) moves the 10 kHz tone to 6 kHz at full level; every tier of resample (bottom) removes it, leaving round-off more than 180 dB below the input.
Figure 7.2. A 1 kHz plus 10 kHz mix converted from 48 kHz to 16 kHz, spectra of the middle 100 ms. Keeping every third sample (top) moves the 10 kHz tone to 6 kHz at full level; every tier of resample (bottom) removes it, leaving round-off more than 180 dB below the input.

An impulse shows the same time alignment: one at input sample 3000 (48 kHz) peaks at output sample (16 kHz) for every tier, and the streaming resampler, fed in chunks, produces the same output.

use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{AudioSamples, StreamingResampler, channels, resample, sample_rate};
use non_empty_slice::NonEmptyVec;

let mut x = vec![0.0f64; 12_000];
x[3_000] = 1.0;
let input: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x.clone()).unwrap(), sample_rate!(48000));
for q in [ResamplingQuality::Fast, ResamplingQuality::Medium, ResamplingQuality::High] {
    let y = resample(&input, sample_rate!(16000), q).unwrap();
    let y = y.as_slice().unwrap();
    let peak = (0..y.len()).max_by(|&a, &b| y[a].abs().total_cmp(&y[b].abs())).unwrap();
    assert_eq!(peak, 1_000);
    // Symmetric filter: the response is symmetric about the peak.
    assert!((y[peak - 1] - y[peak + 1]).abs() < 1e-12);

    let mut stream = StreamingResampler::<f64>::new(sample_rate!(48000), sample_rate!(16000), channels!(1), q).unwrap();
    let mut streamed = Vec::new();
    for chunk in x.chunks(1_000) {
        let piece = AudioSamples::from_mono_vec(NonEmptyVec::new(chunk.to_vec()).unwrap(), sample_rate!(48000));
        if let Some(out) = stream.process_chunk(&piece).unwrap() {
            streamed.extend_from_slice(out.as_slice().unwrap());
        }
    }
    if let Some(out) = stream.finish().unwrap() {
        streamed.extend_from_slice(out.as_slice().unwrap());
    }
    assert_eq!(streamed.len(), y.len());
    assert!(streamed.iter().zip(y).all(|(a, b)| (a - b).abs() < 1e-12));
}

How it works

Naive decimation is plain sampling. With , keeping every third sample returns , and for every integer : on the new grid the 10 kHz tone has exactly the samples of a 6 kHz tone. No filter applied afterwards can separate the two, which is why every tier filters first.

use audio_samples::{sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let x = sine_wave::<f64>(10_000.0, Duration::from_millis(100), sample_rate!(48000), 0.5);
let x = x.as_slice().unwrap();
let y: Vec<f64> = x.iter().step_by(3).copied().collect(); // 1600 samples at 16 kHz
assert_eq!(y.len(), 1_600);
for (m, &v) in y.iter().enumerate() {
    let six_khz = -0.5 * (2.0 * PI * 6_000.0 * m as f64 / 16_000.0).sin();
    // Tolerance: sin of arguments up to ~6e3 rad carries ~1e-12 of rounding.
    assert!((v - six_khz).abs() < 1e-9);
}

A windowed-sinc decimator, written out. Low-pass with a 193-tap Blackman-windowed sinc whose cutoff is kHz kHz, then keep every third sample. The filter is centred (no delay), so the 1 kHz output matches the ideal 16 kHz sine, and the 6 kHz alias is 107.5 dB down: the filter’s stopband, folded back. The library drops that part of the spectrum for this ratio, so its tiers leave only round-off. Since the library adds no delay either, its High output and this one agree sample by sample.

use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{AudioSamples, resample, sample_rate};
use non_empty_slice::NonEmptyVec;
use std::f64::consts::PI;

let (fs_in, fs_out, half) = (48_000.0, 16_000.0, 96usize);
// Windowed-sinc low-pass h[k], k = 0..=2*half, cutoff fc (as a fraction of fs_in).
let fc = 0.95 * (fs_out / 2.0) / fs_in;
let m = 2 * half;
let h: Vec<f64> = (0..=m)
    .map(|i| {
        let t = i as f64 - half as f64;
        let sinc = if t == 0.0 { 2.0 * fc } else { (2.0 * PI * fc * t).sin() / (PI * t) };
        let u = i as f64 / m as f64;
        sinc * (0.42 - 0.5 * (2.0 * PI * u).cos() + 0.08 * (4.0 * PI * u).cos()) // Blackman
    })
    .collect();

// Input: 0.5 sin(1 kHz) + 0.5 sin(10 kHz), 250 ms at 48 kHz.
let x: Vec<f64> = (0..12_000)
    .map(|n| {
        let t = n as f64 / fs_in;
        0.5 * (2.0 * PI * 1_000.0 * t).sin() + 0.5 * (2.0 * PI * 10_000.0 * t).sin()
    })
    .collect();
// y[m] = sum_k h[k] x[3m + half - k]  (filter centred on the kept sample).
let y: Vec<f64> = (0..4_000)
    .map(|o| {
        (0..h.len())
            .filter_map(|k| x.get((3 * o + half).checked_sub(k)?).map(|v| h[k] * v))
            .sum()
    })
    .collect();

let amp = |f: f64| {
    let (re, im) = (1_200..2_800).fold((0.0, 0.0), |(re, im), n| {
        let ph = 2.0 * PI * f * n as f64 / fs_out;
        (re + y[n] * ph.cos(), im - y[n] * ph.sin())
    });
    2.0 * (re * re + im * im).sqrt() / 1_600.0
};
assert!((20.0 * (amp(1_000.0) / 0.5).log10()).abs() < 1e-3); // pass band intact
assert!((20.0 * (amp(6_000.0) / 0.5).log10() + 107.5).abs() < 0.1); // alias 107.5 dB down
// Matches the ideal 16 kHz sine to 1e-5 (window ripple in the pass band).
for n in 1_200..2_800 {
    let ideal = 0.5 * (2.0 * PI * 1_000.0 * n as f64 / fs_out).sin();
    assert!((y[n] - ideal).abs() < 1e-5);
}
// And the library's High tier, also centred, gives the same samples to 1e-5.
let input: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x).unwrap(), sample_rate!(48000));
let lib = resample(&input, sample_rate!(16000), ResamplingQuality::High).unwrap();
let lib = lib.as_slice().unwrap();
assert!((1_200..2_800).all(|n| (lib[n] - y[n]).abs() < 1e-5));

Linear interpolation is a poor interpolation filter. For a 6 kHz tone upsampled from 16 kHz to 48 kHz with Fast, the formula for predicts an attenuation of the tone to dB and an image at Hz at dB.

use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{resample, sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let fs = 48_000.0;
let g = |f: f64| {
    let w = 2.0 * PI * f / fs;
    20.0 * ((3.0 + 4.0 * w.cos() + 2.0 * (2.0 * w).cos()) / 9.0).abs().log10()
};
let x = sine_wave::<f64>(6_000.0, Duration::from_millis(250), sample_rate!(16000), 0.5);
let y = resample(&x, sample_rate!(48000), ResamplingQuality::Fast).unwrap();
let y = &y.as_slice().unwrap()[3_600..8_400]; // 100 ms: whole periods of 6 and 10 kHz
let level = |f: f64| {
    let (re, im) = y.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
        let ph = 2.0 * PI * f * n as f64 / fs;
        (re + v * ph.cos(), im - v * ph.sin())
    });
    20.0 * (2.0 * (re * re + im * im).sqrt() / y.len() as f64 / 0.5).log10()
};
// Measured equals predicted to 1e-6 dB (the resampler computes in f64).
assert!((level(6_000.0) - g(6_000.0)).abs() < 1e-6);
assert!((level(10_000.0) - g(10_000.0)).abs() < 1e-6);
assert!((g(6_000.0) + 3.77).abs() < 0.01 && (g(10_000.0) + 11.8).abs() < 0.05);

The sinc tiers pass the 6 kHz tone unchanged (to 0.0001 dB) and remove the image: for 1 : 3 they set every bin above 8 kHz to zero before the inverse transform, so it is f64 round-off, more than 180 dB down:

use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{resample, sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let x = sine_wave::<f64>(6_000.0, Duration::from_millis(250), sample_rate!(16000), 0.5);
for q in [ResamplingQuality::Medium, ResamplingQuality::High] {
    let y = resample(&x, sample_rate!(48000), q).unwrap();
    let y = &y.as_slice().unwrap()[3_600..8_400];
    let level = |f: f64| {
        let (re, im) = y.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
            let ph = 2.0 * PI * f * n as f64 / 48_000.0;
            (re + v * ph.cos(), im - v * ph.sin())
        });
        20.0 * (2.0 * (re * re + im * im).sqrt() / y.len() as f64 / 0.5).log10()
    };
    assert!(level(6_000.0).abs() < 1e-4);
    assert!(level(10_000.0) < -180.0);
}
Upsampling a tone from 16 kHz to 48 kHz. Fast (linear interpolation) follows the chapter's G(f) (line): the tone droops (dots below 8 kHz) and its image at 16 kHz minus f is only partly removed. Medium and High remove the image to round-off.
Figure 7.3. Upsampling a tone from 16 kHz to 48 kHz. Fast (linear interpolation) follows the chapter's G(f) (line): the tone droops (dots below 8 kHz) and its image at 16 kHz minus f is only partly removed. Medium and High remove the image to round-off.

Ask the library to explain

topics::resampling summarises a conversion: ratio, both Nyquist frequencies, the pass-band edge of the sinc tiers, a table of the three tiers, and a warning for downsampling.

use audio_samples::educational::topics;

let doc = topics::resampling(48_000.0, 16_000.0);
println!("{doc}");
assert!((doc.quantity("Ratio").unwrap().value - 1.0 / 3.0).abs() < 1e-12);
assert_eq!(doc.quantity("Output Nyquist").unwrap().value, 8_000.0);
// Medium's pass band ends at 0.90 x 8 kHz.
assert!((doc.quantity("Sinc pass-band edge").unwrap().value - 7_200.0).abs() < 1e-9);
assert!(doc.has_warning_containing("Downsampling"));
// Upsampling discards nothing, so there is no such warning.
assert!(!topics::resampling(16_000.0, 48_000.0).has_warning_containing("Downsampling"));

Exercises

  1. Alias of a 13 kHz tone. A 13 kHz tone is converted from 48 kHz to 16 kHz by keeping every third sample. Predict the output frequency, then confirm with topics::aliasing and by measuring. Measure the residue that each tier of resample leaves.
  2. Droop at 2 kHz. Predict the gain of Fast upsampling 16 kHz → 48 kHz at 2 kHz from , then measure it.
  3. Alignment at a non-integer ratio. Convert a 1 kHz tone from 44.1 kHz to 16 kHz () with High. Determine whether the output is still time-aligned, and bound the shift by comparing with the ideal 16 kHz sine.

Answers

  1. Hz, at full level after naive decimation. Every tier removes it: measured over the middle 50 ms, Fast leaves dB and Medium and High less than dB (round-off). Over the whole 100 ms all three read about dB, set by the clicks at the ends of the tone (chapter 01).
use audio_samples::educational::topics;
use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{resample, sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let amp = |y: &[f64]| {
    let (re, im) = y.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
        let ph = 2.0 * PI * 3_000.0 * n as f64 / 16_000.0;
        (re + v * ph.cos(), im - v * ph.sin())
    });
    2.0 * (re * re + im * im).sqrt() / y.len() as f64
};
assert_eq!(topics::aliasing(13_000.0, 16_000.0).quantity("Alias frequency").unwrap().value, 3_000.0);
let x = sine_wave::<f64>(13_000.0, Duration::from_millis(100), sample_rate!(48000), 0.5);
let naive: Vec<f64> = x.as_slice().unwrap().iter().step_by(3).copied().collect();
assert_eq!(naive.len(), 1_600); // 300 whole periods of 3 kHz
assert!((amp(&naive) - 0.5).abs() < 1e-9);

for (q, mid_db) in [
    (ResamplingQuality::Fast, -150.0),
    (ResamplingQuality::Medium, -220.0),
    (ResamplingQuality::High, -220.0),
] {
    let y = resample(&x, sample_rate!(16000), q).unwrap();
    let y = y.as_slice().unwrap();
    let db = |a: f64| 20.0 * (a / 0.5).log10();
    assert!(db(amp(&y[400..1_200])) < mid_db); // middle 50 ms: 150 periods
    assert!((db(amp(y)) + 74.0).abs() < 0.5); // whole signal: the edge clicks
}
  1. , so , i.e. dB.
use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{resample, sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let w = PI / 12.0;
let predicted = 20.0 * ((3.0 + 4.0 * w.cos() + 2.0 * (2.0 * w).cos()) / 9.0).log10();
assert!((predicted + 0.40).abs() < 0.005);

let x = sine_wave::<f64>(2_000.0, Duration::from_millis(250), sample_rate!(16000), 0.5);
let y = resample(&x, sample_rate!(48000), ResamplingQuality::Fast).unwrap();
let y = &y.as_slice().unwrap()[3_600..8_400];
let (re, im) = y.iter().enumerate().fold((0.0, 0.0), |(re, im), (n, &v)| {
    let ph = 2.0 * PI * 2_000.0 * n as f64 / 48_000.0;
    (re + v * ph.cos(), im - v * ph.sin())
});
let measured = 20.0 * (2.0 * (re * re + im * im).sqrt() / y.len() as f64 / 0.5).log10();
assert!((measured - predicted).abs() < 0.01);
  1. It is. Output sample is evaluated at the exact input position , so there is no delay to remove and nothing is rounded to whole frames. In the middle 100 ms the output differs from the ideal 16 kHz sine by less than ; a shift of output frames would cause an error of up to , so frames.
use audio_samples::operations::types::ResamplingQuality;
use audio_samples::{resample, sample_rate, sine_wave};
use std::f64::consts::PI;
use std::time::Duration;

let x = sine_wave::<f64>(1_000.0, Duration::from_millis(250), sample_rate!(44100), 0.5);
let y = resample(&x, sample_rate!(16000), ResamplingQuality::High).unwrap();
let y = y.as_slice().unwrap();
assert_eq!(y.len(), 4_000); // ceil(11025 * 160 / 441)
let err = (800..2_400)
    .map(|n| (y[n] - 0.5 * (2.0 * PI * 1_000.0 * n as f64 / 16_000.0).sin()).abs())
    .fold(0.0, f64::max);
assert!(err < 1e-7);
let slope = 0.5 * 2.0 * PI / 16.0; // largest error per frame of shift
assert!((slope - 0.196).abs() < 0.001);
assert!(1e-7 / slope < 5.1e-7);

Common pitfalls

  • Naive decimation is not resampling. Keeping every -th sample folds everything above the new Nyquist frequency back at full level; every ResamplingQuality filters first.
  • Fast trades bandwidth and rejection for speed. Its downsampling filter starts to roll off at and is designed for 70 dB; when upsampling it is linear interpolation, which droops the pass band and leaves images. Use Medium or High for analysis or listening.
  • Measure rejection away from the ends. The input is treated as zero outside the buffer, so a signal that starts or stops abruptly produces broadband clicks that no anti-aliasing filter removes.
  • Other resamplers differ in their defaults. An FFT resampler treats the signal as periodic, and polyphase resamplers use their own FIR filters. Expect small differences in edge behaviour and alignment, not in the pass band.
  • Output length is frames; durations that are not whole numbers of output samples round up.
  • Streaming versus offline. StreamingResampler gives the same, time-aligned samples as resample; it holds back the filter’s look-ahead until more input (or finish) arrives.

References

  • R. E. Crochiere and L. R. Rabiner, Multirate Digital Signal Processing, Prentice-Hall, 1983.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010. Sampling-rate conversion.

See also

08. LPC, the source-filter model and formants

A voiced vowel is a periodic excitation filtered by the vocal tract. The vocal folds produce a periodic train of air pulses (the source), and the throat, mouth and lips act as a resonant filter whose peaks, the formants, determine which vowel is heard. Linear predictive coding (LPC) fits an all-pole filter to a short frame of speech, so it estimates the filter half of that model: its roots are the formants, and a quantised form of its coefficients (line spectral frequencies) is what speech codecs such as SILK transmit.

Concept

Source-filter model. A voiced frame is modelled as

where is the excitation (here an impulse train with one pulse every seconds, the fundamental frequency in Hz), the vocal-tract filter, a gain, the model order and the (dimensionless) predictor coefficients. The usual choice of gain is , the square root of the order- prediction-error energy defined below, so that the model driven by a unit-energy excitation has the frame’s residual energy. This crate writes with a plus sign (the prediction-error filter); many textbooks predict instead, so .

Formants as poles. One formant at frequency (Hz) with 3 dB bandwidth (Hz) is a pair of complex-conjugate poles at radius and angle :

where is the sample rate in Hz and is in radians per sample. The radius formula is a narrow-band approximation: it holds well for an isolated pole pair with and away from 0 and , and this chapter uses it as the definition of when going both ways. Each pole pair contributes a second-order factor to . Inverting: a root of with gives

Linear prediction. The prediction error (residual) is . Minimising its energy over a windowed frame gives the normal (Yule-Walker) equations

with the biased autocorrelation of the windowed frame ( samples, a Hamming window). (The biased estimator is usually written with a factor ; it scales every equally and cancels from the solution, so the crate omits it.) The matrix is Toeplitz, so the Levinson-Durbin recursion solves it in operations, one order at a time (, ):

where is the reflection coefficient ( for a stable filter) and the prediction-error energy of the order- predictor.

Choosing p. Each formant needs two poles and there is roughly one formant per kilohertz of bandwidth; two more poles model the spectral tilt of the source and lip radiation. Hence the rule of thumb ( in Hz), 18 at 16 kHz.

Pre-emphasis. Real glottal pulses fall off at about -12 dB per octave, and radiation from the lips adds about +6 dB per octave, so voiced speech has a net tilt of about -6 dB per octave: high formants are weak and the fit uses poles to model the tilt. The first-order high-pass (FIR) with adds about +6 dB per octave and so flattens that net tilt before analysis. (Exercise 3 uses a source with the full -12 dB per octave and no radiation term, so a -6 dB per octave tilt remains after pre-emphasis.)

The crate’s LPC routines live in the speech-codec module and are exported from the crate root when the opus-codec feature is on (it is part of full_no_plotting): lpc_analysis (Hamming window, autocorrelation, Levinson-Durbin) and levinson_durbin. There is no first-class LPC or formant API outside the codec feature, and no root finder, so this chapter writes the formant step itself.

With the library

We synthesise an /a/-like vowel at 16 kHz: formants (700, 80), (1220, 90) and (2600, 120) Hz as (F, B), excited by an impulse train at Hz, and analyse a 512-sample (32 ms) frame taken after the filter has settled.

use audio_samples::{educational::topics, lpc_analysis, lpc_residual};
use std::f64::consts::PI;

let fs = 16_000.0;
let formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0, 120.0)];

// A(z) as the product of one second-order section per formant.
let mut a_true = vec![1.0f64];
for &(f, b) in &formants {
    let (r, theta) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let sec = [1.0, -2.0 * r * theta.cos(), r * r];
    let mut out = vec![0.0; a_true.len() + 2];
    for (i, ai) in a_true.iter().enumerate() {
        for (j, sj) in sec.iter().enumerate() {
            out[i + j] += ai * sj;
        }
    }
    a_true = out;
}
assert_eq!(a_true.len(), 7); // three pole pairs: order 6

// Source: one impulse every round(16000/120) = 133 samples. Filter: 1/A(z).
let n = 2400;
let mut y = vec![0.0f64; n];
for i in 0..n {
    let e = if i % 133 == 0 { 1.0 } else { 0.0 };
    y[i] = e - (1..7).filter(|&k| k <= i).map(|k| a_true[k] * y[i - k]).sum::<f64>();
}
let frame: Vec<f32> = y[1600..2112].iter().map(|&v| v as f32).collect();

let p = topics::lpc(18, fs).quantity("Rule-of-thumb order").unwrap().value as usize;
assert_eq!(p, 18);
let lpc = lpc_analysis(&frame, p);
assert_eq!(lpc.coeffs.len(), 18); // the order-p solution: a_1 ... a_18
println!("a_1..a_3 = {:?}, E_p = {:.2}", &lpc.coeffs[..3], lpc.prediction_error);

// Inverse filtering with A(z) leaves the residual e[n]: little more than the
// pulses of the source. The prediction gain compares the energies.
let e = lpc_residual(&frame, &lpc);
let energy = |v: &[f32]| v.iter().map(|&s| f64::from(s).powi(2)).sum::<f64>();
let gain_db = 10.0 * (energy(&frame) / energy(&e)).log10();
println!("prediction gain {gain_db:.1} dB");
assert!((gain_db - 13.8).abs() < 0.05, "prediction gain {gain_db}");

lpc_analysis returns an LpcCoefficients holding (as f32, index 0 is ) and the final prediction-error energy . Filtering the frame with (lpc_residual) removes 13.8 dB of its energy: what is left is essentially the excitation pulses, which a predictor built from the previous 18 samples cannot predict.

How it works

Levinson-Durbin, written out. We rebuild the windowed autocorrelation, apply the same small diagonal loading the library uses (), run the recursion and compare. We also check the defining property: the coefficients satisfy all normal equations (an order- answer would not).

use audio_samples::{levinson_durbin, lpc_analysis};
use std::f64::consts::PI;
let fs = 16_000.0;
let mut a_true = vec![1.0f64];
for &(f, b) in &[(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)] {
    let (r, theta) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let sec = [1.0, -2.0 * r * theta.cos(), r * r];
    let mut out = vec![0.0; a_true.len() + 2];
    for (i, ai) in a_true.iter().enumerate() { for (j, sj) in sec.iter().enumerate() { out[i + j] += ai * sj; } }
    a_true = out;
}
let mut y = vec![0.0f64; 2400];
for i in 0..2400 {
    let e = if i % 133 == 0 { 1.0 } else { 0.0 };
    y[i] = e - (1..7).filter(|&k| k <= i).map(|k| a_true[k] * y[i - k]).sum::<f64>();
}
let frame: Vec<f32> = y[1600..2112].iter().map(|&v| v as f32).collect();
let p = 18;
let n = frame.len();
// Hamming-windowed frame (the library rounds it to f32 before correlating).
let xw: Vec<f64> = (0..n)
    .map(|i| {
        let w = 0.54 - 0.46 * (2.0 * PI * i as f64 / (n - 1) as f64).cos();
        f64::from((w * f64::from(frame[i])) as f32)
    })
    .collect();
let r_raw: Vec<f64> = (0..=p)
    .map(|m| (0..n - m).map(|i| xw[i] * xw[i + m]).sum())
    .collect();
let mut r = r_raw.clone();
r[0] *= 1.0 + 1e-5;

// Levinson-Durbin for A(z) = 1 + sum a_k z^-k.
let mut a = vec![0.0f64; p + 1];
let mut err = r[0];
for m in 1..=p {
    let k = -(r[m] + (1..m).map(|i| a[i] * r[m - i]).sum::<f64>()) / err;
    let prev = a.clone();
    for i in 1..m {
        a[i] = prev[i] + k * prev[m - i];
    }
    a[m] = k;
    err *= 1.0 - k * k;
}

let lib = lpc_analysis(&frame, p);
let largest = a.iter().fold(0.0f64, |m, v| m.max(v.abs()));
let diff = (1..=p).map(|k| (a[k] - f64::from(lib.coeffs[k - 1])).abs()).fold(0.0, f64::max);
// The library stores f32 coefficients (relative precision 6e-8), so 1e-6 of
// the largest coefficient is a safe bound.
assert!(diff < 1e-6 * largest, "difference {diff}");
assert!((lib.prediction_error - err).abs() < 1e-9 * err);
// The public recursion on our autocorrelation agrees as well.
let ld = levinson_durbin(&r_raw, p).unwrap();
assert!((1..=p).all(|k| (a[k] - f64::from(ld.coeffs[k - 1])).abs() < 1e-6 * largest));

// Order-p check: every normal equation holds to f32 precision.
let worst = (1..=p)
    .map(|i| ((1..=p).map(|k| f64::from(lib.coeffs[k - 1]) * r[i.abs_diff(k)]).sum::<f64>() + r[i]).abs() / r[0])
    .fold(0.0, f64::max);
assert!(worst < 1e-6, "residual {worst}");

From roots to formants. times is the polynomial . The Durand-Kerner (Weierstrass) iteration updates all root estimates at once, , and converges for polynomials with distinct roots such as these. Each root in the upper half plane is then converted with the , formulas above. LPC also places broad poles (bandwidths of a kilohertz or more) that shape the overall slope; we keep only resonances narrower than 400 Hz.

use audio_samples::lpc_analysis;
use std::f64::consts::PI;
use num_complex::Complex64;
let fs = 16_000.0;
let formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)];
let mut a_true = vec![1.0f64];
for &(f, b) in &formants {
    let (r, theta) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let sec = [1.0, -2.0 * r * theta.cos(), r * r];
    let mut out = vec![0.0; a_true.len() + 2];
    for (i, ai) in a_true.iter().enumerate() { for (j, sj) in sec.iter().enumerate() { out[i + j] += ai * sj; } }
    a_true = out;
}
let mut y = vec![0.0f64; 2400];
for i in 0..2400 {
    let e = if i % 133 == 0 { 1.0 } else { 0.0 };
    y[i] = e - (1..7).filter(|&k| k <= i).map(|k| a_true[k] * y[i - k]).sum::<f64>();
}
let frame: Vec<f32> = y[1600..2112].iter().map(|&v| v as f32).collect();

/// Roots of z^p + c[1] z^(p-1) + ... + c[p] (c[0] = 1), Durand-Kerner.
fn poly_roots(c: &[f64]) -> Vec<Complex64> {
    let p = c.len() - 1;
    let eval = |z: Complex64| c.iter().fold(Complex64::new(0.0, 0.0), |acc, &ci| acc * z + ci);
    let mut z: Vec<Complex64> = (0..p)
        .map(|i| Complex64::from_polar(0.9, 2.0 * PI * i as f64 / p as f64 + 0.4))
        .collect();
    for _ in 0..5000 {
        let mut biggest = 0.0f64;
        for i in 0..p {
            let den = (0..p).filter(|&j| j != i).fold(Complex64::new(1.0, 0.0), |d, j| d * (z[i] - z[j]));
            let step = eval(z[i]) / den;
            z[i] -= step;
            biggest = biggest.max(step.norm());
        }
        if biggest < 1e-14 {
            break;
        }
    }
    z
}

let lpc = lpc_analysis(&frame, 18);
let mut a = vec![1.0];
a.extend(lpc.coeffs.iter().map(|&v| f64::from(v)));
let roots = poly_roots(&a);
assert!(roots.iter().all(|z| z.norm() < 1.0)); // all poles inside the unit circle

let mut resonances: Vec<(f64, f64)> = roots
    .iter()
    .filter(|z| z.im > 0.0)
    .map(|z| (z.arg() * fs / (2.0 * PI), -z.norm().ln() * fs / PI))
    .filter(|&(_, b)| b < 400.0)
    .collect();
resonances.sort_by(|x, y| x.0.total_cmp(&y.0));
println!("narrow resonances (F, B): {resonances:.1?}");
assert_eq!(resonances.len(), 3);
for (&(f_est, _), &(f_true, _)) in resonances.iter().zip(&formants) {
    // A periodic source samples the envelope only at multiples of 120 Hz,
    // which biases autocorrelation LPC by a few hertz; 20 Hz (under 3 % of
    // F1) is a safe bound.
    assert!((f_est - f_true).abs() < 20.0, "{f_est} vs {f_true}");
}
let errors: Vec<f64> = resonances.iter().zip(&formants).map(|(e, t)| (e.0 - t.0).round()).collect();
assert_eq!(errors, vec![11.0, -9.0, -3.0]);
The 18 roots of the LPC polynomial A(z) in the z-plane. The six narrow poles (bandwidth under 400 Hz, orange) close to the unit circle are the three formants and their conjugates; the broad poles (blue) shape the overall spectral slope.
Figure 8.1. The 18 roots of the LPC polynomial A(z) in the z-plane. The six narrow poles (bandwidth under 400 Hz, orange) close to the unit circle are the three formants and their conjugates; the broad poles (blue) shape the overall spectral slope.

The LPC envelope and the FFT. is a smooth curve; the FFT of the frame is a comb of harmonics at multiples of . If the LPC fit is good, the harmonic peaks lie on the envelope up to a constant gain. The lab measures this for harmonics 1 to 33 (up to 3960 Hz): the peaks scatter about the shifted envelope with a standard deviation of 1.06 dB (asserted below 1.5 dB in the lab, which also writes the curves to a CSV file).

Spectrum of the Hamming-windowed vowel frame (grey) with the order-18 LPC envelope from lpc_analysis (blue) and the true vocal-tract response (orange, dashed), each shifted to sit on the harmonic peaks. Green lines mark the formants found from the roots of A(z): 711, 1211 and 2597 Hz against 700, 1220 and 2600 Hz.
Figure 8.2. Spectrum of the Hamming-windowed vowel frame (grey) with the order-18 LPC envelope from lpc_analysis (blue) and the true vocal-tract response (orange, dashed), each shifted to sit on the harmonic peaks. Green lines mark the formants found from the roots of A(z): 711, 1211 and 2597 Hz against 700, 1220 and 2600 Hz.

Ask the library to explain

use audio_samples::educational::{WarningLevel, topics};

let doc = topics::lpc(18, 16_000.0);
println!("{doc}");
assert_eq!(doc.quantity("Rule-of-thumb order").unwrap().value, 18.0);
assert_eq!(doc.quantity("Resonances representable").unwrap().value, 9.0);
assert!(doc.has_warning_containing("silently lowers the order"));

// An order-4 model is far below the rule of thumb.
assert!(topics::lpc(4, 16_000.0).has_warning(WarningLevel::Caution));

The explanation prints the Levinson-Durbin formulas in the crate’s sign convention and warns that lpc_analysis quietly lowers the order to half the frame length for very short frames.

Exercises

  1. Pole radius. Predict the pole radius of the 700 Hz formant ( Hz) at kHz. What radius gives the same bandwidth at kHz?
  2. How many poles? For the frame above, try orders 4, 6, 8, 10 and 12. Predict the smallest order that recovers all three formants (within 150 Hz, with Hz), then check. Why is the answer larger than ?
  3. Pre-emphasis. Pass the impulse train through two real poles at (a glottal-like tilt) before the vocal tract. At order 18, is the 2600 Hz formant still found without pre-emphasis? With ?
  4. Rule of thumb. What order does suggest at 8 kHz and at 44.1 kHz?

Answers

1. ; at 8 kHz, (halving doubles , so the pole moves away from the unit circle).

let r16 = (-std::f64::consts::PI * 80.0 / 16_000.0).exp();
let r8 = (-std::f64::consts::PI * 80.0 / 8_000.0).exp();
assert!((r16 - 0.98441).abs() < 5e-6);
assert!((r8 - 0.96907).abs() < 5e-6);

2. Order 10. Orders 4 and 6 find no narrow resonance and order 8 finds only two. Six poles would suffice in the limit of a long, noise-excited frame, but here the Hamming window, the short frame and the harmonic excitation leave some energy that LPC can only model with extra (broad) poles; the “+2” in the rule of thumb allows for these.

use audio_samples::lpc_analysis;
use num_complex::Complex64;
use std::f64::consts::PI;
let fs = 16_000.0;
let formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)];
let mut a_true = vec![1.0f64];
for &(f, b) in &formants {
    let (r, theta) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let sec = [1.0, -2.0 * r * theta.cos(), r * r];
    let mut out = vec![0.0; a_true.len() + 2];
    for (i, ai) in a_true.iter().enumerate() { for (j, sj) in sec.iter().enumerate() { out[i + j] += ai * sj; } }
    a_true = out;
}
let mut y = vec![0.0f64; 2400];
for i in 0..2400 {
    let e = if i % 133 == 0 { 1.0 } else { 0.0 };
    y[i] = e - (1..7).filter(|&k| k <= i).map(|k| a_true[k] * y[i - k]).sum::<f64>();
}
let frame: Vec<f32> = y[1600..2112].iter().map(|&v| v as f32).collect();
fn poly_roots(c: &[f64]) -> Vec<Complex64> {
    let p = c.len() - 1;
    let eval = |z: Complex64| c.iter().fold(Complex64::new(0.0, 0.0), |acc, &ci| acc * z + ci);
    let mut z: Vec<Complex64> = (0..p).map(|i| Complex64::from_polar(0.9, 2.0 * PI * i as f64 / p as f64 + 0.4)).collect();
    for _ in 0..5000 {
        let mut biggest = 0.0f64;
        for i in 0..p {
            let den = (0..p).filter(|&j| j != i).fold(Complex64::new(1.0, 0.0), |d, j| d * (z[i] - z[j]));
            let step = eval(z[i]) / den;
            z[i] -= step;
            biggest = biggest.max(step.norm());
        }
        if biggest < 1e-14 { break; }
    }
    z
}
let found = |p: usize| -> usize {
    let mut a = vec![1.0];
    a.extend(lpc_analysis(&frame, p).coeffs.iter().map(|&v| f64::from(v)));
    let res: Vec<(f64, f64)> = poly_roots(&a)
        .iter()
        .filter(|z| z.im > 0.0)
        .map(|z| (z.arg() * fs / (2.0 * PI), -z.norm().ln() * fs / PI))
        .filter(|&(_, b)| b < 400.0)
        .collect();
    formants.iter().filter(|&&(f, _)| res.iter().any(|&(fe, _)| (fe - f).abs() < 150.0)).count()
};
let counts: Vec<usize> = [4, 6, 8, 10, 12].iter().map(|&p| found(p)).collect();
assert_eq!(counts, vec![0, 0, 2, 3, 3]);

3. Without pre-emphasis the pole nearest 2600 Hz moves to 2701 Hz and broadens to Hz: the strong low frequencies dominate the prediction error and F3 is lost. After pre-emphasis all three formants are back within 30 Hz (709, 1219 and 2577 Hz).

use audio_samples::lpc_analysis;
use num_complex::Complex64;
use std::f64::consts::PI;
let fs = 16_000.0;
let formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)];
let mut a_true = vec![1.0f64];
for &(f, b) in &formants {
    let (r, theta) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let sec = [1.0, -2.0 * r * theta.cos(), r * r];
    let mut out = vec![0.0; a_true.len() + 2];
    for (i, ai) in a_true.iter().enumerate() { for (j, sj) in sec.iter().enumerate() { out[i + j] += ai * sj; } }
    a_true = out;
}
fn poly_roots(c: &[f64]) -> Vec<Complex64> {
    let p = c.len() - 1;
    let eval = |z: Complex64| c.iter().fold(Complex64::new(0.0, 0.0), |acc, &ci| acc * z + ci);
    let mut z: Vec<Complex64> = (0..p).map(|i| Complex64::from_polar(0.9, 2.0 * PI * i as f64 / p as f64 + 0.4)).collect();
    for _ in 0..5000 {
        let mut biggest = 0.0f64;
        for i in 0..p {
            let den = (0..p).filter(|&j| j != i).fold(Complex64::new(1.0, 0.0), |d, j| d * (z[i] - z[j]));
            let step = eval(z[i]) / den;
            z[i] -= step;
            biggest = biggest.max(step.norm());
        }
        if biggest < 1e-14 { break; }
    }
    z
}
let resonances = |frame: &[f32]| -> Vec<(f64, f64)> {
    let mut a = vec![1.0];
    a.extend(lpc_analysis(frame, 18).coeffs.iter().map(|&v| f64::from(v)));
    poly_roots(&a).iter().filter(|z| z.im > 0.0)
        .map(|z| (z.arg() * fs / (2.0 * PI), -z.norm().ln() * fs / PI)).collect()
};
// Glottal-like source: impulse train through 1/(1 - 0.95 z^-1)^2, then 1/A(z).
let n = 2400;
let (mut g1, mut g2, mut y) = (vec![0.0f64; n], vec![0.0f64; n], vec![0.0f64; n]);
for i in 0..n {
    let e = if i % 133 == 0 { 1.0 } else { 0.0 };
    g1[i] = e + if i > 0 { 0.95 * g1[i - 1] } else { 0.0 };
    g2[i] = g1[i] + if i > 0 { 0.95 * g2[i - 1] } else { 0.0 };
    y[i] = g2[i] - (1..7).filter(|&k| k <= i).map(|k| a_true[k] * y[i - k]).sum::<f64>();
}
let raw: Vec<f32> = y[1600..2112].iter().map(|&v| v as f32).collect();
let pre: Vec<f32> = (1600..2112).map(|i| (y[i] - 0.97 * y[i - 1]) as f32).collect();

let nearest = |res: &[(f64, f64)], f: f64| {
    *res.iter().min_by(|x, y| (x.0 - f).abs().total_cmp(&(y.0 - f).abs())).unwrap()
};
let (f3_raw, b3_raw) = nearest(&resonances(&raw), 2600.0);
assert!(b3_raw > 400.0); // without pre-emphasis F3 is too broad to count
assert_eq!((f3_raw.round(), b3_raw.round()), (2701.0, 729.0));
let with_pre = resonances(&pre);
let mut estimates = Vec::new();
for &(f, _) in &formants {
    let (fe, be) = nearest(&with_pre, f);
    assert!((fe - f).abs() < 30.0 && be < 400.0, "{f} -> {fe} (B {be})");
    estimates.push(fe.round());
}
assert_eq!(estimates, vec![709.0, 1219.0, 2577.0]);

4. 10 at 8 kHz (telephone speech; SILK narrowband also uses 10) and , so about 46, at 44.1 kHz, which is why speech is usually downsampled before LPC.

use audio_samples::educational::topics;
let q = |fs: f64| topics::lpc(10, fs).quantity("Rule-of-thumb order").unwrap().value;
assert_eq!(q(8_000.0), 10.0);
assert!((q(44_100.0) - 46.1).abs() < 1e-9);

Common pitfalls

  • Sign convention. The crate stores coefficients, ; the “predictor” form uses .
  • Two LPC routines. lpc_analysis applies a Hamming window, the autocorrelation method and a diagonal loading; AudioEffects::lpc uses Burg’s method on the raw frame. Their numbers differ slightly.
  • f32 in, f32 out. lpc_analysis takes &[f32] and returns f32 coefficients; compare with a tolerance near relative, not exactly.
  • Short frames. The order is silently lowered to frame.len() / 2.
  • Not every pole is a formant. Filter roots by bandwidth (and frequency) before calling them formants, and expect estimates biased towards harmonics for high-pitched voices.
  • Pre-emphasis changes the gain and the residual, so undo it (with ) if you resynthesise.

References

  • J. Makhoul, “Linear prediction: a tutorial review”, Proceedings of the IEEE 63(4), 561-580, 1975.
  • N. Levinson, “The Wiener RMS (root mean square) error criterion in filter design and prediction”, Journal of Mathematics and Physics 25, 261-278, 1947; J. Durbin, “The fitting of time-series models”, Revue de l’Institut International de Statistique 28(3), 233-244, 1960.
  • G. Fant, Acoustic Theory of Speech Production, Mouton, 1960. The source-filter model.
  • L. R. Rabiner and R. W. Schafer, Digital Processing of Speech Signals, Prentice-Hall, 1978.
  • J.-M. Valin, K. Vos and T. Terriberry, Definition of the Opus Audio Codec, RFC 6716, IETF, 2012. SILK’s LPC orders and line spectral frequencies.

See also

09. Pitch: autocorrelation and YIN

The previous chapter recovered the vocal-tract filter; this one recovers the source. The fundamental frequency of voiced speech carries intonation, stress, speaker identity and, in tone languages, meaning. Pitch estimators look for the period of the waveform rather than for a spectral peak, which is why they still work when the fundamental itself is missing (as it is on a telephone line, which cuts everything below about 300 Hz).

Concept

A signal is periodic with period seconds if ; its fundamental frequency is Hz. In samples the period is the lag , where is the sample rate in Hz; in general is not an integer.

Autocorrelation. The (unnormalised) autocorrelation of an -sample frame at lag (samples) is

It peaks at multiples of the period. The estimator searches (, the search range in Hz) and reports . Because is an integer, the answers lie on the grid , whose spacing near is

in Hz. The true can fall anywhere between two grid points, so the worst-case error is half a step, . At 16 kHz the step is small for a 110 Hz voice ( Hz, error at most 0.38 Hz) but not for higher pitches: Hz at 440 Hz (error at most 6.0 Hz) and Hz at 880 Hz (error at most 23.4 Hz).

YIN (de Cheveigné and Kawahara, 2002) replaces the product by a squared difference, normalises it, and interpolates:

where (squared signal units) is the difference function over all overlapping pairs of samples and (dimensionless) the cumulative-mean-normalised difference (CMND). starts at 1, stays near 1 for lags shorter than the period and dips towards 0 at the period. The estimate is the first lag with ( the threshold, typically 0.1 to 0.2), moved forward to the bottom of that dip, and refined by fitting a parabola through (this is what the crate does; see the note below). With and the vertex lies at :

so the period is fractional and the estimate is no longer restricted to the integer grid. The shift is skipped (left at 0) when is at either end of the search range or when (the vertex would lie more than one lag away). If no lag dips below the crate declares the frame unvoiced.

How this differs from the paper. De Cheveigné and Kawahara’s step 5 (parabolic interpolation) fits the parabola to the raw difference function , not to , because interpolating is slightly biased; their step 6 (“best local estimate”) then re-runs the search around each frame’s estimate. And when no lag dips below , the paper takes the global minimum of instead of declaring the frame unvoiced. The crate interpolates , has no step 6 and reports such frames as unvoiced. Finally, the paper sums over a fixed window of samples starting at the beginning of the frame; the crate sums over all overlapping pairs. A fixed window measures the pitch of the frame’s early part, which matters when the pitch moves within the frame (about 9 cents on a 1.5 octave/s glide with 2048-sample frames at 22.05 kHz).

Octave errors. A signal with period also repeats at , , …; and if its odd harmonics are weak it nearly repeats at . Picking halves the estimate (a sub-octave error); picking doubles it. YIN’s “first dip below ” rule guards against the first kind; the second is controlled by .

Frame length. The difference function needs lags up to plus a window, so both detectors in this crate require , i.e. at least samples, a little more than two periods of .

With the library

detect_pitch_autocorr and detect_pitch_yin analyse the whole signal as one frame and return Ok(None) when no pitch is found.

use audio_samples::{AudioPitchAnalysis, sample_rate, sine_wave};
use std::time::Duration;

let fs = 16_000.0;
let x = sine_wave::<f64>(440.0, Duration::from_millis(50), sample_rate!(16000), 0.8);

let ac = x.detect_pitch_autocorr(80.0, 1000.0).unwrap().unwrap();
let yin = x.detect_pitch_yin(0.1, 80.0, 1000.0).unwrap().unwrap();
println!("autocorrelation {ac:.2} Hz, YIN {yin:.3} Hz");

// The true period is 16000/440 = 36.36 samples. Autocorrelation must pick an
// integer lag (36), so it reports 444.44 Hz: off by 4.4 Hz, within half of
// the 12-Hz grid step f0^2/f_s.
assert_eq!(ac, fs / 36.0);
assert!((ac - 440.0).abs() <= 0.5 * (fs / 36.0 - fs / 37.0));

// The grid steps and worst-case errors quoted in the Concept section: the
// step between the two integer lags that bracket fs / f0, and half of it.
let step = |f0: f64| {
    let tau = (fs / f0).floor();
    fs / tau - fs / (tau + 1.0)
};
for (f0, df, worst) in [(110.0, 0.76, 0.38), (440.0, 12.0, 6.0), (880.0, 46.8, 23.4)] {
    assert!((step(f0) - df).abs() < 0.05, "{f0}: {}", step(f0));
    assert!((step(f0) / 2.0 - worst).abs() < 0.05);
    assert!((step(f0) - f0 * f0 / fs).abs() / step(f0) < 0.1); // close to f0^2/fs
}
// YIN interpolates the period and is within 0.1 Hz (440.0986 Hz).
assert!((yin - 440.0986).abs() < 5e-5);
assert!((yin - 440.0).abs() < 0.1);

The lab repeats this for 110, 220, 440 and 880 Hz: the autocorrelation errors are +0.34, -0.82, +4.44 and +8.89 Hz, always within half a grid step; YIN’s are +0.0006, +0.0124, +0.0986 and +1.2354 Hz.

How it works

Both estimators are short enough to write out. We implement them exactly as the formulas above and compare with the library on the same 440 Hz frame.

use audio_samples::{AudioPitchAnalysis, sample_rate, sine_wave};
use std::time::Duration;

let fs = 16_000.0;
let audio = sine_wave::<f64>(440.0, Duration::from_millis(50), sample_rate!(16000), 0.8);
let x = audio.as_slice().unwrap();
let n = x.len();
let (min_tau, max_tau) = ((fs / 1000.0) as usize, (fs / 80.0) as usize); // 16, 200

// Autocorrelation: argmax of r(tau) over the lag range.
let r = |tau: usize| (0..n - tau).map(|i| x[i] * x[i + tau]).sum::<f64>();
let best = (min_tau..=max_tau).max_by(|&a, &b| r(a).total_cmp(&r(b))).unwrap();
assert_eq!(best, 36);
assert_eq!(fs / best as f64, audio.detect_pitch_autocorr(80.0, 1000.0).unwrap().unwrap());

// YIN step 1: difference function over all n - tau overlapping pairs.
let d: Vec<f64> = (0..=max_tau)
    .map(|tau| (0..n - tau).map(|j| (x[j] - x[j + tau]).powi(2)).sum())
    .collect();
// Step 2: cumulative-mean-normalised difference d'.
let mut cmnd = vec![1.0; max_tau + 1];
let mut running = 0.0;
for tau in 1..=max_tau {
    running += d[tau];
    cmnd[tau] = d[tau] * tau as f64 / running;
}
// Step 3: first lag below theta, then down to the bottom of the dip.
let theta = 0.1;
let mut tau = (min_tau..=max_tau).find(|&t| cmnd[t] < theta).unwrap();
assert_eq!(tau, 34); // d'(34) = 0.0756 is already below 0.1 ...
assert!((cmnd[34] - 0.0756).abs() < 1e-4 && (cmnd[36] - 0.0019).abs() < 1e-4);
while tau < max_tau && cmnd[tau + 1] < cmnd[tau] {
    tau += 1;
}
assert_eq!(tau, 36); // ... but the minimum of the dip is at 36 (d' = 0.0019)
// Step 4: parabolic interpolation, here on d' (the paper's step 5
// interpolates the raw d instead), skipped at the ends of the range or
// when |b| >= |a|.
let a = cmnd[tau + 1] + cmnd[tau - 1] - 2.0 * cmnd[tau];
let b = (cmnd[tau + 1] - cmnd[tau - 1]) / 2.0;
let shift = if tau > min_tau && tau < max_tau && b.abs() < a.abs() { -b / a } else { 0.0 };
assert!((shift - 0.3555).abs() < 1e-4); // the true period is 36.3636 samples
let tau_hat = tau as f64 + shift;
let f_hat = fs / tau_hat;
println!("d'(34..=38) = {:.4?}; period {tau_hat:.4} samples, f0 {f_hat:.4} Hz", &cmnd[34..=38]);

let lib = audio.detect_pitch_yin(theta, 80.0, 1000.0).unwrap().unwrap();
// Same operations in the same order, so agreement is to rounding error.
assert!((f_hat - lib).abs() < 1e-9, "{f_hat} vs {lib}");
Normalised autocorrelation r(tau)/r(0) of the 50 ms, 440 Hz tone at 16 kHz. Over the search range for 80 to 1000 Hz (lags 16 to 200, right of the grey line) the largest value is at lag 36, so detect_pitch_autocorr reports 16000/36 = 444.44 Hz; the true period is 36.36 samples.
Figure 9.1. Normalised autocorrelation r(tau)/r(0) of the 50 ms, 440 Hz tone at 16 kHz. Over the search range for 80 to 1000 Hz (lags 16 to 200, right of the grey line) the largest value is at lag 36, so detect_pitch_autocorr reports 16000/36 = 444.44 Hz; the true period is 36.36 samples.
YIN on the 440 Hz tone. Top: the cumulative-mean-normalised difference d'(tau) starts at 1 and dips at multiples of the period. Bottom: the first lag below the threshold 0.1 is 34; the search moves on to the bottom of the dip at 36, and a parabola through lags 35 to 37 puts the period at 36.36 samples, 440.10 Hz (detect_pitch_yin).
Figure 9.2. YIN on the 440 Hz tone. Top: the cumulative-mean-normalised difference d'(tau) starts at 1 and dips at multiples of the period. Bottom: the first lag below the threshold 0.1 is 34; the search moves on to the bottom of the dip at 36, and a parabola through lags 35 to 37 puts the period at 36.36 samples, 440.10 Hz (detect_pitch_yin).

Octave errors and the missing fundamental. First, harmonics 2 to 6 of 200 Hz with equal amplitudes and nothing at 200 Hz itself. Then a signal whose odd harmonics (1, 3, 5) are 20 dB weaker than its even ones: its true period is still 80 samples (5 ms), but it is almost periodic at 40 samples.

use audio_samples::{AudioPitchAnalysis, AudioSamples, AudioTransforms, sample_rate};
use ndarray::Array1;
use std::f64::consts::PI;

let fs = 16_000.0;
let n = 1600; // 0.1 s: 20 periods of 200 Hz, so FFT bins fall on harmonics
let complex = |harmonics: &[(f64, f64)]| {
    let x: Vec<f64> = (0..n)
        .map(|i| harmonics.iter().map(|&(h, a)| a * (2.0 * PI * h * 200.0 * i as f64 / fs).cos()).sum())
        .collect();
    AudioSamples::new_mono(Array1::from(x), sample_rate!(16000)).unwrap()
};

// 1. Missing fundamental: no energy at 200 Hz, yet both detectors find it.
let missing = complex(&[(2.0, 1.0), (3.0, 1.0), (4.0, 1.0), (5.0, 1.0), (6.0, 1.0)]);
let mag = missing.rfft(std::num::NonZeroUsize::new(n).unwrap()).unwrap();
assert!(mag[[0, 20]] < 1e-9 * mag[[0, 40]]); // bin 20 = 200 Hz is empty
assert!((missing.detect_pitch_yin(0.1, 80.0, 500.0).unwrap().unwrap() - 200.0).abs() < 0.1);
assert_eq!(missing.detect_pitch_autocorr(80.0, 500.0).unwrap().unwrap(), 200.0);

// 2. Weak odd harmonics: an octave error, controlled by the YIN threshold.
let weak = complex(&[(1.0, 0.1), (2.0, 1.0), (3.0, 0.1), (4.0, 1.0), (5.0, 0.1), (6.0, 1.0)]);
let at = |theta: f64| weak.detect_pitch_yin(theta, 80.0, 500.0).unwrap().unwrap();
assert!((at(0.1) - 400.0).abs() < 1.0); // octave error: half the period
assert!((at(0.01) - 200.0).abs() < 0.1); // strict threshold: the true period
// Autocorrelation is biased towards short lags (fewer terms in the sum at
// long lags) and also doubles the pitch.
assert_eq!(weak.detect_pitch_autocorr(80.0, 500.0).unwrap().unwrap(), 400.0);

At the half period (lag 40) the CMND has a deep dip of its own, and any threshold above the bottom of that dip accepts the half period (exercise 3 asks how deep it is). A strict threshold fixes this signal but rejects more real, slightly aperiodic speech frames: that is the trade-off the threshold controls.

d'(tau) of the 200 Hz signal whose odd harmonics are 20 dB weaker than its even ones. The half-period dip at lag 40 reaches 0.0196, below the default threshold 0.1, so detect_pitch_yin reports 400 Hz; with a threshold of 0.019 or 0.01 it continues to the true period, lag 80 (200 Hz).
Figure 9.3. d'(tau) of the 200 Hz signal whose odd harmonics are 20 dB weaker than its even ones. The half-period dip at lag 40 reaches 0.0196, below the default threshold 0.1, so detect_pitch_yin reports 400 Hz; with a threshold of 0.019 or 0.01 it continues to the true period, lag 80 (200 Hz).

Tracking a glide. track_pitch cuts the signal into frames of window_size samples every hop_size samples (no window function, no padding) and runs the detector on each. Each PitchFrame’s time is the frame start; for a linear glide the appropriate reference is the frequency at the frame centre.

use audio_samples::operations::types::PitchDetectionMethod;
use audio_samples::{AudioPitchAnalysis, chirp, nzu, sample_rate};
use std::time::Duration;

let fs = 16_000.0;
// 0.5 s linear glide from 100 to 200 Hz: f(t) = 100 + 200 t.
let glide = chirp::<f64>(100.0, 200.0, Duration::from_millis(500), sample_rate!(16000), 0.8);

// 512 samples (32 ms) is more than the 402 needed to search down to 80 Hz.
let track = glide
    .track_pitch(nzu!(512), nzu!(128), PitchDetectionMethod::Yin, 0.1, 80.0, 400.0)
    .unwrap();
let mut worst: f64 = 0.0;
for frame in track.frames().iter().filter(|f| f.time + 512.0 / fs <= 0.5) {
    let truth = 100.0 + 200.0 * (frame.time + 256.0 / fs);
    let f = frame.frequency.expect("every full frame is voiced");
    worst = worst.max((f - truth).abs());
}
println!("worst error {worst:.2} Hz over {} frames", track.len());
assert!(worst < 1.0);
assert!((worst - 0.12).abs() < 0.005);

// 256 samples (16 ms) cannot hold two periods of 80 Hz: every frame is unvoiced.
let short = glide
    .track_pitch(nzu!(256), nzu!(64), PitchDetectionMethod::Yin, 0.1, 80.0, 400.0)
    .unwrap();
assert!(short.frames().iter().all(|f| f.frequency.is_none()));
assert_eq!(short.mean_pitch(), None);

The lab tracks a 1 s glide from 100 to 300 Hz: with 64 ms and with 32 ms frames every full frame is voiced and the worst error is well below 1 Hz (0.24 and 0.12 Hz); with 16 ms frames none is.

track_pitch with YIN, 512-sample frames every 128 samples, on a 0.5 s linear glide from 100 to 200 Hz. Top: each estimate at its frame centre. Bottom: estimate minus the glide's frequency at the frame centre; the largest deviation is 0.12 Hz.
Figure 9.4. track_pitch with YIN, 512-sample frames every 128 samples, on a 0.5 s linear glide from 100 to 200 Hz. Top: each estimate at its frame centre. Bottom: estimate minus the glide's frequency at the frame centre; the largest deviation is 0.12 Hz.

Ask the library to explain

use audio_samples::educational::{WarningLevel, topics};

// YIN searching 80-400 Hz at 16 kHz.
let doc = topics::yin(0.1, 80.0, 400.0, 16_000.0, Some(256));
println!("{doc}");
assert_eq!(doc.quantity("Longest lag").unwrap().value, 200.0);
assert_eq!(doc.quantity("Minimum frame length").unwrap().value, 402.0);
assert!(doc.has_warning(WarningLevel::Problem)); // 256 < 402
assert!(!topics::yin(0.1, 80.0, 400.0, 16_000.0, Some(512)).has_warning(WarningLevel::Problem));

// Autocorrelation searching 80-1000 Hz: the grid step at the top of the range.
let doc = topics::autocorrelation_pitch(80.0, 1000.0, 16_000.0);
assert_eq!(doc.quantity("Shortest lag").unwrap().value, 16.0);
let step = doc.quantity("Pitch step at f_max").unwrap().value;
assert!((step - (1000.0 - 16_000.0 / 17.0)).abs() < 1e-9); // 58.8 Hz
assert!(doc.has_warning_containing("octave errors"));

The YIN explanation prints the four formulas of this chapter and the minimum frame length; the autocorrelation one quotes the integer-lag pitch steps and warns that a search range spanning more than an octave allows octave errors.

Exercises

  1. Grid step. Near 1 kHz at kHz, how far apart are neighbouring autocorrelation estimates? Compare with .
  2. Low voices. A bass singer goes down to 60 Hz. What is the minimum YIN frame length at 16 kHz? Predict what track_pitch returns on a 70 Hz tone with 512-sample frames and Hz, then check.
  3. Choosing the threshold. For the weak-odd-harmonics signal above, compute yourself and predict the YIN estimate with and .

Answers

1. Lags 16 and 17 give 1000 Hz and 941.18 Hz: a step of 58.8 Hz, against Hz (the approximation is coarse for short lags).

use audio_samples::educational::topics;
let step: f64 = 16_000.0 / 16.0 - 16_000.0 / 17.0;
assert!((step - 58.82).abs() < 0.01);
assert_eq!(1000.0f64 * 1000.0 / 16_000.0, 62.5);
let doc = topics::autocorrelation_pitch(80.0, 1000.0, 16_000.0);
assert!((doc.quantity("Pitch step at f_max").unwrap().value - step).abs() < 1e-9);

2. , so samples (33.4 ms). With 512-sample frames every frame is unvoiced, even though 512 samples hold more than two 70 Hz periods (2 × 228.6 = 457): the frame must cover the whole search range, not only the actual pitch.

use audio_samples::educational::topics;
use audio_samples::operations::types::PitchDetectionMethod;
use audio_samples::{AudioPitchAnalysis, nzu, sample_rate, sine_wave};
use std::time::Duration;

let doc = topics::yin(0.1, 60.0, 400.0, 16_000.0, Some(512));
assert_eq!(doc.quantity("Minimum frame length").unwrap().value, 534.0);
assert!(doc.has_warning_containing("shorter than the 534 samples"));

let low = sine_wave::<f64>(70.0, Duration::from_millis(300), sample_rate!(16000), 0.8);
let track = low
    .track_pitch(nzu!(512), nzu!(128), PitchDetectionMethod::Yin, 0.1, 60.0, 400.0)
    .unwrap();
assert!(track.frames().iter().all(|f| f.frequency.is_none()));
let track = low
    .track_pitch(nzu!(1024), nzu!(256), PitchDetectionMethod::Yin, 0.1, 60.0, 400.0)
    .unwrap();
assert!((track.mean_pitch().unwrap() - 70.0).abs() < 0.5);

3. , the deepest point of the half-period dip, so accepts lag 40 (400 Hz) and rejects it and continues to the true period (200 Hz).

use audio_samples::{AudioPitchAnalysis, AudioSamples, sample_rate};
use ndarray::Array1;
use std::f64::consts::PI;

let fs = 16_000.0;
let amps = [(1.0, 0.1), (2.0, 1.0), (3.0, 0.1), (4.0, 1.0), (5.0, 0.1), (6.0, 1.0)];
let x: Vec<f64> = (0..1600)
    .map(|i| amps.iter().map(|&(h, a): &(f64, f64)| a * (2.0 * PI * h * 200.0 * i as f64 / fs).cos()).sum())
    .collect();

// d'(tau) for the library's lag range (80-500 Hz: lags 32..=200), with d
// summed over all N - tau overlapping pairs as in the Concept section.
let max_tau = 200;
let d: Vec<f64> = (0..=max_tau)
    .map(|tau| (0..x.len() - tau).map(|j| (x[j] - x[j + tau]).powi(2)).sum())
    .collect();
let cmnd = |tau: usize| d[tau] * tau as f64 / d[1..=tau].iter().sum::<f64>();
assert!((cmnd(40) - 0.0196).abs() < 5e-5);
assert!((32..40).all(|t| cmnd(t) > cmnd(40))); // 40 is the bottom of the dip

let audio = AudioSamples::new_mono(Array1::from(x), sample_rate!(16000)).unwrap();
let f = |theta: f64| audio.detect_pitch_yin(theta, 80.0, 500.0).unwrap().unwrap();
assert!((f(0.021) - 400.0).abs() < 1.0);
assert!((f(0.019) - 200.0).abs() < 0.1);

Common pitfalls

  • Frame length is set by , not by the pitch you expect: frames of at most samples always return None.
  • PitchFrame::time is the frame start, not its centre (AudioPitchTracking::yin and pyin centre their frames by default).
  • Not exactly the paper. The crate interpolates (the paper interpolates ) and has no “best local estimate” step. A frame with no dip below is unvoiced, while the paper falls back to the global minimum and always returns a value.
  • The autocorrelation estimate is quantised to ; use YIN (or interpolate the peak yourself) when you need better than .
  • Octave errors are a property of the signal, not a bug: narrow when you know the speaker, and lower when harmonics alternate in strength.
  • detect_pitch_autocorr requires Hz; both methods reject multi-channel audio.

References

  • A. de Cheveigné and H. Kawahara, “YIN, a fundamental frequency estimator for speech and music”, Journal of the Acoustical Society of America 111(4), 1917-1930, 2002.
  • L. R. Rabiner, “On the use of autocorrelation analysis for pitch detection”, IEEE Transactions on Acoustics, Speech, and Signal Processing 25(1), 24-33, 1977.
  • M. Mauch and S. Dixon, “pYIN: a fundamental frequency estimator using probabilistic threshold distributions”, Proc. IEEE ICASSP, 2014. The probabilistic extension implemented by AudioPitchTracking::pyin.

See also

10. Cepstrum, mel and MFCC

Speech recognisers rarely use raw spectra. They warp frequency to approximate the ear’s frequency resolution (the mel scale), take logarithms to turn the source-filter product into a sum, and keep a dozen smooth “cepstral” coefficients that describe the vocal-tract envelope while discarding pitch. This chapter builds that pipeline, mel-frequency cepstral coefficients (MFCCs), from the real cepstrum upwards, and checks each step against the library.

Concept

Real cepstrum. For an -point frame with DFT ,

where is the quefrency in samples ( seconds, the sample rate in Hz) and is the natural logarithm. Because is real and even, is real and even. Taking logs turns the source-filter product into a sum, : the smooth vocal-tract envelope occupies the low quefrencies, and a periodic source with period samples produces a peak at , so . The crate has no cepstrum function; we compute it from AudioTransforms::fft ourselves.

Mel scale. Two conventions are in use, and this crate uses both:

  • HTK (O’Shaughnessy): , inverse . Used by hz_to_mel, mel_to_hz and mel_frequencies.
  • Slaney (Auditory Toolbox): for Hz and above. Used by the mel spectrogram and therefore by MFCCs.

Here is in Hz and in mels; the two scales have very different units (1000 Hz is 1000 HTK mels but 15 Slaney mels), so never mix them.

Mel filterbank. triangular filters with edges equally spaced in mels: , , . Filter (with neighbours , in Hz) weights FFT bin at frequency by

and the mel power in band is .

MFCC, as this library computes it. Per frame, with mel bands from 0 Hz to (no filter normalisation):

where is the log mel energy in dB with an absolute floor of -80 dB, the unnormalised DCT-II (, = n_mfcc) and the liftered coefficient with lifter parameter by default (0 disables it). The orthonormal DCT-II gives and , so with the lifter off this library’s values are larger than the orthonormal ones by for and for .

With the library

use audio_samples::{AudioSamples, AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{MelParams, MfccParams, SpectrogramParams, StftParams, WindowType};
use std::time::Duration;

let fs = 16_000.0;
let audio = sine_wave::<f64>(440.0, Duration::from_millis(250), sample_rate!(16000), 0.5);

// 32 ms frames every 10 ms, the usual speech setting.
let stft = StftParams::new(nzu!(512), nzu!(160), WindowType::Hanning, true).unwrap();
let mel = MelParams::new(nzu!(40), 0.0, fs / 2.0).unwrap();
let mel_power = audio
    .mel_power_spectrogram(&SpectrogramParams::new(stft.clone(), fs).unwrap(), &mel)
    .unwrap();
let mfcc = audio.mfcc(&stft, nzu!(40), &MfccParams::speech_standard()).unwrap();

// 4000 samples, hop 160, centred frames: 1 + 4000/160 = 26 frames.
assert_eq!(mel_power.data().dim(), (40, 26));
assert_eq!(mfcc.data.dim(), (13, 26)); // 13 coefficients, c0 included, lifter 22
// The tone falls in the band whose centre is nearest 440 Hz. Below 1 kHz the
// Slaney scale is linear, so band i (0-based) is centred at (i + 1) * 73.57 Hz.
let frame = 13;
let row = |b: usize| mel_power.data()[[b, frame]];
let loudest = (0..40).max_by(|&a, &b| row(a).total_cmp(&row(b))).unwrap();
let centre = (loudest + 1) as f64 * (200.0 / 3.0) * (15.0 + 27.0 * 8f64.ln() / 6.4f64.ln()) / 41.0;
println!("loudest mel band: {loudest}, centred at {centre:.1} Hz");
assert_eq!(loudest, 5);
assert!((centre - 441.4).abs() < 0.05);

How it works

The real cepstrum and cepstral pitch. A vowel-like frame (the formant filter of chapter 8 excited every 100 samples, Hz), Hann-windowed, 1024 samples. The one-sided FFT holds bins ; the even symmetry of folds the inverse DFT onto those bins.

use audio_samples::{AudioSamples, AudioTransforms, sample_rate};
use ndarray::Array1;
use std::f64::consts::PI;

let fs = 16_000.0;
// Vowel: impulse train (period 100 samples) through three formant resonators.
let mut a = vec![1.0f64];
for &(f, b) in &[(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)] {
    let (r, th) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let s = [1.0, -2.0 * r * th.cos(), r * r];
    let mut o = vec![0.0; a.len() + 2];
    for (i, ai) in a.iter().enumerate() { for (j, sj) in s.iter().enumerate() { o[i + j] += ai * sj; } }
    a = o;
}
let mut y = vec![0.0f64; 2600];
for i in 0..y.len() {
    let e = if i % 100 == 0 { 1.0 } else { 0.0 };
    y[i] = e - (1..a.len()).filter(|&k| k <= i).map(|k| a[k] * y[i - k]).sum::<f64>();
}

let n = 1024;
let frame: Vec<f64> = (0..n)
    .map(|i| (0.5 - 0.5 * (2.0 * PI * i as f64 / (n - 1) as f64).cos()) * y[1500 + i])
    .collect();
let audio = AudioSamples::new_mono(Array1::from(frame), sample_rate!(16000)).unwrap();
let x = audio.fft(std::num::NonZeroUsize::new(n).unwrap()).unwrap(); // bins 0..=512
let logmag: Vec<f64> = (0..=n / 2).map(|k| x[[0, k]].norm().max(1e-12).ln()).collect();

// c[q] = (1/N) [ L0 + L_{N/2} cos(pi q) + 2 sum_{k=1}^{N/2-1} L_k cos(2 pi k q / N) ]
let ceps = |q: usize| {
    let mut s = logmag[0] + logmag[n / 2] * (PI * q as f64).cos();
    for k in 1..n / 2 {
        s += 2.0 * logmag[k] * (2.0 * PI * (k * q) as f64 / n as f64).cos();
    }
    s / n as f64
};
// Search quefrencies for f0 between 60 and 400 Hz.
let (q_lo, q_hi) = ((fs / 400.0) as usize, (fs / 60.0) as usize); // 40, 266
let q_peak = (q_lo..=q_hi).max_by(|&p, &q| ceps(p).total_cmp(&ceps(q))).unwrap();
println!("cepstral peak at q = {q_peak} samples -> f0 = {} Hz", fs / q_peak as f64);
assert_eq!(q_peak, 100);
assert_eq!(fs / q_peak as f64, 160.0);

The lab also prints the low quefrencies (, ), which describe the envelope, and shows that the pitch peak (1.55) is well above every other value in the search range (at most 0.38).

Top: spectrum of the Hann-windowed vowel frame (1024 samples, f0 = 160 Hz): harmonics every 160 Hz under the formant envelope. Bottom: its real cepstrum. The envelope is at low quefrencies (c[1] = 2.32); in the search range for 60 to 400 Hz (lags 40 to 266) the largest value, 1.55, is at q = 100 samples, so f0 = 160 Hz.
Figure 10.1. Top: spectrum of the Hann-windowed vowel frame (1024 samples, f0 = 160 Hz): harmonics every 160 Hz under the formant envelope. Bottom: its real cepstrum. The envelope is at low quefrencies (c[1] = 2.32); in the search range for 60 to 400 Hz (lags 40 to 266) the largest value, 1.55, is at q = 100 samples, so f0 = 160 Hz.

The two mel scales, side by side, and the HTK round trip.

use audio_samples::utils::audio_math::{hz_to_mel, mel_to_hz};

let slaney = |f: f64| if f < 1000.0 { 3.0 * f / 200.0 } else { 15.0 + 27.0 * (f / 1000.0).ln() / 6.4f64.ln() };
let slaney_inv = |m: f64| if m < 15.0 { 200.0 * m / 3.0 } else { 1000.0 * (6.4f64.ln() * (m - 15.0) / 27.0).exp() };

for f in [0.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0] {
    println!("{f:6.0} Hz: HTK {:8.2} mel, Slaney {:6.3} mel", hz_to_mel(f), slaney(f));
    assert!((mel_to_hz(hz_to_mel(f)) - f).abs() < 1e-9); // HTK round trip
    assert!((slaney_inv(slaney(f)) - f).abs() < 1e-9);  // Slaney round trip
}
assert!((hz_to_mel(1000.0) - 999.99).abs() < 0.005);
assert!((hz_to_mel(4000.0) - 2146.06).abs() < 0.005);
assert_eq!(slaney(1000.0), 15.0);
assert!((slaney(4000.0) - 35.164).abs() < 5e-4);

The filterbank. Rebuild the 40 triangles on the Slaney scale and apply them to the library’s own power spectrogram; the result must be the library’s mel power spectrogram.

use audio_samples::{AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{MelParams, SpectrogramParams, StftParams, WindowType};
use std::time::Duration;

let fs = 16_000.0;
let audio = sine_wave::<f64>(440.0, Duration::from_millis(250), sample_rate!(16000), 0.5);
let sp = SpectrogramParams::new(StftParams::new(nzu!(512), nzu!(160), WindowType::Hanning, true).unwrap(), fs).unwrap();
let m = 40;
let lin = audio.linear_power_spectrogram(&sp).unwrap();
let mel = audio.mel_power_spectrogram(&sp, &MelParams::new(nzu!(40), 0.0, fs / 2.0).unwrap()).unwrap();
let (lin, mel) = (lin.data(), mel.data());

let slaney = |f: f64| if f < 1000.0 { 3.0 * f / 200.0 } else { 15.0 + 27.0 * (f / 1000.0).ln() / 6.4f64.ln() };
let slaney_inv = |m: f64| if m < 15.0 { 200.0 * m / 3.0 } else { 1000.0 * (6.4f64.ln() * (m - 15.0) / 27.0).exp() };
let step = (slaney(fs / 2.0) - slaney(0.0)) / (m + 1) as f64;
let edges: Vec<f64> = (0..m + 2).map(|i| slaney_inv(i as f64 * step)).collect();

let mut worst = 0.0f64;
for t in 0..mel.ncols() {
    for i in 0..m {
        let (l, c, r) = (edges[i], edges[i + 1], edges[i + 2]);
        let p: f64 = (0..lin.nrows())
            .map(|k| {
                let f = k as f64 * fs / 512.0;
                ((f - l) / (c - l)).min((r - f) / (r - c)).clamp(0.0, 1.0) * lin[[k, t]]
            })
            .sum();
        worst = worst.max((p - mel[[i, t]]).abs() / mel[[i, t]].max(1e-300));
    }
}
// Same products summed in a different order: rounding-level agreement.
assert!(worst < 1e-10, "{worst}");
The 40 triangular mel filters (Slaney scale, 0 Hz to 8 kHz, peak 1, no normalisation) from mel_filterbank, evaluated at the 257 bins of a 512-point FFT at 16 kHz. They are evenly spaced below 1 kHz and widen logarithmically above. Band 5 (orange, centred at 441.4 Hz) is the loudest for the 440 Hz tone.
Figure 10.2. The 40 triangular mel filters (Slaney scale, 0 Hz to 8 kHz, peak 1, no normalisation) from mel_filterbank, evaluated at the 257 bins of a 512-point FFT at 16 kHz. They are evenly spaced below 1 kHz and widen logarithmically above. Band 5 (orange, centred at 441.4 Hz) is the loudest for the 440 Hz tone.

MFCC, re-derived. From the library’s mel power spectrogram: the dB floor, the unnormalised DCT-II and the lifter, compared with AudioTransforms::mfcc; then the factor relative to the orthonormal DCT.

use audio_samples::{AudioTransforms, nzu, sample_rate, sine_wave};
use spectrograms::{MelParams, MfccParams, SpectrogramParams, StftParams, WindowType};
use std::f64::consts::PI;
use std::time::Duration;

let fs = 16_000.0;
let audio = sine_wave::<f64>(440.0, Duration::from_millis(250), sample_rate!(16000), 0.5);
let stft = StftParams::new(nzu!(512), nzu!(160), WindowType::Hanning, true).unwrap();
let m = 40;
let mel = audio
    .mel_power_spectrogram(&SpectrogramParams::new(stft.clone(), fs).unwrap(), &MelParams::new(nzu!(40), 0.0, fs / 2.0).unwrap())
    .unwrap();
let params = MfccParams::speech_standard(); // 13 coefficients, c0 kept, lifter 22
let lib = audio.mfcc(&stft, nzu!(40), &params).unwrap();
let lib_plain = audio.mfcc(&stft, nzu!(40), &params.with_lifter(0)).unwrap();

let dct = |l: &[f64], k: usize| -> f64 {
    l.iter().enumerate().map(|(i, li)| li * (PI * k as f64 * (i as f64 + 0.5) / m as f64).cos()).sum()
};
let mut worst = 0.0f64;
for t in 0..mel.data().ncols() {
    let l: Vec<f64> = (0..m).map(|i| 10.0 * mel.data()[[i, t]].max(1e-8).log10()).collect();
    for k in 0..13 {
        let lifter = 1.0 + 11.0 * (PI * k as f64 / 22.0).sin();
        worst = worst.max((dct(&l, k) * lifter - lib.data[[k, t]]).abs());
        // Orthonormal DCT-II, no lifter.
        let ortho = dct(&l, k) * if k == 0 { (1.0 / m as f64).sqrt() } else { (2.0 / m as f64).sqrt() };
        let factor = if k == 0 { (m as f64).sqrt() } else { (m as f64 / 2.0).sqrt() };
        assert!((lib_plain.data[[k, t]] - factor * ortho).abs() < 1e-9 * lib_plain.data[[k, t]].abs().max(1.0));
    }
}
// The liftered MFCC values here reach about 2300 in magnitude (2298), so
// 1e-8 absolute is rounding level.
let largest = lib.data.iter().fold(0.0f64, |a, v| a.max(v.abs()));
assert!((largest - 2298.06).abs() < 0.01);
assert!(worst < 1e-8, "{worst}");

So with 40 bands and the lifter off, this crate’s is times the orthonormal value and () times.

One frame (frame 13, 130 ms) of the 440 Hz tone. Top: log mel energies in dB, floored at -80 dB, with the peak in band 5. Bottom: the 13 MFCCs from AudioTransforms::mfcc (unnormalised DCT-II of the top panel), with the default lifter 22 and with the lifter off.
Figure 10.3. One frame (frame 13, 130 ms) of the 440 Hz tone. Top: log mel energies in dB, floored at -80 dB, with the peak in band 5. Bottom: the 13 MFCCs from AudioTransforms::mfcc (unnormalised DCT-II of the top panel), with the default lifter 22 and with the lifter off.

Ask the library to explain

MelParams and MfccParams implement Explain. Given the FFT size, the mel explanation counts filters that contain no FFT bin: with 128 bands and n_fft = 256 at 16 kHz the bins are 62.5 Hz apart but the lowest triangles are only 46.8 Hz wide. The code below checks the prediction against a computed spectrogram.

use audio_samples::educational::{Explain, ExplainContext, WarningLevel, topics};
use audio_samples::{AudioTransforms, nzu, sample_rate, white_noise};
use spectrograms::{MelParams, MfccParams, SpectrogramParams, StftParams, WindowType};
use std::time::Duration;

let mel = MelParams::new(nzu!(128), 0.0, 8000.0).unwrap();
let doc = mel.explain_with(&ExplainContext::new().with_sample_rate(16_000.0).with_n_fft(256));
println!("{doc}");
let empty = doc.quantity("Empty filters").unwrap().value as usize;
assert_eq!(empty, 13);
assert!(doc.has_warning_containing("contain no FFT bin"));
assert!((doc.quantity("Narrowest band width").unwrap().value - 46.77).abs() < 0.01);

// The computed spectrogram of white noise has exactly that many all-zero bands.
let noise = white_noise::<f64>(Duration::from_millis(250), sample_rate!(16000), 0.5, Some(7));
let sp = SpectrogramParams::new(StftParams::new(nzu!(256), nzu!(128), WindowType::Hanning, true).unwrap(), 16_000.0).unwrap();
let s = noise.mel_power_spectrogram(&sp, &mel).unwrap();
let zero_rows = s.data().rows().into_iter().filter(|r| r.iter().all(|&v| v == 0.0)).count();
assert_eq!(zero_rows, empty);

// MFCC: the lifter weights 1 + 11 sin(pi k / 22) peak at k = 11.
let mdoc = MfccParams::speech_standard().explain_with(&ExplainContext::new().with_n_mels(40));
assert_eq!(mdoc.quantity("Largest lifter weight").unwrap().value, 12.0);
// A lifter shorter than the number of coefficients gives negative weights.
let bad = MfccParams::speech_standard().with_lifter(10).explain_with(&ExplainContext::new().with_n_mels(40));
assert!(bad.has_warning(WarningLevel::Caution));

// Cepstrum: the longest quefrency of a 1024-point frame is 512 samples, so f0 > 31.25 Hz.
let cdoc = topics::cepstrum(1024, 16_000.0);
assert_eq!(cdoc.quantity("Lowest detectable f0").unwrap().value, 31.25);
assert!(cdoc.has_warning_containing("no stand-alone cepstrum"));

Exercises

  1. Quefrency. A 250 Hz voice is analysed with 1024-point frames at 16 kHz. At which quefrency (samples and ms) do you expect the cepstral peak? Check with a synthetic vowel.
  2. Units. Predict hz_to_mel(700.0) and the Slaney mel value of 700 Hz.
  3. Empty bands. For 128 mel bands at 16 kHz, what is the smallest power-of-two n_fft with no empty filter?
  4. Comparing with the orthonormal DCT. With 40 mel bands and the default lifter, by what total factor does this crate’s exceed the orthonormal, unliftered (same log mel input)?

Answers

1. samples, 4 ms.

use audio_samples::{AudioSamples, AudioTransforms, sample_rate};
use ndarray::Array1;
use std::f64::consts::PI;
let fs = 16_000.0;
let mut a = vec![1.0f64];
for &(f, b) in &[(700.0, 80.0), (1220.0, 90.0), (2600.0f64, 120.0f64)] {
    let (r, th) = ((-PI * b / fs).exp(), 2.0 * PI * f / fs);
    let s = [1.0, -2.0 * r * th.cos(), r * r];
    let mut o = vec![0.0; a.len() + 2];
    for (i, ai) in a.iter().enumerate() { for (j, sj) in s.iter().enumerate() { o[i + j] += ai * sj; } }
    a = o;
}
let mut y = vec![0.0f64; 2600];
for i in 0..y.len() {
    let e = if i % 64 == 0 { 1.0 } else { 0.0 }; // 250 Hz
    y[i] = e - (1..a.len()).filter(|&k| k <= i).map(|k| a[k] * y[i - k]).sum::<f64>();
}
let n = 1024;
let frame: Vec<f64> = (0..n).map(|i| (0.5 - 0.5 * (2.0 * PI * i as f64 / (n - 1) as f64).cos()) * y[1500 + i]).collect();
let x = AudioSamples::new_mono(Array1::from(frame), sample_rate!(16000)).unwrap()
    .fft(std::num::NonZeroUsize::new(n).unwrap()).unwrap();
let lm: Vec<f64> = (0..=n / 2).map(|k| x[[0, k]].norm().max(1e-12).ln()).collect();
let ceps = |q: usize| (lm[0] + lm[n / 2] * (PI * q as f64).cos()
    + (1..n / 2).map(|k| 2.0 * lm[k] * (2.0 * PI * (k * q) as f64 / n as f64).cos()).sum::<f64>()) / n as f64;
let q_peak = (40..=266).max_by(|&p, &q| ceps(p).total_cmp(&ceps(q))).unwrap();
assert_eq!(q_peak, 64);
assert_eq!(1000.0 * q_peak as f64 / fs, 4.0);

2. HTK: mels. Slaney: mels.

use audio_samples::utils::audio_math::hz_to_mel;
assert!((hz_to_mel(700.0) - 781.17).abs() < 0.005);
assert_eq!(3.0 * 700.0 / 200.0, 10.5);

3. 512: the bins are then 31.25 Hz apart, narrower than the 46.8 Hz lowest triangle, so every triangle contains at least one bin.

use audio_samples::educational::{Explain, ExplainContext};
use audio_samples::nzu;
use spectrograms::MelParams;
let mel = MelParams::new(nzu!(128), 0.0, 8000.0).unwrap();
let empty = |n_fft: usize| {
    mel.explain_with(&ExplainContext::new().with_sample_rate(16_000.0).with_n_fft(n_fft))
        .quantity("Empty filters").unwrap().value
};
assert!(empty(128) > empty(256)); // coarser bins, more empty bands
assert!(empty(256) > 0.0);
assert_eq!(empty(512), 0.0);

4. .

let factor = (40.0f64 / 2.0).sqrt() * (1.0 + 11.0 * (3.0 * std::f64::consts::PI / 22.0).sin());
assert!((factor - 24.91).abs() < 0.005);

Common pitfalls

  • Two mel scales. audio_math::{hz_to_mel, mel_to_hz, mel_frequencies} are HTK; the mel spectrogram and MFCCs are Slaney. Do not label mel spectrogram bands with mel_frequencies.
  • No filter normalisation by default. MelParams::new uses MelNorm::None (peak 1 per triangle), not Slaney’s equal-area normalisation. MelParams::with_norm selects another.
  • Unnormalised DCT and lifter 22 (with counted from 0): MFCC values are much larger than orthonormal-DCT values. Use with_lifter(0) and divide by / to compare.
  • Absolute log floor. The dB step clamps at (-80 dB re 1), not 80 dB below the frame’s peak, so a quiet signal’s MFCCs depend on its level.
  • Symmetric Hann. WindowType::Hanning is the symmetric window; many tools use the periodic one by default, so spectra differ slightly.
  • Empty mel bands appear when bands are narrower than the FFT bin spacing: ask MelParams::explain_with with the FFT size before choosing n_mels.
  • Cepstral pitch needs several periods in the frame and fails on breathy or weak voicing; YIN (chapter 9) is usually more robust.

References

  • S. B. Davis and P. Mermelstein, “Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences”, IEEE Transactions on Acoustics, Speech, and Signal Processing 28(4), 357-366, 1980. The MFCC.
  • M. Slaney, Auditory Toolbox, Version 2, Technical Report 1998-010, Interval Research Corporation, 1998. The Slaney mel scale and filterbank.
  • S. Young et al., The HTK Book, Cambridge University Engineering Department. The HTK mel formula and the sinusoidal lifter.
  • D. O’Shaughnessy, Speech Communication: Human and Machine, Addison-Wesley, 1987. The mel formula.
  • A. M. Noll, “Cepstrum pitch determination”, Journal of the Acoustical Society of America 41(2), 293-309, 1967.

See also

11. Short-time energy, zero crossings and VAD

Recognisers, codecs and diarisers usually run an inexpensive test of whether a frame contains speech before any expensive processing. Voice activity detection (VAD) makes that decision from two per-frame features that date back to the 1970s: short-time energy (speech is louder than the background) and the zero-crossing rate (voiced sounds cross zero slowly, fricatives and noise quickly). This chapter computes both by hand on a synthetic utterance and reproduces the library’s VAD decisions exactly.

Concept

Framing. The signal (samples scaled to ) is cut into frames of samples that start every samples; frame covers . Typical speech settings are ms and ms, i.e. and at kHz (the sample rate in Hz).

Short-time energy is reported as an RMS level in dBFS:

where is the frame RMS (dimensionless, full scale = 1) and the level in decibels relative to full scale. 0 dBFS is an RMS of 1 (a full-scale DC or square wave), so a full-scale sine is at dBFS in this convention; the AES17 convention (0 dBFS = the RMS of a full-scale sine) reads 3.01 dB higher. Where this guide means a peak level, of the largest absolute sample, it says “dBFS peak”. dBFS has no link to loudness in the room: the same file can be played at any volume (chapter 14).

Zero-crossing rate (ZCR) counts sign changes:

in crossings per sample. A sinusoid at Hz crosses zero times per second, so ; conversely a ZCR of corresponds to a “dominant frequency” of about Hz. White noise changes sign on about half of all sample pairs, .

Three classes of speech frame:

classenergyZCR
silence (background)lowhigh (noise-like)
voiced (vowels, nasals)highlow (periodic, energy below 1 kHz)
unvoiced (fricatives such as /s/)mediumhigh (noise-like, energy at 4-8 kHz)

Decision rules. An energy VAD marks frame as speech if , where is a threshold in dBFS, equivalently . A combined VAD also requires , which rejects low hum and noise-like frames (and, as shown below, fricatives).

Post-processing. Raw per-frame decisions switch rapidly between speech and non-speech. The library smooths them with a causal majority vote over frames, then applies hangover: after the last active frame the next frames stay active, which bridges short pauses (stop closures, the gap before a final plosive) at the cost of a later offset. Finally, speech runs shorter than a minimum and silence gaps shorter than a minimum are removed.

Two ZCR conventions in the library. The VAD’s ZCR is per frame, in crossings per sample, and skips exact zeros. AudioStatistics::zero_crossing_rate is for the whole signal and is in crossings per second; its crossing rule treats an exact zero as non-positive. The frame-wise zero_crossing_rate_frames uses centred frames and divides by the frame length, so this chapter computes the VAD’s version directly.

With the library

Build an utterance at 16 kHz with the generators: 300 ms of silence, a 400 ms “vowel” (harmonics of 200 Hz shaped by a resonance at 700 Hz), a 200 ms “fricative” (white noise), 300 ms of silence, plus a dBFS noise floor. Run an energy VAD with 25 ms frames, 10 ms hop, a dBFS threshold and no smoothing or minimum-run rules so that only the threshold and the hangover act.

use audio_samples::operations::types::{VadConfig, VadMethod};
use audio_samples::utils::generation::{MonoSampleBuilder, ToneComponent};
use audio_samples::{AudioSamples, AudioVoiceActivityDetection, compound_tone, nzu, sample_rate, white_noise};
use non_empty_slice::{NonEmptySlice, NonEmptyVec};
use std::time::Duration;

let sr = sample_rate!(16000);
let partials: Vec<ToneComponent> = (1..=20)
    .map(|k| {
        let f = 200.0 * k as f64;
        ToneComponent::new(f, 0.3 / (1.0 + ((f - 700.0) / 200.0).powi(2)))
    })
    .collect();
let vowel = compound_tone::<f64>(NonEmptySlice::from_slice(&partials).unwrap(), Duration::from_millis(400), sr);
let speech = MonoSampleBuilder::<f64>::new(sr)
    .silence(Duration::from_millis(300))
    .add_sample(vowel)
    .white_noise(Duration::from_millis(200), 0.1, Some(1)) // the "s"
    .silence(Duration::from_millis(300))
    .build()
    .unwrap();
let floor = white_noise::<f64>(Duration::from_millis(1200), sr, 1e-3, Some(2));
let x: Vec<f64> = speech.as_slice().unwrap().iter().zip(floor.as_slice().unwrap()).map(|(a, b)| a + b).collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x).unwrap(), sr);

let cfg = VadConfig::default()
    .with_method(VadMethod::Energy)
    .with_hop_size(nzu!(160)).unwrap() // set the hop first: it must stay <= the frame
    .with_frame_size(nzu!(400)).unwrap()
    .with_energy_threshold_db(-40.0)
    .with_smooth_frames(nzu!(1))
    .with_min_speech_frames(0)
    .with_min_silence_frames(0)
    .with_hangover_frames(nzu!(1));
let mask = audio.voice_activity_mask(&cfg).unwrap();
assert_eq!(mask.len().get(), 120); // ceil(19200 / 160) frames (pad_end = true)

// Vowel + fricative form one region, 4480..14960 samples = 0.280-0.935 s
// (the true speech is 0.300-0.900 s).
assert_eq!(audio.speech_regions(&cfg).unwrap(), vec![(4_480, 14_960)]);

// The combined rule (energy AND 0.02 <= ZCR <= 0.30) rejects the noise-like
// fricative and keeps only the vowel (true extent 4800..11200).
let combined = cfg.with_method(VadMethod::Combined);
assert_eq!(audio.speech_regions(&combined).unwrap(), vec![(4_640, 11_600)]);

The boundaries follow from the framing. The region starts at the first frame that overlaps the vowel at all: frame 28 starts at sample 4480 and its last 80 samples are vowel, which is enough to exceed dBFS. It ends at the end of the first inactive frame after the hangover: the last frame touching the fricative is frame 89, hangover keeps frame 90 active, and frame 91 ends at . The combined region starts one frame later because frame 28 is mostly noise floor and therefore has a noise-like ZCR.

The chapter's utterance (silence, vowel, fricative, silence) in 25 ms frames with a 10 ms hop. The frame level crosses the -40 dBFS threshold for the vowel and the fricative; the fricative's zero-crossing rate is outside the 0.02 to 0.30 window, so the combined VAD keeps only the vowel. Decisions from voice_activity_mask.
Figure 11.1. The chapter's utterance (silence, vowel, fricative, silence) in 25 ms frames with a 10 ms hop. The frame level crosses the -40 dBFS threshold for the vowel and the fricative; the fricative's zero-crossing rate is outside the 0.02 to 0.30 window, so the combined VAD keeps only the vowel. Decisions from voice_activity_mask.

How it works

Compute the two features for every frame in plain Rust, check them against theory, and rebuild the VAD mask using only a threshold and a hangover counter.

use audio_samples::operations::types::{VadConfig, VadMethod};
use audio_samples::utils::generation::{MonoSampleBuilder, ToneComponent};
use audio_samples::{AudioSamples, AudioVoiceActivityDetection, compound_tone, nzu, sample_rate, white_noise};
use non_empty_slice::{NonEmptySlice, NonEmptyVec};
use std::time::Duration;
let sr = sample_rate!(16000);
let partials: Vec<ToneComponent> = (1..=20).map(|k| { let f = 200.0 * k as f64;
    ToneComponent::new(f, 0.3 / (1.0 + ((f - 700.0) / 200.0).powi(2))) }).collect();
let vowel = compound_tone::<f64>(NonEmptySlice::from_slice(&partials).unwrap(), Duration::from_millis(400), sr);
let speech = MonoSampleBuilder::<f64>::new(sr).silence(Duration::from_millis(300)).add_sample(vowel)
    .white_noise(Duration::from_millis(200), 0.1, Some(1)).silence(Duration::from_millis(300)).build().unwrap();
let floor = white_noise::<f64>(Duration::from_millis(1200), sr, 1e-3, Some(2));
let x: Vec<f64> = speech.as_slice().unwrap().iter().zip(floor.as_slice().unwrap()).map(|(a, b)| a + b).collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x.clone()).unwrap(), sr);
let cfg = VadConfig::default().with_method(VadMethod::Energy).with_hop_size(nzu!(160)).unwrap()
    .with_frame_size(nzu!(400)).unwrap().with_energy_threshold_db(-40.0).with_smooth_frames(nzu!(1))
    .with_min_speech_frames(0).with_min_silence_frames(0).with_hangover_frames(nzu!(1));
// `x` is the utterance from the previous example (hidden lines rebuild it).
let (frame, hop) = (400usize, 160usize);
let feats: Vec<(f64, f64)> = (0..x.len().div_ceil(hop))
    .map(|m| {
        let fr = &x[m * hop..(m * hop + frame).min(x.len())];
        // RMS: divide by the full frame length (a short last frame counts as zero-padded).
        let rms = (fr.iter().map(|v| v * v).sum::<f64>() / frame as f64).sqrt();
        // ZCR: sign changes between successive non-zero samples, / (F - 1).
        let signs: Vec<f64> = fr.iter().filter(|v| **v != 0.0).map(|v| v.signum()).collect();
        let zc = signs.windows(2).filter(|w| w[0] != w[1]).count();
        (rms, zc as f64 / (frame - 1) as f64)
    })
    .collect();
let db = |r: f64| 20.0 * r.log10();
let (silence, vowel, fricative) = (feats[10], feats[50], feats[78]); // at 0.1, 0.5, 0.78 s

// Silence: the noise floor, RMS 1e-3/sqrt(3) = -64.8 dBFS (random: +-1 dB).
assert!((db(silence.0) + 64.8).abs() < 1.0);
// Vowel: sum of harmonics, RMS sqrt(sum a_k^2 / 2) = -11.7 dBFS. A 25 ms
// frame holds exactly 5 periods of 200 Hz, so the frame RMS matches to 0.05 dB.
let vowel_rms = (1..=20)
    .map(|k| (0.3 / (1.0 + ((200.0 * k as f64 - 700.0) / 200.0).powi(2))).powi(2) / 2.0)
    .sum::<f64>()
    .sqrt();
assert!((db(vowel_rms) + 11.7).abs() < 0.05);
assert!((db(vowel.0) - db(vowel_rms)).abs() < 0.05);
// Fricative: uniform noise of amplitude 0.1, RMS 0.1/sqrt(3) = -24.8 dBFS (+-0.5 dB).
assert!((db(fricative.0) + 24.8).abs() < 0.5);
// ZCR: noise-like frames near 0.5; the vowel near 2 * 780 / 16000 = 0.098,
// set by its strongest partials (600 and 800 Hz).
assert!((silence.1 - 0.5).abs() < 0.06 && (fricative.1 - 0.5).abs() < 0.06);
assert!(vowel.1 > 0.06 && vowel.1 < 0.11);

// The VAD: threshold, then hangover of 1 frame.
let thr = 10f64.powf(-40.0 / 20.0);
let mut hold = 0;
let mine: Vec<bool> = feats
    .iter()
    .map(|&(rms, _)| {
        if rms >= thr { hold = 1; true } else if hold > 0 { hold -= 1; true } else { false }
    })
    .collect();
assert_eq!(mine, audio.voice_activity_mask(&cfg).unwrap().to_vec()); // identical

The library’s whole-signal zero_crossing_rate is zero_crossings divided by the duration in seconds:

use audio_samples::{AudioStatistics, sample_rate, sine_wave};
use std::time::Duration;

// 500 Hz for 1 s: about 2 * 500 = 1000 crossings per second.
let tone = sine_wave::<f64>(500.0, Duration::from_secs(1), sample_rate!(16000), 0.5);
let per_second = tone.zero_crossing_rate();
assert_eq!(per_second, tone.zero_crossings() as f64 / 1.0);
// Within 2 crossings of 1000 (where the first and last samples fall).
assert!((per_second - 1_000.0).abs() <= 2.0);
// In crossings per sample, as the VAD uses: about 2 f / fs = 0.0625.
assert!((per_second / 16_000.0 - 0.0625).abs() < 2e-4);

Ask the library to explain

VadConfig implements Explain. Through a signal it converts frames, hops and hangover into milliseconds and the ZCR window into equivalent tone frequencies. The default configuration (1024-sample frames) is tuned for music-rate audio; at 16 kHz the explainer points out that its frames are long for speech.

use audio_samples::educational::ExplainFor;
use audio_samples::operations::types::VadConfig;
use audio_samples::{nzu, sample_rate, silence};
use std::time::Duration;

let audio = silence::<f32>(Duration::from_millis(1200), sample_rate!(16000));
let doc = audio.explain(&VadConfig::default());
println!("{doc}");
assert_eq!(doc.quantity("Frame duration").unwrap().value, 64.0); // 1024 / 16 kHz
assert_eq!(doc.quantity("ZCR lower bound as a tone").unwrap().value, 160.0); // 0.02 * 8 kHz
assert_eq!(doc.quantity("ZCR upper bound as a tone").unwrap().value, 2_400.0);
assert!(doc.has_warning_containing("64 ms"));

let speech_cfg = VadConfig::default()
    .with_hop_size(nzu!(160)).unwrap()
    .with_frame_size(nzu!(400)).unwrap();
let doc = audio.explain(&speech_cfg);
assert_eq!(doc.quantity("Frame duration").unwrap().value, 25.0);
assert_eq!(doc.quantity("Hangover").unwrap().value, 20.0); // 2 frames x 10 ms
assert_eq!(doc.quantity("Frames").unwrap().value, 120.0);

Exercises

  1. Levels. Predict the RMS level in dBFS of (a) a full-scale sine, (b) the library’s white_noise with amplitude 0.1. Check with AudioStatistics::rms.
  2. Hangover. With the energy VAD above, predict how far the end of the speech region moves when the hangover goes from 1 to 6 frames. Check with speech_regions.
  3. A loud hum. A 100 Hz tone peaking at dBFS (amplitude 0.316) is not speech. Predict its RMS level in this chapter’s (RMS) convention and its per-sample ZCR, then decide which rule rejects it, energy or combined.

Answers

  1. (a) dBFS. (b) Uniform noise on has RMS , so dBFS.
use audio_samples::{AudioStatistics, sample_rate, sine_wave, white_noise};
use std::time::Duration;

let sine = sine_wave::<f64>(1_000.0, Duration::from_secs(1), sample_rate!(16000), 1.0);
assert!((20.0 * sine.rms().log10() + 3.0103).abs() < 1e-3); // whole periods: exact
let noise = white_noise::<f64>(Duration::from_secs(1), sample_rate!(16000), 0.1, Some(7));
// 16000 random samples: the RMS estimate is within about 1 % (0.1 dB).
assert!((20.0 * noise.rms().log10() + 24.77).abs() < 0.1);
  1. Each extra hangover frame keeps one more 10 ms frame active, so the end moves by samples (50 ms): from 14960 to 15760.
use audio_samples::operations::types::{VadConfig, VadMethod};
use audio_samples::utils::generation::{MonoSampleBuilder, ToneComponent};
use audio_samples::{AudioSamples, AudioVoiceActivityDetection, compound_tone, nzu, sample_rate, white_noise};
use non_empty_slice::{NonEmptySlice, NonEmptyVec};
use std::time::Duration;
let sr = sample_rate!(16000);
let partials: Vec<ToneComponent> = (1..=20).map(|k| { let f = 200.0 * k as f64;
    ToneComponent::new(f, 0.3 / (1.0 + ((f - 700.0) / 200.0).powi(2))) }).collect();
let vowel = compound_tone::<f64>(NonEmptySlice::from_slice(&partials).unwrap(), Duration::from_millis(400), sr);
let speech = MonoSampleBuilder::<f64>::new(sr).silence(Duration::from_millis(300)).add_sample(vowel)
    .white_noise(Duration::from_millis(200), 0.1, Some(1)).silence(Duration::from_millis(300)).build().unwrap();
let floor = white_noise::<f64>(Duration::from_millis(1200), sr, 1e-3, Some(2));
let x: Vec<f64> = speech.as_slice().unwrap().iter().zip(floor.as_slice().unwrap()).map(|(a, b)| a + b).collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x).unwrap(), sr);
let cfg = VadConfig::default().with_method(VadMethod::Energy).with_hop_size(nzu!(160)).unwrap()
    .with_frame_size(nzu!(400)).unwrap().with_energy_threshold_db(-40.0).with_smooth_frames(nzu!(1))
    .with_min_speech_frames(0).with_min_silence_frames(0);
let end = |h| audio.speech_regions(&cfg.with_hangover_frames(h)).unwrap()[0].1;
assert_eq!(end(nzu!(1)), 14_960);
assert_eq!(end(nzu!(6)), 15_760);
assert_eq!(end(nzu!(6)) - end(nzu!(1)), 5 * 160);
  1. Its RMS level is dBFS (a sine’s RMS is its peak over ). Its ZCR is about crossings per sample, below , so the combined rule rejects it while the energy rule ( dBFS, far above ) accepts it.
use audio_samples::operations::types::{VadConfig, VadMethod};
use audio_samples::{AudioVoiceActivityDetection, nzu, sample_rate, sine_wave};
use std::time::Duration;

let amp = 10f64.powf(-10.0 / 20.0); // -10 dBFS peak
let hum = sine_wave::<f64>(100.0, Duration::from_millis(500), sample_rate!(16000), amp);
let x = hum.as_slice().unwrap();
// 500 ms holds 50 whole periods, so the RMS is exactly amp / sqrt(2): -13.0 dBFS.
let rms_db = 20.0 * (x.iter().map(|v| v * v).sum::<f64>() / x.len() as f64).sqrt().log10();
assert!((rms_db + 13.01).abs() < 0.01);
let fr = &x[1_000..1_400];
let zc = fr.windows(2).filter(|w| (w[0] > 0.0) != (w[1] > 0.0)).count();
let zcr = zc as f64 / 399.0;
assert!((zcr - 0.0125).abs() < 0.003); // 5 crossings in 400 samples

let cfg = VadConfig::default()
    .with_hop_size(nzu!(160)).unwrap()
    .with_frame_size(nzu!(400)).unwrap()
    .with_energy_threshold_db(-40.0);
let active = |m| hum.voice_activity_mask(&cfg.with_method(m)).unwrap().iter().filter(|&&v| v).count();
assert!(active(VadMethod::Energy) > 0);
assert_eq!(active(VadMethod::Combined), 0);

Common pitfalls

  • Units of ZCR. The VAD uses crossings per sample (per frame); zero_crossing_rate returns crossings per second for the whole signal; zero_crossing_rate_frames returns a per-frame fraction (crossings / frame length, centred frames). Divide by to compare.
  • dBFS conventions. Here a full-scale sine is dBFS (RMS convention). AES17 would call it 0 dBFS.
  • Default frames are long. VadConfig::default() uses 1024 / 512 samples (64 / 32 ms at 16 kHz); speech VAD normally uses 20-30 ms frames.
  • Fricatives fail the combined rule. /s/ and /f/ have speech-like energy but noise-like ZCR, so the default ZCR window (0.02-0.30) drops them. Use the energy rule with hangover if you need whole words.
  • Smoothing delays onsets. The majority vote looks only backwards, so onsets are reported about frames late; hangover delays offsets.
  • Regions are wider than the speech. A region starts at the first frame touching speech and ends at the end of the first inactive frame, so it can extend a frame beyond the true speech on both sides.

References

  • L. R. Rabiner and M. R. Sambur, “An algorithm for determining the endpoints of isolated utterances”, Bell System Technical Journal 54(2), 297-315, 1975. The classic energy and zero-crossing detector.
  • L. R. Rabiner and R. W. Schafer, Digital Processing of Speech Signals, Prentice-Hall, 1978.
  • AES17, AES standard method for digital audio engineering: measurement of digital audio equipment, Audio Engineering Society (the definition of dBFS as the RMS of a full-scale sine).

See also

12. Dynamics: compressors and limiters

Speech varies by 30 dB or more between a whispered consonant and a shouted vowel, and broadcast, telephony and hearing aids all reduce that range so the quiet parts stay audible and the loud parts do not clip. A compressor has three parts: a level detector with attack and release ballistics, a static gain computer in decibels, and a multiplier. This chapter measures each part of the library’s implementation and reimplements the whole processor in about a dozen lines.

Concept

Detector and ballistics. The detector turns the input into a non-negative value : for a peak detector, or the RMS over the last 10 ms. A one-pole smoother then produces the envelope

where is the sample rate in Hz and the time constant in seconds: the attack constant while (the level is rising) and the release constant otherwise. After a step from to the envelope follows

so it covers of the step after one time constant, and its 10-90 % rise time is . (Equipment makers quote attack times in either convention, so numbers are not comparable across products.)

Static gain computer (dB domain). With envelope level (dBFS), threshold (dBFS), ratio (dimensionless) and knee width (dB), the hard-knee compressor’s output level is

so the gain reduction is dB. The quadratic soft knee (Giannoulis, Massberg and Reiss, JAES 2012) blends the two lines over :

It has slope 1 at the lower edge and at the upper edge, so the curve has no corner, and at it already reduces by dB.

Gain. The output is , where is the make-up gain in dB. Working in dB makes the ratio a slope and the threshold an offset.

Limiter. A limiter is the compressor with and the ceiling (dBFS) in place of : . Because the gain follows a smoothed envelope, the output can still exceed at the start of a transient.

Lookahead. Delay the audio by samples and apply to sample the largest reduction computed for samples . The reduction is then in place before the transient arrives. If the envelope starts from zero and the step is to , the reduction applied to the first sample of the step is the one computed samples later, from an envelope of , so the overshoot is

which is about dB for . (The library processes whole buffers, so it compensates the delay: output index stays aligned with input index .)

With the library

The static curve is available directly from calculate_compression_gain (a reduction in dB) and from AudioDynamicRange::get_compression_curve (output levels, make-up gain included).

use audio_samples::operations::dynamic_range::calculate_compression_gain;
use audio_samples::operations::types::KneeType;
use audio_samples::{AudioDynamicRange, AudioSamples, CompressorConfig, sample_rate};
use non_empty_slice::{NonEmptySlice, NonEmptyVec};

// Hard knee, T = -20 dBFS, R = 4: -8 dBFS is 12 dB over, so the output is -20 + 12/4 = -17.
let r = calculate_compression_gain(-8.0, -20.0, 4.0, KneeType::Hard, 0.0);
assert!((r - 9.0).abs() < 1e-12);

// Soft knee W = 10 dB: no reduction at T - W/2, (1 - 1/R) W / 8 = 0.9375 dB at T,
// and back on the hard-knee line at T + W/2 (3.75 dB).
let soft = |l| calculate_compression_gain(l, -20.0, 4.0, KneeType::Soft, 10.0);
assert_eq!(soft(-25.0), 0.0);
assert!((soft(-20.0) - 0.9375).abs() < 1e-12);
assert!((soft(-15.0) - 3.75).abs() < 1e-12);
// The output curve's slope is 1 at the lower knee edge and 1/R at the upper one.
let y = |l: f64| l - soft(l);
let d = 1e-6;
assert!(((y(-25.0 + d) - y(-25.0 - d)) / (2.0 * d) - 1.0).abs() < 1e-5);
assert!(((y(-15.0 + d) - y(-15.0 - d)) / (2.0 * d) - 0.25).abs() < 1e-5);

// The same curve as output levels through the trait (here with a hard knee).
let mut cfg = CompressorConfig::new();
cfg.threshold_db = -20.0;
cfg.ratio = 4.0;
cfg.knee_type = KneeType::Hard;
cfg.knee_width_db = 0.0;
cfg.makeup_gain_db = 0.0;
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(vec![0.5f64; 16]).unwrap(), sample_rate!(48000));
let curve = audio.get_compression_curve(&cfg, NonEmptySlice::new(&[-30.0, -20.0, -8.0]).unwrap()).unwrap();
assert_eq!(curve, vec![-30.0, -20.0, -17.0]);
Static curves from calculate_compression_gain and get_compression_curve: threshold -20 dBFS and ratio 4:1 with a hard knee and with a 10 dB soft knee (the dashed lines at -25 and -15 dBFS mark its edges), and a limiter with a -6 dBFS ceiling. Above the threshold the output rises 1 dB for every 4 dB of input.
Figure 12.1. Static curves from calculate_compression_gain and get_compression_curve: threshold -20 dBFS and ratio 4:1 with a hard knee and with a 10 dB soft knee (the dashed lines at -25 and -15 dBFS mark its edges), and a limiter with a -6 dBFS ceiling. Above the threshold the output rises 1 dB for every 4 dB of input.

The ballistics are visible in the response to a step. Apply a DC level of dBFS for 100 ms, then 0 dBFS for 200 ms (peak detector, attack 5 ms, release 50 ms, hard knee at dBFS, 4:1), and read the per-sample reduction with get_gain_reduction. Above the threshold the hard-knee curve can be inverted, , which recovers the envelope.

use audio_samples::operations::types::{DynamicRangeMethod, KneeType};
use audio_samples::{AudioDynamicRange, AudioSamples, CompressorConfig, sample_rate};
use non_empty_slice::NonEmptyVec;

let fs: f64 = 48_000.0;
let x: Vec<f64> = std::iter::repeat_n(0.01, 4_800).chain(std::iter::repeat_n(1.0, 9_600)).collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x).unwrap(), sample_rate!(48000));
let mut cfg = CompressorConfig::new();
// Set four fields at once (a destructuring assignment): threshold -20 dBFS,
// ratio 4:1, hard knee, knee width 0 dB.
(cfg.threshold_db, cfg.ratio, cfg.knee_type, cfg.knee_width_db) = (-20.0, 4.0, KneeType::Hard, 0.0);
(cfg.attack_ms, cfg.release_ms, cfg.detection_method) = (5.0, 50.0, DynamicRangeMethod::Peak);

let gr = audio.get_gain_reduction(&cfg).unwrap();
let env = |n: usize| 10f64.powf((-20.0 + gr[n] / 0.75) / 20.0); // valid while gr > 0
let reach = |level: f64| (4_800..).find(|&n| gr[n] > 0.0 && env(n) >= level).unwrap();
let (lo, hi) = (0.01, 1.0);
// Sample 4800 is the first at the new level and already one update of the recursion.
let t63_ms = (reach(lo + (1.0 - (-1f64).exp()) * (hi - lo)) - 4_800 + 1) as f64 / fs * 1e3;
let rise_ms = (reach(lo + 0.9 * (hi - lo)) - reach(lo + 0.1 * (hi - lo))) as f64 / fs * 1e3;
// One sample is 0.021 ms, so both are within 0.03 ms of theory.
assert!((t63_ms - 5.0).abs() < 0.03); // tau_A
assert!((rise_ms - 5.0 * 9f64.ln()).abs() < 0.03); // 10.99 ms = 2.2 tau_A
// Settled: the envelope is 0 dBFS, 20 dB over the threshold, so 15 dB of reduction.
assert!((gr[14_000] - 15.0).abs() < 1e-6);
Attack of a peak-detecting compressor (5 ms attack, threshold -20 dBFS, 4:1) on a step from -40 to 0 dBFS at 100 ms. Top: the envelope, recovered from get_gain_reduction by inverting the static curve while the envelope is above the threshold; it reaches 63.2 % of the step after 5 ms and rises from 10 % to 90 % in 11 ms. Bottom: the gain reduction, settling at 15 dB.
Figure 12.2. Attack of a peak-detecting compressor (5 ms attack, threshold -20 dBFS, 4:1) on a step from -40 to 0 dBFS at 100 ms. Top: the envelope, recovered from get_gain_reduction by inverting the static curve while the envelope is above the threshold; it reaches 63.2 % of the step after 5 ms and rises from 10 % to 90 % in 11 ms. Bottom: the gain reduction, settling at 15 dB.

How it works

The whole compressor is an envelope follower, the gain computer and a multiplication. Written out, it matches apply_compressor sample for sample, here with a 6 dB soft knee on a step up and back down (which also tests the release).

use audio_samples::operations::types::{DynamicRangeMethod, KneeType};
use audio_samples::{AudioDynamicRange, AudioSamples, CompressorConfig, sample_rate};
use non_empty_slice::NonEmptyVec;

let fs: f64 = 48_000.0;
let x: Vec<f64> = [(0.01, 4_800), (1.0, 9_600), (0.01, 14_400)]
    .iter()
    .flat_map(|&(v, n)| std::iter::repeat_n(v, n))
    .collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x.clone()).unwrap(), sample_rate!(48000));
let (t, ratio, w) = (-20.0, 4.0, 6.0);
let mut cfg = CompressorConfig::new();
(cfg.threshold_db, cfg.ratio, cfg.knee_type, cfg.knee_width_db) = (t, ratio, KneeType::Soft, w);
(cfg.attack_ms, cfg.release_ms, cfg.detection_method) = (5.0, 50.0, DynamicRangeMethod::Peak);
(cfg.makeup_gain_db, cfg.lookahead_ms) = (0.0, 0.0);
let lib = audio.apply_compressor(&cfg).unwrap();

let (a_att, a_rel) = ((-1.0 / (0.005 * fs)).exp(), (-1.0 / (0.050 * fs)).exp());
let reduction = |l: f64| {
    let o = l - t;
    let slope = 1.0 - 1.0 / ratio;
    if 2.0 * o.abs() <= w { slope * (o + w / 2.0).powi(2) / (2.0 * w) } else { slope * o.max(0.0) }
};
let mut e = 0.0f64;
let mine: Vec<f64> = x
    .iter()
    .map(|&v| {
        let d = v.abs(); // peak detector
        let a = if d > e { a_att } else { a_rel };
        e = a * e + (1.0 - a) * d;
        let level = if e > 0.0 { 20.0 * e.log10() } else { -80.0 };
        v * 10f64.powf(-reduction(level) / 20.0)
    })
    .collect();
let err = mine.iter().zip(lib.as_slice().unwrap()).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max);
// Same operations in the same order, so only last-bit differences remain.
assert!(err < 1e-12);
A soft-knee compressor (threshold -20 dBFS, 4:1, 6 dB knee, 5 ms attack, 50 ms release) on a step from -40 to 0 dBFS and back. Top: input, envelope and output level of apply_compressor. Bottom: gain reduction from get_gain_reduction. The reduction builds up within a few ms and decays over the 50 ms release, so the output dips below the input level after the step down.
Figure 12.3. A soft-knee compressor (threshold -20 dBFS, 4:1, 6 dB knee, 5 ms attack, 50 ms release) on a step from -40 to 0 dBFS and back. Top: input, envelope and output level of apply_compressor. Bottom: gain reduction from get_gain_reduction. The reduction builds up within a few ms and decays over the 50 ms release, so the output dips below the input level after the step down.

The lookahead formula can be checked the same way: a limiter with a dBFS ceiling and a 1 ms attack, on a step from silence to 0 dBFS. Without lookahead the first sample of the step passes without reduction (the envelope is still at , i.e. dBFS), a 6 dB overshoot. With 5 ms of lookahead ( samples) the overshoot is dB.

use audio_samples::operations::types::{DynamicRangeMethod, KneeType};
use audio_samples::{AudioDynamicRange, AudioSamples, LimiterConfig, sample_rate};
use non_empty_slice::NonEmptyVec;

let fs: f64 = 48_000.0;
let x: Vec<f64> = std::iter::repeat_n(0.0, 960).chain(std::iter::repeat_n(1.0, 2_400)).collect();
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(x).unwrap(), sample_rate!(48000));
let peak_db = |lookahead_ms: f64| {
    // Arguments: ceiling -6 dBFS, attack 1 ms, release 100 ms, hard knee of
    // width 0 dB, peak detection, the lookahead in ms, and `false` for the
    // inter-sample-peak option (left off here).
    let lim = LimiterConfig::new(-6.0, 1.0, 100.0, KneeType::Hard, 0.0, DynamicRangeMethod::Peak, lookahead_ms, false);
    let y = audio.apply_limiter(&lim).unwrap();
    20.0 * y.as_slice().unwrap().iter().fold(0.0f64, |m, v| m.max(v.abs())).log10()
};
assert!(peak_db(0.0).abs() < 1e-9); // the step passes at 0 dBFS: 6 dB over the ceiling
let a: f64 = (-1.0 / (0.001 * fs)).exp();
let predicted = -20.0 * (1.0 - a.powi(241)).log10();
assert!((predicted - 0.0575).abs() < 1e-3);
assert!((peak_db(5.0) - (-6.0 + predicted)).abs() < 1e-9);
A limiter (ceiling -6 dBFS, 1 ms attack) on a step from silence to 0 dBFS at 20 ms, from apply_limiter. Without lookahead the start of the step passes at full level, 6 dB over the ceiling; with 5 ms of lookahead the gain is already reduced when the step arrives and the overshoot is 0.06 dB.
Figure 12.4. A limiter (ceiling -6 dBFS, 1 ms attack) on a step from silence to 0 dBFS at 20 ms, from apply_limiter. Without lookahead the start of the step passes at full level, 6 dB over the ceiling; with 5 ms of lookahead the gain is already reduced when the step arrives and the overshoot is 0.06 dB.

Ask the library to explain

CompressorConfig and LimiterConfig implement Explain. With a sample rate (from a signal) the explanation includes the smoothing coefficients, the 10-90 % times, a table of the static curve, and a note when there is no lookahead.

use audio_samples::educational::ExplainFor;
use audio_samples::operations::types::{DynamicRangeMethod, KneeType};
use audio_samples::{CompressorConfig, LimiterConfig, sample_rate, silence};
use std::time::Duration;

let audio = silence::<f32>(Duration::from_millis(10), sample_rate!(48000));
let mut cfg = CompressorConfig::new();
(cfg.threshold_db, cfg.ratio, cfg.knee_type, cfg.knee_width_db) = (-20.0, 4.0, KneeType::Hard, 0.0);
(cfg.attack_ms, cfg.release_ms, cfg.detection_method) = (5.0, 50.0, DynamicRangeMethod::Peak);
let doc = audio.explain(&cfg);
println!("{doc}");
assert!((doc.quantity("Attack 10-90% rise time").unwrap().value - 10.986).abs() < 1e-3);
assert!((doc.quantity("Attack coefficient").unwrap().value - (-1.0f64 / 240.0).exp()).abs() < 1e-12);
assert!((doc.quantity("Gain reduction at 0 dBFS").unwrap().value - 15.0).abs() < 1e-9);
assert!(doc.has_warning_containing("No lookahead"));

let lim = audio.explain(&LimiterConfig::transparent());
println!("{lim}");
assert!(lim.quantity("Gain reduction for a 0 dBFS envelope").is_some());

Exercises

  1. Read the curve. With dBFS and (hard knee), predict the output level for a dBFS input, then check with get_compression_curve.
  2. Knee at the threshold. For a 6 dB soft knee and , predict the reduction exactly at .
  3. Attack in samples. At 16 kHz with ms, predict and how many samples an EnvelopeFollower needs to reach 63.2 % of a step from 0 to 1.
  4. Enough lookahead? For the limiter above, how much lookahead (in samples) keeps the overshoot below 0.01 dB?

Answers

  1. dB over the threshold becomes dB over it: dBFS.
use audio_samples::operations::types::KneeType;
use audio_samples::{AudioDynamicRange, AudioSamples, CompressorConfig, sample_rate};
use non_empty_slice::{NonEmptySlice, NonEmptyVec};

let mut cfg = CompressorConfig::new();
(cfg.threshold_db, cfg.ratio, cfg.knee_type, cfg.makeup_gain_db) = (-18.0, 3.0, KneeType::Hard, 0.0);
let audio: AudioSamples<f64> = AudioSamples::from_mono_vec(NonEmptyVec::new(vec![0.0f64; 4]).unwrap(), sample_rate!(16000));
let y = audio.get_compression_curve(&cfg, NonEmptySlice::new(&[-2.0]).unwrap()).unwrap();
assert!((y[0] - (-18.0 + 16.0 / 3.0)).abs() < 1e-12);
assert!((y[0] + 12.67).abs() < 0.005);
  1. dB.
use audio_samples::operations::dynamic_range::calculate_compression_gain;
use audio_samples::operations::types::KneeType;

let r = calculate_compression_gain(-18.0, -18.0, 3.0, KneeType::Soft, 6.0);
assert!((r - 0.5).abs() < 1e-12);
  1. ; after updates the envelope is , which first reaches at samples (10 ms).
use audio_samples::operations::dynamic_range::EnvelopeFollower;
use audio_samples::operations::types::DynamicRangeMethod;

let a = (-1.0f64 / 160.0).exp();
assert!((a - 0.99377).abs() < 1e-5);
let mut f = EnvelopeFollower::new(10.0, 100.0, 16_000.0, DynamicRangeMethod::Peak);
let k = (1..).find(|_| f.process(1.0) >= 1.0 - (-1f64).exp()).unwrap();
assert_eq!(k, 160);
  1. Solve : , so , i.e. samples (6.8 ms, about ).
let a: f64 = (-1.0 / 48.0f64).exp(); // 1 ms at 48 kHz
let overshoot = |n: i32| -20.0 * (1.0 - a.powi(n + 1)).log10();
let n_min = (0..2_000).find(|&n| overshoot(n) < 0.01).unwrap();
assert_eq!(n_min, 324);
assert!(overshoot(323) >= 0.01);

Common pitfalls

  • Attack and release are time constants, not “time to full reduction”: 63.2 % after , 10-90 % in . Hardware datasheets use either convention.
  • Detector choice shifts the threshold. An RMS detector reads a sine 3.01 dB below its peak, so the same threshold compresses less than with Peak (the default CompressorConfig uses RMS).
  • Threshold reference. Thresholds are in dBFS of the envelope, not of individual samples or of loudness (LUFS).
  • A limiter without lookahead is not a brick wall. The start of every transient passes, and even with lookahead a small overshoot remains. isp_limiting makes the detector read true (inter-sample) peaks rather than sample peaks.
  • Stereo is not linked. Multi-channel audio is compressed per channel, which can shift the stereo image.
  • get_gain_reduction reports the detector-and-curve reduction without lookahead; apply_compressor additionally applies the lookahead max-hold.

References

  • D. Giannoulis, M. Massberg and J. D. Reiss, “Digital dynamic range compressor design: a tutorial and analysis”, Journal of the Audio Engineering Society 60(6), 399-408, 2012. The soft knee used here; the paper also compares detector topologies (where and how the envelope is smoothed).
  • U. Zölzer (ed.), DAFX: Digital Audio Effects, 2nd ed., Wiley, 2011.

See also

13. Onsets and tempo

Onset detection marks the instants at which new sound energy appears, such as the start of a note or a drum hit; tempo estimation finds the period with which those instants repeat. Both are built on an onset detection function (ODF), one number per analysis frame, and both inherit its limitations, so this chapter states units explicitly (samples, frames, seconds, beats per minute) and notes where the library’s defaults fall short.

Concept

Frames. The signal is analysed in frames hopped by samples; frame is centred at seconds ( the sample rate in Hz). At and kHz a frame lasts ms and there are frames per second.

Spectral flux. With the magnitude of frequency bin in frame , the half-wave-rectified flux is

Only increases count, so note offsets do not create onsets. This crate evaluates it on a constant-Q transform (CQT) whose bins ( per octave, octaves) start at Hz, with an analysis window of samples (four periods of the lowest bin). The quality factor is (34.1 at ): bin ’s kernel spans periods of its centre frequency, samples, cut to and centred in the frame. The magnitudes are not squared, despite the method’s name (“energy”). Optionally, values below times a running median of frames are set to zero (adaptive_threshold, = adaptive_threshold_multiplier).

Peak picking, as implemented by pick_peaks, all in frames: optional pre-emphasis and median filtering; normalisation by the maximum; a threshold (window frames, , , by default); strict local maxima above it; finally, peaks are accepted strongest first and dropped if closer than frames to an accepted one. A peak at frame is reported at seconds.

Tempo. A tempo of beats per minute (BPM) is an inter-beat interval of seconds, i.e. a lag of

estimate_tempo smooths the ODF (7-frame moving average), compresses it (), removes the mean and computes for the integer lags that map into 40-240 BPM. Each lag is weighted by a log-normal prior centred on 120 BPM, , and the lag with the largest is chosen. Two consequences: estimates lie on the grid (117.45, 120.19, 123.05 BPM around 120), and a periodic envelope correlates at and too, so metrical-level errors remain possible: half the tempo (an octave error) or a third of it. The prior only biases the choice.

With the library

A click track: four decaying noise bursts, one every 0.5 s (120 BPM). The default configuration finds all four.

use audio_samples::operations::onset::OnsetDetectionConfig;
use audio_samples::{AudioOnsetDetection, AudioSamples, sample_rate};
use ndarray::Array1;

// Bursts at 0.25, 0.75, 1.25 and 1.75 s; 2 s at 44.1 kHz.
let sr = 44_100usize;
let mut x = vec![0.0f64; 2 * sr];
let mut seed = 0x2545_F491_4F6C_DD1Du64;
for k in 0..4 {
    let start = ((0.25 + 0.5 * k as f64) * sr as f64) as usize;
    for i in 0..256 {
        seed ^= seed << 13;
        seed ^= seed >> 7;
        seed ^= seed << 17;
        let r = (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0;
        x[start + i] = 0.9 * (-(i as f64) / 24.0).exp() * r;
    }
}
let audio = AudioSamples::new_mono(Array1::from(x), sample_rate!(44100)).unwrap();

let config = OnsetDetectionConfig::default();
// Peak-picking lengths count frames: a 9-frame threshold window (104.5 ms at
// hop 512 and 44.1 kHz) and a 3-frame minimum separation (34.8 ms).
let pp = &config.peak_picking;
assert_eq!((pp.adaptive_threshold.window_size, pp.min_peak_separation.get()), (9, 3));
assert!((1000.0f64 * 9.0 * 512.0 / 44_100.0 - 104.5).abs() < 0.05);
assert!((1000.0f64 * 3.0 * 512.0 / 44_100.0 - 34.8).abs() < 0.05);
assert_eq!((pp.adaptive_threshold.delta, pp.adaptive_threshold.min_threshold), (0.07, 0.1));
assert!(!pp.pre_emphasis && !pp.median_filter);

let onsets = audio.detect_onsets(&config).unwrap();
println!("{onsets:.4?}");
assert_eq!(onsets.len(), 4);
// Peaks fall on frames 21, 64, 107, 151.
let frames: Vec<f64> = onsets.iter().map(|t| (t * 44_100.0 / 512.0).round()).collect();
assert_eq!(frames, vec![21.0, 64.0, 107.0, 151.0]);
// The first three are the last frame whose centre precedes the burst, 6.2 to
// 7.7 ms before it; the fourth is the frame after, 3.1 ms late. All are within
// one hop (11.6 ms).
for (k, t) in onsets.iter().enumerate() {
    let lead = 0.25 + 0.5 * k as f64 - t;
    assert!(lead.abs() < 0.0078, "lead {lead}");
}

Onset times are quantised to whole frames: 0.5 s is 43.07 frames, so each burst falls 0.77 ms later relative to the frame grid than the one before. The long low-bin kernels (the 72.7 ms window) already respond to a burst that starts after their centre, so the largest increase tends to come in the frame before the burst, 6.2, 7.0 and 7.7 ms early for the first three. By the fourth burst that frame is 8.5 ms early and the frame after only 3.1 ms late, and the frame after has the larger increase.

Top: the four-burst click track (bursts start at 0.25, 0.75, 1.25 and 1.75 s). Bottom: the normalised onset detection function with the default threshold, and the four onsets detect_onsets reports at frames 21, 64, 107 and 151, 6 to 8 ms before the first three bursts and 3 ms after the fourth.
Figure 13.1. Top: the four-burst click track (bursts start at 0.25, 0.75, 1.25 and 1.75 s). Bottom: the normalised onset detection function with the default threshold, and the four onsets detect_onsets reports at frames 21, 64, 107 and 151, 6 to 8 ms before the first three bursts and 3 ms after the fourth.

The defaults, in frames. The default PeakPickingConfig applies neither pre-emphasis nor a median filter, normalises by the maximum, and thresholds with a 9-frame window (104.5 ms), and a floor ; peaks closer than 3 frames (34.8 ms) are merged. Pre-emphasis () is available but off: the ODF is already a difference of spectra, and pre-emphasising it moves each peak to the frame where it rises fastest, which comes before the onset.

The floor removes weak onsets. After normalisation, no peak weaker than a tenth of the strongest one in the clip is reported. The lab’s eight-burst track has three quiet bursts (the first three, 26 dB below the others), and the defaults find only 5 onsets: the quiet bursts peak at 0.036, 0.033 and 0.024 of the largest value. Lowering adaptive_threshold.min_threshold to 0.01 finds all 8.

Lengths chosen as if they counted audio samples are far too large in frames. Starting from the configuration with the 0.01 floor (the lab, on 8 bursts) and switching on one such setting at a time (a median filter of length 3, a threshold window of 1024, a separation of 512) shows the effect of each: the length-3 median deletes every one-frame peak (0 onsets); a 1024-frame threshold window, clipped to the signal length, makes the threshold the global maximum minus (1 onset); a 512-frame separation, reduced to a quarter of the signal (91 frames, 1.06 s), keeps only 3. Switching pre-emphasis on (0.97) still finds all 8 on this signal. The threshold, the minimum spacing and the pre-emphasis all live in peak_picking; OnsetDetectionConfig itself holds the CQT, the hop and the median-based zeroing of the ODF.

How it works

The ODF. Compute the CQT magnitude with the same parameters and sum the rectified frame-to-frame increases; with the median-based zeroing switched off, the result must equal onset_detection_function. Then re-implement peak picking for the default configuration and convert frames to seconds.

use audio_samples::operations::onset::OnsetDetectionConfig;
use audio_samples::{AudioOnsetDetection, AudioSamples, AudioTransforms, sample_rate};
use ndarray::Array1;
use spectrograms::{SpectrogramParams, StftParams};

let sr = 44_100usize;
let mut x = vec![0.0f64; 2 * sr];
let mut seed = 0x2545_F491_4F6C_DD1Du64;
for k in 0..4 {
    let start = ((0.25 + 0.5 * k as f64) * sr as f64) as usize;
    for i in 0..256 {
        seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
        let r = (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0;
        x[start + i] = 0.9 * (-(i as f64) / 24.0).exp() * r;
    }
}
let audio = AudioSamples::new_mono(Array1::from(x), sample_rate!(44100)).unwrap();
let fs = 44_100.0;
let config = OnsetDetectionConfig::default();

// 1. Spectral flux on the CQT magnitude.
let mut raw = config.clone();
raw.adaptive_threshold = false;
let (_, odf_lib) = audio.onset_detection_function(&raw).unwrap();
let n_w = raw.effective_window_size(fs); // floor(4 * 44100 / 55) = 3207 samples
assert_eq!(n_w.get(), 3207);
let stft = StftParams::builder()
    .n_fft(n_w)
    .hop_size(raw.hop_size)
    .window(raw.cqt_params.window.clone())
    .centre(true)
    .build()
    .unwrap();
let cqt = audio
    .cqt_magnitude_spectrogram(&SpectrogramParams::new(stft, fs).unwrap(), &raw.cqt_params)
    .unwrap();
let m = cqt.data(); // (bins, frames)
for t in 1..m.ncols() {
    let flux: f64 = (0..m.nrows()).map(|b| (m[[b, t]] - m[[b, t - 1]]).max(0.0)).sum();
    // Same additions in the same order: exact agreement.
    assert_eq!(flux, odf_lib[t]);
}

// 2. Peak picking with the default settings (on the ODF detect_onsets uses):
//    peak normalisation, threshold, local maxima, separation.
let (_, odf) = audio.onset_detection_function(&config).unwrap();
let max = odf.iter().fold(0.0f64, |a, v| a.max(v.abs()));
let o: Vec<f64> = odf.iter().map(|v| v / max).collect();
let (half, delta, floor, sep) = (9 / 2, 0.07, 0.1, 3);
let mut candidates: Vec<(usize, f64)> = (1..o.len() - 1)
    .filter(|&i| {
        let local_max = o[i.saturating_sub(half)..(i + half + 1).min(o.len())]
            .iter()
            .fold(f64::NEG_INFINITY, |a, v| a.max(*v));
        o[i] > o[i - 1] && o[i] > o[i + 1] && o[i] > (local_max - delta).clamp(floor, 1.0)
    })
    .map(|i| (i, o[i]))
    .collect();
candidates.sort_by(|a, b| b.1.total_cmp(&a.1)); // strongest first
let mut peaks: Vec<usize> = Vec::new();
for (i, _) in candidates {
    if peaks.iter().all(|&p| p.abs_diff(i) >= sep) {
        peaks.push(i);
    }
}
peaks.sort_unstable();

// 3. Frames to seconds: t = i H / f_s.
let ours: Vec<f64> = peaks.iter().map(|&i| i as f64 * 512.0 / fs).collect();
assert_eq!(ours, audio.detect_onsets(&config).unwrap());

The lab also prints the ODF peak heights of its five loud bursts: 1.94, 4.41, 4.62, 5.82 and 5.15, a factor of 3 for bursts of the same amplitude. Each burst is a different noise sample and falls at a different place relative to the frame grid, and the highest bins’ kernels are shorter than a hop, so they see only part of the time between frames (the onset module documents this). A local threshold window copes with such differences.

Tempo. onset_strength_envelope is public, so the autocorrelation and the prior can be written out and compared with estimate_tempo: at 120 BPM, at 80 BPM, and at 80 BPM with quiet off-beats (every other click at a fifth of the amplitude).

use audio_samples::operations::AudioBeatTracking;
use audio_samples::operations::beat::{BeatTrackingConfig, onset_strength_envelope};
use audio_samples::operations::onset::OnsetDetectionConfig;
use audio_samples::{AudioSamples, sample_rate};
use ndarray::Array1;

let (sr, fs, hop) = (44_100usize, 44_100.0, 512.0);
// Clicks every 60/bpm s from 0.1 s; every other click at `off` times 0.9.
let clicks = |bpm: f64, off: f64, seconds: f64| {
    let mut x = vec![0.0f64; (seconds * fs) as usize];
    let mut seed = 0x2545_F491_4F6C_DD1Du64;
    let (mut t, mut k) = (0.1, 0);
    while t < seconds - 0.1 {
        let start = (t * sr as f64) as usize;
        let amp = if k % 2 == 0 { 0.9 } else { 0.9 * off };
        for i in 0..256 {
            seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
            let r = (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0;
            x[start + i] = amp * (-(i as f64) / 24.0).exp() * r;
        }
        t += 60.0 / bpm;
        k += 1;
    }
    AudioSamples::new_mono(Array1::from(x), sample_rate!(44100)).unwrap()
};

let tempo = |env: &[f64]| -> (f64, usize) {
    let frame_rate = fs / hop; // 86.13 frames per second
    let mean = env.iter().sum::<f64>() / env.len() as f64;
    let c: Vec<f64> = env.iter().map(|v| v - mean).collect();
    let (lo, hi) = ((60.0 * frame_rate / 240.0) as usize, (60.0 * frame_rate / 40.0).ceil() as usize);
    let mut best = (f64::NEG_INFINITY, lo);
    for lag in lo..=hi.min(c.len() - 1) {
        let a = (lag..c.len()).map(|i| c[i] * c[i - lag]).sum::<f64>() / (c.len() - lag) as f64;
        if a <= 0.0 {
            continue;
        }
        let z = (60.0 * frame_rate / lag as f64 / 120.0).log2();
        let score = a * (-0.5 * z * z).exp();
        if score > best.0 {
            best = (score, lag);
        }
    }
    (60.0 * frame_rate / best.1 as f64, best.1)
};

let config = BeatTrackingConfig::new(120.0, None, OnsetDetectionConfig::default());
for (bpm, off, expected_lag) in [(120.0, 1.0, 43), (80.0, 1.0, 65), (80.0, 0.2, 129)] {
    let audio = clicks(bpm, off, 8.5);
    let lib = audio.estimate_tempo(&config).unwrap();
    let env = onset_strength_envelope(&audio, &config.onset_config, None).unwrap();
    let (ours, lag) = tempo(&env);
    println!("{bpm} BPM clicks (off-beats x{off}): estimate {lib:.2} BPM (lag {lag} frames)");
    assert!((ours - lib).abs() < 1e-9);
    assert_eq!(lag, expected_lag);
}
// 120 BPM -> lag 43 -> 120.19 BPM (the nearest grid point).
// 80 BPM  -> lag 65 -> 79.51 BPM.
// 80 BPM with quiet off-beats -> lag 129 -> 40.06 BPM: half the tempo.
assert!((60.0 * fs / (hop * 43.0) - 120.19).abs() < 0.005);
assert!((60.0 * fs / (hop * 65.0) - 79.51).abs() < 0.005);
assert!((60.0 * fs / (hop * 129.0) - 40.06).abs() < 0.005);
Autocorrelation of the onset strength envelope against tempo, and the same weighted by the log-normal prior centred on 120 BPM (dashed); both curves are scaled to a maximum of 1. For 120 BPM clicks estimate_tempo picks lag 43 (120.19 BPM); for 80 BPM clicks whose off-beats have a fifth of the amplitude it picks lag 129 (40.06 BPM), half the tempo.
Figure 13.2. Autocorrelation of the onset strength envelope against tempo, and the same weighted by the log-normal prior centred on 120 BPM (dashed); both curves are scaled to a maximum of 1. For 120 BPM clicks estimate_tempo picks lag 43 (120.19 BPM); for 80 BPM clicks whose off-beats have a fifth of the amplitude it picks lag 129 (40.06 BPM), half the tempo.

The halving comes from the signal. The lab (a ten-click track, slightly different from the twelve-click track above) prints the ODF at each of its 80 BPM clicks with quiet off-beats: 3.83, 1.32, 3.61, 0.49, 5.77, 0.38, 5.9, 0.79, 2.82, 0.73. The envelope repeats every two beats, so its autocorrelation at lag 129 (0.00607) is 3.35 times that at lag 65 (0.00181), a larger ratio than the prior weights (0.29 against 0.84) can reverse. A listener might well hear the accented clicks as the beat; the estimator cannot tell which level is meant. With clicks of equal amplitude the lab’s estimates are correct, to the grid, at 60, 80, 100, 120, 140 and 174 BPM (60.09, 79.51, 99.38, 120.19, 139.67 and 172.27).

Ask the library to explain

use audio_samples::educational::{Explain, ExplainContext};
use audio_samples::operations::onset::OnsetDetectionConfig;

let config = OnsetDetectionConfig::default();
let doc = config.explain_with(&ExplainContext::new().with_sample_rate(44_100.0));
println!("{doc}");
assert_eq!(doc.quantity("Window size").unwrap().value, 3207.0);
assert!((doc.quantity("Window duration").unwrap().value - 72.72).abs() < 0.005);
assert!((doc.quantity("Time resolution").unwrap().value - 11.61).abs() < 0.005);
assert!((doc.quantity("Minimum peak separation").unwrap().value - 34.83).abs() < 0.005);
assert_eq!(doc.quantity("CQT bins").unwrap().value, 144.0);
assert!(doc.has_warning_containing("counts onset-function frames"));

The explanation converts every frame count into milliseconds and flags the frames-versus-samples confusion of min_peak_separation.

Exercises

  1. Units. You want onsets at least 50 ms apart with at 44.1 kHz. What min_peak_separation do you set, and what spacing in milliseconds does it actually give?
  2. The tempo grid. At and 44.1 kHz, which BPM values can estimate_tempo return between 115 and 125 BPM?
  3. Choosing the hop. How would halving the hop to 256 samples change the grid spacing near 120 BPM? Predict, then compute.

Answers

1. , so 9 frames, which is 52.2 ms.

use audio_samples::educational::{Explain, ExplainContext};
use audio_samples::operations::onset::OnsetDetectionConfig;
use std::num::NonZeroUsize;
let frames = (0.05f64 * 44_100.0 / 256.0).ceil() as usize;
assert_eq!(frames, 9);
let mut c = OnsetDetectionConfig::percussive(audio_samples::sample_rate!(44100)); // hop 256
assert_eq!(c.hop_size.get(), 256);
c.peak_picking.min_peak_separation = NonZeroUsize::new(frames).unwrap();
let ms = c.explain_with(&ExplainContext::new().with_sample_rate(44_100.0))
    .quantity("Minimum peak separation").unwrap().value;
assert!((ms - 52.24).abs() < 0.005);

2. Lags 42, 43 and 44 frames: 123.05, 120.19 and 117.45 BPM. Lag 41 (126.05 BPM) and lag 45 (114.84 BPM) lie outside the range.

let bpm = |lag: f64| 60.0 * 44_100.0 / (512.0 * lag);
let in_range: Vec<f64> = (30..60)
    .map(|l| bpm(l as f64))
    .filter(|b| (115.0..=125.0).contains(b))
    .map(|b| (b * 100.0).round() / 100.0)
    .collect();
assert_eq!(in_range, vec![123.05, 120.19, 117.45]);
// The neighbours immediately outside the range, and all five values to 0.01 BPM.
let grid: Vec<f64> = (41..=45).map(|l| (bpm(l as f64) * 100.0).round() / 100.0).collect();
assert_eq!(grid, vec![126.05, 123.05, 120.19, 117.45, 114.84]);

3. The lag doubles (86 frames at 120 BPM) and the spacing between grid points roughly halves: from 2.73 BPM (lags 43, 44 at ) to 1.38 BPM (lags 86, 87 at ). The grid is finer, at twice the computational cost.

let bpm = |lag: f64, hop: f64| 60.0 * 44_100.0 / (hop * lag);
let coarse = bpm(43.0, 512.0) - bpm(44.0, 512.0);
let fine = bpm(86.0, 256.0) - bpm(87.0, 256.0);
assert!((coarse - 2.73).abs() < 0.005);
assert!((fine - 1.38).abs() < 0.005);

Common pitfalls

  • Frames, not samples. Every peak-picking length counts ODF frames ( samples each). Convert with frames = seconds .
  • The default floor removes weak onsets. The ODF is normalised by its maximum and the default threshold never drops below 0.1, so an onset whose peak is under a tenth of the clip’s strongest is not reported. Lower adaptive_threshold.min_threshold for material with a wide dynamic range, and check the result with explain_with.
  • Reported times are frame centres, quantised to ; on clean clicks the peak usually falls in the last frame before the onset, so the reported time is within one hop and usually early.
  • “Energy” flux is magnitude flux here: magnitudes are not squared.
  • Octave errors in tempo are expected, not exceptional: check the estimate against and (and ) before trusting it. BeatTrackingConfig::tempo_bpm is ignored by estimate_tempo.
  • A second onset pipeline: AudioRhythm::onset_strength uses a mel spectrogram in dB with a one-frame lag, and AudioRhythm::onset_detect picks peaks with separate pre/post windows in frames; their numbers will not match the functions in this chapter.

References

  • J. P. Bello, L. Daudet, S. Abdallah, C. Duxbury, M. Davies and M. B. Sandler, “A tutorial on onset detection in music signals”, IEEE Transactions on Speech and Audio Processing 13(5), 1035-1047, 2005.
  • S. Dixon, “Onset detection revisited”, Proc. 9th International Conference on Digital Audio Effects (DAFx-06), 2006.
  • S. Dixon, “Automatic extraction of tempo and beat from expressive performances”, Journal of New Music Research 30(1), 39-58, 2001.
  • D. P. W. Ellis, “Beat tracking by dynamic programming”, Journal of New Music Research 36(1), 51-60, 2007. The log-Gaussian tempo prior.
  • J. C. Brown, “Calculation of a constant Q spectral transform”, Journal of the Acoustical Society of America 89(1), 425-434, 1991.

See also

14. Psychoacoustics and codecs

Telephone speech, MP3, AAC and Opus all discard information. Telephone speech (G.711) does so with simple, signal-independent methods: band-limiting and companding (coarse steps for loud samples, fine steps for quiet ones). Perceptual codecs (MP3, AAC, Opus) discard much more, because not everything in the signal is audible: quiet sounds near loud ones are masked, and very quiet sounds fall below the threshold of hearing. (Perceived loudness grows roughly as a power of sound intensity, Stevens’ power law, rather than in proportion to it.) This chapter quantifies those effects, implements G.711 μ-law companding from the standard, and measures the library’s perceptual codec.

Concept

dBFS is not dB SPL. Sound pressure level is an absolute physical quantity,

where is the RMS sound pressure in pascals; 1 Pa is 93.98 dB SPL. Digital audio has only dBFS, decibels relative to digital full scale ( of an amplitude, full scale = 1). As in chapters 02 and 11, an RMS level of 0 dBFS here is an RMS of 1, so a full-scale sine is dBFS (AES17 calls the same sine 0 dBFS); a level read from the largest sample is labelled “dBFS peak”. The link between digital and acoustic levels is the whole playback chain (converter, amplifier, volume knob, transducer, distance), so a file has no absolute level. Psychoacoustic models that compare a signal with the threshold of hearing must assume a calibration; the library’s masking model assumes that 0 dB re one digital unit² corresponds to 0 dB SPL.

Perceptual frequency scales. The ear analyses sound with a bank of overlapping auditory filters whose bandwidth grows with frequency. Zwicker’s critical bandwidth (the Bark scale) is roughly constant, about 100 Hz, below about 500 Hz and roughly proportional to frequency above; the equivalent rectangular bandwidth (ERB) of Glasberg and Moore grows steadily with frequency even at low frequencies. Three scales describe this; this library implements them as follows.

  • Mel (HTK form), in utils::audio_math::hz_to_mel: , with in Hz and in mel (1000 Hz ≈ 1000 mel). The crate’s mel spectrogram uses the Slaney mel scale instead (linear below 1 kHz), see chapter 10.
  • Bark (Traunmüller 1990), in codecs::perceptual::bands::hz_to_bark: Bark, without Traunmüller’s corrections below 2 and above 20.1 Bark. One Bark is one critical band.
  • ERB (Glasberg and Moore 1990). The equivalent rectangular bandwidth of the auditory filter centred at is Hz, which is what hz_to_erb returns (a bandwidth in Hz, despite its name). The perceptual coordinate is the ERB-number scale Cam, in hz_to_erb_number. BandLayout::erb spaces its bands evenly on it.
Top: the Bark scale (hz_to_bark, Traunmüller); 1 kHz is 8.53 Bark and 4 kHz is 17.46 Bark. Bottom: the critical bandwidth (the width of one Bark, from hz_to_bark) and the Glasberg-Moore equivalent rectangular bandwidth (hz_to_erb).
Figure 14.1. Top: the Bark scale (hz_to_bark, Traunmüller); 1 kHz is 8.53 Bark and 4 kHz is 17.46 Bark. Bottom: the critical bandwidth (the width of one Bark, from hz_to_bark) and the Glasberg-Moore equivalent rectangular bandwidth (hz_to_erb).

Absolute threshold of hearing. Terhardt’s (1979) fit to the threshold in quiet, in dB SPL with in Hz and :

It is high at low frequencies, has a minimum of about dB SPL near 3.3 kHz (the ear-canal resonance), and rises again above that minimum, slowly at first and steeply above about 10 kHz.

Threshold of hearing in quiet (Terhardt), from absolute_threshold_of_hearing: 22.95 dB SPL at 100 Hz, 3.37 dB SPL at 1 kHz and a minimum of -4.98 dB SPL near 3.3 kHz. Tones below the curve are inaudible. The library clamps the formula to 60 dB SPL, hence the flat segment below 30 Hz.
Figure 14.2. Threshold of hearing in quiet (Terhardt), from absolute_threshold_of_hearing: 22.95 dB SPL at 100 Hz, 3.37 dB SPL at 1 kHz and a minimum of -4.98 dB SPL near 3.3 kHz. Tones below the curve are inaudible. The library clamps the formula to 60 dB SPL, hence the flat segment below 30 Hz.

Simultaneous masking. A loud component raises the threshold for other components nearby in frequency. Measured on the Bark scale, the masked threshold falls off steeply below the masker (about 25 dB/Bark) and more gently above it (about 10 dB/Bark at moderate levels, shallower for loud maskers): masking spreads upwards in frequency. A classic analytic form is the spreading function of Schroeder, Atal and Hall (1979):

where is the maskee’s Bark position minus the masker’s. Far from the masker its slopes approach dB/Bark above and dB/Bark below. Noise-like maskers mask more than tones: in Johnston’s (1988) model the masked threshold lies about 5.5 dB below a noise masker but dB below a tonal one, where is the masker’s Bark position (so about 15.5 to 38.5 dB across the 24 critical bands). A perceptual coder may add quantisation noise up to the masked threshold without it being audible, so it allocates bits only where the signal-to-mask ratio (signal level minus masked threshold, dB) is positive.

What the library’s masking model does. PsychoacousticConfig stores a simplified form of the Johnston offsets, a constant 14.5 dB for tonal maskers (Johnston’s evaluated at ) and 5.5 dB for noise, and two straight-line slopes. Its presets use 25 dB/Bark upward and 6 dB/Bark downward, which is the reverse of the psychoacoustic asymmetry above (the field documentation says so); we demonstrate it below rather than rely on it. Despite its name, the mpeg1 preset does not reproduce the ISO/IEC 11172-3 (MPEG-1) psychoacoustic model’s spreading function either.

μ-law companding (ITU-T G.711). Speech has a wide dynamic range, and uniform quantisation gives quiet talkers a poor SNR (6.02 dB per bit, minus every dB the signal is below full scale; chapter 02). Companding quantises the logarithm of the amplitude instead. The continuous μ-law curve is

for . G.711 implements a segmented (piecewise-linear) approximation: a 14-bit linear sample becomes an 8-bit code made of a sign bit, a 3-bit segment number and a 4-bit mantissa. The magnitude plus a bias of 33 is located in one of 8 segments (each twice as wide as the last); 16 equal steps in each segment give step sizes of 2, 4, …, 256 (in 14-bit units; the very first code of segment 0 covers magnitude 0 alone, a step of 1). The result is a roughly constant SNR of 35-40 dB over a wide range of levels, with 8 bits instead of 14.

The library’s mu_compress implements this curve without quantising (it maps 0 to 0), and mu_expand inverts it. This chapter also writes the curve out by hand and checks both against it.

Perceptual transform codecs. All three codecs below split the signal into frequency bands with a modified discrete cosine transform (MDCT), a lapped transform with perfect reconstruction, but they use it differently:

  • MP3 (MPEG-1 Layer III) uses a hybrid filterbank: a 32-band polyphase filterbank followed by an MDCT in each band. A psychoacoustic model computes the masked threshold per band, and a bit allocator assigns bits where the signal-to-mask ratio is high.
  • AAC uses a plain MDCT with 50 % overlap (long and short blocks) and the same principle: a psychoacoustic model sets the masked threshold per band, and quantisation noise is shaped to stay under it.
  • Opus’s CELT layer uses an MDCT with a low-overlap window (a fixed 2.5 ms overlap, much less than 50 % of a 20 ms frame) to keep the delay low. It runs no explicit masking model: it codes each band’s energy explicitly and the normalised shape of the band separately, so the energy in every band is preserved (the “constrained energy” idea), and its bit allocation is largely fixed or signalled.

The library’s PerceptualCodec follows this outline (MDCT, Bark bands, the masking model above, bit allocation, scalar quantisation), and codecs::opus is an Opus-inspired teaching codec with SILK-like (LPC), CELT-like (MDCT) and hybrid modes. Neither is bitstream compatible with MP3 or Opus: there is no entropy or range coder and no standard bitstream; the encoded value is an in-memory structure.

With the library

The scales and the threshold of hearing, as implemented:

use audio_samples::absolute_threshold_of_hearing;
use audio_samples::codecs::perceptual::bands::{
    bark_to_hz, erb_number_to_hz, hz_to_bark, hz_to_erb, hz_to_erb_number,
};
use audio_samples::utils::audio_math::{hz_to_mel, mel_to_hz};

// HTK mel: 1000 Hz is (almost exactly) 1000 mel, and the inverse round-trips.
assert!((hz_to_mel(1_000.0) - 1_000.0).abs() < 0.02);
assert!((mel_to_hz(hz_to_mel(4_000.0)) - 4_000.0).abs() < 1e-9);
// Traunmueller Bark: 1 kHz is 8.53 Bark, 4 kHz is 17.46 Bark (f32 arithmetic).
assert!((hz_to_bark(1_000.0) - 8.527).abs() < 1e-3);
assert!((hz_to_bark(4_000.0) - 17.46).abs() < 0.01);
assert!((bark_to_hz(hz_to_bark(1_000.0)) - 1_000.0).abs() < 0.05);
// Glasberg-Moore ERB *bandwidth*: 132.6 Hz at 1 kHz, 456.5 Hz at 4 kHz.
assert!((hz_to_erb(1_000.0) - 132.639).abs() < 1e-3);
assert!((hz_to_erb(4_000.0) - 456.456).abs() < 1e-2);
// Johnston's tonal offset 14.5 + z dB over the 24 critical bands (z = 1..24):
// 15.5 to 38.5 dB. The library's constant 14.5 dB is its z = 0 value.
let johnston_tonal = |z: f64| 14.5 + z;
assert_eq!((johnston_tonal(1.0), johnston_tonal(24.0)), (15.5, 38.5));
// The ERB-number (perceptual coordinate): 15.62 Cam at 1 kHz, and its inverse.
let erb_number = |f: f64| 21.4 * (1.0 + 0.00437 * f).log10();
assert!((erb_number(1_000.0) - 15.62).abs() < 0.01);
assert!((f64::from(hz_to_erb_number(1_000.0)) - erb_number(1_000.0)).abs() < 1e-4);
assert!((erb_number_to_hz(hz_to_erb_number(1_000.0)) - 1_000.0).abs() < 0.05);

// Threshold in quiet (dB SPL): 22.95 at 100 Hz, 3.37 at 1 kHz, -4.98 at 3.3 kHz.
assert!((absolute_threshold_of_hearing(100.0) - 22.95).abs() < 0.01);
assert!((absolute_threshold_of_hearing(1_000.0) - 3.37).abs() < 0.01);
assert!((absolute_threshold_of_hearing(3_300.0) + 4.98).abs() < 0.01);

The masking model’s spreading, with the mpeg1 preset: a tonal masker’s threshold is dB down two Bark above it, but only dB down two Bark below it, so this preset lets masking spread further downwards than upwards, opposite to the psychoacoustic data.

use audio_samples::{MaskerType, PsychoacousticConfig, spreading_attenuation};
use std::num::NonZeroUsize;

let w = PsychoacousticConfig::uniform_weights(NonZeroUsize::new(24).unwrap());
let cfg = PsychoacousticConfig::mpeg1(w.as_non_empty_slice());
let above = spreading_attenuation(10.0, 12.0, MaskerType::Tonal, &cfg);
let below = spreading_attenuation(10.0, 8.0, MaskerType::Tonal, &cfg);
assert!((above - 64.5).abs() < 1e-4);
assert!((below - 26.5).abs() < 1e-4);
// Noise maskers use the smaller 5.5 dB offset: they mask more.
assert!((spreading_attenuation(10.0, 10.0, MaskerType::Noise, &cfg) - 5.5).abs() < 1e-6);
Masked threshold relative to the masker level against the distance from the masker in Bark. The library's mpeg1 preset (spreading_attenuation) falls by 25 dB/Bark above the masker and 6 dB/Bark below it; the Schroeder et al. spreading function (shifted by the 14.5 dB tonal offset) falls steeply below and gently above.
Figure 14.3. Masked threshold relative to the masker level against the distance from the masker in Bark. The library's mpeg1 preset (spreading_attenuation) falls by 25 dB/Bark above the masker and 6 dB/Bark below it; the Schroeder et al. spreading function (shifted by the 14.5 dB tonal offset) falls steeply below and gently above.

In the perceptual codec, a larger bit budget gives less quantisation noise. Encode half a second of a 1 kHz tone (24 Bark bands, 2048-sample MDCT) with two bit budgets and measure the SNR of the decoded signal:

use audio_samples::codecs::{decode, encode};
use audio_samples::{BandLayout, PerceptualCodec, PsychoacousticConfig, sample_rate, sine_wave};
use spectrograms::WindowType;
use std::num::NonZeroUsize;
use std::time::Duration;

let x = sine_wave::<f32>(1_000.0, Duration::from_millis(500), sample_rate!(44100), 0.5);
let snr_db = |budget: u32| {
    let n_bands = NonZeroUsize::new(24).unwrap();
    let layout = BandLayout::bark(n_bands, 44_100.0, NonZeroUsize::new(1024).unwrap());
    let w = PsychoacousticConfig::uniform_weights(n_bands);
    let codec = PerceptualCodec::with_window_size(
        layout, PsychoacousticConfig::mpeg1(w.as_non_empty_slice()),
        WindowType::Hanning, budget, 1, NonZeroUsize::new(2048).unwrap(),
    );
    let y = decode::<PerceptualCodec, f32>(encode(&x, codec).unwrap()).unwrap();
    let (a, b) = (x.as_slice().unwrap(), y.as_slice().unwrap());
    let s: f64 = a.iter().map(|&v| f64::from(v).powi(2)).sum();
    let e: f64 = a.iter().zip(b).map(|(&p, &q)| f64::from(p - q).powi(2)).sum();
    10.0 * (s / e).log10()
};
let (low, high) = (snr_db(32_000), snr_db(128_000));
// About 43 dB and 62 dB (1 dB tolerance: the figures depend on the bit allocator).
assert!((low - 42.7).abs() < 1.0);
assert!((high - 61.9).abs() < 1.0);
assert!(high > low);

SNR is not what the codec optimises: a perceptual codec aims to keep the noise below the masked threshold, which can sound transparent at an SNR far below what a waveform coder would need.

SNR of half a second of a 1 kHz tone after encoding and decoding with the PerceptualCodec (24 Bark bands, 2048-sample MDCT, mpeg1 masking preset), against the bit budget: about 43 dB at 32000 and 62 dB at 128000.
Figure 14.4. SNR of half a second of a 1 kHz tone after encoding and decoding with the PerceptualCodec (24 Bark bands, 2048-sample MDCT, mpeg1 masking preset), against the bit budget: about 43 dB at 32000 and 62 dB at 128000.

How it works

The threshold of hearing and the spreading function, from the formulas.

use audio_samples::absolute_threshold_of_hearing;

let terhardt = |f: f64| {
    let k = f / 1000.0;
    3.64 * k.powf(-0.8) - 6.5 * (-0.6 * (k - 3.3).powi(2)).exp() + 1e-3 * k.powi(4)
};
// The library evaluates the same formula in f32 (and clamps to [-20, 60] dB SPL).
for f in (20..=16_000).step_by(10) {
    let lib = f64::from(absolute_threshold_of_hearing(f as f32));
    assert!((lib - terhardt(f as f64).clamp(-20.0, 60.0)).abs() < 1e-3);
}
// Minimum: about -5 dB SPL near 3.3 kHz.
let (f_min, t_min) = (20..=16_000)
    .map(|f| (f, terhardt(f as f64)))
    .min_by(|a, b| a.1.total_cmp(&b.1))
    .unwrap();
assert!((f_min as f64 - 3_320.0).abs() <= 20.0 && (t_min + 4.98).abs() < 0.01);

// Schroeder et al. (1979): shallow above the masker, steep below.
let s = |dz: f64| 15.81 + 7.5 * (dz + 0.474) - 17.5 * (1.0 + (dz + 0.474).powi(2)).sqrt();
let upper_slope = (s(10.0) - s(8.0)) / 2.0; // dB per Bark, far above the masker
let lower_slope = (s(-8.0) - s(-10.0)) / 2.0; // dB per Bark, far below (rising towards it)
assert!((upper_slope + 10.0).abs() < 0.3);
assert!((lower_slope - 25.0).abs() < 0.3);

G.711 μ-law, from the standard. Encode a 14-bit sample to an 8-bit code and back; check the code against the continuous curve, and compare the SNR with 8-bit linear PCM at several levels.

use std::f64::consts::PI;

fn ulaw_encode(x: i32) -> u8 {
    let (mag, sign) = if x < 0 { (-x, 0x80u8) } else { (x, 0x00u8) };
    let biased = (mag.min(8_159) + 33).min(8_191); // clip, bias, saturate
    let seg = (0..8).find(|&s| biased < (64 << s)).unwrap(); // segment 0..7
    let mant = ((biased >> (seg + 1)) & 0x0F) as u8; // 4-bit mantissa
    !(sign | ((seg as u8) << 4) | mant) // G.711 transmits the code inverted
}
fn ulaw_decode(code: u8) -> i32 {
    let c = !code;
    let (seg, mant) = (i32::from((c >> 4) & 7), i32::from(c & 0x0F));
    let mag = (((mant << 1) + 33) << seg) - 33; // middle of the step
    if c & 0x80 != 0 { -mag } else { mag }
}
assert_eq!(ulaw_encode(0), 0xFF); // positive zero
assert_eq!(ulaw_decode(ulaw_encode(8_159)), 8_031); // largest magnitude
// The error never exceeds half a step: 2^seg in segment seg (1, 2, ..., 128).
for x in -8_159i32..=8_159 {
    let seg = (0..8).find(|&s| (x.abs() + 33).min(8_191) < (64 << s)).unwrap();
    assert!((x - ulaw_decode(ulaw_encode(x))).abs() <= 1 << seg);
}
// The segment/mantissa index (0..127) stays within 2 codes of 127 F(x), mu = 255.
let f = |x: f64| (1.0 + 255.0 * x).ln() / 256f64.ln();
let worst = (1..=8_159)
    .map(|x| (f64::from(!ulaw_encode(x) & 0x7F) - 127.0 * f(f64::from(x) / 8_159.0)).abs())
    .fold(0.0, f64::max);
assert!(worst < 2.0);

// SNR of a sine at a given peak level for a quantiser q.
let snr = |level_db: f64, q: &dyn Fn(f64) -> f64| {
    let a = 10f64.powf(level_db / 20.0);
    let (mut s, mut e) = (0.0, 0.0);
    for n in 0..8_000 {
        let x = a * (2.0 * PI * 0.1234567 * n as f64).sin();
        s += x * x;
        e += (x - q(x)).powi(2);
    }
    10.0 * (s / e).log10()
};
let ulaw = |x: f64| f64::from(ulaw_decode(ulaw_encode((x * 8_159.0).round() as i32))) / 8_159.0;
let lin8 = |x: f64| (x * 127.0).round() / 127.0;
let levels = [0.0, -10.0, -20.0, -30.0, -40.0];
let su: Vec<f64> = levels.iter().map(|&l| snr(l, &ulaw)).collect();
let sl: Vec<f64> = levels.iter().map(|&l| snr(l, &lin8)).collect();
// mu-law stays between 34 and 40.5 dB over 40 dB of level ...
assert!(su.iter().all(|s| (34.0..40.5).contains(s)));
// ... while 8-bit linear starts at 6.02 * 8 + 1.76 = 49.9 dB and loses ~40 dB.
assert!((sl[0] - 49.9).abs() < 0.5);
assert!((sl[0] - sl[4] - 40.0).abs() < 1.5);
assert!(su[4] > sl[4] + 20.0);
Top: the mu-law curve (mu_compress, mu = 255) and the G.711 segmented code index scaled to 1 (steps), which stays within 2 codes of the curve. Bottom: SNR of a sine against its peak level; G.711 stays between 34 and 40.5 dB over 40 dB of level, while 8-bit linear PCM falls from 49.9 dB by about 1 dB per dB.
Figure 14.5. Top: the mu-law curve (mu_compress, mu = 255) and the G.711 segmented code index scaled to 1 (steps), which stays within 2 codes of the curve. Bottom: SNR of a sine against its peak level; G.711 stays between 34 and 40.5 dB over 40 dB of level, while 8-bit linear PCM falls from 49.9 dB by about 1 dB per dB.

The library’s compressor equals the curve written out by hand (so and ), and its expander inverts it:

use audio_samples::{AudioProcessing, AudioSamples, sample_rate};
use non_empty_slice::NonEmptyVec;

let mu: f64 = 255.0;
let f = |x: f64| x.signum() * (1.0 + mu * x.abs()).ln() / (1.0 + mu).ln();
let xs = [-0.9, -0.3, -0.01, 0.0, 0.02, 0.5, 1.0];
let audio: AudioSamples<f64> =
    AudioSamples::from_mono_vec(NonEmptyVec::new(xs.to_vec()).unwrap(), sample_rate!(8000));
let compressed = audio.mu_compress(255.0).unwrap();
for (x, y) in xs.iter().zip(compressed.as_slice().unwrap()) {
    assert!((f(*x) - y).abs() < 1e-12);
}
assert_eq!(compressed.as_slice().unwrap()[3], 0.0); // F(0) = 0
assert!((compressed.as_slice().unwrap()[6] - 1.0).abs() < 1e-12); // F(1) = 1
let back = compressed.mu_expand(255.0).unwrap();
for (x, y) in xs.iter().zip(back.as_slice().unwrap()) {
    assert!((x - y).abs() < 1e-12);
}

Ask the library to explain

There is no explainer for psychoacoustics or codecs (see topics for what exists). The closest is the quantisation topic, which gives the uniform-quantiser SNR that μ-law improves on for quiet signals:

use audio_samples::educational::topics;

let doc = topics::quantisation(8);
println!("{doc}");
// 6.02 * 8 + 1.76 = 49.9 dB for a full-scale sine with 8-bit uniform quantisation.
assert!((doc.quantity("Rule of thumb").unwrap().value - 49.92).abs() < 0.01);
assert!((doc.quantity("SQNR (full-scale sine)").unwrap().value - 49.92).abs() < 0.1);

Exercises

  1. Bark distance. Predict roughly how many Bark lie between 1 kHz and 4 kHz, then compute it with hz_to_bark.
  2. Threshold at 50 Hz. Is a 50 Hz tone at 30 dB SPL audible in quiet according to Terhardt’s formula?
  3. Smallest and largest μ-law steps. Using the segment structure, what is the ratio between the largest and the smallest G.711 step, in dB? Why does this keep the SNR roughly constant?
  4. Calibration. A recording’s speech peaks at dBFS peak. The playback chain is calibrated so that a full-scale sine (RMS dBFS) is 94 dB SPL. What SPL do the speech peaks correspond to (as a sine of that peak)?

Answers

  1. Bark: about 9 critical bands for two octaves, while 0 to 1 kHz is 8.5 Bark.
use audio_samples::codecs::perceptual::bands::hz_to_bark;

let d = hz_to_bark(4_000.0) - hz_to_bark(1_000.0);
assert!((d - 8.93).abs() < 0.01);
  1. dB SPL, so a 30 dB SPL tone at 50 Hz is about 10 dB below threshold: inaudible.
use audio_samples::absolute_threshold_of_hearing;

let t = f64::from(absolute_threshold_of_hearing(50.0));
assert!((t - 40.0).abs() < 0.1);
assert!(30.0 < t);
  1. Steps go from 2 (segment 0) to 256 (segment 7) in 14-bit units, a ratio of 128 or 42.1 dB. The step grows in proportion to the signal amplitude, so the quantisation noise grows with the signal and the SNR stays roughly constant (until the signal falls into segment 0, where μ-law behaves like uniform quantisation).
let steps: Vec<i32> = (0..8).map(|seg| 2 << seg).collect();
assert_eq!((steps[0], steps[7]), (2, 256));
assert!((20.0 * (256.0f64 / 2.0).log10() - 42.14).abs() < 0.01);
  1. A sine with peak dBFS has RMS dBFS, which is 12 dB below the calibration tone: dB SPL.
let calibration_spl = 94.0; // full-scale sine: peak 0 dBFS, RMS -3.01 dBFS
let peak_dbfs = -12.0;
let spl: f64 = calibration_spl + peak_dbfs; // same waveform shape, so offsets carry over
assert!((spl - 82.0).abs() < 1e-12);

Common pitfalls

  • dBFS conventions. Some tools quote the RMS of a full-scale sine as 0 dBFS (AES17); this library uses , which gives dBFS.
  • “Mel” is ambiguous. HTK (2595 log10(1 + f/700)) and Slaney (linear below 1 kHz, logarithmic above) differ; audio_math uses HTK, the mel spectrogram uses Slaney.
  • hz_to_erb returns a bandwidth, not an ERB-number; uniformly spaced ERB bandwidths are uniformly spaced in Hz. Use hz_to_erb_number for the perceptual coordinate.
  • Masking direction. Masking spreads upwards in frequency. The library’s PsychoacousticConfig presets invert the slopes, and its conservative / aggressive preset names are also the reverse of their effect; set the fields yourself if you need a faithful model.
  • mu_compress is the continuous curve, not G.711. It applies without quantising; the 8-bit segmented codes of G.711 are a different, piecewise-linear approximation. For integer μ-law codes use mu_law_encode / mu_law_decode.
  • Not Opus. codecs::opus is a teaching codec; it cannot read or write .opus files.

References

  • E. Terhardt, “Calculating virtual pitch”, Hearing Research 1(2), 155-182, 1979. The threshold-in-quiet formula.
  • H. Traunmüller, “Analytical expressions for the tonotopic sensory scale”, Journal of the Acoustical Society of America 88(1), 97-100, 1990.
  • B. R. Glasberg and B. C. J. Moore, “Derivation of auditory filter shapes from notched-noise data”, Hearing Research 47(1-2), 103-138, 1990.
  • E. Zwicker and H. Fastl, Psychoacoustics: Facts and Models, Springer. Critical bands and masking.
  • M. R. Schroeder, B. S. Atal and J. L. Hall, “Optimizing digital speech coders by exploiting masking properties of the human ear”, Journal of the Acoustical Society of America 66(6), 1647-1652, 1979.
  • J. D. Johnston, “Transform coding of audio signals using perceptual noise criteria”, IEEE Journal on Selected Areas in Communications 6(2), 314-323, 1988.
  • S. S. Stevens, “On the psychophysical law”, Psychological Review 64(3), 153-181, 1957.
  • ITU-T Recommendation G.711, Pulse code modulation (PCM) of voice frequencies.
  • ISO/IEC 11172-3, Coding of moving pictures and associated audio for digital storage media at up to about 1.5 Mbit/s, Part 3: Audio (MPEG-1 audio, including Layer III).
  • J.-M. Valin, K. Vos and T. Terriberry, Definition of the Opus Audio Codec, RFC 6716, IETF, 2012; J.-M. Valin, G. Maxwell, T. B. Terriberry and K. Vos, “High-quality, low-delay music coding in the Opus codec”, 135th Audio Engineering Society Convention, 2013. CELT’s low-overlap MDCT and energy coding.
  • AES17, AES standard method for digital audio engineering: measurement of digital audio equipment, Audio Engineering Society (the definition of dBFS as the RMS of a full-scale sine).

See also

Example gallery

Every example in the crate’s examples/ directory, grouped by task. book/build.sh compiles all of them with the full and educational features and runs all but two, and the build fails if one fails, so the output below is what the current code prints. An example asserts its own results, and a figure repeats the example’s calls or comes from the chapter that covers the same operation, where the same numbers are asserted.

Run one from a checkout of the crate with the command shown under it.

Getting started and loading audio

The crate’s core types, sample conversion and the helpers around them. Reading and writing files is in the separate audio_samples_io crate, which has no example here (see gaps below).

Create audio and convert samples

Builds mono and stereo AudioSamples and converts samples between i16 and f32, showing how each sample type maps to the other.

examples/basics.rs

cargo run --example basics --features statistics
Output
=> Converting i16 to f32...
32767_i16 -> 1.00_f32
=> And back again to i16...
1.00_f32 -> 32767_i16

-----

Mono audio: AudioSamples<f32>: 1 ch × 3 samples @ 16000 Hz (0.000 s)
  ch 0: [0.1000, 0.2000, 0.3000]

-----

Stereo audio: AudioSamples<f32>: 2 ch × 3 samples @ 44100 Hz (0.000 s)
  ch 0: [0.1000, 0.2000, 0.3000]
  ch 1: [0.4000, 0.5000, 0.6000]

-----

Converted stereo audio to i16: AudioSamples<i16>: 2 ch × 3 samples @ 44100 Hz (0.000 s)
  ch 0: [3277, 6553, 9830]
  ch 1: [13107, 16384, 19660]

Generated sine wave audio: AudioSamples<f32>: 1 ch × 88200 samples @ 44100 Hz (2.000 s)
  ch 0: [0.0000, 0.0626, 0.1251, ..., -0.1870, -0.1251, -0.0626]

-----

Compound Tone wave info:
Number of channels: 1
Samples per channel: 88200
Duration (seconds): 2.00
Sample rate: 44100 Hz
-----

== Statistics ==
Mean: -0.000000000000000025134845074506946
RMS: 0.8100925881737456
Min: -1.387568
Max: 1.387568
Variance: 0.6562500014140327
... 8 more lines

Statistics of a signal

Peak, RMS, mean, variance, zero crossings and autocorrelation of a generated tone.

examples/statistics.rs

cargo run --example statistics --features statistics
Output
Compound Tone wave info:
|-Number of channels: 1
|-Samples per channel: 88200
|-Duration (seconds): 2.00
|-Sample rate: 44100 Hz
-----

== Statistics ==
Mean: -0.000000000000000025134845074506946
RMS: 0.8100925881737456
Min: -1.387568
Max: 1.387568
Variance: 0.6562500014140327
Standard Deviation: 0.8100925881737424
Peak: 1.387568
Zero Crossings: 1760
Zero Crossing Rate: 880
Autocorrelation (lag 1): NonEmptyVec { inner: [0.6562500014140247, 0.6537430192068365] }
Spectral-centroid: 565.7142851653853
Spectral-rolloff (0.85): 880

Compound Tone wave info:
|-Number of channels: 1
|-Samples per channel: 88200
|-Duration (seconds): 2.00
|-Sample rate: 44100 Hz

Cross-correlation with 880 Hz tone: NonEmptyVec { inner: [0.2500000002845455, 0.2480404062699262] }

Unit conversions

Hz, mel and MIDI conversions, decibels, and the other small helpers in audio_samples::utils.

examples/utils_demo.rs

cargo run --example utils_demo
Output
Audio Maths Utility Functions Demo
==========================================

Frequency Scale Conversions
=============================

Hz ↔ Mel Scale Conversions:
  100 Hz → 150.5 mels → 100.0 Hz (error: 0.000)
  440 Hz → 549.6 mels → 440.0 Hz (error: 0.000)
  1000 Hz → 1000.0 mels → 1000.0 Hz (error: 0.000)
  4000 Hz → 2146.1 mels → 4000.0 Hz (error: 0.000)
  8000 Hz → 2840.0 mels → 8000.0 Hz (error: 0.000)

Hz ↔ MIDI Note Number Conversions:
  440 Hz (A4) → MIDI 69.0 → 440.00 Hz (error: 0.000)
  261.63 Hz (C4) → MIDI 60.0 → 261.63 Hz (error: 0.000)
  523.25 Hz (C5) → MIDI 72.0 → 523.25 Hz (error: 0.000)
  1046.5 Hz (C6) → MIDI 84.0 → 1046.50 Hz (error: 0.000)
  82.41 Hz (E2) → MIDI 40.0 → 82.41 Hz (error: 0.000)

Mel Scale Properties:
  The mel scale provides perceptually uniform frequency spacing:
  Generated 40 mel-spaced frequencies from 80 Hz to 8000 Hz:
  First 5: 80.0, 129.8, 182.7, 239.0, 298.9
  Last 5: 6093.5, 6526.8, 6987.9, 7478.3, 8000.0

Amplitude ↔ Decibel Conversions
==================================

Linear Amplitude to dB:
  0.001 → -60.0 dB → 0.001 (error: 0.000000)
  0.100 → -20.0 dB → 0.100 (error: 0.000000)
  0.500 → -6.0 dB → 0.500 (error: 0.000000)
  1.000 → 0.0 dB → 1.000 (error: 0.000000)
  2.000 → 6.0 dB → 2.000 (error: 0.000000)
  10.000 → 20.0 dB → 10.000 (error: 0.000000)

Power to dB (10*log10):
  Power 0.001 → -30.0 dB
  Power 0.100 → -10.0 dB
... 130 more lines

Detection helpers

Finds the fundamental frequency and the silent regions of a signal without configuring an analysis.

examples/detection.rs

cargo run --example detection
Output
Fundamental frequency: Some(441.0) Hz
Silence regions: [(0.0, 2.2675736961451248e-5), (0.05, 0.05002267573696145), (0.1, 0.10002267573696146), (0.15, 0.15002267573696146), (0.2, 0.20002267573696145)]
Detected sample rate: None

Errors as values

How to inspect a typed error, react to it and walk its chain of causes.

examples/errors.rs

cargo run --example errors --features fancy
Output
1. Source spans - the caret points at what's wrong
──────────────────────────────────────────────────
audio_samples::parse::note_name

  × invalid note name: unrecognised note
   ╭────
 1 │ H4
   · ┬
   · ╰── unrecognised note
   ╰────
  help: expected scientific pitch notation like `A4`, `C#3`, `Bb2`


audio_samples::parse::note_name

  × invalid note name: invalid octave
   ╭────
 1 │ C#x
   ·   ┬
   ·   ╰── invalid octave
   ╰────
  help: expected scientific pitch notation like `A4`, `C#3`, `Bb2`


audio_samples::parse::enum_value

  × unrecognised value for PadSide
   ╭────
 1 │ middle
   · ───┬──
   ·    ╰── not one of the accepted values
   ╰────
  help: expected one of: left, right, both



2. Inspecting a diagnostic programmatically
───────────────────────────────────────────
  display  : Parameter 'cutoff_hz' value 25000 is outside valid range [20, 22050]: exceeds the Nyquist limit for 44.1 kHz audio
... 70 more lines

Errors as diagnostics

Renders the same errors as miette diagnostics with codes, help text and source spans.

examples/error_diagnostics.rs

cargo run --example error_diagnostics --features fancy
Output
audio_samples::parse::note_name

  × invalid note name: unrecognised note
   ╭────
 1 │ H4
   · ┬
   · ╰── unrecognised note
   ╰────
  help: expected scientific pitch notation like `A4`, `C#3`, `Bb2`


audio_samples::parse::note_name

  × invalid note name: invalid octave
   ╭────
 1 │ C#x
   ·   ┬
   ·   ╰── invalid octave
   ╰────
  help: expected scientific pitch notation like `A4`, `C#3`, `Bb2`


audio_samples::parameter::out_of_range (https://docs.rs/audio_samples/3.0.0/audio_samples/enum.ParameterError.html#variant.OutOfRange)

  × Parameter 'cutoff_hz' value 25000 is outside valid range [20, 22050]:
  │ exceeds the Nyquist limit for 44.1 kHz audio
  help: pass a value for `cutoff_hz` in [20, 22050]; got 25000


audio_samples::parse::enum_value

  × unrecognised value for PadSide
   ╭────
 1 │ middle
   · ───┬──
   ·    ╰── not one of the accepted values
   ╰────
  help: expected one of: left, right

Spectrograms

STFT, spectra and the transforms built on them.

FFT, STFT, mel, MFCC, chroma, CQT

One call of each main transform on a tone, with the resulting shapes, then reconstruction with the inverse STFT.

examples/transforms.rs

cargo run --example transforms --features transforms,statistics
A 2 s linear chirp from 100 Hz to 7.9 kHz at 16 kHz (amplitude 0.5). Top: linear_db_spectrogram with N = 512, H = 128 and a -80 dB floor, in dB re 1. Bottom: mel_power_spectrogram with 40 bands, in dB; the mel scale spends more bands on low frequencies, so the line bends.
Figure 1. A 2 s linear chirp from 100 Hz to 7.9 kHz at 16 kHz (amplitude 0.5). Top: linear_db_spectrogram with N = 512, H = 128 and a -80 dB floor, in dB re 1. Bottom: mel_power_spectrogram with 40 bands, in dB; the mel scale spends more bands on low frequencies, so the line bends.
Output
=== Basic Transforms ===
FFT: shape=(1, 8193)
Dominant FFT bin: 163 (~438.7 Hz)
STFT: shape=(513, 35)
MFCC: shape=(13, 35)
Chroma: shape=(12, 35)
PSD: bins=513 psd_len=513 f0≈0.0Hz
CQT: shape=(84, 1)

=== Reconstruction ===
iSTFT reconstructed: peak=0.8000 rms=0.5659

Tutorial 3: the DFT, windows and leakage

Measures leakage for bin-centred and off-bin tones and compares windows. Text in chapter 3.

examples/tutorial_03_dft_windows.rs

cargo run --example tutorial_03_dft_windows --features educational,full_no_plotting
Top: the four windows for N = 512. Bottom: their spectra (zero-padded 16 times), relative to the peak, against the offset from the tone in bins. Lower side lobes come with a wider main lobe. The peak side-lobe levels in the legend are those the explainer reports.
Figure 2. Top: the four windows for N = 512. Bottom: their spectra (zero-padded 16 times), relative to the peak, against the offset from the tone in bins. Lower side lobes come with a wider main lobe. The peak side-lobe levels in the legend are those the explainer reports.
Output
=== Tutorial 03: the DFT, windows and leakage ===

1. A naive DFT loop versus the library's fft
   max |X_lib - X_naive| over 33 bins = 7.04e-14
   X[0] = 16.000+0.000i, X[4] = -0.000-32.000i, X[9] = 16.000-0.000i
   rfft(x)[4] = 32.000 (a real magnitude, |X[4]|)

2. Bin frequencies for N = 512 at 16 kHz
   Δf = fs/N = 31.25 Hz; bin 32 is 1000 Hz; 257 bins up to 8000 Hz

3. Leakage: a 1000 Hz (bin 32) and a 1015.625 Hz (bin 32.5) tone, N = 512
   rectangular: peak drop 3.86 dB (window figure 3.92 dB), level 19.5 bins away -34.0 dB
   Hann       : peak drop 1.42 dB (window figure 1.42 dB), level 19.5 bins away -86.0 dB

4. Window figures at N = 512 (measured here | topics::window)
   window       CG             ENBW (bins)    scalloping (dB)  PSL (dB)
   rectangular  1.0000|1.0000  1.0000|1.0000  3.922|3.922     -13.26|-13.26
   Hann         0.4990|0.4990  1.5029|1.5029  1.418|1.418     -31.47|-31.47
   Hamming      0.5391|0.5391  1.3647|1.3647  1.747|1.747     -42.67|-42.67
   Blackman     0.4192|0.4192  1.7301|1.7301  1.095|1.095     -58.11|-58.11
   symmetric Hann: w[0] = 0, w[511] = 0.0e0, w[256] = 0.999991 (periodic Hann would give 1)

5. Tones at 1000 and 1020 Hz (20 Hz apart)
   512 samples, N = 512:              1 peak(s) (Δf = 31.25 Hz)
   512 samples zero-padded to 8192:   1 peak(s) (grid 1.95 Hz, same main lobe)
   4096 samples, N = 8192:            2 peak(s) (main lobe 8x narrower)

6. WindowType::Hanning explained at N = 512, 16 kHz

Hann window
===========
A 512-point Hann window. Its main lobe is 2.00384 bins wide at -6 dB and its highest side lobe is at -31.4676 dB; each bin collects noise from 1.50294 bins' worth of bandwidth.

Formulas
--------
  Window coefficients as generated (n = 0, …, N-1):
                          ⎛ 2 πn  ⎞
      w[n] = 0.5 - 0.5 cos⎜───────⎟
                          ⎝ N - 1 ⎠

... 58 more lines

Tutorial 4: STFT and spectrograms

Frame counts, the inverse STFT and the time-frequency trade-off. Text in chapter 4.

examples/tutorial_04_stft_spectrograms.rs

cargo run --example tutorial_04_stft_spectrograms --features educational,full_no_plotting
The chapter's trade-off measurement, hop 2 ms. Top: summed STFT magnitude of two tones at 1000 and 1050 Hz; only the 128 ms window (N = 2048) separates them. Bottom: frame energy of a click at 250 ms; it stays above half its maximum for 6 ms with the 16 ms window (N = 256) and 46 ms with the 128 ms window.
Figure 3. The chapter's trade-off measurement, hop 2 ms. Top: summed STFT magnitude of two tones at 1000 and 1050 Hz; only the 128 ms window (N = 2048) separates them. Bottom: frame energy of a click at 250 ms; it stays above half its maximum for 6 ms with the 16 ms window (N = 256) and 46 ms with the 128 ms window.
Output
=== Tutorial 04: STFT and spectrograms ===

1. STFT of 1 s of noise at 16 kHz, N = 512, H = 128, Hann
   centre = true : 126 frames (formula: 126), 257 bins
   centre = false: 122 frames (formula: 122)
   frame 10 by hand vs stft(): max |difference| = 1.85e-14

2. istft: 16000 samples (formula (M-1)H + N - 2⌊N/2⌋ = 16000), max error 3.33e-16

3. Time-frequency trade-off (hop 32 samples = 2 ms)
   N =  256: Δf =  62.50 Hz, window  16.0 ms -> 1 peak(s) for 1000+1050 Hz; click spread 6 ms
   N = 2048: Δf =   7.81 Hz, window 128.0 ms -> 2 peak(s) for 1000+1050 Hz; click spread 46 ms
   click spread ratio = 7.67 (window ratio 8)

4. Linear / log-Hz / mel spectrograms of a full-scale 1 kHz sine
   rows: linear 257, log-Hz 64, mel 40; frames 126
   linear dB peak = 42.13 dB re 1 (predicted 20 log10(Σw/2) = 42.13 dB), above 0 dB
   silence: every bin equals the floor, -80 dB re 1: true
   strongest mel band: 13 centred at 1031 Hz (neighbour spacing 81 Hz)

5. StftParams explained for a speech signal with f0 in 80-400 Hz
   N = 1024: Δf =  15.6 Hz, frames = 63, short-window warning false, coarse-bin warning false
   N =  256: Δf =  62.5 Hz, frames = 251, short-window warning true, coarse-bin warning false
   N =  128: Δf = 125.0 Hz, frames = 501, short-window warning true, coarse-bin warning true

Short-time Fourier transform (STFT)
===================================
Frames of 512 samples (Hann window) every 128 samples (75% overlap), centred by padding ⌊N/2⌋ zeros at both ends. Each frame gives 257 frequency bins spaced 31.25 Hz apart, one frame every 8 ms.

Formulas
--------
  Frame m: window N samples starting at mH - p and take an N-point DFT (samples outside the signal are 0):
                                            2π     
                                        -j ──── k n
              N - 1                         N      
      Xₘ[k] =   ∑   x[mH + n - p] w[n] e           
              n = 0                                

  Number of frames for L samples (at least 1):
          ⌊  L + 2p - N  ⌋    
... 65 more lines

Mel and MFCC

Tutorial 10: cepstrum, mel and MFCC

Derives the real cepstrum, the mel filterbank and MFCCs and checks them against the library. Text in chapter 10.

examples/tutorial_10_cepstrum_mel_mfcc.rs

cargo run --example tutorial_10_cepstrum_mel_mfcc --features educational,full_no_plotting
The 40 triangular mel filters (Slaney scale, 0 Hz to 8 kHz, peak 1, no normalisation) from mel_filterbank, evaluated at the 257 bins of a 512-point FFT at 16 kHz. They are evenly spaced below 1 kHz and widen logarithmically above. Band 5 (orange, centred at 441.4 Hz) is the loudest for the 440 Hz tone.
Figure 4. The 40 triangular mel filters (Slaney scale, 0 Hz to 8 kHz, peak 1, no normalisation) from mel_filterbank, evaluated at the 257 bins of a 512-point FFT at 16 kHz. They are evenly spaced below 1 kHz and widen logarithmically above. Band 5 (orange, centred at 441.4 Hz) is the loudest for the 440 Hz tone.
One frame (frame 13, 130 ms) of the 440 Hz tone. Top: log mel energies in dB, floored at -80 dB, with the peak in band 5. Bottom: the 13 MFCCs from AudioTransforms::mfcc (unnormalised DCT-II of the top panel), with the default lifter 22 and with the lifter off.
Figure 5. One frame (frame 13, 130 ms) of the 440 Hz tone. Top: log mel energies in dB, floored at -80 dB, with the peak in band 5. Bottom: the 13 MFCCs from AudioTransforms::mfcc (unnormalised DCT-II of the top panel), with the default lifter 22 and with the lifter off.
Output
== Tutorial 10: cepstrum, mel and MFCC ==

1. Real cepstrum of a 1024-sample Hann-windowed vowel frame (f0 = 160 Hz, period 100 samples)
   low quefrencies (vocal tract): c[1..=3] = 2.318, 0.466, -0.055
   largest peak for q in 40..=266 (400 Hz down to 60 Hz): q = 100 samples = 6.25 ms -> f0 = 160.0 Hz
   peak height 1.553; next highest value away from it 0.379
   topics::cepstrum(1024, 16000): lowest detectable f0 2 f_s/N = 31.25 Hz

2. Two mel scales: audio_math (HTK) and the mel spectrogram (Slaney)
   f (Hz) | HTK 2595 log10(1 + f/700) | Slaney | HTK round trip error (Hz)
        0 |                      0.00 |  0.000 | 0.0e0
      500 |                    607.45 |  7.500 | 1.1e-13
     1000 |                    999.99 | 15.000 | 2.3e-13
     2000 |                   1521.36 | 25.082 | 2.3e-13
     4000 |                   2146.06 | 35.164 | 4.5e-13
     8000 |                   2840.02 | 45.246 | 1.8e-12

3. Mel filterbank re-built and applied to the library's power spectrogram
   19 frames x 40 bands; worst relative difference 6.7e-14
   lowest band centre 73.570 Hz (explain) vs 73.570 Hz (ours)

4. MFCC = DCT-II(10 log10 max(P_mel, 1e-8)) with lifter 22, re-derived
   13 coefficients x 19 frames; worst |difference| 9.1e-13 (values up to 1613)
   lifter 0: library / orthonormal = 6.3246 for c0 (sqrt(M) = 6.3246), 4.4721 for c5 (sqrt(M/2) = 4.4721)

5. Empty mel bands: 128 bands, n_fft = 256 at 16 kHz
   explain predicts 13 empty filters; the computed spectrogram has 13 all-zero rows

Mel-frequency cepstral coefficients (MFCC)
==========================================
Each frame's mel power spectrum is converted to dB, decorrelated with a DCT-II, and the first 13 coefficients are kept, liftered with L = 22.

Formulas
--------
  Log mel energies in dB with an absolute floor of -80 dB (mel filterbank 0 Hz to f_s/2, no normalisation):
      Lᵢ = 10 log max(Pᵢ, 10⁻⁸)
              10               

  Unnormalised DCT-II, as implemented. An orthonormal DCT-II would return c_0/sqrt(M) and c_k·sqrt(2/M) instead:
                                  1    
... 127 more lines

Psychoacoustic analysis

Band layouts on the Bark and mel scales and the perceptual importance of each band.

examples/psychoacoustic.rs

cargo run --example psychoacoustic --features psychoacoustic
Top: the Bark scale (hz_to_bark, Traunmüller); 1 kHz is 8.53 Bark and 4 kHz is 17.46 Bark. Bottom: the critical bandwidth (the width of one Bark, from hz_to_bark) and the Glasberg-Moore equivalent rectangular bandwidth (hz_to_erb).
Figure 6. Top: the Bark scale (hz_to_bark, Traunmüller); 1 kHz is 8.53 Bark and 4 kHz is 17.46 Bark. Bottom: the critical bandwidth (the width of one Bark, from hz_to_bark) and the Glasberg-Moore equivalent rectangular bandwidth (hz_to_erb).
Output
=== Psychoacoustic Analysis ===
Signal: 8820 samples @ 44100 Hz

MDCT coefficients: 10240 total
Spectral bins:     1024 (avg energy per bin)
Bands analysed:    24

Band   CentreHz     Energy dB  SMR dB   Importance AllowNoise
------------------------------------------------------------
0      78.5         13.50      -14.37   0.0000     27.87     
1      161.1        13.92      -1.75    0.0000     15.67     
2      250.6        16.86      -1.53    0.0000     18.39     
3      348.1        24.81      0.50     0.5000     24.31     
4      454.6        44.54      0.50     0.5000     44.04     
5      571.3        15.90      0.50     0.5000     15.40     
6      699.9        5.42       -5.12    0.0000     10.54     
7      842.3        31.06      0.50     0.5000     30.56     
8      1000.8       9.95       0.50     0.5000     9.45      
9      1178.3       2.78       0.02     0.0249     2.76      
10     1378.5       -1.68      -3.79    0.0000     2.11      
11     1605.9       -5.21      -6.54    0.0000     1.34      
12     1866.5       -7.93      -8.26    0.0000     0.33      
13     2168.3       -11.14     -10.10   0.0000     -1.03     
14     2521.8       -13.79     -11.04   0.0000     -2.74     
15     2941.4       -16.60     -12.19   0.0000     -4.41     
16     3447.7       -19.59     -14.66   0.0000     -4.92     
17     4070.7       -22.51     -19.42   0.0000     -3.09     
18     4855.9       -25.43     -25.49   0.0000     0.06      
19     5876.2       -28.69     -30.65   0.0000     1.95      
20     7255.8       -32.10     -35.62   0.0000     3.52      
21     9224.9       -35.84     -43.70   0.0000     7.86      
22     12264.0      -39.85     -62.97   0.0000     23.11     
23     17571.0      -43.56     -103.56  0.0000     60.00     

Top 5 bands by perceptual importance:
  #1: band 3 (348 Hz) - importance=0.5000, SMR=0.50 dB
  #2: band 4 (455 Hz) - importance=0.5000, SMR=0.50 dB
  #3: band 5 (571 Hz) - importance=0.5000, SMR=0.50 dB
  #4: band 7 (842 Hz) - importance=0.5000, SMR=0.50 dB
  #5: band 8 (1001 Hz) - importance=0.5000, SMR=0.50 dB
... 4 more lines

Pitch

Pitch and harmonics

YIN against autocorrelation, a pitch track, harmonic magnitudes and the harmonic-to-noise ratio.

examples/pitch_analysis.rs

cargo run --example pitch_analysis --features pitch-analysis
track_pitch with YIN, 512-sample frames every 128 samples, on a 0.5 s linear glide from 100 to 200 Hz. Top: each estimate at its frame centre. Bottom: estimate minus the glide's frequency at the frame centre; the largest deviation is 0.12 Hz.
Figure 7. track_pitch with YIN, 512-sample frames every 128 samples, on a 0.5 s linear glide from 100 to 200 Hz. Top: each estimate at its frame centre. Bottom: estimate minus the glide's frequency at the frame centre; the largest deviation is 0.12 Hz.
Output
Search 80-1000 Hz = lags 44..=551 samples; frame must exceed 1103 samples
True f0           : 440.000 Hz (period 100.227 samples)
Pitch (YIN)       : 440.019 Hz
Pitch (autocorr)  : 441.000 Hz  (integer lag 100 → fs/lag; neighbours 436.6 / 445.5 Hz)
Pitch contour     : 85 frames (84 voiced), mean 440.018 Hz
Spectral HNR      : 3.01 dB (window-leakage limited, see docs)
Harmonic magnitudes (relative to the fundamental): [1.000, 0.000, 0.000, 0.000, 0.000, 0.000]
Estimated key of a D major triad: D Major (confidence 0.783)
  (a bare triad is ambiguous between related keys; the Krumhansl-Schmuckler
   correlation needs a passage with a full scale for a reliable answer)

Tutorial 9: autocorrelation and YIN

Derives both estimators and shows why they make octave errors. Text in chapter 9.

examples/tutorial_09_pitch.rs

cargo run --example tutorial_09_pitch --features educational,full_no_plotting
YIN on the 440 Hz tone. Top: the cumulative-mean-normalised difference d'(tau) starts at 1 and dips at multiples of the period. Bottom: the first lag below the threshold 0.1 is 34; the search moves on to the bottom of the dip at 36, and a parabola through lags 35 to 37 puts the period at 36.36 samples, 440.10 Hz (detect_pitch_yin).
Figure 8. YIN on the 440 Hz tone. Top: the cumulative-mean-normalised difference d'(tau) starts at 1 and dips at multiples of the period. Bottom: the first lag below the threshold 0.1 is 34; the search moves on to the bottom of the dip at 36, and a parabola through lags 35 to 37 puts the period at 36.36 samples, 440.10 Hz (detect_pitch_yin).
Output
== Tutorial 09: pitch by autocorrelation and YIN ==

1. Integer-lag resolution of autocorrelation (f_s = 16000 Hz, 50 ms sine frames)
   f0 (Hz) | period (samples) | grid step | f0^2/f_s | autocorr (Hz) | YIN (Hz)
       110 |           145.45 |      0.76 |     0.76 |       110.345 | 110.0006
       220 |            72.73 |      3.04 |     3.02 |       219.178 | 220.0124
       440 |            36.36 |     12.01 |    12.10 |       444.444 | 440.0986
       880 |            18.18 |     46.78 |    48.40 |       888.889 | 881.2354
   440 Hz: autocorr picks lag 36 -> 444.44 Hz; YIN gives 440.0986 Hz

2. YIN written out (lags 16..200, theta = 0.1)
   d'(34..=38) = [0.0756, 0.0261, 0.0019, 0.0060, 0.0403]
   first lag below theta: 34; bottom of the dip: 36; interpolated period 36.3555 samples
   ours 440.098619 Hz, detect_pitch_yin 440.098619 Hz

3. Missing fundamental: harmonics 2..6 of 200 Hz, equal amplitudes
   |X| at 200 Hz = 6.1e-13, at 400 Hz = 800: no energy at f0
   YIN 200.01 Hz, autocorrelation 200.00 Hz: both find the 200 Hz period
   Weak odd harmonics (h = 1, 3, 5 at 0.1; h = 2, 4, 6 at 1.0), true period 80 samples:
   d'(40) = 0.0196 (half period), d'(80) = 4.7e-28 (true period)
   YIN theta = 0.1 -> 400.26 Hz (octave error); theta = 0.01 -> 200.02 Hz
   autocorrelation -> 400.00 Hz (octave error)

4. track_pitch on a 1 s linear glide 100 -> 300 Hz (YIN, theta 0.1, 80-400 Hz)
   frames must hold more than 2 floor(f_s/f_min) + 1 = 401 samples (402 or more)
   N = 1024 (64 ms), hop 256:  59 of  59 full frames voiced, max |error| 0.24 Hz
   N =  512 (32 ms), hop 128: 122 of 122 full frames voiced, max |error| 0.12 Hz
   N =  256 (16 ms), hop  64:   0 of 247 full frames voiced, max |error| n/a

5. topics::autocorrelation_pitch(80, 1000, 16000): pitch step at 1 kHz = 58.8 Hz

Autocorrelation pitch estimation
================================
The estimator correlates the frame with lagged copies of itself for lags 16 to 200 samples and reports f_s divided by the best lag. Frames need at least 402 samples.

Formulas
--------
  Unnormalised autocorrelation over the whole frame:
             N - 1 - τ              
      r(τ) =     ∑     x[i] x[i + τ]
... 104 more lines

Tutorial 8: LPC and formants

Linear prediction of a synthetic vowel and the formants read from its poles. Text in chapter 8.

examples/tutorial_08_lpc_formants.rs

cargo run --example tutorial_08_lpc_formants --features educational,full_no_plotting
Spectrum of the Hamming-windowed vowel frame (grey) with the order-18 LPC envelope from lpc_analysis (blue) and the true vocal-tract response (orange, dashed), each shifted to sit on the harmonic peaks. Green lines mark the formants found from the roots of A(z): 711, 1211 and 2597 Hz against 700, 1220 and 2600 Hz.
Figure 9. Spectrum of the Hamming-windowed vowel frame (grey) with the order-18 LPC envelope from lpc_analysis (blue) and the true vocal-tract response (orange, dashed), each shifted to sit on the harmonic peaks. Green lines mark the formants found from the roots of A(z): 711, 1211 and 2597 Hz against 700, 1220 and 2600 Hz.
Output
== Tutorial 08: LPC, the source-filter model and formants ==

1. Source-filter synthesis at f_s = 16000 Hz, f0 = 120 Hz
   formant F =    700 Hz, B =   80 Hz  ->  pole radius r = 0.98441, angle = 0.2749 rad
   formant F =   1220 Hz, B =   90 Hz  ->  pole radius r = 0.98248, angle = 0.4791 rad
   formant F =   2600 Hz, B =  120 Hz  ->  pole radius r = 0.97671, angle = 1.0210 rad
   analysis frame: samples 1600..2112 (32 ms, 3.8 pitch periods)

2. LPC of order p = 18 (rule of thumb f_s/1000 + 2 = 18)
   lpc_analysis vs Levinson-Durbin written out: max |difference| = 9.5e-8 (largest |a_k| = 2.51)
   prediction-error energy E_p: library 44.8301, ours 44.8301
   worst normal-equation residual / R[0]: library 8.6e-8; an order-17 solution would give 5.8e-5

3. Durand-Kerner: 18 roots of A(z), worst |A(z_i)| = 1.2e-16, largest |z_i| = 0.9871 (inside the unit circle: stable)
   all pole pairs (F, B) in Hz:
     F =   711.3  B =    65.9
     F =  1210.8  B =    76.6
     F =  1656.9  B =  1547.6
     F =  2597.1  B =   138.6
     F =  4099.2  B =  1134.9
     F =  5114.2  B =  1205.6
     F =  6088.8  B =  1248.8
     F =  7047.5  B =  1271.9
   true formant -> narrow LPC resonance (B < 400 Hz):
     F =    700 Hz (B =  80)  ->    711.3 Hz (B =  65.9), error +11.3 Hz
     F =   1220 Hz (B =  90)  ->   1210.8 Hz (B =  76.6), error  -9.2 Hz
     F =   2600 Hz (B = 120)  ->   2597.1 Hz (B = 138.6), error  -2.9 Hz

4. Harmonic peaks of |FFT| (h f0, h = 1..33, up to 3960 Hz) vs LPC envelope 20 log10|1/A|:
   constant gain offset 20.5 dB, scatter about it 1.06 dB (standard deviation)
   wrote /tmp/tutorial_08_envelope.csv (columns: freq_hz, fft_db, lpc_envelope_db, true_envelope_db)

5. Model order (formants recovered within 150 Hz with B < 400 Hz):
   p =  4: 0 of 3
   p =  6: 0 of 3
   p =  8: 2 of 3
   p = 10: 3 of 3
   p = 12: 3 of 3
   p = 18: 3 of 3
   p = 24: 3 of 3
... 71 more lines

Beats and onsets

Tutorial 13: onsets and tempo

Onset detection and tempo estimation on a click track, with the peak picking derived by hand. Text in chapter 13.

examples/tutorial_13_onsets_tempo.rs

cargo run --example tutorial_13_onsets_tempo --features educational,full_no_plotting
Top: the four-burst click track (bursts start at 0.25, 0.75, 1.25 and 1.75 s). Bottom: the normalised onset detection function with the default threshold, and the four onsets detect_onsets reports at frames 21, 64, 107 and 151, 6 to 8 ms before the first three bursts and 3 ms after the fourth.
Figure 10. Top: the four-burst click track (bursts start at 0.25, 0.75, 1.25 and 1.75 s). Bottom: the normalised onset detection function with the default threshold, and the four onsets detect_onsets reports at frames 21, 64, 107 and 151, 6 to 8 ms before the first three bursts and 3 ms after the fourth.
Autocorrelation of the onset strength envelope against tempo, and the same weighted by the log-normal prior centred on 120 BPM (dashed); both curves are scaled to a maximum of 1. For 120 BPM clicks estimate_tempo picks lag 43 (120.19 BPM); for 80 BPM clicks whose off-beats have a fifth of the amplitude it picks lag 129 (40.06 BPM), half the tempo.
Figure 11. Autocorrelation of the onset strength envelope against tempo, and the same weighted by the log-normal prior centred on 120 BPM (dashed); both curves are scaled to a maximum of 1. For 120 BPM clicks estimate_tempo picks lag 43 (120.19 BPM); for 80 BPM clicks whose off-beats have a fifth of the amplitude it picks lag 129 (40.06 BPM), half the tempo.
Output
== Tutorial 13: onsets and tempo ==

1. Click track: 8 noise bursts at 0.25, 0.75, ..., 3.75 s (44.1 kHz), the first three 26 dB quieter
   default configuration: 5 onsets
   threshold floor 0.01:  8 onsets
     0.2438 s (true 0.25 s, -6.2 ms)
     0.7430 s (true 0.75 s, -7.0 ms)
     1.2423 s (true 1.25 s, -7.7 ms)
     1.7531 s (true 1.75 s, +3.1 ms)
     2.2523 s (true 2.25 s, +2.3 ms)
     2.7516 s (true 2.75 s, +1.6 ms)
     3.2508 s (true 3.25 s, +0.8 ms)
     3.7500 s (true 3.75 s, +0.0 ms)
   normalised peaks per burst (the floor is 0.1): [0.036, 0.033, 0.024, 0.333, 0.757, 0.794, 1.0, 0.884]

2. Peak-picking lengths sized in samples instead of frames (one change at a time)
   floor 0.01 + median_filter (length 3)      -> 0 onsets
   floor 0.01 + threshold window 1024 frames  -> 1 onsets
   floor 0.01 + min separation 512 frames     -> 3 onsets
   floor 0.01 + pre-emphasis 0.97             -> 8 onsets

3. The onset detection function and peak picking, re-derived
   CQT: 144 bins x 367 frames, window 3207 samples; sum of rectified increases vs library ODF: max diff 0.0e0
   ODF peak frames [21, 64, 107, 151, 194, 237, 280, 323], heights [0.21, 0.19, 0.14, 1.94, 4.41, 4.62, 5.82, 5.15]
   the strongest of the five loud bursts' ODF peaks is 3.0 times the weakest
   our peak picking, floor 0.1: frames [151, 194, 237, 280, 323]
   our peak picking, floor 0.01: frames [21, 64, 107, 151, 194, 237, 280, 323]
   t = i H / f_s reproduces detect_onsets exactly

4. Tempo by autocorrelation of the onset envelope (hop 512, 86.13 frames/s)
   true BPM | estimate | lag (frames) | estimate / true
         60 |    60.09 |           86 | 1.002
         80 |    79.51 |           65 | 0.994
        100 |    99.38 |           52 | 0.994
        120 |   120.19 |           43 | 1.002
        140 |   139.67 |           37 | 0.998
        174 |   172.27 |           30 | 0.990
         80 |    40.06 |          129 | 0.501 (quiet off-beats)
   80 BPM, quiet off-beats: autocorrelation at lag 65 (79.5 BPM) 0.00181, at lag 129 (40.1 BPM) 0.00607
   prior weights: lag 65 -> 0.84, lag 129 -> 0.29
... 80 more lines

Onsets and beats on a waveform

Detects onsets and beats in a percussive pattern and marks them on an interactive waveform.

examples/plotting_event_markers.rs

cargo run --example plotting_event_markers --features plotting,onset-detection,beat-tracking,statistics
Onsets and beats from the example, as markers on the waveform. Open in its own page
Output
=== Event Markers Example ===

Generated percussive audio: 4 seconds at 120 BPM

--- Onset Detection ---
Detected 16 onsets:
  Onset 1: 0.006s
  Onset 2: 0.244s
  Onset 3: 0.482s
  Onset 4: 0.743s
  Onset 5: 0.981s
  Onset 6: 1.242s
  Onset 7: 1.480s
  Onset 8: 1.741s
  Onset 9: 1.980s
  Onset 10: 2.241s
  Onset 11: 2.479s
  Onset 12: 2.746s
  Onset 13: 2.978s
  Onset 14: 3.245s
  Onset 15: 3.483s
  Onset 16: 3.744s
Rendered onsets marker plot (632613 bytes)
Rendered onsets_labeled marker plot (634161 bytes)

--- Beat Tracking ---
Detected tempo: 120.0 BPM
Detected 8 beats:
  Beat 1: 0.482s
  Beat 2: 0.975s
  Beat 3: 1.474s
  Beat 4: 1.974s
  Beat 5: 2.473s
  Beat 6: 2.978s
  Beat 7: 3.477s
  Beat 8: 3.884s
Rendered beats marker plot (631603 bytes)
Rendered beats_numbered marker plot (632346 bytes)

--- Combined Visualization ---
... 3 more lines

Separation

Harmonic and percussive separation

Mixes a tone with impulses, then separates them with AudioDecomposition::hpss.

examples/hpss.rs

cargo run --example hpss --features decomposition,statistics,editing
The signal of the hpss example and its two parts from AudioDecomposition::hpss. The tone stays in the harmonic part and the impulses every 0.5 s go to the percussive part. Each curve is the peak envelope in blocks of 200 samples.
Figure 12. The signal of the hpss example and its two parts from AudioDecomposition::hpss. The tone stays in the harmonic part and the impulses every 0.5 s go to the percussive part. Each curve is the peak envelope in blocks of 200 samples.
Output
Harmonic/Percussive Source Separation (HPSS) Example
=========================================

Signal Parameters:
  • Sample rate: 44100 Hz
  • Duration: 3 seconds
  • Samples: 132300

Creating harmonic component (sine wave)...
  • Frequency: 440 Hz
  • Amplitude: 0.6
  • RMS: 0.424

Creating percussive component (impulse train)...
  • Interval: 0.5 seconds
  • Amplitude: 0.8
  • Number of impulses: 5
  • RMS: 0.001

Mixing components...
  • Mixed RMS: 0.212
  • Mixed peak: 0.300

Separating with HPSS...
  • Harmonic RMS: 0.212
  • Percussive RMS: 0.003
  • Percussive peak: 0.130

Effects and editing

Gain, clipping and windows

Scaling, clipping, windowing and a low-pass filter applied one after another, with the level after each.

examples/processing.rs

cargo run --example processing --features processing,editing,transforms
Output
Input:  peak=0.8000  rms=0.5657
Scaled: peak=0.4000  rms=0.2828
Normalized (Peak): peak=1.0000  rms=0.7071
Clipped: peak=0.7000  rms=0.5795
Windowed: peak=0.7000  rms=0.3549
Filtered (moving avg): len=44092  peak=0.7000  rms=0.3495
µ-law round-trip: peak=0.7000  rms=0.3495
Two-tone: peak=0.3998  rms=0.2236
Low-pass 1kHz: peak=0.2940  rms=0.1947

Trim, pad, fade, split and join

The editing operations on a tone, with the length after each step.

examples/editing.rs

cargo run --example editing --features editing
Output
Original:  dur=1.000s  peak=0.8000
Trim 0.2..0.6s: dur=0.400s
Padded: dur=1.500s
Trim silence: dur=1.000s
Faded: peak=0.8000  rms=0.5476
Split into 4 segments
Concatenated: dur=1.000s
Repeated x3: dur=3.000s
Reverse: first_sample=-0.0501
Pad to 2s: dur=2.000s
Mixed: peak=0.8000  rms=0.4308

Channels

Mono to stereo and back, extracting a channel, panning and balance, interleaving.

examples/channels.rs

cargo run --example channels --features channels,statistics
Output
Mono: channels=1 peak=0.8000
Stereo: channels=2 peak=0.8000
Extracted: left_peak=0.9600 right_peak=0.4800
Back to mono (avg): channels=1 peak=0.2400
Interleave/deinterleave: 2 channels

Compressor and limiter

The static curve of a compressor, its gain reduction on a modulated tone, then a mastering limiter.

examples/dynamic_range.rs

cargo run --example dynamic_range --features dynamic-range,statistics
Static curves from calculate_compression_gain and get_compression_curve: threshold -20 dBFS and ratio 4:1 with a hard knee and with a 10 dB soft knee (the dashed lines at -25 and -15 dBFS mark its edges), and a limiter with a -6 dBFS ceiling. Above the threshold the output rises 1 dB for every 4 dB of input.
Figure 13. Static curves from calculate_compression_gain and get_compression_curve: threshold -20 dBFS and ratio 4:1 with a hard knee and with a 10 dB soft knee (the dashed lines at -25 and -15 dBFS mark its edges), and a limiter with a -6 dBFS ceiling. Above the threshold the output rises 1 dB for every 4 dB of input.
Output
Input: peak=0.9497 rms=0.4191
Compressor curve (dB out): [-37.0, -27.0, -17.0, -12.333333333333334, -9.000000000000002]
Max gain reduction: 9.74 dB
Compressed: peak=0.7108 rms=0.2233
Limited: peak=0.7108 rms=0.2233

Tutorial 12: dynamics

Compressor and limiter behaviour measured on steps in level. Text in chapter 12.

examples/tutorial_12_dynamics.rs

cargo run --example tutorial_12_dynamics --features educational,full_no_plotting
A soft-knee compressor (threshold -20 dBFS, 4:1, 6 dB knee, 5 ms attack, 50 ms release) on a step from -40 to 0 dBFS and back. Top: input, envelope and output level of apply_compressor. Bottom: gain reduction from get_gain_reduction. The reduction builds up within a few ms and decays over the 50 ms release, so the output dips below the input level after the step down.
Figure 14. A soft-knee compressor (threshold -20 dBFS, 4:1, 6 dB knee, 5 ms attack, 50 ms release) on a step from -40 to 0 dBFS and back. Top: input, envelope and output level of apply_compressor. Bottom: gain reduction from get_gain_reduction. The reduction builds up within a few ms and decays over the 50 ms release, so the output dips below the input level after the step down.
Output
== Tutorial 12: dynamics ==

1. Static curve, T = -20 dBFS, R = 4:1
   L (dBFS)   hard: Y (dBFS)   soft W = 10 dB: Y (dBFS)
     -40.0       -40.000          -40.000
     -25.0       -25.000          -25.000
     -22.0       -22.000          -22.337
     -20.0       -20.000          -20.938
     -18.0       -19.500          -19.837
     -15.0       -18.750          -18.750
      -8.0       -17.000          -17.000
       0.0       -15.000          -15.000
   get_compression_curve(-30, -20, -8) = [-30.0, -20.0, -17.0]

2. Ballistics on a step: -40 dBFS -> 0 dBFS -> -40 dBFS (attack 5 ms, release 50 ms)
   63.2 % of the step after 5.021 ms (tau_A = 5 ms)
   10-90 % rise time 10.979 ms (tau_A ln 9 = 10.986 ms)
   release: down to 36.8 % of the step after 50.000 ms (tau_R = 50 ms)

3. How it works: follower + gain computer + gain, by hand
   max |mine - apply_compressor| = 1.11e-16

4. Limiter: ceiling -6 dBFS, attack 1 ms, on a step from silence to 0 dBFS
   lookahead 0 ms: output peak 0.0000 dBFS (overshoot 6.0000 dB)
   lookahead 5 ms: output peak -5.9425 dBFS (overshoot 0.0575 dB)
   predicted overshoot -20 log10(1 - a^241) = 0.0575 dB

5. Explain

Compressor
==========
Above -20 dBFS the compressor lets the level rise only 1 dB per 4 dB of input; the gain follows the signal with a 5 ms attack and 50 ms release, then 0 dB of make-up gain is added.

Formulas
--------
  Overshoot above the threshold (dB):
      o = L - T

  Hard-knee gain reduction (dB): above T the output rises only 1/R dB per input dB:
           ⎧ 0   if  o ≤ 0          
... 88 more lines

Voice activity detection

Per-frame level and zero-crossing rate on a synthetic vowel in noise, then the energy and combined detectors.

examples/vad.rs

cargo run --example vad --features vad,editing
The chapter's utterance (silence, vowel, fricative, silence) in 25 ms frames with a 10 ms hop. The frame level crosses the -40 dBFS threshold for the vowel and the fricative; the fricative's zero-crossing rate is outside the 0.02 to 0.30 window, so the combined VAD keeps only the vowel. Decisions from voice_activity_mask.
Figure 15. The chapter's utterance (silence, vowel, fricative, silence) in 25 ms frames with a 10 ms hop. The frame level crosses the -40 dBFS threshold for the vowel and the fricative; the fricative's zero-crossing rate is outside the 0.02 to 0.30 window, so the combined VAD keeps only the vowel. Decisions from voice_activity_mask.
Output
Per-frame features (25 ms frames):
  noise : level  -64.9 dBFS, ZCR 0.466 crossings/sample
  vowel : level   -9.5 dBFS, ZCR 0.095 crossings/sample

Combined VAD (−40 dBFS, ZCR 0.02-0.30):
  frames: 100, speech frames: 52
  speech region: samples 4160..12880  (0.260 s - 0.805 s; true 0.250 s - 0.750 s)
  (regions extend past the true end by the hangover of 2 frames plus up to one frame)

220 Hz sine at 44.1 kHz (ZCR ≈ 0.0100):
  Energy   method: 87 active frames
  Combined method: 0 active frames (ZCR below zcr_min = 0.02)

Tutorial 11: energy and VAD

Short-time energy, zero crossings and a detector built from them. Text in chapter 11.

examples/tutorial_11_energy_vad.rs

cargo run --example tutorial_11_energy_vad --features educational,full_no_plotting
Output
== Tutorial 11: short-time energy, ZCR and VAD ==

1-2. Frame features (25 ms frames, 10 ms hop), one frame from each segment:
     silence   level  -64.4 dBFS   ZCR 0.484 crossings/sample (~3870 Hz)
     vowel     level  -11.7 dBFS   ZCR 0.098 crossings/sample (~782 Hz)
     fricative level  -25.2 dBFS   ZCR 0.516 crossings/sample (~4130 Hz)
     silence   level  -64.4 dBFS   ZCR 0.494 crossings/sample (~3950 Hz)
     predicted vowel level -11.7 dBFS

     library zero_crossing_rate() over the whole signal: 5891 crossings/s = 0.368 crossings/sample
3. Energy VAD (-40 dBFS, hangover 1, no smoothing): library versus hand-written
     masks identical (120 frames); regions: [(4480, 14960)]
     speech 0.280-0.935 s (true 0.300-0.900 s)

4. Combined rule (energy AND 0.02 <= ZCR <= 0.30) drops the fricative
     regions: [(4640, 11600)]
     speech 0.290-0.725 s (vowel 0.300-0.700 s)

5. Hangover: region end versus hangover frames
     hangover  1 frames ( 10 ms): region ends at 14960 (0.935 s)
     hangover  3 frames ( 30 ms): region ends at 15280 (0.955 s)
     hangover  6 frames ( 60 ms): region ends at 15760 (0.985 s)
     hangover 10 frames (100 ms): region ends at 16400 (1.025 s)

6. The library's explanation of the default configuration at 16 kHz:

Voice activity detection
========================
Each 1024-sample frame (hop 512) is classified as speech by its RMS level (≥ -40 dBFS), then the decisions are smoothed by a 5-frame majority vote, extended by 2 hangover frame(s), and runs shorter than 3 speech / 5 silence frames are removed.

Formulas
--------
  Frame RMS; F' is the available frame length and N_d = F when pad_end is set (the missing tail counts as zeros), else F':
           ──────────────────────
          │ 1   F' - 1           
      r = │────   ∑    x²[mH + i]
          │ N   i = 0            
          √  d                   

  Zero-crossing rate in crossings per sample; a sinusoid at f gives z ≈ 2f/f_s:
... 59 more lines

Resampling and sampling

Resample a signal

Changes the rate by target and by ratio at two quality settings, and checks the resulting length.

examples/resampling.rs

cargo run --example resampling --features resampling,statistics,processing
Level after converting a 48 kHz tone to 16 kHz with resample, measured at the frequency at which it appears, for each ResamplingQuality. Below 8 kHz this is the pass band (Fast rolls off first); above 8 kHz it is the residue of the alias, more than 180 dB down (round-off): for 1 : 3 the resampler drops everything above 8 kHz.
Figure 16. Level after converting a 48 kHz tone to 16 kHz with resample, measured at the frequency at which it appears, for each ResamplingQuality. Below 8 kHz this is the pass band (Fast rolls off first); above 8 kHz it is the residue of the alias, more than 180 dB down (round-off): for 1 : 3 the resampler drops everything above 8 kHz.
Output
Input: sr=44100Hz len=44100 peak=0.8000
Resampled: sr=16000Hz len=16000 peak=0.8000
Ratio 0.5: sr=22050Hz len=22050 peak=0.8000

Tutorial 7: resampling

The quality settings measured against each other. Text in chapter 7.

examples/tutorial_07_resampling.rs

cargo run --example tutorial_07_resampling --features educational,full_no_plotting
A 1 kHz plus 10 kHz mix converted from 48 kHz to 16 kHz, spectra of the middle 100 ms. Keeping every third sample (top) moves the 10 kHz tone to 6 kHz at full level; every tier of resample (bottom) removes it, leaving round-off more than 180 dB below the input.
Figure 17. A 1 kHz plus 10 kHz mix converted from 48 kHz to 16 kHz, spectra of the middle 100 ms. Keeping every third sample (top) moves the 10 kHz tone to 6 kHz at full level; every tier of resample (bottom) removes it, leaving round-off more than 180 dB below the input.
Output
== Tutorial 07: Resampling ==

Resampling
==========
Converting 48000 Hz to 16000 Hz (ratio 0.333333) discards bandwidth, so content above the new Nyquist frequency must be filtered out first. The output can represent frequencies up to 8000 Hz.

Formulas
--------
  Conversion ratio:
           fₒᵤₜ 
      r = ──────
           fᵢₙ  

  Anti-aliasing / anti-imaging cut-off must not exceed the lower Nyquist frequency:
            min(fᵢₙ, fₒᵤₜ) 
      f  ≤ ────────────────
       c          2        

  Band-limited interpolation with a windowed-sinc kernel h (every tier except Fast upsampling, which interpolates linearly):
                     ⎛ m     ⎞
      y[m] = ∑ x[n] h⎜─── - n⎟
             n       ⎝ r     ⎠


Symbols
-------
  fᵢₙ   input rate   48000 Hz
  fₒᵤₜ  output rate  16000 Hz

Derived quantities
------------------
  Ratio                r = 0.333333      fₒᵤₜ / fᵢₙ
  Input Nyquist        fᵢₙ/2 = 24000 Hz  fᵢₙ / 2
  Output Nyquist       fₒᵤₜ/2 = 8000 Hz  fₒᵤₜ / 2
  Sinc pass-band edge  f_c = 7200 Hz     pass · min(fᵢₙ, fₒᵤₜ)/2

Quality presets (ResamplingQuality)
-----------------------------------
  Quality  Method                                                                Pass-band edge (Hz)
  --------------------------------------------------------------------------------------------------
... 49 more lines

Tutorial 1: sampling and aliasing

Predicts and measures where a tone above Nyquist lands. Text in chapter 1.

examples/tutorial_01_sampling_aliasing.rs

cargo run --example tutorial_01_sampling_aliasing --features educational,full_no_plotting
An 11 kHz sine (blue) sampled at 16 kHz. The samples (dots, from sine_wave) lie exactly on a 5 kHz sine with inverted sign (orange): after sampling the two tones cannot be told apart.
Figure 18. An 11 kHz sine (blue) sampled at 16 kHz. The samples (dots, from sine_wave) lie exactly on a 5 kHz sine with inverted sign (orange): after sampling the two tones cannot be told apart.
Output
=== Tutorial 01: sampling and aliasing ===

1. Folding formula f_a = |f - round(f/fs) fs|
      1000 Hz sampled at  16000 Hz appears at   1000 Hz (library: 1000 Hz)
      7000 Hz sampled at   8000 Hz appears at   1000 Hz (library: 1000 Hz)
     11000 Hz sampled at  16000 Hz appears at   5000 Hz (library: 5000 Hz)
     17000 Hz sampled at  16000 Hz appears at   1000 Hz (library: 1000 Hz)
     25000 Hz sampled at  16000 Hz appears at   7000 Hz (library: 7000 Hz)

2. An 11 kHz tone at 48 kHz, reduced to 16 kHz
   naive: peak at 5000 Hz, |X| = 1000.0 (A N/2 = 1000)
   fast tier, steady state (middle 100 ms): 5 kHz residue at -271.9 dB
   medium tier, steady state (middle 100 ms): 5 kHz residue at -191.5 dB
   high tier, steady state (middle 100 ms): 5 kHz residue at -223.9 dB
   High tier, whole signal: 5 kHz bin 78.4 dB below the naive alias; largest bin (7652 Hz, edge transients) 74.5 dB below
   High tier: max |y| over the first 50 samples 0.116, over the middle 3.1e-9
   (a 16 kHz signal cannot represent an 11 kHz tone: resampling must remove it, not move it)

3. A 700 Hz square wave at 16 kHz, 1 s (1 Hz bins)
   power outside the odd harmonics: naive -14.77 dB, band-limited -247.2 dB (re total)
   13th harmonic 9100 Hz folds to 6900 Hz, level -22.2 dB re fundamental

4. topics::sampling(16 kHz) and topics::aliasing(11 kHz, 16 kHz)

Sampling
========
Sampling at 16000 Hz takes one sample every 0.0625 ms. Frequencies below 8000 Hz are represented unambiguously; anything above folds back (aliases) into that range.

Formulas
--------
  A sample is the analogue signal read every T seconds:
                          1  
      x[n] = xₐ(nT), T = ────
                          fₛ 

  Nyquist frequency: the highest representable frequency:
            fₛ 
      f  = ────
       N    2  

... 91 more lines

Tutorial 2: quantisation and dither

Quantisation error with and without dither. Text in chapter 2.

examples/tutorial_02_quantisation_dither.rs

cargo run --example tutorial_02_quantisation_dither --features educational,full_no_plotting
Spectra of the quantisation error of the 2.5 LSB sine, each bin relative to the mean bin power. Without dither (top) the error is concentrated at harmonics of 997 Hz, such as the 3rd at 2991 Hz; with TPDF dither (bottom) it is flat noise.
Figure 19. Spectra of the quantisation error of the 2.5 LSB sine, each bin relative to the mean bin power. Without dither (top) the error is concentrated at harmonics of 997 Hz, such as the 3rd at 2991 Hz; with TPDF dither (bottom) it is flat noise.
Output
=== Tutorial 02: quantisation and dither ===

1. Integer <-> float convention (i16)
   [-1, -0.5, 0, 0.5, 1] -> [-32768, -16384, 0, 16384, 32767]
   step below zero 1/32768 = 3.051758e-5, above zero 1/32767 = 3.051851e-5

2. SQNR of a full-scale 997 Hz sine at 48 kHz (1 s)
   bits  measured  6.02b+1.76   (dB)
      4     25.62       25.84
      8     49.98       49.92
     12     74.03       74.00
     16     98.10       98.08
   crate i16 round trip: SQNR = 98.10 dB (topics::quantisation(16) says 98.09 dB)

3. A 997 Hz sine of amplitude 2.5 LSB at 16 kHz, quantised to i16
   error power / (Δ²/12): undithered 1.23, TPDF-dithered 3.02
   3rd-harmonic bin of the error re mean bin power: undithered +31.9 dB, dithered -4.5 dB
   correlation(error, signal): undithered -0.516, dithered -0.001

4. topics::quantisation(16)

Quantisation
============
16-bit quantisation maps each sample to one of 65536 levels, 3.0518e-5 apart on the [-1, 1] scale. For a full-scale sine the rounding noise is 98.0905 dB below the signal.

Formulas
--------
  Float to integer as implemented (x clamped to [-1, 1], round half away from zero):
          ⎧           b - 1                   
          ⎨ round(x ·2     )   if  x < 0      
      q = ⎨           b - 1                   
          ⎩round(x ·(2      - 1))   if  x ≥ 0 

  Step size over the full scale [-1, 1):
           2      1 - b
      Δ = ──── = 2     
            b          
           2           

  Noise power of rounding error uniformly distributed in one step:
... 47 more lines

Filters

IIR filters

Applies a Butterworth low-pass to a two-tone signal and checks the frequency response of the design.

examples/iir_filtering.rs

cargo run --example iir_filtering --features iir-filtering,editing,statistics
Magnitude responses from IirFilterDesign::frequency_response at 16 kHz, cutoff 1 kHz. Both Butterworth filters are -3.01 dB at the cutoff; at 2 kHz the 4th order is 25.5 dB down, the 8th order 51.0 dB and the 4th-order Chebyshev I (1 dB ripple) 35.5 dB. The lower panel enlarges the pass band, where the Chebyshev ripples between 0 and -1 dB.
Figure 20. Magnitude responses from IirFilterDesign::frequency_response at 16 kHz, cutoff 1 kHz. Both Butterworth filters are -3.01 dB at the cutoff; at 2 kHz the 4th order is 25.5 dB down, the 8th order 51.0 dB and the 4th-order Chebyshev I (1 dB ripple) 35.5 dB. The lower panel enlarges the pass band, where the Chebyshev ripples between 0 and -1 dB.
Output
Input: peak=0.4892 rms=0.2693
Low-pass: peak=0.3542 rms=0.2475
Response @ [0.0, 500.0, 1000.0, 1500.0, 2000.0, 2500.0, 3000.0, 3500.0, 4000.0, 4500.0] Hz => mag [0.9999999999999987, 0.9980722163186098, 0.7071067811865464, 0.1922087723917023, 0.06112218038423145, 0.02469141840265588, 0.011686761964355665, 0.006167823300007615, 0.0035218401102965063, 0.0021336060715858073]
Chebyshev HP: peak=0.0003 rms=0.0001

Process a long signal in blocks

Low-pass filters a minute of audio 4096 samples at a time with SosFilter, which keeps its state between blocks, and checks the result equals filtering the whole signal.

examples/block_processing.rs

cargo run --example block_processing --features iir-filtering,statistics
Output
235 blocks of 4096 samples
960000 samples filtered, highest block RMS 0.3537
the last block equals the same samples of the whole-signal result

Parametric EQ

A three-band equaliser and a single band applied to a harmonic tone, with the response at chosen frequencies.

examples/parametric_eq.rs

cargo run --example parametric_eq --features parametric-eq,statistics
Response of the three-band equaliser of the parametric_eq example, from eq_frequency_response: a -3 dB low shelf at 120 Hz, a +4 dB peak at 1 kHz and a +2 dB high shelf at 8 kHz.
Figure 21. Response of the three-band equaliser of the parametric_eq example, from eq_frequency_response: a -3 dB low shelf at 120 Hz, a +4 dB peak at 1 kHz and a +2 dB high shelf at 8 kHz.
Output
Input: peak=1.3539 rms=0.8581
EQ applied: peak=1.6396 rms=0.9043
+ Notch 500Hz: peak=1.3540 rms=0.8225
EQ magnitude response @ [60.0, 120.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 12000.0] Hz => [0.723596870857937, 0.8454759231555222, 1.0045484751040326, 1.1147466109195308, 1.5848337914425283, 1.115525527293748, 1.0313278236841315, 1.1267070943722988, 1.2350490085725792]

Tutorial 5: convolution and FIR filters

Designs a windowed-sinc low-pass and measures its response. Text in chapter 5.

examples/tutorial_05_convolution_fir.rs

cargo run --example tutorial_05_convolution_fir --features educational,full_no_plotting
Magnitude responses measured by filtering sines with apply_filter (dots) against the responses computed from the taps (lines). Top: the 63-tap low-pass, -6 dB at its 2 kHz cutoff and below -59 dB from 3 kHz. Bottom: the 8-tap moving average at 8 kHz, which follows the Dirichlet kernel with nulls at multiples of 1 kHz.
Figure 22. Magnitude responses measured by filtering sines with apply_filter (dots) against the responses computed from the taps (lines). Top: the 63-tap low-pass, -6 dB at its 2 kHz cutoff and below -59 dB from 3 kHz. Bottom: the 8-tap moving average at 8 kHz, which follows the Dirichlet kernel with nulls at multiples of 1 kHz.
Output
=== Tutorial 05: convolution and FIR filters ===

1. Lengths: N = 1000 input samples, M = 31 taps
   convolve: 1030 samples (N + M - 1 = 1030); apply_filter: 970 samples (N - M + 1 = 970)
   direct sum vs convolve (FFT): 8.9e-16; vs apply_filter: 6.7e-16

2. Impulse response equals the taps: max |y[n] - h[n]| = 2.8e-17

3. 8-tap moving average at 8 kHz: |H(f)| = |sin(pi f M/fs) / (M sin(pi f/fs))|
      250 Hz: closed form 0.901764, measured 0.901764
      500 Hz: closed form 0.640729, measured 0.640729
      750 Hz: closed form 0.304489, measured 0.304489
     1000 Hz: closed form 0.000000, measured 0.000000
     1500 Hz: closed form 0.224994, measured 0.224994
     2000 Hz: closed form 0.000000, measured 0.000000
     3000 Hz: closed form 0.000000, measured 0.000000

4. Linear phase and group delay
   symmetric 63 taps: group delay 31 samples at 100, 500, 1000, 1500 Hz
   taps [0.5, 0.3, 0.2]: group delay 0.70 samples at DC, 0.25 at Nyquist
   impulse at n = 100: full-convolution peak at n = 131; apply_filter peak at index 69 (= 131 - (M-1))
   Gaussian pulse centroid moves by 31.000000 samples

5. Windowed-sinc low-pass: M = 63, fc = 2 kHz, fs = 16 kHz, Hamming
        0 Hz: |H| = 1.00000 (  -0.00 dB)
      500 Hz: |H| = 0.99994 (  -0.00 dB)
     1000 Hz: |H| = 0.99989 (  -0.00 dB)
     1500 Hz: |H| = 1.00312 (   0.03 dB)
     2000 Hz: |H| = 0.50050 (  -6.01 dB)
     3000 Hz: |H| = 0.00105 ( -59.57 dB)
     4000 Hz: |H| = 0.00073 ( -62.73 dB)
     6000 Hz: |H| = 0.00040 ( -67.98 dB)
   dense scan: first stop-band lobe -52.2 dB at 2534 Hz; largest above 3 kHz -59.6 dB
   201 taps through apply_filter (FFT path) vs direct sum: 1.6e-15

6. topics::fir for the 63-tap design

FIR filter
==========
63 taps at 16000 Hz. The taps are symmetric (type I), so the phase is linear and every frequency is delayed by 31 samples (1.9375 ms). apply_filter (Rust AudioProcessing::apply_filter, Python AudioSamples.apply_filter) returns the fully overlapping part of the convolution, 62 samples shorter than the input.
... 60 more lines

Tutorial 6: IIR filters

Poles, zeros, stability and notch filters. Text in chapter 6.

examples/tutorial_06_iir_filters.rs

cargo run --example tutorial_06_iir_filters --features educational,full_no_plotting
Poles (crosses) and zeros (circle) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, computed from its sos_coefficients. All four zeros are at z = -1 (Nyquist); the poles lie inside the unit circle, the largest at radius 0.8629.
Figure 23. Poles (crosses) and zeros (circle) of the 4th-order Butterworth low-pass, 1 kHz at 16 kHz, computed from its sos_coefficients. All four zeros are at z = -1 (Nyquist); the poles lie inside the unit circle, the largest at radius 0.8629.
Output
== Tutorial 06: IIR filters ==

1. Butterworth low-pass, N = 4, f_c = 1000 Hz, f_s = 16000 Hz
   2 second-order sections [b0 b1 b2 a0 a1 a2]:
   [+9.334986e-4 +1.866997e-3 +9.334986e-4 1.0 -1.365117 +0.477592]
   [+1.000000e0 +2.000000e0 +1.000000e0 1.0 -1.611727 +0.744521]
   |H| at 0, fc, 2fc, 4fc: 0.000 dB, -3.0103 dB, -25.50 dB, -56.11 dB
   matches |H|^2 = 1/(1 + (tan(pi f/fs)/tan(pi fc/fs))^8) to 1e-12

2. Re-deriving the design: analogue poles -> pre-warp -> bilinear transform
   pole +0.805864 +0.308391j  |p| = 0.862856  (distance to library pole 1.7e-16)
   pole +0.682559 +0.108194j  |p| = 0.691080  (distance to library pole 1.5e-16)
   pole +0.682559 -0.108194j  |p| = 0.691080  (distance to library pole 1.8e-16)
   pole +0.805864 -0.308391j  |p| = 0.862856  (distance to library pole 1.1e-16)
   overall gain: derived 9.334986e-4, library product of b0 9.334986e-4
   zero-pole-gain response agrees with the library to 1e-12

3. The difference equation, by hand
   impulse response h[0..4] = [0.000933, 0.006513, 0.021794, 0.047990]
   max |hand - library| = 5.55e-17
   sum of h[n] over 20 ms = 1.000000 (DC gain)

4. Stability: pole radius versus normalised cutoff (N = 4)
   fc =   4000 Hz  (fc/fs = 0.25000)  max |p| = 0.668179
   fc =   1000 Hz  (fc/fs = 0.06250)  max |p| = 0.862856
   fc =    250 Hz  (fc/fs = 0.01562)  max |p| = 0.963168
   fc =     50 Hz  (fc/fs = 0.00313)  max |p| = 0.992515
   order 8 at 10 Hz: stability margin 1 - max|p| = 7.66e-4
   -> the explainer warns: poles within 1e-3 of the unit circle

5. Butterworth versus Chebyshev type I (N = 4, 1 dB ripple)
   pass band 0..fc: Butterworth -3.010..0.000 dB, Chebyshev -1.000..-0.000 dB
   at 2 fc: Butterworth -25.50 dB, Chebyshev -35.48 dB

6. Zero-phase filtering with filtfilt
   1 kHz tone: sosfilt gain -3.010 dB, lag 8 samples; filtfilt gain -6.021 dB, lag 0 samples

== Explain: what the library says about this design ==

Butterworth low-pass filter (order 4)
... 76 more lines

Plotting

The plotting feature draws interactive Plotly pages. Each example renders its plots to HTML; the frames below show one plot from each. They load the Plotly library from a CDN.

Waveform and spectrogram

The two basic plots of a stereo tone.

examples/plotting_basic.rs

cargo run --example plotting_basic --features plotting,transforms
Mel spectrogram from the example. Open in its own page
Output
Creating test audio signal...
Audio stats: 2 channels, 88200 samples, peak = 0.49999987312894345

Creating waveform plot...
Rendered waveform plot (1969527 bytes of HTML)

Creating spectrogram plot...
Rendered spectrogram plot (345252 bytes of HTML)

Magnitude spectrum

dB and linear scales and a zoomed frequency range.

examples/plotting_spectrum.rs

cargo run --example plotting_spectrum --features plotting,transforms
Spectrum zoomed to 0 to 2 kHz. Open in its own page
Output
Testing MagnitudeSpectrumPlot...
Creating magnitude spectrum (dB scale)...
Rendered dB spectrum (4963214 bytes)
Creating magnitude spectrum (linear scale)...
Rendered linear spectrum (5031834 bytes)
Creating zoomed magnitude spectrum...
Rendered zoomed spectrum (440190 bytes)
Note: Enable 'html_view' feature to open in browser
All magnitude spectrum tests passed.

Spectrogram frequency range

The automatic zoom to the occupied frequencies, turned off, and overridden by hand.

examples/plotting_auto_zoom.rs

cargo run --example plotting_auto_zoom --features plotting,transforms
Spectrogram with the automatic zoom. Open in its own page
Output
Testing auto-zoom feature...
Creating spectrogram with auto-zoom enabled...
Rendered auto-zoom spectrogram (173037 bytes)
Creating spectrogram with auto-zoom disabled...
Rendered fixed-range spectrogram (172988 bytes)
Creating spectrogram with manual frequency range...
Rendered manual-range spectrogram (173006 bytes)

Frequency padding

The padding around the automatic frequency range.

examples/plotting_configurable_padding.rs

cargo run --example plotting_configurable_padding --features plotting,transforms
Spectrogram with 30 % padding. Open in its own page
Output
Testing configurable frequency range padding...

Creating spectrogram with 0% (tight fit) padding...
  Rendered (173037 bytes)
Creating spectrogram with 10% (default) padding...
  Rendered (173037 bytes)
Creating spectrogram with 30% (more context) padding...
  Rendered (173037 bytes)
Creating spectrogram with 50% (lots of context) padding...
  Rendered (173037 bytes)

Overlays and shaded regions

Lines and shaded regions over a waveform, and a pitch contour over a spectrogram.

examples/plotting_overlays.rs

cargo run --example plotting_overlays --features plotting,transforms
Waveform with overlays. Open in its own page
Output
Creating test audio signal...
Audio stats: 1 channels, 88200 samples, peak = 0.4999998731289437

Creating waveform plot with overlays...
Rendered waveform plot with overlays (976512 bytes)

Creating spectrogram plot with overlays...
Rendered spectrogram plot with overlays (338699 bytes)

Creating spectrogram with pitch contour...
Rendered spectrogram with pitch contour (338570 bytes)

RMS, peak, ZCR and energy overlays

Waveforms with analysis curves computed by the dsp_overlays module.

examples/plotting_dsp_overlays.rs

cargo run --example plotting_dsp_overlays --features plotting,statistics
Waveform with several overlays together. Open in its own page
Output
=== DSP Overlays Example ===

Generated 88200 samples at 44100 Hz
Duration: 2.00 seconds

DSP overlay parameters:
  Window size: 2048 samples (~46.4ms)
  Hop size: 512 samples (~11.6ms)

Creating waveform with RMS envelope overlay...
  Rendered rms overlay (995105 bytes)

Creating waveform with Peak envelope overlay...
  Rendered peak overlay (995105 bytes)

Creating waveform with ZCR overlay...
  Rendered zcr overlay (994128 bytes)
  Note: ZCR uses secondary y-axis (right side)

Creating waveform with Energy overlay...
  Rendered energy overlay (995356 bytes)
  Note: Energy uses secondary y-axis (right side)

Creating waveform with multiple overlays...
  Rendered combined overlay (1001924 bytes)

Creating comparison with different window sizes...
  Rendered window_comparison overlay (1018753 bytes)

Spectral centroid and rolloff overlays

Spectrograms of a chirp with centroid and rolloff curves on top.

examples/plotting_spectral_overlays.rs

cargo run --example plotting_spectral_overlays --features plotting,statistics
Spectrogram with centroid and rolloff. Open in its own page
Output
=== Spectral Overlays Example ===

Generated chirp signal: 200 Hz → 2000 Hz sweep over 4 seconds

Spectral analysis parameters:
  Window size: 2048 samples (~46.4ms)
  Hop size: 512 samples (~11.6ms)

--- Spectral Centroid Overlay ---
Computed spectral centroid for 345 windows
Centroid range: 215 Hz to 2014 Hz
Rendered centroid spectral overlay (677876 bytes)
  White line with cyan markers = Spectral Centroid

--- Spectral Rolloff Overlay ---
Computed spectral rolloff (85%) for 345 windows
Rolloff range: 215 Hz to 2067 Hz
Rendered rolloff spectral overlay (676204 bytes)
  White line with cyan markers = Spectral Rolloff (85%)

--- Combined Spectral Features ---
Rendered combined spectral overlay (689193 bytes)
  Shows both Centroid and Rolloff tracks with legend

--- Multiple Rolloff Percentages ---
Rendered rolloff_comparison spectral overlay (698867 bytes)

Composite figures

A waveform and a spectrogram arranged vertically and horizontally.

examples/plotting_composite_basics.rs

cargo run --example plotting_composite_basics --features plotting,transforms
Vertical composite. Open in its own page
Output
Testing CompositePlot with waveform + spectrogram...
Creating waveform plot...
Creating spectrogram plot...
Creating vertical composite...
Rendered vertical composite (1751191 bytes)
Creating horizontal composite...
Rendered horizontal composite (1751188 bytes)
Note: Enable 'html_view' feature to open in html_view

Composite figures with overlays

A modulated tone with its envelope, stacked over its spectrum.

examples/plotting_composite_advanced.rs

cargo run --example plotting_composite_advanced --features plotting,envelopes
Waveform with overlays over the spectrum. Open in its own page
Output
Testing advanced plot composition with overlays...
Computing RMS envelope...
Creating waveform plot with overlays...
Creating magnitude spectrum plot...
Creating composite plot...
Rendered composite plot (1625115 bytes)
Note: Enable 'html_view' feature to open in browser

Explanations, and the rest

Explanations in the terminal

Prints what common settings mean, using the same text as the explain API.

examples/explain.rs

cargo run --example explain --features educational,full_no_plotting
Output
Aliasing
========
A tone at 7000 Hz, sampled at 8000 Hz, produces the same samples as a 1000 Hz tone. Only frequencies up to the Nyquist frequency (4000 Hz) are represented faithfully.

Formulas
--------
  Folded (alias) frequency: where the tone appears after sampling:
                                  ⎛ f  ⎞
      fₐ = | f - k fₛ |, k = round⎜────⎟
                                  ⎝ fₛ ⎠

  Tones that differ by a multiple of f_s give identical samples:
      cos(2πf n T) = cos(2π(f + m fₛ) n T), m ∈ ℤ


Symbols
-------
  f   tone frequency           7000 Hz
  fₛ  sample rate              8000 Hz
  k   nearest multiple of f_s  1

Derived quantities
------------------
  Nyquist frequency     f_N = 4000 Hz                 fₛ / 2
  Normalised frequency  f / fₛ = 0.875 cycles/sample  f / fₛ
  Alias frequency       fₐ = 1000 Hz                  | f - k fₛ |

Analogue frequencies that produce identical samples
---------------------------------------------------
  Analogue tone (Hz)  Appears at (Hz)
  -----------------------------------
  1000                1000
  7000                1000
  9000                1000
  15000               1000
  17000               1000
  23000               1000

Trade-offs
----------
... 349 more lines

Explanation documents

Runs a chain of operations in explain mode and opens the resulting document in a browser, so it is compiled but not run for this page.

examples/educational.rs

cargo run --example educational --features educational,processing

Tutorial 14: psychoacoustics and codecs

Hearing thresholds, masking, mu-law and the perceptual codec. Text in chapter 14.

examples/tutorial_14_psychoacoustics_codecs.rs

cargo run --example tutorial_14_psychoacoustics_codecs --features educational,full_no_plotting
Masked threshold relative to the masker level against the distance from the masker in Bark. The library's mpeg1 preset (spreading_attenuation) falls by 25 dB/Bark above the masker and 6 dB/Bark below it; the Schroeder et al. spreading function (shifted by the 14.5 dB tonal offset) falls steeply below and gently above.
Figure 24. Masked threshold relative to the masker level against the distance from the masker in Bark. The library's mpeg1 preset (spreading_attenuation) falls by 25 dB/Bark above the masker and 6 dB/Bark below it; the Schroeder et al. spreading function (shifted by the 14.5 dB tonal offset) falls steeply below and gently above.
Output
== Tutorial 14: psychoacoustics and codecs ==

1. dBFS versus dB SPL
   peak 0.5 sine: -6.02 dBFS peak, -9.03 dBFS RMS
   1 Pa = 93.98 dB SPL; with a full-scale sine calibrated to 94 dB SPL the tone is 87.98 dB SPL

2. Perceptual frequency scales at 100 Hz, 1 kHz, 4 kHz
      100 Hz:   150.5 mel (HTK),  0.77 Bark, ERB bandwidth   35.5 Hz, ERB-number  3.37 Cam
     1000 Hz:  1000.0 mel (HTK),  8.53 Bark, ERB bandwidth  132.6 Hz, ERB-number 15.62 Cam
     4000 Hz:  2146.1 mel (HTK), 17.46 Bark, ERB bandwidth  456.5 Hz, ERB-number 27.11 Cam

3. Absolute threshold of hearing (Terhardt 1979), dB SPL
      100 Hz:  22.95 dB SPL
     1000 Hz:   3.37 dB SPL
     3300 Hz:  -4.98 dB SPL
    10000 Hz:  10.58 dB SPL
   minimum -4.98 dB SPL at 3320 Hz

4. Spreading of simultaneous masking (threshold relative to its peak)
   Schroeder et al. 1979: -9.9 dB/Bark above the masker, +24.9 dB/Bark below (rising towards it)
   library mpeg1 preset: attenuation 2 Bark above 64.5 dB, 2 Bark below 26.5 dB

5. G.711 mu-law: 14-bit linear -> 8-bit code
   segmented code versus 127 F(x), mu = 255: worst difference 1.81 codes
   level (dBFS peak)   SNR mu-law   SNR 8-bit linear
               0         39.7 dB       50.0 dB
             -10         37.1 dB       40.5 dB
             -20         38.3 dB       29.3 dB
             -30         34.5 dB       20.5 dB
             -40         34.2 dB       11.1 dB
   library mu_compress equals F(x) and mu_expand inverts it, to 1e-12

6. Perceptual MDCT codec (24 Bark bands, 2048-sample MDCT), 1 kHz tone, 0.5 s at 44.1 kHz
   bit budget   32000: SNR  42.67 dB
   bit budget   64000: SNR  49.10 dB
   bit budget  128000: SNR  61.92 dB
   bit budget  256000: SNR  88.53 dB

All checks passed.

Benchmark harness

The native side of the benchmark against librosa. It reads signal files written by benches/librosa_compare/run.sh, so it is compiled but not run for this page.

examples/librosa_bench/main.rs

cargo run --example librosa_bench --features full_no_plotting

Gaps

Reading and writing files has no Rust example yet. That code is in the audio_samples_io crate, and this crate does not depend on it.

For instructors

This page is for lecturers and teaching assistants who are considering audio_samples for a speech and audio processing course. It says what the library offers a course, how the teaching material is organised and checked, how to verify results against SciPy and other references, and where the library’s conventions differ from them.

What the library gives a course

  • One object that carries its own metadata. An AudioSamples<T> holds the samples, the sample rate and the channel layout together, so students cannot silently mix sample rates or forget which axis is time.

  • Rust and Python with the same core. The Python package (audio_samples on PyPI) is a thin binding over this crate, so a result computed in a notebook and in a Rust lab comes from the same code.

  • Descriptive errors. Invalid parameters produce diagnostics that name the parameter, the value and the valid range (with the fancy feature, as coloured miette reports). In Python most of them are raised as audio_samples.exceptions classes carrying .code and .help (a few parameter constructors raise a plain ValueError).

  • Built-in explanations (educational feature). A supported configuration can describe what it will do before it runs: the formula the code evaluates, every symbol with its unit, the derived resolution and latency numbers, and warnings about suspicious settings.

    use audio_samples::educational::{Explain, ExplainContext};
    use spectrograms::{StftParams, WindowType};
    use std::num::NonZeroUsize;
    
    let stft = StftParams::new(
        NonZeroUsize::new(256).unwrap(),
        NonZeroUsize::new(128).unwrap(),
        WindowType::Hanning,
        true,
    )
    .unwrap();
    let ctx = ExplainContext::new()
        .with_sample_rate(16_000.0)
        .with_f0_range(80.0, 300.0);
    let doc = stft.explain_with(&ctx);
    // 256 samples at 16 kHz last 16 ms, shorter than two periods of 80 Hz
    // (25 ms), so the explanation carries a warning.
    assert!(!doc.warnings.is_empty());
    println!("{doc}"); // terminal text; doc.to_markdown() for Jupyter or an LMS page

    The same is available in Python as audio.explain(params) and the audio_samples.explain module, rendered as Markdown with maths in Jupyter.

How the material is organised

The guide has one chapter per topic of a typical module, from sampling and quantisation to codecs. Every chapter follows the same pattern:

  1. Concept: the theory, with every symbol and unit defined.
  2. With the library: the API that does it.
  3. How it works: the same result re-derived from first principles in a few lines of plain code, checked against the library.
  4. Ask the library to explain: the explain API for that topic.
  5. Exercises, with an answer key that is itself executable.

Each chapter has a matching Rust lab, examples/tutorial_NN_<topic>.rs, and a matching Python notebook in the Python documentation (docs/source/tutorials/NN_<topic>.ipynb).

What is checked

Every number in the guide’s prose is computed and asserted, in a doctest of the same chapter or in its lab. The prose of the module documentation is checked by doctests where it has examples; explanatory text without an example (for instance comparisons with other libraries or citations) is checked by hand, not tested. Concretely:

  • every guide code block is a doctest (cargo test --doc --features educational,full_no_plotting -- guide);
  • every lab assert!s what it prints (cargo run --release --example tutorial_NN_<topic> --features educational,full_no_plotting);
  • every notebook ends its exercises with asserted solution cells and is executed headlessly by pytest --nbmake docs/source/tutorials;
  • a pre-commit hook runs the guide doctests, the explain API tests and the changed labs whenever teaching material changes.

If you adapt a chapter, keep this property: change the number in the code, and the test fails if the prose no longer matches.

Suggested labs

Each lab is sized for a two-hour session. The Rust lab and the Python notebook cover the same material, so pick the language that suits the cohort.

LabTopicAfterwards, students should be able to
01Sampling and aliasingpredict the alias frequency of a tone above Nyquist; explain why decimation needs a low-pass filter
02Quantisation and ditherderive and measure SQNR ≈ 6.02 b + 1.76 dB; show what TPDF dither does to quiet signals
03DFT, windows and leakagemap bins to hertz; choose a window from its main-lobe width and side-lobe level
04STFT and spectrogramstrade time resolution against frequency resolution; compute frame counts; read a mel spectrogram
05Convolution and FIR filtersrelate full and valid convolution lengths; design a windowed-sinc low-pass; measure group delay
06IIR filtersdesign a Butterworth filter, find its poles and zeros, judge stability, measure −3 dB at the cutoff
07Resamplingresample without aliasing; measure the alias rejection of each quality tier
08LPC and formantsfit an all-pole model with Levinson–Durbin and read formants from its roots
09Pitchestimate f0 with autocorrelation and YIN; explain octave errors
10Cepstrum, mel and MFCCcompute a cepstrum and an MFCC pipeline step by step
11Energy and VADbuild an energy and zero-crossing voice activity detector with hangover
12Dynamicsdraw a compressor’s static curve and measure attack and release time constants
13Onsets and tempocompute spectral flux, pick peaks and estimate tempo
14Psychoacoustics and codecsconvert between perceptual scales; implement μ-law companding

Assessment ideas that use the explain API: give students a configuration and ask them to predict the explanation’s numbers (Δf, Δt, frame count, gain at the cutoff) before running it; or give them a deliberately poor configuration and ask them to remove every warning.

Verifying results against SciPy and other references

The IIR filters are checked against golden fixtures from SciPy, FFmpeg, DSPFilters and liquid-dsp (tests/filter_reference.rs, generator in tests/reference/). For other topics, compare with these conventions in mind:

Topicaudio_samplesReferenceTo compare like with like
STFT windowsymmetric Hann (WindowType::Hanning)SciPy: periodic Hannscipy.signal.windows.hann(N, sym=True)
STFT paddingcentre = true pads ⌊N/2⌋ zeros at each endtorch.stft: reflectionpad_mode="constant"
rfftmagnitudes |X[k]|numpy: complex spectrumnp.abs(np.fft.rfft(x))
Mel spectrogramSlaney mel scale, no filter normalisation, applied to power–a Slaney-scale mel filterbank without normalisation
Mel helpers in utils::audio_mathhz_to_mel etc.: HTK formula; hz_to_mel_with_scale etc. take a MelScale–MelScale::Slaney for the Slaney scale
dB10·log10(max(P, floor)) re 1: an absolute floor–no clipping relative to the maximum
MFCCunnormalised DCT-II, lifter 22–rescale by the DCT normalisation factors; set the lifter
Zero-crossing ratecrossings per second over the whole signal–divide by the sample rate; frame the signal
Welch PSDdensity scaling (power per Hz), symmetric Hann, no detrendingSciPy: periodic Hann, constant detrendwindow=hann(N, sym=True), detrend=False
Integer to floatasymmetric: −1.0 ↔ −32768, +1.0 ↔ 32767soundfile: divide by 32768differs by at most one least significant bit
YINde Cheveigné and Kawahara steps 1–4, then parabolic interpolation of the normalised difference d′ (the paper’s step 5 interpolates the raw difference d, and its step 6 is omitted), with d summed over all N − τ overlapping pairs; a frame with no dip below the threshold is unvoiced; detect_pitch_yin is clip-widethe paper: sums d over a fixed window, falls back to the global minimumcompare with track_pitch, framewise, on clearly voiced frames

To compare with librosa, see the migration guide: it lists the crate’s librosa-compatible APIs and how the APIs used in this guide differ from librosa.

Known limitations worth telling students about are documented in each module.

Limitations of the teaching material itself:

  • No figures in the Rust guide. Rustdoc pages are text and code; plots of spectra, spectrograms, pole-zero diagrams and so on are in the Python notebooks. A few labs write CSV files to the system temporary directory that you can plot with any tool.
  • All signals are synthetic. No speech or music recordings are bundled: every example uses generated tones, chirps, noise, click tracks and synthetic vowels, so that every number is reproducible. To work with real recordings, load a WAV file with the companion crate audio_samples_io.
  • Maths is written as LaTeX ($…$). On docs.rs it is rendered by KaTeX (documentation/katex-header.html); a plain local cargo doc shows the LaTeX source unless you pass RUSTDOCFLAGS="--html-in-header documentation/katex-header.html". The formulas are written to stay readable as source text.

Setting up a course environment

  • Rust: the guide’s README lists the exact [dependencies] block a student needs to compile the chapter code in their own crate (audio_samples with the educational and full_no_plotting features, plus spectrograms, ndarray, num-complex and non-empty-slice). Add plotting for HTML plots. Reading and writing WAV or FLAC files is in the companion crate audio_samples_io.
  • Python: pip install audio_samples, then pip install matplotlib scipy librosa jupyter pytest nbmake for the notebooks and their checks. The notebooks need the audio_samples.explain module; if the installed release lacks it, build the bindings from source with maturin develop --release.

Learning guide

A short, runnable course in speech and audio processing built on audio_samples.

#ChapterRust lab
01Sampling and aliasingcargo run --release --example tutorial_01_sampling_aliasing --features educational,full_no_plotting
02Quantisation and dithercargo run --release --example tutorial_02_quantisation_dither --features educational,full_no_plotting
03The DFT, windows and leakagecargo run --release --example tutorial_03_dft_windows --features educational,full_no_plotting
04STFT and spectrogramscargo run --release --example tutorial_04_stft_spectrograms --features educational,full_no_plotting
05Convolution and FIR filterscargo run --release --example tutorial_05_convolution_fir --features educational,full_no_plotting
06IIR filters: design, poles, zeros and stabilitycargo run --release --example tutorial_06_iir_filters --features educational,full_no_plotting
07Resamplingcargo run --release --example tutorial_07_resampling --features educational,full_no_plotting
08LPC, the source-filter model and formantscargo run --release --example tutorial_08_lpc_formants --features educational,full_no_plotting
09Pitch: autocorrelation and YINcargo run --release --example tutorial_09_pitch --features educational,full_no_plotting
10Cepstrum, mel and MFCCcargo run --release --example tutorial_10_cepstrum_mel_mfcc --features educational,full_no_plotting
11Short-time energy, zero crossings and VADcargo run --release --example tutorial_11_energy_vad --features educational,full_no_plotting
12Dynamics: compressors and limiterscargo run --release --example tutorial_12_dynamics --features educational,full_no_plotting
13Onsets and tempocargo run --release --example tutorial_13_onsets_tempo --features educational,full_no_plotting
14Psychoacoustics and codecscargo run --release --example tutorial_14_psychoacoustics_codecs --features educational,full_no_plotting

See also For instructors.

Reading the guide

The chapters are the Markdown files in documentation/guide/, with standard LaTeX maths ($...$ inline, $$...$$ display). They are published three ways from the same files:

  • in the API documentation, as the audio_samples::guide module (cargo doc --open --features educational,full_no_plotting), where every code block is a doctest;
  • as an illustrated book with figures computed by the library (book/README.md in the repository says how to build it);
  • as plain Markdown, readable in any Markdown viewer with maths support.

In the raw Markdown, code lines that start with # are setup lines that rustdoc hides.

The labs are the files examples/tutorial_NN_<topic>.rs; run them from a checkout of this repository with the commands in the table. A matching Python notebook for each chapter is in the Python bindings’ documentation (docs/source/tutorials/).

Setting up

Every code block in the guide is a doctest of this crate. To compile the snippets in a crate of your own, add these dependencies to its Cargo.toml (the versions are the ones this crate itself builds against):

[dependencies]
audio_samples = { version = "3", features = ["educational", "full_no_plotting"] }
spectrograms = "2.2.1"    # StftParams, WindowType, MelParams, LogParams, ...
ndarray = "0.17"          # Array1 and the array! macro
num-complex = "0.4"       # complex numbers in the "How it works" sections
non-empty-slice = "0.6"   # NonEmptySlice / NonEmptyVec arguments

audio_samples does not re-export these crates, so they must be listed explicitly, with compatible versions: the StftParams you pass to stft, for example, must come from the same spectrograms release that audio_samples uses. If the audio_samples release on crates.io does not include the guide and the educational feature, use a path dependency on a checkout of this repository instead (audio_samples = { path = "../audio_samples", features = [...] }).

The guide’s signals are all generated in code. To analyse your own recordings, read WAV or FLAC files with the companion crate audio_samples_io, whose read function returns an AudioSamples value.