Algorithm Search⌘K

Algorithmadvanced

Statistical model voice activity detection

Also called Sohn VAD, likelihood ratio VAD.

Decide speech or noise per frame by a likelihood ratio test of Gaussian models of the spectral bins, smoothed by an HMM hangover.

Time
O(F N log N) worst
Space
O(N) extra
Where
F = the number of frames; N = the frame and FFT length
Properties
deterministicnot exactnot in placeonline
Origin
Jongseo Sohn, Nam Soo Kim, Wonyong Sung, 1999

The statistical model VAD of Sohn, Kim and Sung decides for each frame whether it contains speech by a likelihood ratio test between two Gaussian models of its DFT coefficients, noise alone and speech plus noise, and then smooths the decisions with a two-state hidden Markov model. It is one solution of voice activity detection. The older Rabiner-Sambur endpoint detector uses thresholds on energy and zero crossings instead, and finds only the start and end of one word; this method labels every frame and uses the same noise model as the Ephraim-Malah estimator.

In plain words

The method first listens to a short stretch of noise and learns how loud the noise is at each frequency. For every new frame, it asks two questions at each frequency: how likely is this frame if it is only noise, and how likely is it if speech is added. The ratio of the two answers says which story fits better. The ratios of all frequencies are multiplied, so a frame wins the "speech" vote only when many frequencies agree. Speech comes in runs of frames, not in single frames, so a small model of switching between "speech" and "noise" carries the belief from one frame to the next. This stops short gaps inside words from being cut.

The problem

Given a signal cut into frames and a stretch of noise at the start, label each frame 1 for speech and 0 for noise. Each frame has DFT coefficients XkX_k, k=0,…,K−1k = 0, \dots, K - 1. The two hypotheses are

H0:Xk=Nk,H1:Xk=Sk+Nk,H_0: X_k = N_k, \qquad H_1: X_k = S_k + N_k,

with NkN_k and SkS_k independent complex Gaussians of variances λk\lambda_k and λkξk\lambda_k \xi_k, where λk\lambda_k is the noise power and ξk\xi_k the a priori signal-to-noise ratio of bin kk. The model treats the bins as independent.

The algorithm

Under the model, p(Xk∣H0)=1πλke−∣Xk∣2/λkp(X_k \mid H_0) = \frac{1}{\pi \lambda_k} e^{-|X_k|^2 / \lambda_k} and p(Xk∣H1)=1πλk(1+ξk)e−∣Xk∣2/(λk(1+ξk))p(X_k \mid H_1) = \frac{1}{\pi \lambda_k (1 + \xi_k)} e^{-|X_k|^2 / (\lambda_k (1 + \xi_k))}. With the a posteriori SNR γk=∣Xk∣2/λk\gamma_k = |X_k|^2 / \lambda_k, the ratio of one bin is

Λk=p(Xk∣H1)p(Xk∣H0)=11+ξkexp⁡(γkξk1+ξk).\Lambda_k = \frac{p(X_k \mid H_1)}{p(X_k \mid H_0)} = \frac{1}{1 + \xi_k} \exp\left(\frac{\gamma_k \xi_k}{1 + \xi_k}\right).

The noise power comes from the first frames, which must be noise. The a priori SNR is unknown and comes from the decision-directed rule ξk=max⁡(αA^k2/λk+(1−α)max⁡(γk−1,0),ξmin⁡)\xi_k = \max(\alpha \hat A_k^2 / \lambda_k + (1 - \alpha) \max(\gamma_k - 1, 0), \xi_{\min}), where A^k2\hat A_k^2 is the estimated clean power of the previous frame. Two states, 0 for noise and 1 for speech, with a01a_{01} the chance of a switch from noise to speech and a10a_{10} the reverse, give the smoothed statistic G(n)G(n).

  1. SOHN-VAD(x, frames of N samples, init frames, alpha, xi_min, a01, a10, threshold eta)
  2. 1X(n) <- the DFT of the windowed frame n, for every n
  3. 2lambda_k <- the mean of |X_k|^2 over the first init frames
  4. 3for each frame n: gamma_k <- |X_k(n)|^2 / lambda_k
  5. 4xi_k <- max(alpha A_k^2 / lambda_k + (1 - alpha) max(gamma_k - 1, 0), xi_min)
  6. 5log Lambda(n) <- sum over k of gamma_k xi_k / (1 + xi_k) - log(1 + xi_k)
  7. 6log G(n) <- log Lambda(n) + log(a01 + a11 G(n - 1)) - log(a00 + a10 G(n - 1))
  8. 7speech(n) <- [log G(n) > log eta]
  9. 8A_k^2 <- (xi_k / (1 + xi_k))^2 |X_k(n)|^2; if not speech(n), move lambda_k toward |X_k(n)|^2

