Algorithm Search⌘K

Algorithmcore

Code-excited linear prediction

Also called CELP.

Speech coding by an LPC synthesis filter driven by an excitation chosen from codebooks to minimize perceptually weighted error.

Time
O(S (Q + C) L^2 + S L p) worst
Space
O(C L + Q) extra
Where
C = the size of the fixed codebook; L = the subframe length; Q = the number of pitch lags; S = the number of subframes; p = the LPC order
Properties
deterministicnot exactnot in placeonline
Origin
Manfred R. Schroeder, Bishnu S. Atal, 1985

Code-excited linear prediction, CELP, is a method of speech coding in which the decoder passes an excitation through an all-pole synthesis filter 1/A(z)1/A(z), and the encoder chooses that excitation from codebooks by trying every entry and keeping the one whose synthesized output is closest to the input under a perceptual weighting. The filter comes from linear predictive coding, as in the older LPC vocoder, but the LPC vocoder drives it with pulses or noise and sends only a voicing flag and a pitch. CELP sends the index of a code vector, which makes it vector quantization of the excitation, with the error measured after the filter instead of on the vector itself.

In plain words

Speech is a buzz or a hiss shaped by the mouth. A CELP coder sends the shape of the mouth, a few numbers every 20 ms, and a description of the buzz. To describe the buzz, both sides keep the same book of short noise patterns. For each piece of 5 ms, the coder tries every pattern in the book: it plays each one through the mouth filter and compares the result with the real speech. It sends the number of the pattern that sounds closest and a loudness. It also tries copies of the buzz it sent a little earlier, because voiced speech repeats at the pitch. The receiver looks up the same pattern and plays it through the same filter. The comparison ignores errors that the ear does not hear well, near the loud parts of the spectrum.

The problem

Given speech sampled at fsf_s (8 kHz for telephone speech), send it at a low bit rate, such as 4.8 to 16 kbit/s, so that the decoded speech sounds as close to the input as possible. The quality is measured by listeners with the mean opinion score or by objective measures. The encoder may look at the whole input; the decoder has only the bits.

The algorithm

Speech is cut into frames of NN samples (20 ms) and each frame into subframes of LL samples (5 ms). For each frame the encoder computes LPC coefficients a1,…,apa_1, \ldots, a_p with A(z)=1−∑kakz−kA(z) = 1 - \sum_k a_k z^{-k}, by the autocorrelation method and the Levinson-Durbin recursion. The perceptual weighting filter is

W(z)=A(z/γ1)A(z/γ2),0<γ2<γ1≤1,W(z) = \frac{A(z/\gamma_1)}{A(z/\gamma_2)}, \qquad 0 < \gamma_2 < \gamma_1 \le 1,

for example γ1=0.9\gamma_1 = 0.9 and γ2=0.6\gamma_2 = 0.6. It lowers the weight of the error near the formants, where the loud speech masks it, and raises it between them. The values of γ\gamma are a heuristic choice.

For each subframe, the excitation is e=gavT+gfcke = g_a v_T + g_f c_k, where vTv_T is the past excitation delayed by TT samples (the adaptive codebook, which models the pitch) and ckc_k is entry kk of a fixed codebook. The weighted error is W(z)(s−s^)W(z)(s - \hat s) with s^=e/A(z)\hat s = e / A(z). It is affine in ee:

ew=t−He,e_w = t - H e,

where tt is the weighted error when e=0e = 0, which the filter states from the past subframes still produce, and HH is the lower triangular matrix of the zero-state impulse response hh of W(z)/A(z)W(z)/A(z). For one vector y=Hcy = H c the best gain is g=⟨t,y⟩/⟨y,y⟩g = \langle t, y \rangle / \langle y, y \rangle, and the error energy falls from ∥t∥2\|t\|^2 to

∥t∥2−⟨t,y⟩2⟨y,y⟩.\|t\|^2 - \frac{\langle t, y \rangle^2}{\langle y, y \rangle}.

So the search picks the vector with the largest ⟨t,y⟩2/⟨y,y⟩\langle t, y \rangle^2 / \langle y, y \rangle. The two codebooks are searched one after the other.

  1. CELP-ENCODE(s, fixed codebook c_1 .. c_C, lags T_1 .. T_Q)
  2. 1for each frame: a <- LPC of the frame; W(z) <- A(z/gamma1) / A(z/gamma2)
  3. 2h <- the first L samples of the impulse response of W(z) / A(z)
  4. 3for each subframe: t <- the weighted error with zero excitation, from the current filter states
  5. 4for each lag T: y_T <- h * v_T; pick T with the largest <t, y_T>^2 / <y_T, y_T>; g_a <- <t, y_T> / <y_T, y_T>
  6. 5t <- t - g_a y_T
  7. 6for each k: y_k <- h * c_k; pick k with the largest <t, y_k>^2 / <y_k, y_k>; g_f <- <t, y_k> / <y_k, y_k>
  8. 7e <- g_a v_T + g_f c_k; run the filters on e; append e to the past excitation
  9. 8send (a, T, g_a, k, g_f), quantized

