Algorithm Search⌘K

Algorithmcore

Rabiner-Sambur endpoint detection

Also called energy and zero-crossing endpoint detection, Rabiner-Sambur algorithm.

Find the start and end of an isolated word from short-time energy thresholds, refined by zero-crossing rate to keep weak fricatives.

Time
O(L) worst
Space
O(T) extra
Where
L = the number of samples; T = the number of 10 ms frames
Properties
deterministicexactnot in placeoffline
Origin
Lawrence R. Rabiner, Marvin R. Sambur, 1975

The Rabiner-Sambur algorithm finds the first and the last frame of a single spoken word in a recording that starts with about 100 ms of silence. It uses only two numbers per 10 ms frame: the short-time energy and the zero-crossing rate. It returns one pair of endpoints for the whole recording, while a general voice activity detector labels every frame as speech or non-speech and can find many segments. The thresholds are rules of thumb fixed from the silence at the start, where a likelihood ratio VAD uses a statistical model of the noise and of speech.

In plain words

Before a person says a word, the recording holds only background noise. The algorithm listens to this short quiet part to learn how loud and how busy the background is. Then it looks for the place where the sound becomes clearly louder than the background, and for the place where it becomes quiet again. Loudness alone misses soft sounds such as "f", "th" or "h" at the start or end of a word, because they are hardly louder than the noise. Such sounds are hiss, so the signal crosses zero many more times than in the background. The algorithm therefore looks a little before the start and a little after the end, and if it finds enough hissing frames there, it moves the endpoint out to include them.

The problem

Given a recording ss of an isolated word at a sample rate fsf_s, in which the first 100 ms are background only, find frame indices N1≤N2N_1 \le N_2 such that the word occupies the frames N1N_1 to N2N_2, or report that there is no word. The frames are 10 ms long, with no overlap and no padding, so a recording of LL samples gives T=⌊L/(fs/100)⌋T = \lfloor L / (f_s / 100) \rfloor frames. This page uses fs=16f_s = 16 kHz, so a frame has 160 samples.

The algorithm

For each frame ii the energy is E[i]=∑n∣s[n]∣E[i] = \sum_n |s[n]| over the frame, and Z[i]Z[i] is the number of adjacent sample pairs in the frame with different signs, where 0 counts as positive. All the constants below are the heuristic values of the paper.

  1. RABINER-SAMBUR(s, f_s)
  2. 1cut s into 10 ms frames; for each frame i: E[i] ← Σ |s[n]|, Z[i] ← number of sign changes
  3. 2IZC, σ ← mean and standard deviation of Z[0 .. 9]; IZCT ← min(25, IZC + 2σ)
  4. 3IMN ← mean of E[0 .. 9]; IMX ← max E; ITL ← min(0.03 (IMX - IMN) + IMN, 4 IMN); ITU ← 5 ITL
  5. 4N1 ← first i, going forward, with E[i] > ITL after which E goes above ITU before it falls to ITL or below; if there is none, return "no word"
  6. 5N2 ← the same, going backward from the last frame
  7. 6if at least 3 of the 25 frames before N1 have Z > IZCT, then N1 ← the earliest of them
  8. 7if at least 3 of the 25 frames after N2 have Z > IZCT, then N2 ← the latest of them
  9. 8return (N1, N2)

Line L4 rejects short bursts: a frame above ITL starts the word only if the energy then reaches ITU without dropping back first, so a click that stays under ITU is skipped. The fixed bound of 25 crossings per 10 ms in line L2 keeps a noisy background from raising IZCT above the level of a fricative. The search in lines L6 and L7 is limited to 25 frames, 250 ms, because a weak fricative is shorter than that.

The paper calls IMN the energy of the silence measured in the first 100 ms; this page takes it as the mean of EE over those 10 frames, and takes σ\sigma as the population standard deviation.

Example

Take a recording of 128 frames at 16 kHz: 300 ms of low-pass background noise, 10 frames of white noise with standard deviation 0.006 as a weak fricative, 500 ms of a 300 Hz tone with amplitude 0.3 as the voiced part, 8 more frames of the fricative, and 300 ms of background. The background is white noise of standard deviation 0.0006 through the one-pole filter 1/(1−0.98z−1)1/(1 - 0.98 z^{-1}), so it has few zero crossings.