Line L6 starts from the stationary odds G(0)=a01/a10G(0) = a_{01} / a_{10}. The code takes A^k2\hat A_k^2 from the Wiener gain ξk/(1+ξk)\xi_k / (1 + \xi_k); the amplitude of the Ephraim-Malah estimator is a common alternative. The noise power is updated with a factor 0.98 in the frames judged noise. All the sums are in log space, because the product over 129 bins easily overflows.

Example

Take fs=8000f_s = 8000 Hz, white Gaussian noise with standard deviation 0.01 for one second, and a 500 Hz tone of amplitude 0.01 from sample 2800 to sample 5200. The tone has half the power of the noise, an SNR of −3-3 dB over the whole band. Frames of 256 samples with a hop of 128 and the Hamming window give 61 frames and 129 bins. The parameters are α=0.98\alpha = 0.98, ξmin⁡=10−2.5\xi_{\min} = 10^{-2.5}, 10 noise frames at the start, a01=0.2a_{01} = 0.2, a10=0.1a_{10} = 0.1 and log⁡η=10\log \eta = 10 (random seed 7).

frame start log⁡Λ(n)\log \Lambda(n) log⁡G(n)\log G(n) decision
19 2432 1.92 3.84 0
21 2688 5.34 7.28 0
22 2816 17.82 20.02 1
23 2944 30.33 32.53 1
39 4992 48.72 50.92 1
40 5120 0.41 2.61 0
42 5376 -0.42 1.77 0

The decisions are frames 22 to 39. Frames 22 to 38 lie wholly inside the tone, and frame 39 (samples 4992 to 5247) holds it for 208 of its 256 samples. Frames 20, 21 and 40 hold the tone for only part of their length and are labeled noise. The tone lies in a few bins, so it is found even though its total power is below the noise. In frame 42 the frame alone favors noise (log⁡Λ<0\log \Lambda < 0), and the memory of the previous speech frames raises log⁡G\log G to 1.77, still below the threshold. These values are measurements of this run.

Correctness

These are theorems, proved in proofs/correctness.md:

  • The bin ratio. Under the two Gaussian models, log⁡Λk=γkξk/(1+ξk)−log⁡(1+ξk)\log \Lambda_k = \gamma_k \xi_k / (1 + \xi_k) - \log(1 + \xi_k), and it increases with γk\gamma_k for ξk>0\xi_k > 0. So for known λk\lambda_k and ξk\xi_k, the test of line L7 without smoothing is the most powerful test of its size, by the Neyman-Pearson lemma.
  • The smoothing is a forward recursion. If the states form a Markov chain with transitions aija_{ij}, started from its stationary law, and each frame depends only on its own state, then G(n)G(n) of line L6 equals the posterior odds P(qn=1∣X(1..n))/P(qn=0∣X(1..n))P(q_n = 1 \mid X(1..n)) / P(q_n = 0 \mid X(1..n)). This is the ratio of the two variables of the forward algorithm.
  • No smoothing as a special case. With a01=a10=1/2a_{01} = a_{10} = 1/2, G(n)=Λ(n)G(n) = \Lambda(n).

The models are approximations: speech bins are not Gaussian, neighbor bins are correlated by the window, and ξk\xi_k is an estimate. The decision-directed estimate grows with the current γk\gamma_k, so even pure noise gives log⁡Λ(n)>0\log \Lambda(n) > 0 on average: in 5 runs of pure noise with these settings, every frame had log⁡Λ(n)\log \Lambda(n) between 0.5 and 6.9. This is why the threshold log⁡η=10\log \eta = 10 is tuned, not the value 0 that the posterior odds would suggest. That the method is robust at low SNR is a measurement, reported by Sohn, Kim and Sung against the G.729 Annex B VAD.

Proof: Correctness of the statistical model VADfull

