Algorithm Search⌘K

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.

Time
O(M log M) worst
Space
O(M) extra
Where
M = the FFT length, a power of two at least the frame length
Properties
deterministicnot exactnot in placeonline
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, O(Mlog⁡M)O(M \log M) operations for an FFT length MM.

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 x[0…N−1]x[0 \ldots N-1] of a speech signal at a sample rate fsf_s Hz, and a search range fmin⁡≤F0≤fmax⁡f_{\min} \le F_0 \le f_{\max} (for example 50 to 500 Hz), decide whether the frame is voiced, and if it is, estimate its fundamental frequency F0F_0 in Hz. The frame should hold at least two periods of fmin⁡f_{\min}, so 40 ms or more for fmin⁡=50f_{\min} = 50 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 M≥NM \ge N, a power of two, the real cepstrum of the windowed and zero padded frame yy is

c[q]=1M∑k=0M−1ln⁡∣Y[k]∣ e2πikq/M,Y[k]=∑n=0M−1y[n] e−2πikn/M.c[q] = \frac{1}{M} \sum_{k=0}^{M-1} \ln |Y[k]|\, e^{2\pi i k q / M}, \qquad Y[k] = \sum_{n=0}^{M-1} y[n]\, e^{-2\pi i k n / M}.

The index qq is the quefrency in samples. A pitch period of PP samples belongs to the frequency fs/Pf_s / P.

  1. CEPSTRAL-PITCH(x, fs, fmin, fmax, M, θ) ▷ x is a frame of N ≤ M samples
  2. 1y[n] ← w[n] x[n] for n < N, and y[n] ← 0 for N ≤ n < M ▷ w is the Hamming window
  3. 2Y ← the DFT of y, by the FFT
  4. 3L[k] ← ln |Y[k]| for 0 ≤ k < M, with a small floor so that ln 0 never occurs
  5. 4c ← the inverse DFT of L, by the FFT ▷ the real cepstrum
  6. 5q_min ← ⌈fs / fmax⌉; q_max ← ⌊fs / fmin⌋
  7. 6q* ← the q in [q_min, q_max] with the largest c[q], the smallest such q on ties
  8. 7if c[q*] ≤ θ then return unvoiced
  9. 8return fs / q*

Lines L1 to L4 compute the real cepstrum. Since yy is real, ∣Y[k]∣=∣Y[M−k]∣|Y[k]| = |Y[M-k]|, so LL is real and even, and its inverse DFT is real and equals its forward DFT divided by MM; the code uses the same FFT twice. Line L5 turns the frequency range into a range of periods, which must stay below M/2M / 2. Line L6 is the peak search. Line L7 is the voicing decision with a threshold θ\theta; its value is a heuristic, set on labeled speech, and this page does not take one from Noll. The floor in line L3 is 10−1210^{-12} times the largest magnitude.

Noll took the power spectrum of the log power spectrum, so his cepstrum is (2c[q])2(2 c[q])^2 in the notation here, up to a constant. Its largest peak is at the same quefrency whenever that peak of cc is positive, so the two forms pick the same period.

Example

Take fs=8000f_s = 8000 Hz and one resonance at 500 Hz with pole radius r=0.9r = 0.9, so the bandwidth is −(fs/π)ln⁡r=268.3-(f_s / \pi) \ln r = 268.3 Hz. In the sign convention A(z)=1−a1z−1−a2z−2A(z) = 1 - a_1 z^{-1} - a_2 z^{-2} the coefficients are a1=2rcos⁡(2π⋅500/8000)=1.662983a_1 = 2r \cos(2\pi \cdot 500 / 8000) = 1.662983 and a2=−r2=−0.81a_2 = -r^2 = -0.81. A pulse train at F0=160F_0 = 160 Hz, one pulse every 50 samples, passes through 1/A(z)1 / A(z). The frame is the 400 samples (50 ms) from sample 100 on, with a Hamming window and M=512M = 512. The search range 60 to 400 Hz gives qmin⁡=20q_{\min} = 20 and qmax⁡=133q_{\max} = 133.