Lines L2 and L3 give IZC=8.9IZC = 8.9 and IZCT=20.37IZCT = 20.37, IMN=0.4288IMN = 0.4288 and IMX=30.69IMX = 30.69. Since 0.03(IMX−IMN)+IMN=1.33680.03(IMX - IMN) + IMN = 1.3368 is below 4 IMN=1.7154\,IMN = 1.715, ITL=1.3368ITL = 1.3368 and ITU=6.6838ITU = 6.6838. The fricative frames have energies between about 0.73 and 0.82, below ITL, so lines L4 and L5 find only the tone: N1=40N_1 = 40 and N2=89N_2 = 89. But the fricative frames have between 62 and 96 crossings, far above IZCT, while the background frames have about 9. In line L6, all 10 frames 30 to 39 before N1N_1 have Z>IZCTZ > IZCT, so N1N_1 moves to 30. In line L7, the 8 frames 90 to 97 qualify, so N2N_2 moves to 97. The result is (30,97)(30, 97), which is the whole word. The same recording without the fricatives gives (30,79)(30, 79), the tone alone, because the refinement finds no frames with high ZZ.

Correctness

Whether the frames N1N_1 to N2N_2 are the word depends on the recording, and the thresholds are heuristics that Rabiner and Sambur tuned on their data. What can be proved is what the output means in terms of EE and ZZ. The full proofs are below.

  • The thresholds are ordered. If IMN>0IMN > 0, then IMN<ITLIMN < ITL when IMX>IMNIMX > IMN, and ITL<ITUITL < ITU always (theorem).
  • The interval holds every loud frame. If line L4 finds N1N_1, then line L5 finds an N2≥N1N_2 \ge N_1, every frame with E>ITUE > ITU lies between N1N_1 and N2N_2 after lines L4 and L5, and the refinement only widens the interval (theorem).
  • The ends are word-like. After line L5, E[N1]>ITLE[N_1] > ITL and E[N2]>ITLE[N_2] > ITL, and each connects to a frame above ITU through frames above ITL. After lines L6 and L7, a moved endpoint is a frame with Z>IZCTZ > IZCT (theorem).
  • Gain does not matter. Multiplying the recording by c>0c > 0 multiplies every EE and every threshold of line L3 by cc and leaves every ZZ unchanged, so the endpoints do not change (theorem).
Proof: What the endpoints of Rabiner and Sambur guarantee about energy and zero crossingsfull

The thresholds of the algorithm are heuristics, so no proof can show that the output is the word. We prove what the output means in terms of the frame measures EE and ZZ. We work in the real RAM with T≥10T \ge 10 frames, and we use the words of lines L1 to L8.

Call a frame high if E[i]>ITUE[i] > ITU and active if E[i]>ITLE[i] > ITL. A run is a maximal block of consecutive active frames. A run is strong if it holds a high frame.

Lemma 1 (the thresholds are ordered). If IMN>0IMN > 0, then ITL≥IMN>0ITL \ge IMN > 0 and ITU=5 ITL>ITLITU = 5\,ITL > ITL. If also IMX>IMNIMX > IMN, then ITL>IMNITL > IMN.

Proof. Since IMNIMN is the mean of the first 10 energies and IMXIMX is the maximum of all of them, IMX≥IMNIMX \ge IMN. So 0.03(IMX−IMN)+IMN≥IMN0.03(IMX - IMN) + IMN \ge IMN, and 4 IMN>IMN4\,IMN > IMN. Their minimum is at least IMNIMN, and strictly above it when IMX>IMNIMX > IMN. Finally 5 ITL>ITL5\,ITL > ITL because ITL>0ITL > 0. □\square

By Lemma 1, a high frame is active when IMN>0IMN > 0, so every high frame lies in a strong run. If IMN=0IMN = 0 (digital silence), then ITL=ITU=0ITL = ITU = 0, a frame is active exactly when it is high, and everything below still holds.

Lemma 2 (line L4 finds the start of the first strong run). The forward scan of line L4 returns the first frame of the first strong run, and returns nothing if there is no strong run. Line L5 returns the last frame of the last strong run.

