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

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.