qq 1 2 3 20 49 50 51 62 100 133
c[q]c[q] 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 c[50]=1.2539c[50] = 1.2539 and then the second rahmonic c[100]=0.4304c[100] = 0.4304, so line L6 gives q∗=50q^* = 50 and line L8 returns 8000/50=1608000 / 50 = 160 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 q∗=53q^* = 53, 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 0,50,…,2500, 50, \ldots, 250 with the amplitudes 0.8j0.8^j, filter them by the same 1/A(z)1 / A(z), and take the cepstrum with no window and M=4096M = 4096. The filter alone has the cepstrum h^[n]=(pn+pˉn)/n\hat h[n] = (p^n + \bar p^n) / n for its poles pp and pˉ\bar p, which gives h^[1]=1.6630\hat h[1] = 1.6630, h^[2]=0.5728\hat h[2] = 0.5728 and h^[3]=0.1860\hat h[3] = 0.1860. The computed values are c[3]=0.09299=h^[3]/2c[3] = 0.09299 = \hat h[3] / 2, c[50]=0.40007=(h^[50]+0.8)/2c[50] = 0.40007 = (\hat h[50] + 0.8) / 2 and c[100]=0.16000=(h^[100]+0.82/2)/2c[100] = 0.16000 = (\hat h[100] + 0.8^2 / 2) / 2, 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 ln⁡∣Y∣\ln |Y| is real and even, so its inverse DFT is real and is the forward DFT divided by MM.

For the model, let hh be the impulse response of an all-pole filter 1/A(z)1 / A(z) with all poles pip_i inside the unit circle, and let e[n]=∑j=0K−1βjδ[n−jP]e[n] = \sum_{j=0}^{K-1} \beta^j \delta[n - jP] be KK pulses of period PP with 0<β<10 < \beta < 1. The signal is x=h∗ex = h * e, with no window. The log of the transform of a convolution is the sum of the logs, so the complex cepstrum is x^=h^+e^\hat x = \hat h + \hat e. Expanding the logarithms in power series gives h^[n]=∑ipin/n\hat h[n] = \sum_i p_i^n / n for n≥1n \ge 1, and e^\hat e is 0 except at the multiples of PP, where e^[jP]=βj/j\hat e[jP] = \beta^j / j, minus βjK/j\beta^j K / j when KK divides jj. Both are causal, because both factors are minimum phase, so the real cepstrum is c[n]=x^[n]/2c[n] = \hat x[n] / 2 for n≥1n \ge 1.

Theorem. Let K≥2K \ge 2 and ρ=max⁡∣h^[n]∣\rho = \max |\hat h[n]| over the range qmin⁡≤n≤qmax⁡q_{\min} \le n \le q_{\max}, which holds PP. If β−β2/2>2ρ\beta - \beta^2 / 2 > 2\rho, the cepstrum of the model signal, without aliasing, has its unique largest value in the range at n=Pn = P.

The reason is that c[P]≥(β−ρ)/2c[P] \ge (\beta - \rho) / 2, while every other nn in the range has c[n]≤(ρ+β2/2)/2c[n] \le (\rho + \beta^2 / 2) / 2, since e^[jP]≤βj/j≤β2/2\hat e[jP] \le \beta^j / j \le \beta^2 / 2 for j≥2j \ge 2. The bound ρ≤∑i∣pi∣qmin⁡/qmin⁡\rho \le \sum_i |p_i|^{q_{\min}} / q_{\min} shows that the filter part dies out fast: the vocal tract lives at low quefrency. With a finite MM the DFT cepstrum is the aliased sum ∑lc[q+lM]\sum_l c[q + lM], 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 xx 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 yy be real of length MM, YY its DFT and L[k]=ln⁡∣Y[k]∣L[k] = \ln |Y[k]|. Then the inverse DFT c[q]=1M∑kL[k]e2πikq/Mc[q] = \frac{1}{M} \sum_k L[k] e^{2\pi i k q / M} is real, c[q]=c[M−q]c[q] = c[M - q], and c[q]=1M∑kL[k]e−2πikq/Mc[q] = \frac{1}{M} \sum_k L[k] e^{-2\pi i k q / M}.