The decoder builds the same ee from the received values and passes it through 1/A(z)1/A(z). The encoder contains this decoder, in line L7, so both keep the same filter states and the same past excitation. Real coders quantize aa (usually as line spectral pairs) and the gains, and add a postfilter after the decoder; the code on this page does not quantize.

Example

One search. Take a subframe of L=4L = 4 with target t=(1,0.5,−0.25,0)t = (1, 0.5, -0.25, 0), so ∥t∥2=1.3125\|t\|^2 = 1.3125, impulse response h=(1,0.5,0.25,0.125)h = (1, 0.5, 0.25, 0.125), and a codebook of four vectors:

kk ckc_k yk=h∗cky_k = h * c_k ⟨t,yk⟩\langle t, y_k \rangle ⟨yk,yk⟩\langle y_k, y_k \rangle score gain
0 (1, 0, 0, 0) (1, 0.5, 0.25, 0.125) 1.1875 1.328125 1.0618 0.8941
1 (0, 1, 0, 0) (0, 1, 0.5, 0.25) 0.375 1.3125 0.1071 0.2857
2 (1, -1, 0, 0) (1, -0.5, -0.25, -0.125) 0.8125 1.328125 0.4971 0.6118
3 (0.5, 0.5, 0.5, 0.5) (0.5, 0.75, 0.875, 0.9375) 0.65625 2.45703 0.1753 0.2671

The encoder sends k=0k = 0 with gain 0.8941, and the weighted error energy falls from 1.3125 to 1.3125−1.0618=0.25071.3125 - 1.0618 = 0.2507. After the filter, vector 2 matches the first sample of tt as well as vector 0 does, but its second sample has the wrong sign, so it fits worse. The search compares the outputs of the filter, not the code vectors.

A vowel. A pulse train at 125 Hz with a little noise, through a resonance at 500 Hz, at 8 kHz, coded with LPC order 10, frames of 160 and subframes of 40 samples, a Gaussian codebook of 128 vectors and lags 20 to 147, gives a signal to noise ratio of 9.9 dB without quantization. Most subframes choose the lag 64, the period, or 128, twice the period. With the adaptive codebook off, the ratio is 4.2 dB. Both numbers are measurements on this one signal.

Correctness

CELP is a lossy coder, so correctness means that each step does what it claims; the proofs are in proofs/correctness.md. The weighted error is affine in the excitation, ew=t−Hee_w = t - He, because the filters are linear and their states from the past act as a fixed input. For a fixed vector y≠0y \ne 0, the error ∥t−gy∥2\|t - g y\|^2 is a quadratic in gg with its least value ∥t∥2−⟨t,y⟩2/⟨y,y⟩\|t\|^2 - \langle t, y \rangle^2 / \langle y, y \rangle at g=⟨t,y⟩/⟨y,y⟩g = \langle t, y \rangle / \langle y, y \rangle, so picking the largest score picks the least error over all vectors and gains. This is a theorem, and the tests compare it with a brute force search. The search of the two codebooks one after the other is not jointly optimal: a search over all pairs with both gains solved together can only be better. Since the encoder runs the decoder, the decoded output is exactly the s^\hat s that the encoder measured. If the true excitation is a gain times a code vector and AA is known, the search finds it with zero error.

That this error measure predicts what listeners hear is a heuristic, supported by listening tests.

Proof: Correctness of the CELP codebook searchfull

CELP is a lossy coder, so we prove the claims each step makes: the weighted error is affine in the excitation, the score picks the vector and gain of least weighted error, the sequential search is bounded by the joint search, the decoder reproduces the encoder's output, and an excitation that is in the codebook is found exactly.

Setup

In one subframe of LL samples, let ss be the input, ee the excitation, s^\hat s the output of the synthesis filter 1/A(z)1/A(z) from its current state, and ewe_w the output of the weighting filter W(z)=A(z/γ1)/A(z/γ2)W(z) = A(z/\gamma_1)/A(z/\gamma_2) applied to s−s^s - \hat s from its current state. All three filters are linear, causal and time-invariant within the subframe.

Lemma 1 (the weighted error is affine)