Proof. The scan keeps a candidate cc. At a frame that is not active it clears cc. At an active frame with no candidate it sets cc to that frame, so cc is always the first frame of the run that contains the current frame. At a high frame it returns cc. So the scan returns at the first high frame it meets, with the first frame of its run, and that run is the first strong run, because any earlier strong run would hold an earlier high frame. If there is no high frame, it returns nothing. The backward scan is the same on the reversed sequence, where the first frame of a run is its last frame in time. □\square

Theorem 1 (the interval holds every loud frame). If line L4 returns N1N_1, then line L5 returns some N2≥N1N_2 \ge N_1, every high frame ii satisfies N1≤i≤N2N_1 \le i \le N_2, and lines L6 and L7 only lower N1N_1 and raise N2N_2.

Proof. If L4 returns, a strong run exists, so L5 returns too. By Lemma 2, N1N_1 is the start of the first strong run and N2N_2 the end of the last one, so N1≤N2N_1 \le N_2, and every high frame lies in some strong run, between the start of the first and the end of the last. Line L6 replaces N1N_1 only by a frame among the 25 before it, and line L7 replaces N2N_2 only by a frame among the 25 after it. □\square

Theorem 2 (the ends are word-like). After line L5, E[N1]>ITLE[N_1] > ITL and E[N2]>ITLE[N_2] > ITL, and the frames from N1N_1 to the first high frame, and from the last high frame to N2N_2, are all active. If line L6 changes N1N_1, then Z[N1]>IZCTZ[N_1] > IZCT, N1N_1 was at most 25 frames before the old value, and at least 3 frames in that span have Z>IZCTZ > IZCT; the same holds for line L7 and N2N_2.

Proof. The first part is Lemma 2: N1N_1 and N2N_2 are ends of strong runs, so they are active, and the frames of a run are active. Line L6 moves N1N_1 only when at least 3 of the 25 frames before it have Z>IZCTZ > IZCT, and then to the earliest of those frames, which has Z>IZCTZ > IZCT. Line L7 is symmetric. □\square

Theorem 3 (gain does not matter). Let s′[n]=c s[n]s'[n] = c\, s[n] with c>0c > 0. Then the algorithm returns the same result for s′s' as for ss.

Proof. Each E′[i]=c E[i]E'[i] = c\,E[i], and the sign of c s[n]c\,s[n] is the sign of s[n]s[n] (with 00 counted as positive in both), so Z′=ZZ' = Z and IZCT′=IZCTIZCT' = IZCT. Then IMN′=c IMNIMN' = c\,IMN and IMX′=c IMXIMX' = c\,IMX, and since c>0c > 0 factors out of the minimum, ITL′=c ITLITL' = c\,ITL and ITU′=c ITUITU' = c\,ITU. Every comparison E′[i]>ITL′E'[i] > ITL' or E′[i]>ITU′E'[i] > ITU' has the same answer as for ss, so lines L4 to L7 make the same choices. □\square

The tests check the frame measures and the thresholds by hand, Lemma 2 against a direct search over all frames, the rules of lines L6 and L7 with exactly 2 and 3 hits and with ZZ equal to IZCT, and the full detector on a synthetic word with and without weak fricatives.

Complexity

In the real RAM, line L1 reads every sample once, O(L)O(L) time. Lines L2 and L3 cost O(T)O(T), lines L4 and L5 each scan at most TT frames, and lines L6 and L7 look at 25 frames each. The total is O(L)O(L) time, and the arrays EE and ZZ take O(T)O(T) memory. For one second at 16 kHz this is 16 000 samples and 100 frames.

Properties

  • Offline. IMX in line L3 is the maximum over the whole recording, and line L5 scans from the end, so the algorithm needs the whole recording before it answers.
  • One word. It returns one interval. Pauses inside the word, such as the closure before a stop consonant, stay inside the interval, but two words with a long pause give one interval that holds both.
  • Few parameters. All thresholds adapt to the recording through IMN, IMX and the statistics of ZZ in the silence. Nothing is trained.
  • Gain invariant, not offset invariant. A gain changes nothing, but a DC offset changes the zero crossings of the quiet frames.

Variants and improvements

  • Squared energy or log energy. Many later detectors use ∑s[n]2\sum s[n]^2 or its log in place of the sum of magnitudes. The thresholds must then be set again, since the ratios 0.03, 4 and 5 were chosen for the sum of magnitudes.
  • Adaptive background. Continuous speech systems update the noise statistics in pauses, in place of reading them once from the first 100 ms. This turns the method into a frame-wise voice activity detector.
  • Statistical detectors. A likelihood ratio VAD models the noise and the speech spectra and decides per frame, which works at a lower signal to noise ratio.
  • Hangover. Detectors for streams keep the speech label for a few frames after the energy drops, which plays the role of the backward search here.