We prove the three exact statements of the page: the form of the bin ratio and its optimality for known parameters, the meaning of the smoothed statistic G(n)G(n) as posterior odds, and the special case without memory.

Lemma 1 (the bin ratio)

Let XX be complex Gaussian with mean 0 and variance vv, with density p(X)=1πve−∣X∣2/vp(X) = \frac{1}{\pi v} e^{-|X|^2 / v}. Under H0H_0, v=λv = \lambda; under H1H_1, v=λ(1+ξ)v = \lambda(1 + \xi) with ξ≥0\xi \ge 0. With γ=∣X∣2/λ\gamma = |X|^2 / \lambda,

log⁡p(X∣H1)p(X∣H0)=γξ1+ξ−log⁡(1+ξ).\log \frac{p(X \mid H_1)}{p(X \mid H_0)} = \frac{\gamma \xi}{1 + \xi} - \log(1 + \xi).

Proof. The ratio is λλ(1+ξ)exp⁡(∣X∣2λ−∣X∣2λ(1+ξ))\frac{\lambda}{\lambda(1 + \xi)} \exp\left(\frac{|X|^2}{\lambda} - \frac{|X|^2}{\lambda(1 + \xi)}\right). The exponent is γ(1−11+ξ)=γξ/(1+ξ)\gamma (1 - \frac{1}{1 + \xi}) = \gamma \xi / (1 + \xi). Take the log. □\square

Under H1H_1 the variance is λ+λξ\lambda + \lambda\xi because SS and NN are independent complex Gaussians and their variances add.

Monotonicity. For ξ>0\xi > 0 the derivative with respect to γ\gamma is ξ/(1+ξ)>0\xi / (1 + \xi) > 0, so log⁡Λk\log \Lambda_k increases strictly with γk\gamma_k. For ξ=0\xi = 0 it is identically 0.

Theorem 1 (the frame test is most powerful for known parameters)

Let λk\lambda_k and ξk\xi_k be known, and let the bins be independent under both hypotheses. For every level ϵ\epsilon, the test that decides H1H_1 when ∑klog⁡Λk>c\sum_k \log \Lambda_k > c, with cc chosen so that P(decide H1∣H0)=ϵP(\text{decide } H_1 \mid H_0) = \epsilon, has the largest P(decide H1∣H1)P(\text{decide } H_1 \mid H_1) among all tests with P(decide H1∣H0)≤ϵP(\text{decide } H_1 \mid H_0) \le \epsilon.

Proof. By independence, the likelihood ratio of the whole frame is ∏kΛk\prod_k \Lambda_k, and its log is the sum. Under H0H_0 the sum has a continuous distribution (it is an affine function of the independent exponential variables γk\gamma_k with positive coefficients, for the bins with ξk>0\xi_k > 0), so a cc with exactly the level ϵ\epsilon exists. The Neyman-Pearson lemma states that a test that rejects H0H_0 exactly when the likelihood ratio exceeds a constant, at level ϵ\epsilon, is most powerful at that level. □\square

Theorem 2 (the smoothed statistic is the posterior odds)

Let q1,q2,…q_1, q_2, \dots be a Markov chain on {0,1}\{0, 1\} with transitions aija_{ij} (a00=1−a01a_{00} = 1 - a_{01}, a11=1−a10a_{11} = 1 - a_{10}, 0<a01,a10<10 < a_{01}, a_{10} < 1), started from its stationary law π1=a01/(a01+a10)\pi_1 = a_{01} / (a_{01} + a_{10}), π0=a10/(a01+a10)\pi_0 = a_{10} / (a_{01} + a_{10}). Let the frames X(n)X(n) be independent given the states, with X(n)X(n) depending only on qnq_n, and let Λ(n)=p(X(n)∣qn=1)/p(X(n)∣qn=0)\Lambda(n) = p(X(n) \mid q_n = 1) / p(X(n) \mid q_n = 0). Define G(0)=a01/a10G(0) = a_{01} / a_{10} and

G(n)=Λ(n)a01+a11G(n−1)a00+a10G(n−1).G(n) = \Lambda(n) \frac{a_{01} + a_{11} G(n - 1)}{a_{00} + a_{10} G(n - 1)}.