Let tt be ewe_w when e=0e = 0, and let hh be the first LL samples of the zero-state impulse response of W(z)/A(z)W(z)/A(z), with HH the L×LL \times L lower triangular matrix Hn,j=h[n−j]H_{n,j} = h[n - j] for j≤nj \le n. Then for every ee,

ew(e)=t−He.e_w(e) = t - H e .

Proof. A linear filter that starts from a state σ\sigma and gets an input uu produces the sum of its zero-input response to σ\sigma and its zero-state response to uu. Apply this to the synthesis filter: s^(e)=s^(0)+Ge\hat s(e) = \hat s(0) + G e, where GG is the zero-state response matrix of 1/A(z)1/A(z). So s−s^(e)=(s−s^(0))−Ges - \hat s(e) = (s - \hat s(0)) - G e. Apply it again to the weighting filter, whose state is the same in both cases: ew(e)=ew(0)−KGee_w(e) = e_w(0) - K G e, where KK is the zero-state matrix of W(z)W(z). The product KGKG of two lower triangular Toeplitz matrices is the zero-state matrix of the cascade W(z)/A(z)W(z)/A(z), whose first column is hh. So KG=HKG = H and ew(0)=te_w(0) = t. □\square

The test of the code checks this identity on random states, inputs and excitations.

Lemma 2 (the best gain for one vector)

For t,y∈RLt, y \in \mathbb{R}^L with y≠0y \ne 0,

min⁡g∈R∥t−gy∥2=∥t∥2−⟨t,y⟩2⟨y,y⟩,\min_{g \in \mathbb{R}} \|t - g y\|^2 = \|t\|^2 - \frac{\langle t, y \rangle^2}{\langle y, y \rangle},

attained only at g∗=⟨t,y⟩/⟨y,y⟩g^* = \langle t, y \rangle / \langle y, y \rangle.

Proof. ∥t−gy∥2=∥t∥2−2g⟨t,y⟩+g2⟨y,y⟩\|t - g y\|^2 = \|t\|^2 - 2g \langle t, y \rangle + g^2 \langle y, y \rangle is a quadratic in gg with positive leading coefficient ⟨y,y⟩\langle y, y \rangle, so its unique minimum is where the derivative −2⟨t,y⟩+2g⟨y,y⟩-2\langle t, y \rangle + 2g \langle y, y \rangle is 0, at g∗g^*. Substituting gives the value. □\square

Theorem 1 (the search is exact)

Let yk=Hcky_k = H c_k for k=1,…,Nk = 1, \ldots, N. The function search returns k∗k^* and g∗g^* with

∥t−g∗yk∗∥2=min⁡kmin⁡g∥t−gyk∥2,\|t - g^* y_{k^*}\|^2 = \min_{k} \min_{g} \|t - g y_k\|^2,

over all kk with yk≠0y_k \ne 0, together with this least error.

Proof. By Lemma 2, min⁡g∥t−gyk∥2=∥t∥2−σk\min_g \|t - g y_k\|^2 = \|t\|^2 - \sigma_k with the score σk=⟨t,yk⟩2/⟨yk,yk⟩\sigma_k = \langle t, y_k \rangle^2 / \langle y_k, y_k \rangle. The minimum over kk of ∥t∥2−σk\|t\|^2 - \sigma_k is attained at a kk of largest σk\sigma_k, which is the kk the loop keeps (the first one, on ties). The gain it returns is ⟨t,yk∗⟩/⟨yk∗,yk∗⟩\langle t, y_{k^*} \rangle / \langle y_{k^*}, y_{k^*} \rangle, which attains the minimum by Lemma 2, and the error it returns is ∥t∥2−σk∗\|t\|^2 - \sigma_{k^*}. □\square

By Lemma 1, the vector yk=Hcky_k = H c_k is exactly the change in the weighted error caused by the excitation ckc_k, so Theorem 1 is a statement about the weighted error of the coded speech: among single vectors of the codebook with free gain, the chosen one leaves the least weighted error in this subframe.

Let the adaptive search choose TT and gag_a by Theorem 1 on tt, and the fixed search choose kk and gfg_f by Theorem 1 on t′=t−gayTt' = t - g_a y_T. Then the joint optimum

Ejoint=min⁡T′,k′,g1,g2∥t−g1yT′−g2yk′∥2E_{\text{joint}} = \min_{T', k', g_1, g_2} \|t - g_1 y_{T'} - g_2 y_{k'}\|^2

is at most the sequential error Eseq=∥t′−gfyk∥2E_{\text{seq}} = \|t' - g_f y_k\|^2.

Proof. The sequential choice (T,k,ga,gf)(T, k, g_a, g_f) is one of the choices over which the joint minimum is taken, and Eseq=∥t−gayT−gfyk∥2E_{\text{seq}} = \|t - g_a y_T - g_f y_k\|^2. □\square