When to use it

Use the Rabiner-Sambur detector for isolated words recorded in a quiet room, such as command words for a dynamic time warping recognizer, where a clean start and end matter and the recording begins with silence. It is cheap and needs no training data. Do not use it for continuous speech, for streams without a known silent start, or at low signal to noise ratios: there a statistical voice activity detector or the silence model of an HMM recognizer does better.

Pitfalls

  • No silence at the start. If the speaker starts at once, the first 10 frames contain speech, IMN and IZC are far too high, and the word is cut or missed.
  • DC offset. A constant offset can make the background never cross zero, so IZC is near 0 and IZCT is small, or it can hide the crossings of a fricative. Remove the mean before line L1.
  • Hum and hiss. A background with many zero crossings, such as broadband hiss, makes IZCT reach the bound of 25, and then fricatives that are quieter than the hiss are not found.
  • Mouth noise. Lip smacks and breaths just before or after the word can exceed ITU or have high ZZ, and then they are included.
  • Frame length. The bound of 25 crossings is per 10 ms. With another frame length, scale it by the frame length.

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.

nlsdsp.pyI0RawGitHub
# 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
rabiner_sambur_endpoint_detection.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rabiner-sambur-endpoint-detection/. The authors are listed in prov/B6AHEG.jsonl.

"""The endpoint detector of Rabiner and Sambur (1975) for an isolated word.

The signal is cut into frames of 10 ms with no overlap and no padding. Each frame
gets an energy E (the sum of the magnitudes of its samples) and a zero-crossing
count Z. The first 100 ms (10 frames) are taken to be background silence.

Two energy thresholds, ITL below ITU, give a first estimate (N1, N2) of the
word: N1 is the first frame where E rises above ITL and then goes above ITU before
it falls back to ITL or below; N2 is the same from the end. Then the zero-crossing
threshold IZCT moves N1 back (and N2 forward) over at most 25 frames, to take in
weak fricatives, when 3 or more of those frames have Z above IZCT.

The constants 0.03, 4, 5, 25 crossings, 2 standard deviations, 25 frames and
3 frames are the heuristic values of the paper. IMN is taken here as the mean
energy of the silence frames. A frame index is 0 based; the word is the frames
N1 to N2, both included.
"""

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

from nlsdsp import frames


def frame_energy(frame: Sequence[float]) -> float:
    """E = sum of |s[n]| over the frame."""
    return sum(abs(v) for v in frame)


def zero_crossings(frame: Sequence[float]) -> int:
    """The number of n with sgn(s[n]) != sgn(s[n - 1]) inside the frame, where sgn(0) = +1."""
    return sum(1 for a, b in zip(frame, frame[1:]) if (a >= 0.0) != (b >= 0.0))


def features(x: Sequence[float], fs: float = 16000.0) -> Tuple[List[float], List[int]]:
    """E and Z of each 10 ms frame. A signal of L samples gives floor(L / (fs / 100)) frames."""
    n = int(round(fs / 100.0))
    fr = frames(x, n, n)
    return [frame_energy(f) for f in fr], [zero_crossings(f) for f in fr]


def thresholds(
    energy: Sequence[float], zcr: Sequence[int], silence_frames: int = 10, zc_fixed: float = 25.0
) -> Tuple[float, float, float]:
    """(ITL, ITU, IZCT) from the energy and zero-crossing sequences."""
    if len(energy) < silence_frames or silence_frames < 1:
        raise ValueError("the signal must hold the silence frames")
    sil_z = list(zcr[:silence_frames])
    izc = sum(sil_z) / len(sil_z)
    sigma = math.sqrt(sum((z - izc) ** 2 for z in sil_z) / len(sil_z))
    izct = min(zc_fixed, izc + 2.0 * sigma)  # @line L2
    imx = max(energy)
    imn = sum(energy[:silence_frames]) / silence_frames
    itl = min(0.03 * (imx - imn) + imn, 4.0 * imn)
    itu = 5.0 * itl  # @line L3
    return itl, itu, izct