Then for every n≥1n \ge 1, G(n)=P(qn=1∣X(1),…,X(n))P(qn=0∣X(1),…,X(n))G(n) = \frac{P(q_n = 1 \mid X(1), \dots, X(n))}{P(q_n = 0 \mid X(1), \dots, X(n))}.

Proof. Let fn(j)=p(X(1),…,X(n),qn=j)f_n(j) = p(X(1), \dots, X(n), q_n = j), the forward variables. They satisfy f1(j)=πj p(X(1)∣j)f_1(j) = \pi_j\, p(X(1) \mid j) and fn(j)=p(X(n)∣j)∑ifn−1(i) aijf_n(j) = p(X(n) \mid j) \sum_i f_{n-1}(i)\, a_{ij}. The posterior odds equal fn(1)/fn(0)f_n(1) / f_n(0), since both posteriors have the same denominator p(X(1),…,X(n))p(X(1), \dots, X(n)). We show fn(1)/fn(0)=G(n)f_n(1) / f_n(0) = G(n) by induction.

For n=1n = 1: f1(1)/f1(0)=Λ(1) π1/π0=Λ(1) a01/a10f_1(1) / f_1(0) = \Lambda(1)\, \pi_1 / \pi_0 = \Lambda(1)\, a_{01} / a_{10}. The recursion gives G(1)=Λ(1)a01+a11a01/a10a00+a01=Λ(1)a01(a10+a11)a10(a00+a01)=Λ(1)a01a10G(1) = \Lambda(1) \frac{a_{01} + a_{11} a_{01} / a_{10}}{a_{00} + a_{01}} = \Lambda(1) \frac{a_{01}(a_{10} + a_{11})}{a_{10}(a_{00} + a_{01})} = \Lambda(1) \frac{a_{01}}{a_{10}}, since a10+a11=a00+a01=1a_{10} + a_{11} = a_{00} + a_{01} = 1.

For n≥2n \ge 2, divide numerator and denominator by fn−1(0) p(X(n)∣0)f_{n-1}(0)\, p(X(n) \mid 0):

fn(1)fn(0)=p(X(n)∣1)(fn−1(0)a01+fn−1(1)a11)p(X(n)∣0)(fn−1(0)a00+fn−1(1)a10)=Λ(n)a01+a11G(n−1)a00+a10G(n−1),\frac{f_n(1)}{f_n(0)} = \frac{p(X(n) \mid 1) (f_{n-1}(0) a_{01} + f_{n-1}(1) a_{11})}{p(X(n) \mid 0) (f_{n-1}(0) a_{00} + f_{n-1}(1) a_{10})} = \Lambda(n) \frac{a_{01} + a_{11} G(n - 1)}{a_{00} + a_{10} G(n - 1)},

using fn−1(1)/fn−1(0)=G(n−1)f_{n-1}(1) / f_{n-1}(0) = G(n - 1) from the hypothesis. □\square

So the decision G(n)>1G(n) > 1 is the maximum a posteriori decision for frame nn given the frames up to nn, and G(n)>ηG(n) > \eta is the Bayes decision when a false alarm costs η\eta times as much as a miss. The code uses log⁡G\log G and computes log⁡(a+b eℓ)\log(a + b\, e^{\ell}) with a stable log-add, which changes no value.

Corollary (no memory)

If a01=a10=1/2a_{01} = a_{10} = 1/2, then G(n)=Λ(n)G(n) = \Lambda(n) for all nn.

Proof. All four transitions are 1/21/2, so the fraction in the recursion is (1+G)/(1+G)=1(1 + G) / (1 + G) = 1. □\square

Remarks

The tests check Lemma 1 against the two densities computed directly, Theorem 2 against the sum over all 2n2^n state paths for n≤6n \le 6, and the corollary. The decision-directed ξk\xi_k depends on the data, so Theorem 1 does not apply exactly to the running detector; the page says how this shifts the threshold.

Complexity

Each frame needs one FFT of NN points and O(N)O(N) work for the ratios, the decision-directed rule and the noise update, so the time is O(FNlog⁡N)O(F N \log N) for FF frames. The state is the noise power, the previous clean power and GG, so the extra memory is O(N)O(N), and the method runs online with a delay of one frame.