The inequality can be strict, so the sequential search is a heuristic for the joint problem. It is used because it costs Q+CQ + C filterings, for QQ lags and CC code vectors, instead of QCQ C pairs.

Theorem 3 (the decoder reproduces the encoder)

If the decoder gets the same aa, TT, gag_a, kk and gfg_f for every subframe, its output equals the s^\hat s computed in the encoder, sample by sample.

Proof. By induction on the subframes. Before the first subframe both have zero synthesis states and zero past excitation. If the states and the past excitation agree before a subframe, both build the same vTv_T from the same past excitation, the same e=gavT+gfcke = g_a v_T + g_f c_k, and run the same recursion s^[n]=e[n]+∑kaks^[n−k]\hat s[n] = e[n] + \sum_k a_k \hat s[n - k] from the same state, with the same floating point operations in the same order. So the outputs, the new states and the new past excitation agree. □\square

Theorem 4 (exact recovery)

Suppose AA is known, the adaptive codebook is off, the input is s=1A(z)etrues = \frac{1}{A(z)} e^{\text{true}} from a zero state, and in each subframe etrue=gcje^{\text{true}} = g c_j for some code vector cjc_j and gain g≠0g \ne 0, with no other code vector cic_i such that HciH c_i is a multiple of HcjH c_j. Then the encoder finds jj and gg in every subframe, and s^=s\hat s = s.

Proof. By induction on the subframes, assume that s^=s\hat s = s up to the current subframe. Then the synthesis filter of the encoder has the same state as the filter that made ss, and the weighting filter has been fed s−s^=0s - \hat s = 0, so its state is 0. With e=0e = 0, the output s^(0)\hat s(0) is the zero-input response of that state, and s=s^(0)+Getrues = \hat s(0) + G e^{\text{true}}. Hence t=W(z)t = W(z) applied to GetrueG e^{\text{true}} from a zero state, that is t=Hetrue=gHcjt = H e^{\text{true}} = g H c_j. The score of cjc_j is ⟨t,yj⟩2/⟨yj,yj⟩=g2∥yj∥2=∥t∥2\langle t, y_j \rangle^2 / \langle y_j, y_j \rangle = g^2 \|y_j\|^2 = \|t\|^2, the largest possible by the Cauchy-Schwarz inequality, and equality for another cic_i would need yiy_i to be a multiple of yjy_j, which is excluded. So the search picks jj with gain ⟨t,yj⟩/∥yj∥2=g\langle t, y_j \rangle / \|y_j\|^2 = g, the excitation is etruee^{\text{true}}, and s^=s\hat s = s on this subframe as well. □\square

Remarks

The matrix HH is invertible, since its diagonal is h[0]=1h[0] = 1, so distinct code vectors ci≠λcjc_i \ne \lambda c_j give yi≠λyjy_i \ne \lambda y_j. The condition of Theorem 4 therefore holds when no two code vectors are multiples of each other, which is true with probability 1 for a Gaussian codebook.

In floating point, Theorem 4 holds up to rounding: the test asks for the indices exactly and for the gains and the output within 10−910^{-9}.

Complexity

Line L1 costs O(Np+p2)O(N p + p^2) per frame. In the real RAM, lines L4 and L6 filter every candidate, which costs O(L2)O(L^2) per vector by direct convolution, so a subframe costs O((Q+C)L2)O((Q + C) L^2), and the whole input O(S(Q+C)L2)O(S (Q + C) L^2) for SS subframes. The filtered fixed codebook can be computed once per frame, as the code does, since hh changes only with AA. The memory is O(CL)O(C L) for the filtered codebook. With L=40L = 40, C=1024C = 1024 and Q=128Q = 128, this is about a million multiplications per subframe, which was the main obstacle of CELP in 1985. Later coders cut it with structured codebooks: overlapping, sparse or algebraic vectors whose filtered versions can be updated in O(L)O(L) each, or searched without filtering every one.

Properties

  • Analysis by synthesis. The encoder judges each choice by its output after the decoder's filter, not by a distance in the parameter space.
  • Perceptual error. The weighting hides the noise under the formants, so the coded speech sounds better than its plain signal to noise ratio suggests.
  • Low delay. The delay is one frame plus any look-ahead, often 20 to 30 ms; the variant LD-CELP of ITU-T G.728 works with a delay of a few milliseconds by using backward-adapted LPC.
  • Not for music. The source-filter model fits one voice. Music and several talkers are coded poorly at the same rate.