Proof. Since yy is real, Y[M−k]=Y[k]‾Y[M - k] = \overline{Y[k]}, so L[M−k]=L[k]L[M - k] = L[k] (indices mod MM). Substitute k→M−kk \to M - k in the sum for c[q]c[q]: the sum becomes 1M∑kL[k]e−2πikq/M\frac{1}{M} \sum_k L[k] e^{-2\pi i k q / M}, which is the forward DFT of LL divided by MM, and also the complex conjugate of the original sum because LL is real. A number equal to its conjugate is real. The same substitution with q→M−qq \to M - q gives c[M−q]=c[q]c[M - q] = c[q]. □\square

So line L4, which applies the forward FFT to LL and divides by MM, computes cc, and lines L5 and L6 need only q<M/2q < M / 2.

The model. Let A(z)=∏i=1p(1−piz−1)A(z) = \prod_{i=1}^{p} (1 - p_i z^{-1}) with every ∣pi∣<1|p_i| < 1, let hh be the impulse response of 1/A(z)1 / A(z), and let

e[n]=∑j=0K−1βjδ[n−jP],0<β<1,  P≥1,  K≥1.e[n] = \sum_{j=0}^{K-1} \beta^j \delta[n - jP], \qquad 0 < \beta < 1, \; P \ge 1, \; K \ge 1.

The signal is x=h∗ex = h * e. We use the transforms on the unit circle, X(ω)=H(ω)E(ω)X(\omega) = H(\omega) E(\omega), and the complex cepstrum x^[n]=12π∫−ππlog⁡X(ω) eiωn dω\hat x[n] = \frac{1}{2\pi} \int_{-\pi}^{\pi} \log X(\omega)\, e^{i \omega n}\, d\omega with the continuous branch of the logarithm that is 0 at z=∞z = \infty. The real cepstrum is c[n]=12π∫ln⁡∣X(ω)∣ eiωn dω=(x^[n]+x^[−n])/2c[n] = \frac{1}{2\pi} \int \ln |X(\omega)|\, e^{i\omega n}\, d\omega = (\hat x[n] + \hat x[-n]) / 2, because ln⁡∣X∣=Re⁡log⁡X\ln |X| = \operatorname{Re} \log X.

Lemma 2 (convolution adds cepstra). x^=h^+e^\hat x = \hat h + \hat e and cx=ch+cec_x = c_h + c_e.

Proof. log⁡(HE)=log⁡H+log⁡E\log (H E) = \log H + \log E for the continuous branches, and ln⁡∣HE∣=ln⁡∣H∣+ln⁡∣E∣\ln |HE| = \ln |H| + \ln |E|. The inverse transform is linear. □\square

Lemma 3 (the all-pole part). h^[0]=0\hat h[0] = 0, h^[n]=∑ipin/n\hat h[n] = \sum_i p_i^n / n for n≥1n \ge 1 and h^[n]=0\hat h[n] = 0 for n<0n < 0. The coefficients of A(z)=1−∑kakz−kA(z) = 1 - \sum_k a_k z^{-k} give the same values by h^[n]=an+∑k=1n−1(k/n) h^[k] an−k\hat h[n] = a_n + \sum_{k=1}^{n-1} (k / n)\, \hat h[k]\, a_{n-k}, with an=0a_n = 0 for n>pn > p.

