Algorithmcore
Cepstral pitch detection
Also called Noll cepstral pitch detector.
Estimate the pitch period of a voiced frame from the quefrency of the largest peak of the real cepstrum in the plausible range.
- Solves
- Pitch detection
- Time
- O(M log M) worst
- Space
- O(M) extra
- Where
- M = the FFT length, a power of two at least the frame length
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- A. Michael Noll, 1967
Cepstral pitch detection finds the fundamental frequency of a voiced frame of speech from the largest peak of its real cepstrum inside the range of plausible pitch periods. It is one method for the problem of pitch detection: the cepstrum page defines the transform, and this page is the detector that A. Michael Noll built on it in 1964 and 1967. Inside this area it is the oldest of three trackers: pYIN works on the time-domain difference function of YIN and adds a hidden Markov model, and RAPT uses the normalized cross-correlation and a dynamic program over frames, while the cepstral detector decides each frame alone from the log spectrum. One frame costs two FFTs, operations for an FFT length .
In plain words
A voiced sound is a buzz from the vocal folds that passes through the mouth and throat. The buzz gives the spectrum many evenly spaced peaks, one per harmonic, and the mouth shapes the broad outline of those peaks. If you take the logarithm of the spectrum, the outline and the comb of harmonics no longer multiply but add. A second Fourier transform then puts the slow outline near zero and the fast comb at one place: the length of one buzz period. So the detector looks for the tallest peak among the lengths that a voice can have, and calls the frame unvoiced when that peak is too small.
The problem
Given one frame of a speech signal at a sample rate Hz, and a search range (for example 50 to 500 Hz), decide whether the frame is voiced, and if it is, estimate its fundamental frequency in Hz. The frame should hold at least two periods of , so 40 ms or more for Hz. A tracker runs the detector on frames every 10 ms or so. The problem and its error measures (gross errors, octave errors, voicing errors) are on the pitch detection page.
The algorithm
For an FFT length , a power of two, the real cepstrum of the windowed and zero padded frame is
The index is the quefrency in samples. A pitch period of samples belongs to the frequency .
CEPSTRAL-PITCH(x, fs, fmin, fmax, M, θ) ▷ x is a frame of N ≤ M samples- 1
y[n] ← w[n] x[n] for n < N, and y[n] ← 0 for N ≤ n < M ▷ w is the Hamming window - 2
Y ← the DFT of y, by the FFT - 3
L[k] ← ln |Y[k]| for 0 ≤ k < M, with a small floor so that ln 0 never occurs - 4
c ← the inverse DFT of L, by the FFT ▷ the real cepstrum - 5
q_min ← ⌈fs / fmax⌉; q_max ← ⌊fs / fmin⌋ - 6
q* ← the q in [q_min, q_max] with the largest c[q], the smallest such q on ties - 7
if c[q*] ≤ θ then return unvoiced - 8
return fs / q*
Lines L1 to L4 compute the real cepstrum. Since is real, , so is real and even, and its inverse DFT is real and equals its forward DFT divided by ; the code uses the same FFT twice. Line L5 turns the frequency range into a range of periods, which must stay below . Line L6 is the peak search. Line L7 is the voicing decision with a threshold ; its value is a heuristic, set on labeled speech, and this page does not take one from Noll. The floor in line L3 is times the largest magnitude.
Noll took the power spectrum of the log power spectrum, so his cepstrum is in the notation here, up to a constant. Its largest peak is at the same quefrency whenever that peak of is positive, so the two forms pick the same period.
Example
Take Hz and one resonance at 500 Hz with pole radius , so the bandwidth is Hz. In the sign convention the coefficients are and . A pulse train at Hz, one pulse every 50 samples, passes through . The frame is the 400 samples (50 ms) from sample 100 on, with a Hamming window and . The search range 60 to 400 Hz gives and .
| 1 | 2 | 3 | 20 | 49 | 50 | 51 | 62 | 100 | 133 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0.8079 | 0.3034 | 0.0862 | 0.0028 | 0.0249 | 1.2539 | 0.0018 | 0.1366 | 0.4304 | -0.0016 |
The low quefrencies hold the resonance. Inside the range, the largest values are and then the second rahmonic , so line L6 gives and line L8 returns Hz, the true pitch. The same frame at 100, 125 and 200 Hz gives exactly those values. At 150 Hz the period is 53.33 samples, and the detector returns , which is 150.94 Hz: the answer is a whole number of samples.
The theory is exact for a model signal. Take six pulses at the samples with the amplitudes , filter them by the same , and take the cepstrum with no window and . The filter alone has the cepstrum for its poles and , which gives , and . The computed values are , and , as the lemmas of the proof predict.
Correctness
The detector is an estimator, so no theorem says that it finds the true pitch of real speech. What can be proved is what the cepstrum of a model voiced signal is, and when its largest peak in the range is the pitch period. The full proof is in proofs/correctness.md; this is the outline.
Lines L2 to L4 compute the real cepstrum, because is real and even, so its inverse DFT is real and is the forward DFT divided by .
For the model, let be the impulse response of an all-pole filter with all poles inside the unit circle, and let be pulses of period with . The signal is , with no window. The log of the transform of a convolution is the sum of the logs, so the complex cepstrum is . Expanding the logarithms in power series gives for , and is 0 except at the multiples of , where , minus when divides . Both are causal, because both factors are minimum phase, so the real cepstrum is for .
Theorem. Let and over the range , which holds . If , the cepstrum of the model signal, without aliasing, has its unique largest value in the range at .
The reason is that , while every other in the range has , since for . The bound shows that the filter part dies out fast: the vocal tract lives at low quefrency. With a finite the DFT cepstrum is the aliased sum , and the theorem holds when the margin is larger than twice the aliased tail. The Hamming window of line L1 breaks the exact model, because it multiplies and not only the pulses; that the peak survives windowing is a measurement, as in the example, not a theorem.
Proof: The cepstrum of a model voiced signal and when its peak is the pitch periodfull
The cepstral detector is an estimator, so its correctness has two parts. First, lines L1 to L4 compute the real cepstrum. Second, for a model voiced signal, the largest value of the cepstrum in the search range is at the pitch period, under a stated condition. We work in the real RAM. The window of line L1 is not part of the model, and we say below what is lost.
Lemma 1 (two FFTs give the real cepstrum). Let be real of length , its DFT and . Then the inverse DFT is real, , and .
Proof. Since is real, , so (indices mod ). Substitute in the sum for : the sum becomes , which is the forward DFT of divided by , and also the complex conjugate of the original sum because is real. A number equal to its conjugate is real. The same substitution with gives .
So line L4, which applies the forward FFT to and divides by , computes , and lines L5 and L6 need only .
The model. Let with every , let be the impulse response of , and let
The signal is . We use the transforms on the unit circle, , and the complex cepstrum with the continuous branch of the logarithm that is 0 at . The real cepstrum is , because .
Lemma 2 (convolution adds cepstra). and .
Proof. for the continuous branches, and . The inverse transform is linear.
Lemma 3 (the all-pole part). , for and for . The coefficients of give the same values by , with for .
Proof. For , , a convergent power series in . Summing over gives , and the coefficients of this Laurent series are the complex cepstrum. For the recursion, differentiate : , so . Comparing the coefficients of gives , which is the recursion.
Lemma 4 (the pulse part). unless with , and
Proof. . Both factors have their zeros at . For , and . Writing in the second sum, its coefficient of is .
By Lemmas 2 to 4, is 0 at negative indices, so for :
Theorem. Let and , and let . If , then over the real cepstrum of the model signal has its unique maximum at .
Proof. At we have , and does not divide 1, so and . (With there is one pulse and no period: .) At any other in the range, either , or with and , since decreases in for . So . The condition gives .
The value is small when the poles are not close to the unit circle: by Lemma 3, for . For one pole pair of radius and the bound is , so any satisfies the condition.
Finite FFT length. The DFT of length samples the transform at , and the inverse DFT of the sampled log magnitude is the aliased sum . The series converges absolutely, because . So the theorem holds for when is larger than twice , which tends to 0 as grows. This is the condition under which the code returns for the model; the test of the implementation checks the closed form of Lemmas 3 and 4 to with .
What the window changes. Line L1 multiplies by a window. The product is not for a new pulse train , so the lemmas do not apply exactly. When the window changes little over the length of , , and is a pulse train with slowly varying amplitudes, whose cepstrum still sits at multiples of . This is an approximation. That the peak stays at for real frames is a measurement, as in the example on the page. Lines L5 to L8 then return for the largest peak in the range, as the page states, and the voicing threshold of line L7 is a heuristic.
Complexity
Lines L1 and L3 cost , lines L2 and L4 are two FFTs of length , and lines L5 to L8 cost . A frame costs operations in the real RAM, and the extra memory is for , and . A track of frames costs . At kHz with Hz, the frame is at least 640 samples and .
Properties
- One frame at a time. The estimate depends only on the frame, so the detector runs on a stream with a delay of one frame. There is no smoothing across frames.
- Scale invariant in the peak. Multiplying by adds to every , which changes only . The peak and the voicing value do not change with the loudness.
- Separates source and filter. The vocal tract response adds to the low quefrencies and the excitation adds peaks at multiples of the period. The same split, kept to the low quefrencies, gives cepstral features such as MFCCs.
- Integer periods. The estimate is for a whole number . At 8 kHz and 150 Hz one sample of period is about 2.8 Hz.
- Not exact in general. The model theorem needs a minimum-phase excitation and a resonance that decays fast. Real speech meets it only roughly.
Variants and improvements
- Interpolated peak. A parabola through , and gives a fractional period, as YIN does for its difference function. A longer FFT does not help, because it only interpolates the spectrum.
- Liftering. Setting outside the pitch range and transforming back gives the smoothed spectral envelope, which serves formant estimation.
- Tracking. A median filter or a dynamic program over the candidate peaks of nearby frames removes isolated octave errors, which is the idea of RAPT and of the hidden Markov model in pYIN.
- Noll's rules. Noll compared the peak with thresholds that he set by experiment, and added rules against octave errors. The exact rules and their values are in the 1967 paper; they are heuristics.
- Clipping and power forms. Noll's squared form, , and the plain give the same period when the peak is positive.
When to use it
Use the cepstral detector when you want a simple frame-by-frame pitch estimate for clean voiced speech with a known pitch range, or when you already compute a cepstrum for other features. It needs no training and only FFTs. For noisy speech, for music, or when a smooth track matters, prefer pYIN or RAPT, which keep several candidates per frame and choose a track over time.
Pitfalls
- Searching the low quefrencies. The resonances give large values near , here . Without the lower limit of line L5 the detector can return a pitch of thousands of Hz.
- A frame that is too short. If the frame holds fewer than two periods, the harmonics are not resolved in the spectrum and there is no pitch peak. Use at least two periods of .
- A range up to M / 2. The cepstrum of a real frame is even, so , and quefrencies above are copies. Keep .
- Taking the log of zero. Zero padding and silence give spectral values of 0. Put a floor under before the log.
- High voices. A high pitch puts few harmonics in the spectrum and makes the peak near the resonance part, so the peak is weak and the detector says unvoiced.
- Integer period bias. For a period of 53.33 samples the estimate is 53 samples. Interpolate when you need better than one sample.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cepstral-pitch-detection/. The authors are listed in prov/AZJ97D.jsonl.
"""Cepstral pitch detection (Noll 1967) on one frame and on a whole signal.
The real cepstrum of a frame x of N samples, with the DFT length M >= N, is
c[q] = (1 / M) sum_{k=0}^{M-1} ln |X[k]| exp(2 pi i k q / M), q = 0 .. M - 1,
where X is the DFT of the windowed frame, zero padded to M. The index q is the
quefrency in samples. For voiced speech, the excitation adds a peak at the pitch
period P, and the vocal tract fills only the low quefrencies. The detector
returns fs / q* for the largest peak q* in [ceil(fs / fmax), floor(fs / fmin)].
Noll used the power spectrum of ln |X|^2, which is the square of 2 c[q] here,
so it has its largest peak at the same quefrency when that peak is positive.
"""
import math
from typing import List, Optional, Sequence, Tuple
from nlsdsp import fft, frames, hamming
def _log_magnitude(spec: Sequence[complex]) -> List[float]:
"""ln |X[k]| with a floor of 1e-12 times the largest magnitude, so that ln 0 never occurs."""
mags = [abs(v) for v in spec]
top = max(mags)
if top == 0.0:
raise ValueError("the frame is all zeros")
floor = 1e-12 * top
return [math.log(max(m, floor)) for m in mags]
def real_cepstrum(frame: Sequence[float], nfft: int, window: bool = True) -> List[float]:
"""The real cepstrum c[0 .. nfft - 1] of the frame, by two FFTs."""
n = len(frame)
if n > nfft:
raise ValueError("the frame is longer than the FFT length")
w = hamming(n) if window else [1.0] * n
y = [w[i] * frame[i] for i in range(n)] + [0.0] * (nfft - n) # @line L1
spec = fft(y) # @line L2
logmag = _log_magnitude(spec) # @line L3
# ln |X| is real and even in k, so the inverse DFT equals the forward DFT divided by nfft
return [v.real / nfft for v in fft(logmag)] # @line L4
def real_cepstrum_direct(frame: Sequence[float], nfft: int, window: bool = True) -> List[float]:
"""The same cepstrum from the definition with O(nfft^2) cosine sums. For tests only."""
n = len(frame)
w = hamming(n) if window else [1.0] * n
y = [w[i] * frame[i] for i in range(n)] + [0.0] * (nfft - n)
spec = []
for k in range(nfft):
re = sum(y[t] * math.cos(2 * math.pi * k * t / nfft) for t in range(nfft))
im = -sum(y[t] * math.sin(2 * math.pi * k * t / nfft) for t in range(nfft))
spec.append(complex(re, im))
logmag = _log_magnitude(spec)
return [sum(logmag[k] * math.cos(2 * math.pi * k * q / nfft) for k in range(nfft)) / nfft for q in range(nfft)]
def quefrency_range(fs: float, fmin: float, fmax: float) -> Tuple[int, int]:
"""The integer quefrencies (in samples) of the pitch periods between fmin and fmax Hz."""
if not 0 < fmin < fmax:
raise ValueError("need 0 < fmin < fmax")
return math.ceil(fs / fmax), math.floor(fs / fmin)
def cepstral_pitch(
frame: Sequence[float],
fs: float,
fmin: float = 50.0,
fmax: float = 500.0,
nfft: Optional[int] = None,
threshold: float = 0.0,
window: bool = True,
) -> Tuple[Optional[float], int, float]:
"""Return (f0 in Hz or None for unvoiced, the peak quefrency q*, the peak value c[q*]).
nfft defaults to the smallest power of 2 that is at least the frame length.
The frame should hold at least two periods of fmin, and floor(fs / fmin) must
be below nfft / 2. The threshold on c[q*] is a heuristic voicing decision.
"""
if nfft is None:
nfft = 1
while nfft < len(frame):
nfft *= 2
c = real_cepstrum(frame, nfft, window)
qmin, qmax = quefrency_range(fs, fmin, fmax) # @line L5
if qmin < 1 or qmax >= nfft // 2:
raise ValueError("the quefrency range does not fit in half the FFT length")
best = qmin
for q in range(qmin, qmax + 1): # @line L6
if c[q] > c[best]:
best = q
if c[best] <= threshold: # @line L7
return None, best, c[best]
return fs / best, best, c[best] # @line L8
def track(
x: Sequence[float],
fs: float,
frame_len: int,
hop: int,
fmin: float = 50.0,
fmax: float = 500.0,
threshold: float = 0.0,
) -> List[Optional[float]]:
"""Run the detector on each frame of x; None marks a frame judged unvoiced."""
return [cepstral_pitch(f, fs, fmin, fmax, None, threshold)[0] for f in frames(x, frame_len, hop)]
def all_pole_cepstrum(a: Sequence[float], count: int) -> List[float]:
"""The complex cepstrum h^[0 .. count - 1] of 1 / A(z), A(z) = 1 - sum a_k z^-k, minimum phase.
h^[0] = 0 and h^[n] = a_n + sum_{k=1}^{n-1} (k / n) h^[k] a_{n-k}, with a_n = 0 for n > p.
It equals sum_i p_i^n / n over the poles p_i. The real cepstrum is h^[n] / 2 for n >= 1.
"""
p = len(a)
h = [0.0] * count
for n in range(1, count):
acc = a[n - 1] if n <= p else 0.0
for k in range(max(1, n - p), n):
acc += (k / n) * h[k] * a[n - k - 1]
h[n] = acc
return h
nlsdsp.py 191 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small signal processing tools for the natural-language-and-speech pages.
A signal is a list of floats x[0], ..., x[L - 1], usually in [-1, 1]. A frame is
a list of floats. A spectrum is a list of floats or complex numbers.
The defaults of the area are fs = 16000 Hz, frames of 400 samples (25 ms), a hop
of 160 samples (10 ms), the symmetric Hamming window and an FFT length of 512.
The LPC sign convention is A(z) = 1 - sum_{k=1}^{p} a_k z^-k, so the prediction
of x[n] is sum_{k=1}^{p} a_k x[n - k].
This module holds no algorithm of any page of the area: no mel scale, no mel
filter bank, no feature extractor, no pre-emphasis and no zero-crossing rate.
The pages build those on top of it.
"""
import cmath
import math
from typing import List, Sequence, Tuple
def frames(x: Sequence[float], frame_len: int, hop: int) -> List[List[float]]:
"""Cut x into frames of frame_len samples, one every hop samples, with no padding.
A signal of L >= frame_len samples gives 1 + (L - frame_len) // hop frames.
A signal shorter than one frame gives no frame. The last samples that do not
fill a frame are dropped.
"""
if frame_len <= 0 or hop <= 0:
raise ValueError("frame_len and hop must be positive")
n = len(x)
if n < frame_len:
return []
count = 1 + (n - frame_len) // hop
return [list(x[i * hop : i * hop + frame_len]) for i in range(count)]
def hamming(n: int) -> List[float]:
"""The symmetric Hamming window w[i] = 0.54 - 0.46 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def hann(n: int) -> List[float]:
"""The symmetric Hann window w[i] = 0.5 - 0.5 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def fft(x: Sequence[complex]) -> List[complex]:
"""The DFT X[k] = sum_n x[n] exp(-2 pi i k n / N) by the iterative radix 2 FFT.
The length N must be a power of 2. The cost is O(N log N) operations.
"""
n = len(x)
if n == 0 or n & (n - 1):
raise ValueError("the FFT length must be a power of 2")
a = [complex(v) for v in x]
# bit reversal permutation
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
w_step = cmath.exp(-2j * math.pi / size)
for start in range(0, n, size):
w = 1.0 + 0.0j
for k in range(start, start + half):
u = a[k]
v = a[k + half] * w
a[k] = u + v
a[k + half] = u - v
w *= w_step
size *= 2
return a
def power_spectrum(frame: Sequence[float], nfft: int) -> List[float]:
"""|X[k]|^2 for k = 0 to nfft / 2, where X is the DFT of the frame zero padded to nfft."""
if len(frame) > nfft:
raise ValueError("the frame is longer than the FFT length")
spec = fft(list(frame) + [0.0] * (nfft - len(frame)))
return [abs(spec[k]) ** 2 for k in range(nfft // 2 + 1)]
def dct2(x: Sequence[float], k: int) -> List[float]:
"""The first k coefficients of the orthonormal DCT-II of x.
c[j] = s_j sum_{n=0}^{N-1} x[n] cos(pi j (2 n + 1) / (2 N)), with s_0 = sqrt(1 / N)
and s_j = sqrt(2 / N) for j >= 1. The full transform (k = N) is an orthogonal matrix.
"""
n = len(x)
if n == 0:
raise ValueError("empty input")
if k < 0 or k > n:
raise ValueError("k must be between 0 and len(x)")
out = []
for j in range(k):
s = math.sqrt((1.0 if j == 0 else 2.0) / n)
out.append(s * sum(x[i] * math.cos(math.pi * j * (2 * i + 1) / (2 * n)) for i in range(n)))
return out
def autocorr(x: Sequence[float], max_lag: int) -> List[float]:
"""r[k] = sum_{n=0}^{L-1-k} x[n] x[n + k] for k = 0 to max_lag (no normalization)."""
n = len(x)
return [sum(x[i] * x[i + k] for i in range(n - k)) if k < n else 0.0 for k in range(max_lag + 1)]
def levinson(r: Sequence[float], p: int) -> Tuple[List[float], float]:
"""Solve the normal equations of linear prediction of order p by the Levinson-Durbin recursion.
Returns (a, e): a = [a_1, ..., a_p] with A(z) = 1 - sum a_k z^-k, and e the
prediction error of order p. Needs r[0] > 0 and len(r) > p. If the error
reaches 0 before order p (a perfectly predictable signal), the remaining
coefficients are 0.
"""
if len(r) <= p:
raise ValueError("need r[0] to r[p]")
if r[0] <= 0:
raise ValueError("r[0] must be positive")
a = [0.0] * (p + 1) # a[0] is unused
e = float(r[0])
for i in range(1, p + 1):
if e <= 0.0:
break
acc = r[i] - sum(a[j] * r[i - j] for j in range(1, i))
k = acc / e
new = a[:]
new[i] = k
for j in range(1, i):
new[j] = a[j] - k * a[i - j]
a = new
e *= 1.0 - k * k
return a[1:], e
def sine(f: float, fs: float, n: int, amp: float = 1.0, phase: float = 0.0) -> List[float]:
"""x[i] = amp sin(2 pi f i / fs + phase) for i = 0 to n - 1."""
return [amp * math.sin(2.0 * math.pi * f * i / fs + phase) for i in range(n)]
def pulse_train(f0: float, fs: float, n: int) -> List[float]:
"""Unit pulses at the samples round(j fs / f0), j = 0, 1, 2, ..., and 0 elsewhere, n samples."""
if f0 <= 0:
raise ValueError("f0 must be positive")
x = [0.0] * n
period = fs / f0
j = 0
while True:
pos = int(math.floor(j * period + 0.5))
if pos >= n:
break
x[pos] = 1.0
j += 1
return x
def white_noise(rng, n: int, sigma: float) -> List[float]:
"""n samples of Gaussian noise with mean 0 and standard deviation sigma, from rng (a random.Random)."""
return [rng.gauss(0.0, sigma) for _ in range(n)]
def all_pole(x: Sequence[float], a: Sequence[float]) -> List[float]:
"""Filter x through 1 / A(z): y[n] = x[n] + sum_{k=1}^{p} a_k y[n - k], with zero initial state."""
p = len(a)
y: List[float] = []
for i, v in enumerate(x):
acc = float(v)
for k in range(1, p + 1):
if i - k < 0:
break
acc += a[k - 1] * y[i - k]
y.append(acc)
return y
test_cepstral_pitch_detection.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cepstral-pitch-detection/. The authors are listed in prov/AZJ97D.jsonl.
import cmath
import math
import random
from cepstral_pitch_detection import (
all_pole_cepstrum,
cepstral_pitch,
quefrency_range,
real_cepstrum,
real_cepstrum_direct,
track,
)
from nlsdsp import all_pole, pulse_train, white_noise
FS = 8000
R = 0.9
THETA = 2 * math.pi * 500 / FS
A = [2 * R * math.cos(THETA), -R * R] # one resonance at 500 Hz with pole radius 0.9
def voiced(f0, n=800):
return all_pole(pulse_train(f0, FS, n), A)
def test_fft_cepstrum_matches_the_definition():
rng = random.Random(1)
frame = [rng.uniform(-1, 1) for _ in range(40)]
fast = real_cepstrum(frame, 64)
slow = real_cepstrum_direct(frame, 64)
assert max(abs(u - v) for u, v in zip(fast, slow)) < 1e-9
def test_cepstrum_is_even():
rng = random.Random(2)
frame = [rng.uniform(-1, 1) for _ in range(100)]
c = real_cepstrum(frame, 128)
for q in range(1, 64):
assert abs(c[q] - c[128 - q]) < 1e-9
def test_all_pole_cepstrum_recursion_matches_the_poles():
poles = [R * cmath.exp(1j * THETA), R * cmath.exp(-1j * THETA)]
h = all_pole_cepstrum(A, 30)
assert h[0] == 0.0
for n in range(1, 30):
assert abs(h[n] - sum(p ** n for p in poles).real / n) < 1e-12
def test_model_signal_has_the_closed_form_cepstrum():
# x = h * p, with p a train of 6 pulses of period 50 and amplitudes 0.8^j, no window.
beta, period, count, m = 0.8, 50, 6, 4096
p = [0.0] * m
for j in range(count):
p[j * period] = beta ** j
c = real_cepstrum(all_pole(p, A), m, window=False)
h = all_pole_cepstrum(A, 2 * period + 1)
assert abs(c[3] - h[3] / 2) < 1e-9
assert abs(c[period] - (h[period] + beta) / 2) < 1e-9
assert abs(c[2 * period] - (h[2 * period] + beta ** 2 / 2) / 2) < 1e-9
assert abs(c[period + 7] - h[period + 7] / 2) < 1e-9
def test_integer_periods_are_found_exactly():
for f0 in (100, 125, 160, 200):
x = voiced(f0)
est, q, _ = cepstral_pitch(x[100:500], FS, 60, 400, 512)
assert q == FS // f0
assert est == f0
def test_the_peak_is_the_brute_force_argmax_in_the_range():
x = voiced(160)
c = real_cepstrum(x[100:500], 512)
qmin, qmax = quefrency_range(FS, 60, 400)
assert (qmin, qmax) == (20, 133)
best = max(range(qmin, qmax + 1), key=lambda q: (c[q], -q))
assert cepstral_pitch(x[100:500], FS, 60, 400, 512)[1] == best
def test_example_values():
x = voiced(160)
c = real_cepstrum(x[100:500], 512)
assert abs(c[50] - 1.2539) < 1e-4
assert abs(c[100] - 0.4304) < 1e-4
assert abs(c[1] - 0.8079) < 1e-4
def test_fractional_period_is_within_one_sample():
x = voiced(150) # period 53.33 samples
est, q, _ = cepstral_pitch(x[100:500], FS, 60, 400, 512)
assert q in (53, 54)
assert abs(FS / est - FS / 150) < 1
def test_noise_is_unvoiced_and_the_track_follows_the_voicing():
rng = random.Random(7)
noise = white_noise(rng, 800, 0.5)
assert cepstral_pitch(noise[:400], FS, 60, 400, 512, threshold=0.3)[0] is None
x = voiced(125) + noise
out = track(x, FS, 400, 400, 60, 400, threshold=0.3)
assert out == [125.0, 125.0, None, None]
History
Bogert, Healy and Tukey named the cepstrum in 1963 in work on echoes in seismic signals. A. Michael Noll, at Bell Telephone Laboratories, applied it to the pitch of speech in a short paper in 1964 and in a full paper in the Journal of the Acoustical Society of America in 1967. His detector took the power spectrum of the log power spectrum of short frames, picked the largest peak with rules found by experiment, and drove a channel vocoder. Oppenheim and Schafer gave the theory of homomorphic deconvolution at the same time, and Rabiner and Schafer made the cepstral detector a standard method in their 1978 book.
References
- A. Michael Noll, Cepstrum pitch determination, Journal of the Acoustical Society of America 41(2), 1967, 293 to 309, the definition of the cepstrum as the power spectrum of the logarithm of the power spectrum, and the description of the pitch detector and its decision rules (section numbers not confirmed)
- Short-time spectrum and cepstrum techniques for vocal-pitch detection, the whole paper, the first report of the method
- L. R. Rabiner and R. W. Schafer, Digital Processing of Speech Signals, Prentice Hall, 1978, Chapter 7 (homomorphic speech processing), the part on pitch detection with the cepstrum
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AZJ97D Edit this page History Report an error Markdown