Variants and improvements

  • Algebraic CELP (ACELP). The fixed codebook has a few pulses of ±1\pm 1 at structured positions, so it needs no storage and can be searched fast. ITU-T G.729 and the AMR codecs of mobile phones use it.
  • VSELP and other structured codebooks. Vectors built as sums of a few basis vectors, so the search over 2M2^M vectors costs about MM filterings.
  • LD-CELP. Backward adaptation of LPC from the decoded speech, for low delay (ITU-T G.728, 16 kbit/s).
  • Postfilter. A filter like W(z)W(z) at the decoder deepens the valleys between formants and makes the noise less audible.
  • Joint search. Searching the two codebooks together, or keeping several candidates from the first search, lowers the error at a higher cost.

When to use it

Use CELP for speech at 4 to 16 kbit/s where a delay of tens of milliseconds is acceptable, such as mobile telephony and voice over IP. For high quality wideband speech and music at higher rates, transform coders and hybrid codecs such as Opus are a better fit. At very low rates, under about 2 kbit/s, parametric and neural codecs do better.

Pitfalls

  • Encoder and decoder out of step. The encoder must update its filter states and its past excitation from the decoded values, not from the input. Otherwise the adaptive codebook of the two sides differs and the error grows.
  • Lags shorter than the subframe. If T<LT < L, the delayed excitation is not yet known for the whole subframe; repeat the first TT samples, as the code does.
  • Unstable filters. Rounding or quantizing aa can move a pole outside the unit circle. Interpolate and quantize line spectral pairs, whose order guarantees a stable filter, instead of the aka_k.
  • Gains that are not quantized jointly. Gains are large in voiced onsets; quantizing them on a fixed scale clips them. Real coders quantize the two gains together with a vector quantizer.
  • The search cost. Filtering every vector of a large random codebook in each subframe is slow; use a structured codebook.

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.

code_excited_linear_prediction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/code-excited-linear-prediction/. The authors are listed in prov/X96A2P.jsonl.

"""Code-excited linear prediction (CELP): an analysis-by-synthesis speech coder.

Per frame, an LPC polynomial A(z) = 1 - sum a_k z^-k models the spectral envelope.
Per subframe, the excitation is g_a v_T + g_f c_k: v_T is the past excitation
delayed by the lag T (the adaptive codebook, for the pitch), c_k is entry k of a
fixed codebook of random vectors. The encoder picks T, k and the gains that
minimize the energy of the weighted error W(z) (s - s_hat), with
W(z) = A(z / gamma1) / A(z / gamma2), where s_hat is the excitation through 1 / A(z).

The weighted error of a subframe is affine in the excitation e:
    ew(e) = t - H e,
where t is the weighted error with e = 0 (the filters run on from their states)
and H is the zero-state response of W(z) / A(z). For a single vector y = H c the
best gain is g = <t, y> / <y, y>, and the error falls by <t, y>^2 / <y, y>, so the
search picks the c with the largest such score. The two codebooks are searched
one after the other, which is the usual suboptimal but fast order.

This code does not quantize the LPC coefficients or the gains; a real coder does,
and its bit rate depends on that.
"""

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from nlsdsp import autocorr, hamming, levinson


def bandwidth_expand(a: Sequence[float], gamma: float) -> List[float]:
    """The coefficients of A(z / gamma): a_k gamma^k."""
    return [c * gamma ** (k + 1) for k, c in enumerate(a)]


def lpc(frame: Sequence[float], order: int) -> List[float]:
    """LPC by the autocorrelation method on a Hamming window; zeros for a silent frame."""
    w = hamming(len(frame))
    r = autocorr([x * v for x, v in zip(frame, w)], order)
    if r[0] <= 1e-12:
        return [0.0] * order
    r = [r[0] * (1 + 1e-9)] + r[1:]  # a tiny white noise floor keeps A(z) well conditioned
    return levinson(r, order)[0]


class Filters:
    """The states of the synthesis filter 1 / A(z) and of the weighting filter W(z) on the error s - s_hat."""

    def __init__(self, order: int) -> None:
        self.syn = [0.0] * order  # past s_hat, newest first
        self.err_in = [0.0] * order  # past s - s_hat, newest first
        self.err_out = [0.0] * order  # past weighted error, newest first

    def copy(self) -> "Filters":
        f = Filters(0)
        f.syn, f.err_in, f.err_out = self.syn[:], self.err_in[:], self.err_out[:]
        return f

    def run(
        self, s: Sequence[float], e: Sequence[float], a: Sequence[float], w1: Sequence[float], w2: Sequence[float]
    ) -> Tuple[List[float], List[float]]:
        """Advance over one subframe of speech s and excitation e. Returns (s_hat, weighted error)."""
        s_hat, ew = [], []
        for x, u in zip(s, e):
            y = u + sum(c * m for c, m in zip(a, self.syn))
            self.syn = [y] + self.syn[:-1]
            d = x - y
            v = d - sum(c * m for c, m in zip(w1, self.err_in)) + sum(c * m for c, m in zip(w2, self.err_out))
            self.err_in = [d] + self.err_in[:-1]
            self.err_out = [v] + self.err_out[:-1]
            s_hat.append(y)
            ew.append(v)
        return s_hat, ew


