09. Pitch: autocorrelation and YIN

The previous notebook recovered the vocal-tract filter; this one recovers the source. The fundamental frequency \(f_0\) 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).

Learning outcomes. After working through this notebook you can

  • estimate \(f_0\) with autocorrelation and explain why its answers lie on the grid \(f_s/\tau\);

  • compute YIN’s difference function and cumulative-mean-normalised difference (CMND) in NumPy and reproduce detect_pitch_yin to rounding error;

  • recognise octave errors and the missing fundamental, and control them with the YIN threshold;

  • track pitch over time with track_pitch and choose a frame length from \(f_{min}\).

import matplotlib.pyplot as plt
import numpy as np

import audio_samples as aus

rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")  # generators default to float32
FS = 16_000  # sample rate in Hz used throughout

Concept

A signal is periodic with period \(T_0\) seconds if \(x(t) = x(t + T_0)\); its fundamental frequency is \(f_0 = 1/T_0\) Hz. In samples the period is the lag \(\tau_0 = f_s/f_0\), where \(f_s\) is the sample rate in Hz; in general \(\tau_0\) is not an integer.

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

\[r(\tau) = \sum_{i=0}^{N-1-\tau} x[i]\,x[i+\tau]\]

It peaks at multiples of the period. The estimator searches \(\tau_{min} = \lfloor f_s/f_{max} \rfloor \le \tau \le \tau_{max} = \lfloor f_s/f_{min} \rfloor\) (\(f_{min}\), \(f_{max}\) the search range in Hz) and reports \(\hat{f}_0 = f_s/\hat{\tau}\). Because \(\hat{\tau}\) is an integer, the answers lie on the grid \(f_s/\tau\), whose spacing near \(f_0\) is

\[\Delta f = \frac{f_s}{\tau} - \frac{f_s}{\tau + 1} = \frac{f_s}{\tau(\tau+1)} \approx \frac{f_0^2}{f_s}\]

so the worst-case error is \(\Delta f/2\). For a 110 Hz voice at 16 kHz that is small (\(\Delta f \approx 0.76\) Hz, so the error is at most 0.38 Hz), but at 440 Hz the step is \(\Delta f \approx 12\) Hz (errors up to about 6 Hz) and at 880 Hz it is about 47 Hz (errors up to about 23 Hz).

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

\[d(\tau) = \sum_{j=0}^{N-1-\tau} \left(x[j] - x[j+\tau]\right)^2\]
\[d'(0) = 1, \qquad d'(\tau) = \frac{d(\tau)}{\frac{1}{\tau}\sum_{i=1}^{\tau} d(i)}\]