Proof. For ∣z∣≥1>∣pi∣|z| \ge 1 > |p_i|, −log⁡(1−piz−1)=∑n≥1pinz−n/n-\log(1 - p_i z^{-1}) = \sum_{n \ge 1} p_i^n z^{-n} / n, a convergent power series in z−1z^{-1}. Summing over ii gives log⁡H(z)=∑n≥1(∑ipin/n)z−n\log H(z) = \sum_{n \ge 1} (\sum_i p_i^n / n) z^{-n}, and the coefficients of this Laurent series are the complex cepstrum. For the recursion, differentiate log⁡H=−log⁡A\log H = -\log A: z H′(z)/H(z)=−zA′(z)/A(z)z\, H'(z) / H(z) = -z A'(z) / A(z), so A(z)⋅∑nnh^[n]z−n=∑kkakz−kA(z) \cdot \sum_n n \hat h[n] z^{-n} = \sum_k k a_k z^{-k}. Comparing the coefficients of z−nz^{-n} gives nh^[n]−∑k=1n−1an−k kh^[k]=nann \hat h[n] - \sum_{k=1}^{n-1} a_{n-k}\, k \hat h[k] = n a_n, which is the recursion. □\square

Lemma 4 (the pulse part). e^[n]=0\hat e[n] = 0 unless n=jPn = jP with j≥1j \ge 1, and

e^[jP]=βjj−[K∣j] Kβjj.\hat e[jP] = \frac{\beta^j}{j} - [K \mid j]\, \frac{K \beta^j}{j}.

Proof. E(z)=∑j=0K−1βjz−jP=1−βKz−KP1−βz−PE(z) = \sum_{j=0}^{K-1} \beta^j z^{-jP} = \dfrac{1 - \beta^K z^{-KP}}{1 - \beta z^{-P}}. Both factors have their zeros at ∣z∣<1|z| < 1. For ∣z∣≥1|z| \ge 1, −log⁡(1−βz−P)=∑j≥1βjz−jP/j-\log(1 - \beta z^{-P}) = \sum_{j \ge 1} \beta^j z^{-jP} / j and log⁡(1−βKz−KP)=−∑m≥1βKmz−mKP/m\log(1 - \beta^K z^{-KP}) = -\sum_{m \ge 1} \beta^{Km} z^{-mKP} / m. Writing j=mKj = mK in the second sum, its coefficient of z−jPz^{-jP} is −βj/(j/K)=−Kβj/j-\beta^j / (j / K) = -K \beta^j / j. □\square

By Lemmas 2 to 4, x^\hat x is 0 at negative indices, so c[n]=x^[n]/2c[n] = \hat x[n] / 2 for n≥1n \ge 1:

c[n]=12h^[n]+12e^[n].c[n] = \tfrac12 \hat h[n] + \tfrac12 \hat e[n].

Theorem. Let K≥2K \ge 2 and 1≤qmin⁡≤P≤qmax⁡1 \le q_{\min} \le P \le q_{\max}, and let ρ=max⁡qmin⁡≤n≤qmax⁡∣h^[n]∣\rho = \max_{q_{\min} \le n \le q_{\max}} |\hat h[n]|. If β−β2/2>2ρ\beta - \beta^2 / 2 > 2\rho, then over qmin⁡≤n≤qmax⁡q_{\min} \le n \le q_{\max} the real cepstrum of the model signal has its unique maximum at n=Pn = P.

Proof. At n=Pn = P we have j=1j = 1, and K≥2K \ge 2 does not divide 1, so e^[P]=β\hat e[P] = \beta and c[P]≥(β−ρ)/2c[P] \ge (\beta - \rho) / 2. (With K=1K = 1 there is one pulse and no period: e^[P]=0\hat e[P] = 0.) At any other nn in the range, either e^[n]=0\hat e[n] = 0, or n=jPn = jP with j≥2j \ge 2 and e^[n]≤βj/j≤β2/2\hat e[n] \le \beta^j / j \le \beta^2 / 2, since βj/j\beta^j / j decreases in jj for 0<β<10 < \beta < 1. So c[n]≤(ρ+β2/2)/2c[n] \le (\rho + \beta^2 / 2) / 2. The condition gives (β−ρ)/2>(ρ+β2/2)/2(\beta - \rho) / 2 > (\rho + \beta^2 / 2) / 2. □\square