def impulse_response(a: Sequence[float], w1: Sequence[float], w2: Sequence[float], n: int) -> List[float]:
    """The first n samples of the zero-state impulse response of W(z) / A(z)."""
    f = Filters(len(a))
    # the weighted error of s = 0 and e = delta is minus the response of W / A
    _, ew = f.run([0.0] * n, [1.0] + [0.0] * (n - 1), a, w1, w2)
    return [-v for v in ew]


def convolve(h: Sequence[float], c: Sequence[float]) -> List[float]:
    """y[n] = sum_{j <= n} h[n - j] c[j] for n < len(c): zero-state filtering truncated to the subframe."""
    return [sum(h[n - j] * c[j] for j in range(n + 1)) for n in range(len(c))]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    return sum(u * v for u, v in zip(x, y))


def search(target: Sequence[float], filtered: Sequence[Sequence[float]]) -> Tuple[int, float, float]:
    """The index of the best vector, its gain and the remaining error energy.

    The best vector maximizes <t, y>^2 / <y, y>; ties go to the smallest index.
    """
    best, best_score, best_gain = -1, -1.0, 0.0
    for k, y in enumerate(filtered):
        energy = dot(y, y)
        if energy <= 0:
            continue
        corr = dot(target, y)
        score = corr * corr / energy
        if score > best_score:
            best, best_score, best_gain = k, score, corr / energy
    if best < 0:
        return 0, 0.0, dot(target, target)
    return best, best_gain, dot(target, target) - best_score


def adaptive_vector(past: Sequence[float], lag: int, n: int) -> List[float]:
    """v[i] = past[-lag + i] for i < lag, then repeated with period lag: the past excitation delayed by lag."""
    v = []
    for i in range(n):
        v.append(past[len(past) - lag + i] if i < lag else v[i - lag])
    return v


def random_codebook(size: int, n: int, seed: int = 1) -> List[List[float]]:
    """A Gaussian codebook as in Schroeder and Atal, each vector scaled to unit energy."""
    rng = random.Random(seed)
    book = []
    for _ in range(size):
        v = [rng.gauss(0.0, 1.0) for _ in range(n)]
        z = math.sqrt(dot(v, v))
        book.append([x / z for x in v])
    return book


def encode(
    s: Sequence[float],
    codebook: Sequence[Sequence[float]],
    order: int = 10,
    frame_len: int = 160,
    sub_len: int = 40,
    lags: Optional[range] = range(20, 148),
    gamma1: float = 0.9,
    gamma2: float = 0.6,
    lpc_given: Optional[Sequence[Sequence[float]]] = None,
) -> Tuple[List[Dict], List[float]]:
    """Encode s. Returns the parameters of every subframe and the decoded speech of the encoder's own decoder.

    lags = None turns the adaptive codebook off. lpc_given, one list of a_k per
    frame, replaces the LPC analysis (for tests with a known filter).
    """
    max_lag = lags[-1] if lags else 0
    past = [0.0] * max(max_lag, 1)
    state = Filters(order)
    params: List[Dict] = []
    out: List[float] = []
    for fi, start in enumerate(range(0, len(s) - frame_len + 1, frame_len)):
        frame = s[start : start + frame_len]
        a = list(lpc_given[fi]) if lpc_given is not None else lpc(frame, order)  # @line L1
        w1, w2 = bandwidth_expand(a, gamma1), bandwidth_expand(a, gamma2)
        h = impulse_response(a, w1, w2, sub_len)  # @line L2
        filtered_book = [convolve(h, c) for c in codebook]
        for sub in range(0, frame_len, sub_len):
            seg = frame[sub : sub + sub_len]
            _, t = state.copy().run(seg, [0.0] * sub_len, a, w1, w2)  # @line L3
            lag, g_a, v = 0, 0.0, [0.0] * sub_len
            if lags:
                vs = [adaptive_vector(past, T, sub_len) for T in lags]
                j, g_a, _ = search(t, [convolve(h, x) for x in vs])  # @line L4
                lag, v = lags[j], vs[j]
                y = convolve(h, v)
                t = [x - g_a * u for x, u in zip(t, y)]  # @line L5
            k, g_f, err = search(t, filtered_book)  # @line L6
            e = [g_a * x + g_f * c for x, c in zip(v, codebook[k])]  # @line L7
            s_hat, _ = state.run(seg, e, a, w1, w2)
            past = (past + e)[-len(past) :]
            out.extend(s_hat)
            params.append({"a": a, "lag": lag, "g_a": g_a, "k": k, "g_f": g_f, "err": err})  # @line L8
    return params, out