where \(d(\tau)\) (squared signal units) is the difference function over all \(N - \tau\) overlapping pairs of samples and \(d'(\tau)\) (dimensionless) the CMND. \(d'\) 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 \(d'(\tau) < \theta\) (\(\theta\) the threshold, typically 0.1 to 0.2), moved forward to the bottom of that dip, and refined by a parabola through \(d'(\tau_0-1), d'(\tau_0), d'(\tau_0+1)\). With \(a = d'(\tau_0+1) + d'(\tau_0-1) - 2d'(\tau_0)\) and \(b = (d'(\tau_0+1) - d'(\tau_0-1))/2\) the vertex lies at \(\tau_0 - b/a\):

\[\hat{\tau} = \tau_0 + \frac{1}{2}\,\frac{d'(\tau_0-1) - d'(\tau_0+1)}{d'(\tau_0-1) - 2d'(\tau_0) + d'(\tau_0+1)}, \qquad \hat{f}_0 = \frac{f_s}{\hat{\tau}}\]

so the period estimate is fractional and not restricted to the integer grid. The shift is skipped (left at 0) when \(\tau_0\) is at either end of the search range or when \(|b| \ge |a|\) (the vertex would lie more than one lag away). If no lag dips below \(\theta\) the frame is declared unvoiced.

Two details differ from the paper. De Cheveigné and Kawahara’s step 5 takes the period from a parabola fitted to the raw difference function \(d(\tau)\), because the abscissa of the interpolated \(d'\) minimum is slightly biased; this library takes it from \(d'\). And when no lag dips below \(\theta\), the paper falls back to the global minimum of \(d'\), where this library returns “unvoiced”. The paper’s step 6, a “best local estimate” search around each frame, is not implemented. Finally, the paper sums \(d(\tau)\) over a fixed window of \(W\) samples from the start of the frame; this library sums over all \(N - \tau\) overlapping pairs, so it measures the pitch of the whole frame rather than of its early part.

Octave errors. A signal with period \(\tau_0\) also repeats at \(2\tau_0, 3\tau_0, \dots\); and if its odd harmonics are weak it nearly repeats at \(\tau_0/2\). Picking \(2\tau_0\) halves the estimate; picking \(\tau_0/2\) doubles it. YIN’s “first dip below \(\theta\)” rule guards against the first kind; the second is controlled by \(\theta\).

Frame length. The difference function needs lags up to \(\tau_{max}\) plus a window, so both detectors in this library require \(N > 2\tau_{max} + 1\), i.e. at least \(N_{min} = 2(\tau_{max}+1)\) samples, a little more than two periods of \(f_{min}\).

# The grid steps and worst-case errors quoted above (tau: the nearest integer lag).
for f0, step, step_tol, worst, worst_tol in [(110.0, 0.76, 0.005, 0.38, 0.005),
                                             (440.0, 12.0, 0.05, 6.0, 0.05),
                                             (880.0, 47.0, 0.5, 23.0, 0.5)]:
    tau = round(FS / f0)
    delta_f = FS / (tau * (tau + 1))
    print(f"{f0:5.0f} Hz: tau = {tau}, grid step {delta_f:6.3f} Hz, worst-case error {delta_f / 2:6.3f} Hz")
    assert abs(delta_f - step) < step_tol and abs(delta_f / 2 - worst) < worst_tol
  110 Hz: tau = 145, grid step  0.756 Hz, worst-case error  0.378 Hz
  440 Hz: tau = 36, grid step 12.012 Hz, worst-case error  6.006 Hz
  880 Hz: tau = 18, grid step 46.784 Hz, worst-case error 23.392 Hz

With the library

detect_pitch_autocorr(min_frequency, max_frequency) and detect_pitch_yin(threshold, min_frequency, max_frequency) analyse the whole signal as one frame and return None when no pitch is found. A 50 ms, 440 Hz tone:

x = aus.sine_wave(440.0, 0.05, sample_rate=FS, amplitude=0.8, dtype=F64)
ac = x.detect_pitch_autocorr(80.0, 1000.0)
yin = x.detect_pitch_yin(0.1, 80.0, 1000.0)
print(f"autocorrelation {ac:.2f} Hz, YIN {yin:.4f} Hz")

# The true period is 16000/440 = 36.36 samples. Autocorrelation must pick an integer
# lag (36), so it reports 444.44 Hz: within half of the grid step f_s/36 - f_s/37.
assert ac == FS / 36
assert abs(ac - 440.0) <= 0.5 * (FS / 36 - FS / 37)
# YIN interpolates the period and is within 0.1 Hz (440.0986 Hz).
assert abs(yin - 440.0986) < 5e-5
assert abs(yin - 440.0) < 0.1
autocorrelation 444.44 Hz, YIN 440.0986 Hz

Repeating 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 (the same numbers as the Rust guide’s lab).

rows = []
for f0 in (110.0, 220.0, 440.0, 880.0):
    tone = aus.sine_wave(f0, 0.05, sample_rate=FS, amplitude=0.8, dtype=F64)
    e_ac = tone.detect_pitch_autocorr(80.0, 1000.0) - f0
    e_yin = tone.detect_pitch_yin(0.1, 80.0, 1000.0) - f0
    tau = round(FS / f0)
    half_step = 0.5 * FS / (tau * (tau + 1))
    assert abs(e_ac) <= half_step + 1e-9
    rows.append((f0, e_ac, e_yin))
    print(f"{f0:5.0f} Hz: autocorrelation {e_ac:+6.2f} Hz (half step {half_step:5.2f}), YIN {e_yin:+.4f} Hz")

assert np.allclose([r[1] for r in rows], [0.34, -0.82, 4.44, 8.89], atol=0.005)
assert np.allclose([r[2] for r in rows], [0.0006, 0.0124, 0.0986, 1.2354], atol=5e-5)  # rounding of the quoted values
  110 Hz: autocorrelation  +0.34 Hz (half step  0.38), YIN +0.0006 Hz
  220 Hz: autocorrelation  -0.82 Hz (half step  1.48), YIN +0.0124 Hz
  440 Hz: autocorrelation  +4.44 Hz (half step  6.01), YIN +0.0986 Hz
  880 Hz: autocorrelation  +8.89 Hz (half step 23.39), YIN +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.

xs = x.to_numpy()
n = len(xs)
min_tau, max_tau = int(FS / 1000.0), int(FS / 80.0)  # 16, 200

# Autocorrelation: argmax of r(tau) over the lag range.
r = np.array([xs[: n - tau] @ xs[tau:] for tau in range(max_tau + 1)])
best = min_tau + int(np.argmax(r[min_tau : max_tau + 1]))
assert best == 36 and FS / best == x.detect_pitch_autocorr(80.0, 1000.0)

# YIN step 1: difference function over all n - tau overlapping pairs.
d = np.array([np.sum((xs[: n - tau] - xs[tau:]) ** 2) for tau in range(max_tau + 1)])
# Step 2: cumulative-mean-normalised difference d'.
cmnd = np.ones(max_tau + 1)
cmnd[1:] = d[1:] * np.arange(1, max_tau + 1) / np.cumsum(d[1:])
# Step 3: first lag below theta, then down to the bottom of the dip.
theta = 0.1
tau = min_tau + int(np.argmax(cmnd[min_tau : max_tau + 1] < theta))
assert tau == 34  # d'(34) = 0.0756 is already below 0.1 ...
assert abs(cmnd[34] - 0.0756) < 1e-4 and abs(cmnd[36] - 0.0019) < 1e-4
while tau < max_tau and cmnd[tau + 1] < cmnd[tau]:
    tau += 1
assert tau == 36  # ... but the minimum of the dip is at 36
# Step 4: parabolic interpolation (skipped at the ends of the range or when |b| >= |a|).
a = cmnd[tau + 1] + cmnd[tau - 1] - 2 * cmnd[tau]
b = (cmnd[tau + 1] - cmnd[tau - 1]) / 2
shift = -b / a if min_tau < tau < max_tau and abs(b) < abs(a) else 0.0
assert abs(shift - 0.3555) < 1e-4  # the true period is 36.3636 samples
tau_hat = tau + shift
f_hat = FS / tau_hat
print(f"d'(34..38) = {np.round(cmnd[34:39], 4)}; period {tau_hat:.4f} samples, f0 {f_hat:.4f} Hz")
# Same operations on the same f64 samples: agreement to rounding error.
assert abs(f_hat - x.detect_pitch_yin(theta, 80.0, 1000.0)) < 1e-9

fig, axs = plt.subplots(1, 2, figsize=(8, 3))
lags = np.arange(max_tau + 1)
axs[0].plot(lags[: max_tau + 1], r / r[0])
axs[0].axvline(best, color="C3", ls=":")
axs[0].set(xlabel="Lag (samples)", ylabel="r(τ)/r(0)", title="Autocorrelation")
axs[1].plot(lags, cmnd)
axs[1].axhline(theta, color="C2", ls="--", label="θ = 0.1")
axs[1].axvline(tau_hat, color="C3", ls=":", label="τ̂")
axs[1].set(xlabel="Lag (samples)", ylabel="d'(τ)", title="YIN CMND", xlim=(0, 120))
axs[1].legend()
plt.tight_layout()
plt.show()
d'(34..38) = [0.0756 0.0261 0.0019 0.006  0.0403]; period 36.3555 samples, f0 440.0986 Hz
../_images/3a61c4d16e17ceca560fef27c1eee7e840380fe9194be9d2940581c384fdaaa2.png

An independent reference: librosa.yin. librosa implements the same CMND and parabolic interpolation, but frame by frame, with its own window (\(W\) = half the frame length, here 512 of 1024 samples) and with a fallback to the global minimum when no dip goes below the threshold. On 0.5 s tones (median over frames) both implementations stay within 0.4 % of the truth, and they do not agree with each other to better than that because the windows differ.

import librosa

for f0 in (110.0, 220.0, 440.0, 880.0):
    tone = aus.sine_wave(f0, 0.5, sample_rate=FS, amplitude=0.8, dtype=F64)
    est_lib = np.median(librosa.yin(tone.to_numpy(), fmin=80, fmax=1000, sr=FS, frame_length=1024,
                                    center=False, trough_threshold=0.1))
    est_aus = tone.detect_pitch_yin(0.1, 80.0, 1000.0)
    print(f"{f0:5.0f} Hz: audio_samples {est_aus - f0:+.3f} Hz, librosa {est_lib - f0:+.3f} Hz")
    assert abs(est_aus - f0) / f0 < 0.004 and abs(est_lib - f0) / f0 < 0.004
  110 Hz: audio_samples +0.001 Hz, librosa +0.434 Hz
  220 Hz: audio_samples +0.015 Hz, librosa +0.400 Hz
  440 Hz: audio_samples +0.108 Hz, librosa +0.562 Hz
  880 Hz: audio_samples +1.286 Hz, librosa +1.668 Hz

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.

N_C = 1600  # 0.1 s: 20 periods of 200 Hz, so FFT bins land on harmonics
i = np.arange(N_C)


def complex_tone(harmonics):
    y = sum(amp * np.cos(2 * np.pi * h * 200.0 * i / FS) for h, amp in harmonics)
    return aus.AudioSamples.new_mono(y, sample_rate=FS)


# 1. Missing fundamental: no energy at 200 Hz, yet both detectors find it.
missing = complex_tone([(2, 1.0), (3, 1.0), (4, 1.0), (5, 1.0), (6, 1.0)])
spec = np.asarray(missing.rfft(N_C))[0]  # bin k is at k * 10 Hz
assert spec[20] < 1e-9 * spec[40]  # bin 20 = 200 Hz is empty
assert abs(missing.detect_pitch_yin(0.1, 80.0, 500.0) - 200.0) < 0.1
assert missing.detect_pitch_autocorr(80.0, 500.0) == 200.0

# 2. Weak odd harmonics: an octave error, controlled by the YIN threshold.
weak = complex_tone([(1, 0.1), (2, 1.0), (3, 0.1), (4, 1.0), (5, 0.1), (6, 1.0)])
yin_at = lambda theta: weak.detect_pitch_yin(theta, 80.0, 500.0)
assert abs(yin_at(0.1) - 400.0) < 1.0  # octave error: half the period
assert abs(yin_at(0.01) - 200.0) < 0.1  # strict threshold: the true period
# Autocorrelation is biased towards short lags (fewer terms in the sum at long lags)
# and doubles the pitch too.
assert weak.detect_pitch_autocorr(80.0, 500.0) == 400.0
# librosa.yin makes the same octave error on this signal at theta = 0.1.
est = np.median(librosa.yin(weak.to_numpy(), fmin=80, fmax=500, sr=FS, frame_length=1024, center=False))
assert abs(est - 400.0) < 1.0
print(f"YIN(0.1) {yin_at(0.1):.2f} Hz, YIN(0.01) {yin_at(0.01):.2f} Hz, librosa {est:.2f} Hz")
YIN(0.1) 400.26 Hz, YIN(0.01) 200.02 Hz, librosa 400.28 Hz

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

Tracking a glide. track_pitch(window_size, hop_size, method, threshold, min_frequency, max_frequency) 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. PitchContour.frames() and mean_pitch() are methods, not properties.

# 0.5 s linear glide from 100 to 200 Hz: f(t) = 100 + 200 t.
glide = aus.chirp(100.0, 200.0, 0.5, sample_rate=FS, amplitude=0.8, dtype=F64)
YIN = aus.PitchDetectionMethod.yin

# 512 samples (32 ms) is more than the 402 needed to search down to 80 Hz.
track = glide.track_pitch(512, 128, YIN, 0.1, 80.0, 400.0)
full = [f for f in track.frames() if f.time + 512 / FS <= 0.5]
truth = np.array([100 + 200 * (f.time + 256 / FS) for f in full])
est = np.array([f.frequency for f in full])  # every full frame is voiced
worst = np.max(np.abs(est - truth))
print(f"worst error {worst:.2f} Hz over {len(full)} full frames ({len(track)} frames in total)")
assert worst < 1.0 and abs(worst - 0.12) < 0.005

# 256 samples (16 ms) cannot hold two periods of 80 Hz: every frame is unvoiced.
short = glide.track_pitch(256, 64, YIN, 0.1, 80.0, 400.0)
assert all(f.frequency is None for f in short.frames()) and short.mean_pitch() is None

fig, ax = plt.subplots(figsize=(8, 3))
ax.plot([f.time + 256 / FS for f in full], est, "o", ms=3, label="track_pitch (YIN), frame centre")
ax.plot([f.time + 256 / FS for f in full], truth, lw=1, label="true f(t)")
ax.set(xlabel="Time (s)", ylabel="f0 (Hz)", title="Tracking a 100-200 Hz glide")
ax.legend()
plt.show()
worst error 0.12 Hz over 59 full frames (61 frames in total)
../_images/1d60c336ae05e0e2bccde5c2b5078dbe122d631928cbc3762bcc7d12e3fb4de9.png

Ask the library to explain

aus.explain.yin and aus.explain.autocorrelation_pitch evaluate the formulas at your settings: lag range, minimum frame length, the integer-lag pitch steps, and warnings for frames that are too short or ranges prone to octave errors.

doc = aus.explain.yin(0.1, 80.0, 400.0, 16_000.0, frame_length=256)
assert doc.quantity("Longest lag") == 200
assert doc.quantity("Minimum frame length") == 402
assert doc.has_warning("problem")  # 256 < 402
assert not aus.explain.yin(0.1, 80.0, 400.0, 16_000.0, frame_length=512).has_warning("problem")
doc

YIN pitch estimation

YIN searches lags 40 to 200 samples (400 Hz to 80 Hz at 16000 Hz) for the first dip of the normalised difference function below θ = 0.1 and refines it by parabolic interpolation of d’. Frames need at least 402 samples.

Formulas

Difference function over all N − τ overlapping pairs, for τ = 1 … τ_max (the paper uses a fixed window W instead, which biases gliding pitch towards the frame’s start):

$$ d(\tau) = \sum_{j=0}^{N-1-\tau} \left( x[j] - x[j+\tau] \right)^2 $$

Cumulative-mean-normalised difference (CMND); the running mean always starts at τ = 1:

$$ d’(\tau) = \frac{d(\tau)}{\frac{1}{\tau} \sum_{i=1}^{\tau} d(i)}, \quad d’(0) = 1 $$

Absolute threshold: first lag below θ, then step forward while d’ keeps falling (bottom of the dip); no dip means unvoiced (no estimate):

$$ \tau_0 = \min { \tau \ge \tau_{min} : d’(\tau) < \theta } $$

Parabolic interpolation of d’ gives a fractional period. De Cheveigné & Kawahara (2002, JASA 111(4)) step 5 interpolates the raw difference function d(τ) instead, and their step 6 (best local estimate) is not implemented:

$$ \hat{\tau} = \tau_0 + \frac{1}{2} \frac{d’(\tau_0 - 1) - d’(\tau_0 + 1)}{d’(\tau_0 - 1) - 2 d’(\tau_0) + d’(\tau_0 + 1)}, \quad \hat{f}_0 = \frac{f_s}{\hat{\tau}} $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $x$ | analysis frame (N samples) | | | $\tau$ | lag in samples | | | $\theta$ | CMND threshold | 0.1 | | $\tau_{min}$ | shortest lag searched | 40 samples | | $\tau_{max}$ | longest lag searched | 200 samples |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Shortest lag | $\tau_{min}$ = 40 samples | $\lfloor f_s / f_{max} \rfloor$ | | Longest lag | $\tau_{max}$ = 200 samples | $\lfloor f_s / f_{min} \rfloor$ | | Minimum frame length | $N_{min}$ = 402 samples | $2(\tau_{max} + 1)$ | | Minimum frame duration | $N_{min} / f_s$ = 25.125 ms | $1000 N_{min} / f_s$ |

Trade-offs

  • A lower threshold rejects more unvoiced or noisy frames but misses weakly periodic ones.

  • Parabolic interpolation refines the period below one sample, so the estimate is not limited to f_s/integer values.

  • Extending f_min downwards lengthens the frame the method needs (N ≥ 2(f_s/f_min + 1)), costing time resolution.

Warnings

  • Problem: A 256-sample frame is shorter than the 402 samples needed to search down to 80 Hz; the estimator returns no pitch. Hint: Use frames of at least 402 samples or raise f_min.

See also

  • Single estimate: audio_samples::AudioPitchAnalysis::detect_pitch_yin

  • Single estimate (Python): audio_samples.AudioSamples.detect_pitch_yin

  • Low-level routine: audio_samples::operations::pitch_analysis::yin_pitch_detection

  • Python: audio_samples.explain.yin

doc = aus.explain.autocorrelation_pitch(80.0, 1000.0, 16_000.0)
assert doc.quantity("Shortest lag") == 16
step = doc.quantity("Pitch step at f_max")
assert abs(step - (1000.0 - 16_000.0 / 17)) < 1e-9  # 58.8 Hz
assert doc.has_warning_containing("octave errors")
doc

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:

$$ r(\tau) = \sum_{i=0}^{N-1-\tau} x[i] , x[i+\tau] $$

The lag with the largest positive correlation is taken as the period:

$$ \hat{\tau} = \arg\max_{\tau_{min} \le \tau \le \tau_{max}} r(\tau), \quad \hat{f}_0 = \frac{f_s}{\hat{\tau}} $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $x$ | analysis frame (N samples) | | | $\tau$ | lag in samples | | | $\tau_{min}$ | shortest lag searched | 16 samples | | $\tau_{max}$ | longest lag searched | 200 samples |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Shortest lag | $\tau_{min}$ = 16 samples | $\lfloor f_s / f_{max} \rfloor$ | | Longest lag | $\tau_{max}$ = 200 samples | $\lfloor f_s / f_{min} \rfloor$ | | Minimum frame length | $N_{min}$ = 402 samples | $2(\tau_{max} + 1)$ | | Minimum frame duration | $N_{min} / f_s$ = 25.125 ms | $1000 N_{min} / f_s$ | | Pitch step at f_max | $\Delta f_{hi}$ = 58.8235 Hz | $f_s/\tau_{min} - f_s/(\tau_{min}+1)$ | | Pitch step at f_max (cents) | $\Delta c_{hi}$ = 104.955 cents | $1200 \log_2((\tau+1)/\tau)$ | | Pitch step at f_min (cents) | $\Delta c_{lo}$ = 8.6346 cents | $1200 \log_2((\tau+1)/\tau)$ |

Trade-offs

  • The sum has N-τ terms, so r(τ) is biased towards short lags; this suppresses sub-octave errors but favours harmonics when the fundamental is weak.

  • Without normalisation the method is fast but more sensitive to loudness changes and noise than YIN.

Warnings

  • Info: The search range spans 3.64386 octaves, so octave errors (picking 2τ₀ or τ₀/2) are possible. Hint: Narrow the range when the expected pitch is known.

See also

  • Single estimate: audio_samples::AudioPitchAnalysis::detect_pitch_autocorr

  • Single estimate (Python): audio_samples.AudioSamples.detect_pitch_autocorr

  • YIN: audio_samples::educational::topics::yin

  • YIN (Python): audio_samples.explain.yin

Exercises

Exercise 1 (grid step). Near 1 kHz at \(f_s = 16\) kHz, how far apart are neighbouring autocorrelation estimates? Compare with \(f_0^2/f_s\). Store the step in Hz in answer.

answer = None  # TODO
# Solution
answer = 16_000 / 16 - 16_000 / 17
assert abs(answer - 58.82) < 0.01
assert 1000.0**2 / 16_000 == 62.5  # tau(tau+1) ~ tau^2 is coarse for short lags
assert abs(aus.explain.autocorrelation_pitch(80.0, 1000.0, 16_000.0).quantity("Pitch step at f_max") - answer) < 1e-9
print(f"{answer:.2f} Hz versus f0^2/f_s = 62.5 Hz")
58.82 Hz versus f0^2/f_s = 62.5 Hz

Exercise 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 \(f_{min} = 60\) Hz, then check. Store the minimum frame length in answer.

answer = None  # TODO
# Solution
answer = 2 * (16_000 // 60 + 1)  # tau_max = 266
assert answer == 534  # 33.4 ms
doc = aus.explain.yin(0.1, 60.0, 400.0, 16_000.0, frame_length=512)
assert doc.quantity("Minimum frame length") == answer
assert doc.has_warning_containing("shorter than the 534 samples")

low = aus.sine_wave(70.0, 0.3, sample_rate=FS, amplitude=0.8, dtype=F64)
# 512 samples hold more than two 70 Hz periods (457 samples), but not the whole *search* range:
assert all(f.frequency is None for f in low.track_pitch(512, 128, YIN, 0.1, 60.0, 400.0).frames())
assert abs(low.track_pitch(1024, 256, YIN, 0.1, 60.0, 400.0).mean_pitch() - 70.0) < 0.5

Exercise 3 (choosing the threshold). For the weak-odd-harmonics signal above, compute \(d'(40)\) yourself (lag range of the 80-500 Hz search, \(\tau_{max} = 200\)) and predict the YIN estimate with \(\theta = 0.021\) and \(\theta = 0.019\). Store \(d'(40)\) in answer.

answer = None  # TODO
# Solution
w = weak.to_numpy()
max_tau = 200
# d summed over all N - tau overlapping pairs, as in the Concept section.
d = np.array([np.sum((w[: len(w) - t] - w[t:]) ** 2) for t in range(max_tau + 1)])
cm = lambda t: d[t] * t / d[1 : t + 1].sum()
answer = cm(40)
assert abs(answer - 0.0196) < 5e-5
assert all(cm(t) > answer for t in range(32, 40))  # 40 is the bottom of the dip
assert abs(weak.detect_pitch_yin(0.021, 80.0, 500.0) - 400.0) < 1.0  # accepts the half period
assert abs(weak.detect_pitch_yin(0.019, 80.0, 500.0) - 200.0) < 0.1  # continues to the true period
print(f"d'(40) = {answer:.4f}")
d'(40) = 0.0196

Common pitfalls

  • Frame length is set by \(f_{min}\), not by the pitch you expect: frames of at most \(2\lfloor f_s/f_{min} \rfloor + 1\) samples always return None.

  • detect_pitch_yin is clip-global: one number for the whole signal, silence included. Use track_pitch for anything longer than a steady frame.

  • PitchFrame.time is the frame start, not its centre; shift by half a frame to compare with a tracker that reports centred frames.

  • No fallback. This library’s YIN declares a frame with no dip below \(\theta\) unvoiced, instead of falling back to the global minimum of \(d'\) (as the librosa.yin reference above does), and it sums the difference function over all \(N - \tau\) overlapping pairs rather than a fixed window.

  • The autocorrelation estimate is quantised to \(f_s/\tau\); use YIN when you need better than \(f_0^2/f_s\).

  • Octave errors are a property of the signal, not of the implementation: narrow \([f_{min}, f_{max}]\) when you know the speaker, and lower \(\theta\) when harmonics alternate in strength.

  • Generators default to float32. Pass dtype=np.dtype("float64") when you want to compare with a float64 re-derivation to rounding error.

See also

  • Rust guide chapter: Pitch: autocorrelation and YIN (available from the next release; until then build the docs locally with cargo doc --features educational,full_no_plotting --open).

  • Python API: AudioSamples.detect_pitch_yin, AudioSamples.detect_pitch_autocorr, AudioSamples.track_pitch, PitchContour, PitchFrame, aus.explain.yin, aus.explain.autocorrelation_pitch (API reference).

  • Previous: 08. LPC and formants. Next: 10. Cepstrum, mel and MFCC, which finds the pitch a third way.

References

  • de Cheveigné, A. and Kawahara, H. (2002). YIN, a fundamental frequency estimator for speech and music. Journal of the Acoustical Society of America, 111(4), 1917-1930.

  • Rabiner, L. R. and Schafer, R. W. (1978). Digital Processing of Speech Signals. Prentice-Hall. Chapter 4 (short-time autocorrelation and pitch period estimation).