The value ρ\rho is small when the poles are not close to the unit circle: by Lemma 3, ∣h^[n]∣≤∑i∣pi∣n/n≤∑i∣pi∣qmin⁡/qmin⁡|\hat h[n]| \le \sum_i |p_i|^n / n \le \sum_i |p_i|^{q_{\min}} / q_{\min} for n≥qmin⁡n \ge q_{\min}. For one pole pair of radius 0.90.9 and qmin⁡=20q_{\min} = 20 the bound is 2⋅0.920/20=0.01222 \cdot 0.9^{20} / 20 = 0.0122, so any β≥0.05\beta \ge 0.05 satisfies the condition.

Finite FFT length. The DFT of length MM samples the transform at ω=2πk/M\omega = 2\pi k / M, and the inverse DFT of the sampled log magnitude is the aliased sum cM[q]=∑lc[q+lM]c_M[q] = \sum_{l} c[q + lM]. The series converges absolutely, because ∣c[n]∣≤(∑i∣pi∣∣n∣+Kβ∣n∣/P)/(2∣n∣)|c[n]| \le (\sum_i |p_i|^{|n|} + K \beta^{|n| / P}) / (2|n|). So the theorem holds for cMc_M when β−β2/2−2ρ\beta - \beta^2/2 - 2\rho is larger than twice max⁡q∣cM[q]−c[q]∣\max_q |c_M[q] - c[q]|, which tends to 0 as MM grows. This is the condition under which the code returns q∗=Pq^* = P for the model; the test of the implementation checks the closed form of Lemmas 3 and 4 to 10−910^{-9} with M=4096M = 4096.

What the window changes. Line L1 multiplies xx by a window. The product is not h∗e′h * e' for a new pulse train e′e', so the lemmas do not apply exactly. When the window changes little over the length of hh, w⋅(h∗e)≈h∗(w⋅e)w \cdot (h * e) \approx h * (w \cdot e), and w⋅ew \cdot e is a pulse train with slowly varying amplitudes, whose cepstrum still sits at multiples of PP. This is an approximation. That the peak stays at PP for real frames is a measurement, as in the example on the page. Lines L5 to L8 then return fs/q∗f_s / q^* 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 O(M)O(M), lines L2 and L4 are two FFTs of length MM, and lines L5 to L8 cost O(qmax⁡−qmin⁡)⊆O(M)O(q_{\max} - q_{\min}) \subseteq O(M). A frame costs O(Mlog⁡M)O(M \log M) operations in the real RAM, and the extra memory is O(M)O(M) for YY, LL and cc. A track of TT frames costs O(TMlog⁡M)O(T M \log M). At fs=16f_s = 16 kHz with fmin⁡=50f_{\min} = 50 Hz, the frame is at least 640 samples and M=1024M = 1024.

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 xx by g>0g > 0 adds ln⁡g\ln g to every L[k]L[k], which changes only c[0]c[0]. 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 fs/q∗f_s / q^* for a whole number q∗q^*. 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 c[q∗−1]c[q^* - 1], c[q∗]c[q^*] and c[q∗+1]c[q^* + 1] 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 c[q]=0c[q] = 0 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, (2c)2(2c)^2, and the plain cc 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 q=1q = 1, here c[1]=0.8079c[1] = 0.8079. 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 fmin⁡f_{\min}.
  • A range up to M / 2. The cepstrum of a real frame is even, so c[q]=c[M−q]c[q] = c[M - q], and quefrencies above M/2M / 2 are copies. Keep qmax⁡<M/2q_{\max} < M / 2.
  • Taking the log of zero. Zero padding and silence give spectral values of 0. Put a floor under ∣Y[k]∣|Y[k]| 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.

cepstral_pitch_detection.pyI0RawGitHub
# 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

  1. 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)
  2. Short-time spectrum and cepstrum techniques for vocal-pitch detection, the whole paper, the first report of the method
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example