Properties

  • Adapts to the noise. The noise power is updated in frames judged noise, so slowly changing noise is followed.
  • Uses the spectrum. A tone or a formant that stands above the noise in a few bins is found even when the total energy barely changes, which energy thresholds miss.
  • Calibrated in principle. G(n)G(n) is a posterior odds under the model, so the threshold has a meaning. In practice the model errors shift it, as above.
  • Hang-over by a model. The HMM replaces fixed rules of the form "keep speech for 5 more frames".

Variants and improvements

  • Geometric mean. Compare the mean 1K∑klog⁡Λk\frac{1}{K} \sum_k \log \Lambda_k with a threshold, which makes the threshold independent of the number of bins.
  • Other distributions. Laplacian or Gamma models of the speech coefficients fit speech better than the Gaussian.
  • Better noise tracking. Minimum statistics or MMSE noise trackers update the noise power during speech as well.
  • Multiple observations. Use the ratios of several past and future frames in one test, at the cost of delay.
  • Learned detectors. Neural VADs, trained on labeled speech, now reach lower error rates in hard noise; this method remains a light, training-free baseline.

When to use it

Use it as a front end of speech coding, of enhancement with spectral subtraction or a Wiener filter, and of recognition, when the noise is stationary or changes slowly and the start of the signal is noise. For clean, isolated words an energy and zero-crossing rule is simpler. For music, babble or other speech-like noise, a trained detector works better.

Pitfalls

  • Speech at the start. If the first frames contain speech, the noise power is too high and quiet speech is missed for a long time.
  • Noise power absorbing speech. A false "noise" decision during long speech updates the noise power toward the speech and makes later misses more likely.
  • Threshold and bin count. The sum over bins grows with the frame length, so the threshold must change with it, or use the geometric mean.
  • Floor of the SNR. Without ξmin⁡\xi_{\min}, ξk\xi_k can be 0, and then Λk=1\Lambda_k = 1 for every input: the bin stops voting.
  • Overflow. Λ(n)\Lambda(n) for a loud frame is far beyond the range of floating point. Work with log⁡Λ\log \Lambda and log⁡G\log G.

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.

likelihood_ratio_vad.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-vad/. The authors are listed in prov/4HXQ9X.jsonl.

"""Statistical model voice activity detection (Sohn, Kim and Sung).

Each DFT bin X_k of a frame is complex Gaussian with variance lambda_k under H0
(noise only) and lambda_k (1 + xi_k) under H1 (speech plus noise), where
lambda_k is the noise power and xi_k the a priori SNR. With the a posteriori
SNR gamma_k = |X_k|^2 / lambda_k, the likelihood ratio of one bin is

    Lambda_k = p(X_k | H1) / p(X_k | H0) = exp(gamma_k xi_k / (1 + xi_k)) / (1 + xi_k).

The bins are independent under the model, so the frame ratio is the product.
The a priori SNR comes from the decision-directed rule, and an HMM of two states
(0 noise, 1 speech) smooths the decisions over time: G(n), the ratio of the two
forward variables, follows

    G(n) = Lambda(n) (a01 + a11 G(n - 1)) / (a00 + a10 G(n - 1)),

which is the posterior odds of speech in frame n given frames 1 to n. Everything
is computed in log space.
"""

import math
from typing import List, Sequence, Tuple

from nlsdsp import fft, frames, hamming
from nlslog import log_add


def log_lr_bin(gamma: float, xi: float) -> float:
    """log Lambda_k = gamma xi / (1 + xi) - log(1 + xi)."""
    return gamma * xi / (1.0 + xi) - math.log1p(xi)


def decision_directed(prev_amp2: float, noise: float, gamma: float, alpha: float, xi_min: float) -> float:
    """xi = max(alpha A^2 / lambda + (1 - alpha) max(gamma - 1, 0), xi_min), A^2 the previous clean power estimate."""
    return max(alpha * prev_amp2 / noise + (1.0 - alpha) * max(gamma - 1.0, 0.0), xi_min)


def hmm_log_odds(log_lambdas: Sequence[float], a01: float, a10: float) -> List[float]:
    """log G(n) for every frame, from the stationary prior odds a01 / a10."""
    a00, a11 = 1.0 - a01, 1.0 - a10
    la00, la01, la10, la11 = (math.log(v) for v in (a00, a01, a10, a11))
    lg = math.log(a01 / a10)
    out = []
    for ll in log_lambdas:
        lg = ll + log_add(la01, la11 + lg) - log_add(la00, la10 + lg)  # @line L6
        out.append(lg)
    return out


