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
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 (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 samples (20 ms) and each frame into subframes of samples (5 ms). For each frame the encoder computes LPC coefficients with , by the autocorrelation method and the Levinson-Durbin recursion. The perceptual weighting filter is
for example and . It lowers the weight of the error near the formants, where the loud speech masks it, and raises it between them. The values of are a heuristic choice.
For each subframe, the excitation is , where is the past excitation delayed by samples (the adaptive codebook, which models the pitch) and is entry of a fixed codebook. The weighted error is with . It is affine in :
where is the weighted error when , which the filter states from the past subframes still produce, and is the lower triangular matrix of the zero-state impulse response of . For one vector the best gain is , and the error energy falls from to
So the search picks the vector with the largest . The two codebooks are searched one after the other.
CELP-ENCODE(s, fixed codebook c_1 .. c_C, lags T_1 .. T_Q)- 1
for each frame: a <- LPC of the frame; W(z) <- A(z/gamma1) / A(z/gamma2) - 2
h <- the first L samples of the impulse response of W(z) / A(z) - 3
for each subframe: t <- the weighted error with zero excitation, from the current filter states - 4
for 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> - 5
t <- t - g_a y_T - 6
for 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> - 7
e <- g_a v_T + g_f c_k; run the filters on e; append e to the past excitation - 8
send (a, T, g_a, k, g_f), quantized
The decoder builds the same from the received values and passes it through . The encoder contains this decoder, in line L7, so both keep the same filter states and the same past excitation. Real coders quantize (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 with target , so , impulse response , and a codebook of four vectors:
| 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 with gain 0.8941, and the weighted error energy falls from 1.3125 to . After the filter, vector 2 matches the first sample of 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, , because the filters are linear and their states from the past act as a fixed input. For a fixed vector , the error is a quadratic in with its least value at , 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 that the encoder measured. If the true excitation is a gain times a code vector and 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 samples, let be the input, the excitation, the output of the synthesis filter from its current state, and the output of the weighting filter applied to from its current state. All three filters are linear, causal and time-invariant within the subframe.
Lemma 1 (the weighted error is affine)
Let be when , and let be the first samples of the zero-state impulse response of , with the lower triangular matrix for . Then for every ,
Proof. A linear filter that starts from a state and gets an input produces the sum of its zero-input response to and its zero-state response to . Apply this to the synthesis filter: , where is the zero-state response matrix of . So . Apply it again to the weighting filter, whose state is the same in both cases: , where is the zero-state matrix of . The product of two lower triangular Toeplitz matrices is the zero-state matrix of the cascade , whose first column is . So and .
The test of the code checks this identity on random states, inputs and excitations.
Lemma 2 (the best gain for one vector)
For with ,
attained only at .
Proof. is a quadratic in with positive leading coefficient , so its unique minimum is where the derivative is 0, at . Substituting gives the value.
Theorem 1 (the search is exact)
Let for . The function search returns and with
over all with , together with this least error.
Proof. By Lemma 2, with the score . The minimum over of is attained at a of largest , which is the the loop keeps (the first one, on ties). The gain it returns is , which attains the minimum by Lemma 2, and the error it returns is .
By Lemma 1, the vector is exactly the change in the weighted error caused by the excitation , 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.
Theorem 2 (sequential search versus joint search)
Let the adaptive search choose and by Theorem 1 on , and the fixed search choose and by Theorem 1 on . Then the joint optimum
is at most the sequential error .
Proof. The sequential choice is one of the choices over which the joint minimum is taken, and .
The inequality can be strict, so the sequential search is a heuristic for the joint problem. It is used because it costs filterings, for lags and code vectors, instead of pairs.
Theorem 3 (the decoder reproduces the encoder)
If the decoder gets the same , , , and for every subframe, its output equals the 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 from the same past excitation, the same , and run the same recursion 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.
Theorem 4 (exact recovery)
Suppose is known, the adaptive codebook is off, the input is from a zero state, and in each subframe for some code vector and gain , with no other code vector such that is a multiple of . Then the encoder finds and in every subframe, and .
Proof. By induction on the subframes, assume that up to the current subframe. Then the synthesis filter of the encoder has the same state as the filter that made , and the weighting filter has been fed , so its state is 0. With , the output is the zero-input response of that state, and . Hence applied to from a zero state, that is . The score of is , the largest possible by the Cauchy-Schwarz inequality, and equality for another would need to be a multiple of , which is excluded. So the search picks with gain , the excitation is , and on this subframe as well.
Remarks
The matrix is invertible, since its diagonal is , so distinct code vectors give . 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 .
Complexity
Line L1 costs per frame. In the real RAM, lines L4 and L6 filter every candidate, which costs per vector by direct convolution, so a subframe costs , and the whole input for subframes. The filtered fixed codebook can be computed once per frame, as the code does, since changes only with . The memory is for the filtered codebook. With , and , 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 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 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 vectors costs about 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 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 , the delayed excitation is not yet known for the whole subframe; repeat the first samples, as the code does.
- Unstable filters. Rounding or quantizing can move a pole outside the unit circle. Interpolate and quantize line spectral pairs, whose order guarantees a stable filter, instead of the .
- 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.
# 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
- 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
- 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.
| 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 X96A2P Edit this page History Report an error Markdown