def first_crossing(energy: Sequence[float], order: Sequence[int], itl: float, itu: float) -> Optional[int]:
    """The first index, in the given order, where E goes above ITL and then above ITU
    before it falls to ITL or below. None if there is no such index."""
    cand: Optional[int] = None
    for i in order:
        if energy[i] <= itl:
            cand = None
            continue
        if cand is None:
            cand = i
        if energy[i] > itu:
            return cand
    return None


def refine(zcr: Sequence[int], start: int, step: int, izct: float, span: int = 25, need: int = 3) -> int:
    """Look at the span frames before start (step = -1) or after it (step = +1). If need or
    more of them have Z > IZCT, return the one of them farthest from start; else return start."""
    hits = []
    for d in range(1, span + 1):
        j = start + step * d
        if j < 0 or j >= len(zcr):
            break
        if zcr[j] > izct:
            hits.append(j)
    return hits[-1] if len(hits) >= need else start


def endpoints_from_features(
    energy: Sequence[float], zcr: Sequence[int], silence_frames: int = 10
) -> Optional[Tuple[int, int]]:
    """(N1, N2) as frame indices, or None when no frame goes above ITU."""
    if len(energy) != len(zcr):
        raise ValueError("energy and zcr must have the same length")
    itl, itu, izct = thresholds(energy, zcr, silence_frames)
    n = len(energy)
    n1 = first_crossing(energy, range(n), itl, itu)  # @line L4
    if n1 is None:
        return None
    n2 = first_crossing(energy, range(n - 1, -1, -1), itl, itu)  # @line L5
    n1 = refine(zcr, n1, -1, izct)  # @line L6
    n2 = refine(zcr, n2, +1, izct)  # @line L7
    return n1, n2  # @line L8


def detect_endpoints(x: Sequence[float], fs: float = 16000.0) -> Optional[Tuple[int, int]]:
    """The word boundaries (N1, N2) as frame indices of 10 ms, or None if no word is found."""
    energy, zcr = features(x, fs)  # @line L1
    return endpoints_from_features(energy, zcr)
test_rabiner_sambur_endpoint_detection.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rabiner-sambur-endpoint-detection/. The authors are listed in prov/B6AHEG.jsonl.

import random

from nlsdsp import all_pole, sine, white_noise
from rabiner_sambur_endpoint_detection import (
    detect_endpoints,
    endpoints_from_features,
    features,
    first_crossing,
    frame_energy,
    refine,
    thresholds,
    zero_crossings,
)

FS = 16000.0


def _background(rng, n):
    # low-pass noise: a lag-one correlation near 0.98 gives few zero crossings
    return all_pole(white_noise(rng, n, 0.0006), [0.98])


def _word(rng, lead_fricative=0, tail_fricative=0):
    """300 ms of background, an optional weak fricative, 500 ms of tone, an optional fricative, 300 ms of background."""
    sig = _background(rng, 4800)
    sig += white_noise(rng, 160 * lead_fricative, 0.006)
    sig += [s + b for s, b in zip(sine(300.0, FS, 8000, 0.3), _background(rng, 8000))]
    sig += white_noise(rng, 160 * tail_fricative, 0.006)
    sig += _background(rng, 4800)
    return sig


def test_frame_measures():
    assert frame_energy([0.5, -0.25, 0.0, 1.0]) == 1.75
    # zero counts as positive: + - + + - gives 3 sign changes
    assert zero_crossings([1.0, -1.0, 1.0, 0.0, -1.0]) == 3
    assert zero_crossings([0.0, 0.0, 0.0]) == 0
    e, z = features(sine(300.0, FS, 1600), FS)
    assert len(e) == 10 and len(z) == 10
    assert all(5 <= v <= 7 for v in z)  # about 2 f / fs * 160 = 6 per frame
    e, _ = features([0.0] * 1599, FS)
    assert len(e) == 9


def test_thresholds_by_hand():
    energy = [1.0] * 10 + [100.0]
    zcr = [10] * 10 + [3]
    itl, itu, izct = thresholds(energy, zcr)
    assert abs(itl - 3.97) < 1e-12 and abs(itu - 19.85) < 1e-12
    assert izct == 10.0
    # a noisy silence: IZC + 2 sigma is above 25, so the fixed value IF = 25 wins
    _, _, izct = thresholds(energy, [20, 30] * 5 + [3])
    assert izct == 25.0
    # a loud word: 0.03 (IMX - IMN) + IMN is above 4 IMN, so ITL = 4 IMN
    itl, itu, _ = thresholds([1.0] * 10 + [1000.0], zcr)
    assert itl == 4.0 and itu == 20.0