def vad(
    x: Sequence[float],
    frame_len: int = 256,
    hop: int = 128,
    init_frames: int = 10,
    alpha: float = 0.98,
    xi_min: float = 10 ** (-2.5),
    noise_update: float = 0.98,
    a01: float = 0.2,
    a10: float = 0.1,
    log_eta: float = 10.0,
) -> Tuple[List[int], List[float], List[float]]:
    """Return (decisions, log Lambda per frame, log G per frame). The first init_frames frames must be noise.

    frame_len must be a power of 2. The decision is 1 (speech) when log G(n) > log_eta. The
    default log_eta = 10 is tuned for frames of 256 samples (129 bins), not derived.
    """
    w = hamming(frame_len)
    spectra = []
    for fr in frames(x, frame_len, hop):  # @line L1
        spec = fft([v * wi for v, wi in zip(fr, w)])
        spectra.append([abs(spec[k]) ** 2 for k in range(frame_len // 2 + 1)])
    if len(spectra) < init_frames or init_frames < 1:
        raise ValueError("need at least init_frames frames, and init_frames >= 1")
    nbins = frame_len // 2 + 1
    noise = [sum(s[k] for s in spectra[:init_frames]) / init_frames for k in range(nbins)]  # @line L2
    noise = [max(v, 1e-12) for v in noise]
    prev_amp2 = [0.0] * nbins
    a00, a11 = 1.0 - a01, 1.0 - a10
    la00, la01, la10, la11 = (math.log(v) for v in (a00, a01, a10, a11))
    lg = math.log(a01 / a10)
    decisions, log_lambdas, log_odds = [], [], []
    for pw in spectra:
        total = 0.0
        xis = []
        for k in range(nbins):
            gamma = pw[k] / noise[k]  # @line L3
            xi = decision_directed(prev_amp2[k], noise[k], gamma, alpha, xi_min)  # @line L4
            xis.append(xi)
            total += log_lr_bin(gamma, xi)  # @line L5
        lg = total + log_add(la01, la11 + lg) - log_add(la00, la10 + lg)  # @line L6
        speech = 1 if lg > log_eta else 0  # @line L7
        for k in range(nbins):  # @line L8
            g = xis[k] / (1.0 + xis[k])
            prev_amp2[k] = g * g * pw[k]
            if not speech:
                noise[k] = noise_update * noise[k] + (1.0 - noise_update) * pw[k]
        decisions.append(speech)
        log_lambdas.append(total)
        log_odds.append(lg)
    return decisions, log_lambdas, log_odds
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
nlslog.py 152 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/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_likelihood_ratio_vad.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-vad/. The authors are listed in prov/4HXQ9X.jsonl.

import itertools
import math
import random
import unittest

from likelihood_ratio_vad import decision_directed, hmm_log_odds, log_lr_bin, vad
from nlsdsp import sine, white_noise

FS = 8000


def tone_in_noise(seed, amp, n=8000):
    rng = random.Random(seed)
    x = white_noise(rng, n, 0.01)
    tone = sine(500, FS, 2400, amp)
    for i in range(2400):
        x[2800 + i] += tone[i]
    return x


class TestBinRatio(unittest.TestCase):
    def test_matches_gaussian_densities(self):
        # p(X | H) = exp(-|X|^2 / v) / (pi v) for a complex Gaussian of variance v.
        rng = random.Random(1)
        for _ in range(200):
            lam = rng.uniform(0.1, 5.0)
            xi = rng.uniform(0.0, 20.0)
            x2 = rng.uniform(0.0, 30.0)
            p0 = math.exp(-x2 / lam) / (math.pi * lam)
            v1 = lam * (1.0 + xi)
            p1 = math.exp(-x2 / v1) / (math.pi * v1)
            self.assertAlmostEqual(log_lr_bin(x2 / lam, xi), math.log(p1 / p0), places=9)

    def test_increasing_in_gamma(self):
        for xi in (0.01, 1.0, 10.0):
            vals = [log_lr_bin(g, xi) for g in (0.0, 0.5, 1.0, 2.0, 5.0)]
            self.assertEqual(vals, sorted(vals))
        self.assertEqual(log_lr_bin(3.0, 0.0), 0.0)

    def test_decision_directed(self):
        self.assertAlmostEqual(decision_directed(2.0, 1.0, 5.0, 0.98, 0.001), 0.98 * 2.0 + 0.02 * 4.0)
        self.assertEqual(decision_directed(0.0, 1.0, 0.5, 0.98, 0.001), 0.001)


class TestHmm(unittest.TestCase):
    def test_forward_odds_against_enumeration(self):
        rng = random.Random(2)
        a01, a10 = 0.2, 0.1
        trans = [[1 - a01, a01], [a10, 1 - a10]]
        prior = [a10 / (a01 + a10), a01 / (a01 + a10)]
        for _ in range(20):
            lams = [rng.uniform(-3.0, 3.0) for _ in range(6)]
            got = hmm_log_odds(lams, a01, a10)
            for n in range(1, 7):
                mass = [0.0, 0.0]
                for path in itertools.product((0, 1), repeat=n):
                    p = prior[path[0]]
                    for t in range(1, n):
                        p *= trans[path[t - 1]][path[t]]
                    for t in range(n):
                        if path[t] == 1:
                            p *= math.exp(lams[t])
                    mass[path[-1]] += p
                self.assertAlmostEqual(got[n - 1], math.log(mass[1] / mass[0]), places=9)

    def test_memoryless_chain_gives_frame_ratio(self):
        lams = [0.5, -2.0, 7.0, 1.0]
        for a, b in zip(hmm_log_odds(lams, 0.5, 0.5), lams):
            self.assertAlmostEqual(a, b, places=12)

    def test_vad_uses_the_same_recursion(self):
        x = tone_in_noise(7, 0.01)
        _, ll, lg = vad(x, init_frames=10, log_eta=10.0)
        for a, b in zip(hmm_log_odds(ll, 0.2, 0.1), lg):
            self.assertAlmostEqual(a, b, places=9)


class TestDetection(unittest.TestCase):
    def test_page_example(self):
        x = tone_in_noise(7, 0.01)
        d, ll, lg = vad(x, init_frames=10, log_eta=10.0)
        self.assertEqual(len(d), 61)
        self.assertEqual(d, [0] * 22 + [1] * 18 + [0] * 21)
        self.assertAlmostEqual(ll[22], 17.82, places=2)
        self.assertAlmostEqual(lg[22], 20.02, places=2)
        self.assertAlmostEqual(ll[42], -0.42, places=2)

    def test_noise_only_has_no_detections(self):
        for seed in range(4):
            rng = random.Random(100 + seed)
            d, _, _ = vad(white_noise(rng, 8000, 0.01), init_frames=10, log_eta=10.0)
            self.assertEqual(sum(d), 0)

    def test_errors_only_at_edges(self):
        for seed in range(3):
            d, _, _ = vad(tone_in_noise(seed, 0.02), init_frames=10, log_eta=10.0)
            self.assertEqual(sum(d[:20]) + sum(d[42:]), 0)
            self.assertEqual(sum(d[22:39]), 17)

    def test_short_input(self):
        with self.assertRaises(ValueError):
            vad([0.0] * 300, init_frames=10)


if __name__ == "__main__":
    unittest.main()

History

Before 1999, VADs for speech coding, such as the one of the G.729 Annex B standard, combined thresholds on energy, zero crossings and spectral features. Jongseo Sohn, Nam Soo Kim and Wonyong Sung of Seoul National University proposed in 1999 to treat the decision as a likelihood ratio test of Gaussian models of the DFT coefficients, the models that Ephraim and Malah had used for speech enhancement in 1984, with the decision-directed estimate of the a priori SNR and a hang-over based on a hidden Markov model. The method became a standard baseline; MATLAB's voiceActivityDetector, for example, follows it, with switch probabilities of 0.2 and 0.1 by default.

References

  1. Jongseo Sohn, Nam Soo Kim and Wonyong Sung, A statistical model-based voice activity detection, IEEE Signal Processing Letters 6(1), 1999, 1 to 3, the Gaussian models of the DFT coefficients, the likelihood ratio of each bin, the decision-directed estimate of the a priori SNR and the HMM-based hang-over scheme
  2. Philipos C. Loizou, Speech Enhancement, Theory and Practice, second edition, CRC Press, 2013, Section 9.4.3.1 (likelihood ratio approach), p. 406

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