def decode(params: Sequence[Dict], codebook: Sequence[Sequence[float]], sub_len: int = 40, max_lag: int = 147) -> List[float]:
    """The decoder: rebuild each excitation and pass it through 1 / A(z)."""
    order = len(params[0]["a"]) if params else 0
    syn = [0.0] * order
    past = [0.0] * max(max_lag, 1)
    out = []
    for p in params:
        v = adaptive_vector(past, p["lag"], sub_len) if p["lag"] else [0.0] * sub_len
        e = [p["g_a"] * x + p["g_f"] * c for x, c in zip(v, codebook[p["k"]])]
        for u in e:
            y = u + sum(c * m for c, m in zip(p["a"], syn))
            syn = [y] + syn[:-1]
            out.append(y)
        past = (past + e)[-len(past) :]
    return out


def snr_db(s: Sequence[float], s_hat: Sequence[float]) -> float:
    """10 log10 of the signal energy over the error energy."""
    noise = sum((x - y) ** 2 for x, y in zip(s, s_hat))
    return 10.0 * math.log10(dot(s, s) / noise) if noise > 0 else math.inf
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_code_excited_linear_prediction.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/code-excited-linear-prediction/. The authors are listed in prov/X96A2P.jsonl.

import itertools
import random

from code_excited_linear_prediction import (
    Filters,
    adaptive_vector,
    bandwidth_expand,
    convolve,
    decode,
    dot,
    encode,
    impulse_response,
    random_codebook,
    search,
    snr_db,
)
from nlsdsp import all_pole, pulse_train

FS = 8000


def vowel(seed=7, n=1280):
    rng = random.Random(seed)
    src = [p + 0.05 * rng.gauss(0, 1) for p in pulse_train(125, FS, n)]
    s = all_pole(src, [1.662983, -0.81])
    peak = max(abs(v) for v in s)
    return [0.5 * v / peak for v in s]


def error(t, y, g):
    return sum((a - g * b) ** 2 for a, b in zip(t, y))


def test_search_matches_brute_force_on_tiny_codebooks():
    rng = random.Random(1)
    for _ in range(40):
        n = 4
        h = [rng.uniform(-1, 1) for _ in range(n)]
        t = [rng.uniform(-1, 1) for _ in range(n)]
        book = [[rng.choice((-1.0, 0.0, 1.0)) for _ in range(n)] for _ in range(6)]
        ys = [convolve(h, c) for c in book]
        k, g, err = search(t, ys)
        # brute force over the vectors and over gains on a fine grid
        grid = [i / 200 for i in range(-1000, 1001)]
        brute = min(error(t, y, gg) for y in ys for gg in grid)
        assert err <= brute + 1e-12
        assert abs(err - error(t, ys[k], g)) < 1e-9
        assert all(err <= error(t, y, dot(t, y) / dot(y, y)) + 1e-12 for y in ys if dot(y, y) > 0)


def test_search_example_of_the_page():
    t = [1.0, 0.5, -0.25, 0.0]
    h = [1.0, 0.5, 0.25, 0.125]
    book = [[1, 0, 0, 0], [0, 1, 0, 0], [1, -1, 0, 0], [0.5, 0.5, 0.5, 0.5]]
    ys = [convolve(h, c) for c in book]
    assert ys[2] == [1.0, -0.5, -0.25, -0.125]
    k, g, err = search(t, ys)
    assert k == 0
    assert abs(g - 1.1875 / 1.328125) < 1e-15
    assert abs(err - (1.3125 - 1.1875**2 / 1.328125)) < 1e-15


def test_weighted_error_is_affine_in_the_excitation():
    rng = random.Random(2)
    a = [1.2, -0.6, 0.1]
    w1, w2 = bandwidth_expand(a, 0.9), bandwidth_expand(a, 0.6)
    state = Filters(3)
    state.run([rng.uniform(-1, 1) for _ in range(30)], [rng.uniform(-1, 1) for _ in range(30)], a, w1, w2)
    s = [rng.uniform(-1, 1) for _ in range(20)]
    e = [rng.uniform(-1, 1) for _ in range(20)]
    _, t = state.copy().run(s, [0.0] * 20, a, w1, w2)
    _, ew = state.copy().run(s, e, a, w1, w2)
    he = convolve(impulse_response(a, w1, w2, 20), e)
    assert max(abs(x - (u - v)) for x, u, v in zip(ew, t, he)) < 1e-12