def _first_crossing_spec(energy, order, itl, itu):
    order = list(order)
    for pos, i in enumerate(order):
        if energy[i] > itl and (pos == 0 or energy[order[pos - 1]] <= itl):
            run = []
            for j in order[pos:]:
                if energy[j] <= itl:
                    break
                run.append(j)
            if any(energy[j] > itu for j in run):
                return i
    return None


def test_first_crossing_against_the_spec():
    rng = random.Random(9)
    for _ in range(400):
        n = rng.randint(1, 30)
        energy = [rng.choice([0.0, 1.0, 2.0, 3.0, 6.0]) * rng.uniform(0.5, 1.5) for _ in range(n)]
        for order in (range(n), range(n - 1, -1, -1)):
            assert first_crossing(energy, order, 1.5, 5.0) == _first_crossing_spec(energy, order, 1.5, 5.0)


def test_refine_rules():
    z = [0] * 40
    for j in (12, 20, 30):
        z[j] = 50
    assert refine(z, 35, -1, 25.0) == 12  # three hits in the 25 frames before 35: go to the earliest
    assert refine(z, 37, -1, 25.0) == 12  # frames 12 to 36 are the 25 frames before 37
    assert refine(z, 38, -1, 25.0) == 38  # frame 12 is now outside, and two hits are not enough
    z[12] = 0
    assert refine(z, 35, -1, 25.0) == 35  # two hits are not enough
    z = [0] * 40
    for j in (5, 6, 9):
        z[j] = 26
    assert refine(z, 2, +1, 25.0) == 9
    z[9] = 25  # Z must be strictly above IZCT
    assert refine(z, 2, +1, 25.0) == 2


def test_tone_word():
    # the tone fills the frames 30 to 79
    assert detect_endpoints(_word(random.Random(1)), FS) == (30, 79)


def test_weak_fricatives_are_found_by_the_zero_crossings():
    rng = random.Random(1)
    sig = _word(rng, lead_fricative=10, tail_fricative=8)
    energy, zcr = features(sig, FS)
    itl, _, izct = thresholds(energy, zcr)
    # the fricative frames stay under ITL, so the energy alone misses them
    assert all(e < itl for e in energy[30:40]) and all(z > izct for z in zcr[30:40])
    assert first_crossing(energy, range(len(energy)), *thresholds(energy, zcr)[:2]) == 40
    assert endpoints_from_features(energy, zcr) == (30, 97)


def test_background_alone_gives_no_word():
    for seed in range(5):
        assert detect_endpoints(_background(random.Random(seed), 16000), FS) is None


def test_bad_arguments():
    try:
        detect_endpoints([0.0] * 1000, FS)
    except ValueError:
        pass
    else:
        raise AssertionError("a signal shorter than 100 ms must fail")
    try:
        endpoints_from_features([1.0] * 12, [0] * 11)
    except ValueError:
        pass
    else:
        raise AssertionError("lengths must match")

History

Endpoint detection was a central problem for the isolated word recognizers of the 1970s, which matched a whole word against stored templates and failed when the word boundaries were wrong. Rabiner and Sambur published their detector in 1975, at Bell Laboratories, and added the zero-crossing search to recover the weak fricatives that an energy detector cuts off. The method appears in the 1978 textbook of Rabiner and Schafer and became a standard teaching example of time domain speech processing. Later recognizers based on hidden Markov models handled silence with their own models, and modern systems use statistical or neural voice activity detectors.

References

  1. L. R. Rabiner and M. R. Sambur, An algorithm for determining the endpoints of isolated utterances, The Bell System Technical Journal 54(2), 1975, 297 to 315, the description of the algorithm: the silence statistics of the first 100 ms, the thresholds ITL, ITU and IZCT, the energy search for N1 and N2, and the search over 25 frames for weak fricatives
  2. L. R. Rabiner and R. W. Schafer, Digital Processing of Speech Signals, Prentice Hall, 1978, Chapter 4 (time domain processing of speech), the discussion of speech and silence discrimination with energy and zero-crossing rate

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