def test_equal_gammas_give_no_weighting():
    a = [1.2, -0.6]
    h = impulse_response(a, bandwidth_expand(a, 0.8), bandwidth_expand(a, 0.8), 30)
    plain = all_pole([1.0] + [0.0] * 29, a)
    assert max(abs(x - y) for x, y in zip(h, plain)) < 1e-12


def test_adaptive_vector_repeats_short_lags():
    past = [float(i) for i in range(10)]
    assert adaptive_vector(past, 4, 7) == [6.0, 7.0, 8.0, 9.0, 6.0, 7.0, 8.0]
    assert adaptive_vector(past, 8, 5) == [2.0, 3.0, 4.0, 5.0, 6.0]


def test_exact_recovery_when_the_excitation_is_in_the_codebook():
    rng = random.Random(3)
    book = random_codebook(16, 20, seed=5)
    a = [1.3, -0.7]
    choice = [(rng.randrange(16), rng.uniform(0.5, 2.0) * rng.choice((-1, 1))) for _ in range(8)]
    e = [g * x for k, g in choice for x in book[k]]
    s = all_pole(e, a)
    params, out = encode(s, book, order=2, frame_len=40, sub_len=20, lags=None, lpc_given=[a] * 4)
    assert [p["k"] for p in params] == [k for k, _ in choice]
    assert all(abs(p["g_f"] - g) < 1e-9 for p, (_, g) in zip(params, choice))
    assert max(abs(x - y) for x, y in zip(out, s)) < 1e-9


def test_decoder_matches_the_encoder_and_the_pitch_lag_is_found():
    s = vowel()
    book = random_codebook(128, 40)
    params, out = encode(s, book)
    assert decode(params, book) == out  # the encoder runs the same decoder
    lags = [p["lag"] for p in params[4:]]
    assert sum(1 for t in lags if t in (63, 64, 65, 127, 128, 129)) >= 0.5 * len(lags)  # period 64 or twice it


def test_adaptive_codebook_raises_the_snr():
    s = vowel()
    book = random_codebook(128, 40)
    with_pitch = snr_db(s, encode(s, book)[1])
    without = snr_db(s, encode(s, book, lags=None)[1])
    assert with_pitch > 8.0  # a measurement on this signal, without quantization
    assert with_pitch > without + 3.0


def test_sequential_search_is_no_better_than_joint_search():
    rng = random.Random(4)
    for _ in range(50):
        t = [rng.uniform(-1, 1) for _ in range(5)]
        ya = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(3)]
        yf = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(3)]
        j, ga, _ = search(t, ya)
        rest = [x - ga * y for x, y in zip(t, ya[j])]
        _, _, seq = search(rest, yf)
        best = min(
            error(t, [p * ga2 + q * gf2 for p, q in zip(u, v)], 1.0)
            for u, v in itertools.product(ya, yf)
            for ga2, gf2 in [solve2(t, u, v)]
        )
        assert best <= seq + 1e-12


def solve2(t, u, v):
    """The least squares gains of t ~ ga u + gf v."""
    uu, vv, uv, tu, tv = dot(u, u), dot(v, v), dot(u, v), dot(t, u), dot(t, v)
    det = uu * vv - uv * uv
    return (tu * vv - tv * uv) / det, (tv * uu - tu * uv) / det

History

Bishnu Atal and Joel Remde introduced multipulse excitation in 1982, which first chose the excitation by analysis by synthesis. Manfred Schroeder and Bishnu Atal at Bell Laboratories published CELP at ICASSP 1985, with a codebook of Gaussian noise vectors, a pitch predictor and a perceptual weighting filter, and reported high quality speech at low bit rates, with an exhaustive search that was then far too slow for real time. Structured codebooks made it practical. The US federal standard FS-1016 (4.8 kbit/s, 1991), ITU-T G.728 (16 kbit/s, 1992) and G.729 (8 kbit/s, 1996), and the AMR codecs of GSM and UMTS are all CELP coders.

References

  1. Manfred R. Schroeder and Bishnu S. Atal, Code-excited linear prediction (CELP), high-quality speech at very low bit rates, Proceedings of the IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP), 1985, 937 to 940, the description of the coder (the random codebook, the long-delay pitch predictor, the perceptual weighting and the exhaustive search) and the reported speech quality
  2. Lawrence R. Rabiner and Ronald W. Schafer, Digital Processing of Speech Signals, Prentice-Hall, 1978, Chapter 8 (linear predictive coding of speech, the autocorrelation method and the synthesis filter)

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
  • at least three sources
  • a scene preset for the example