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.
- Solves
- Voice activity detection
- Time
- O(L) worst
- Space
- O(T) extra
- Where
- L = the number of samples; T = the number of 10 ms frames
- Model
- Real RAM
- Properties
- deterministicexactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 of an isolated word at a sample rate , in which the first 100 ms are background only, find frame indices such that the word occupies the frames to , or report that there is no word. The frames are 10 ms long, with no overlap and no padding, so a recording of samples gives frames. This page uses kHz, so a frame has 160 samples.
The algorithm
For each frame the energy is over the frame, and 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.
RABINER-SAMBUR(s, f_s)- 1
cut s into 10 ms frames; for each frame i: E[i] ← Σ |s[n]|, Z[i] ← number of sign changes - 2
IZC, σ ← mean and standard deviation of Z[0 .. 9]; IZCT ← min(25, IZC + 2σ) - 3
IMN ← mean of E[0 .. 9]; IMX ← max E; ITL ← min(0.03 (IMX - IMN) + IMN, 4 IMN); ITU ← 5 ITL - 4
N1 ← 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" - 5
N2 ← the same, going backward from the last frame - 6
if at least 3 of the 25 frames before N1 have Z > IZCT, then N1 ← the earliest of them - 7
if at least 3 of the 25 frames after N2 have Z > IZCT, then N2 ← the latest of them - 8
return (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 over those 10 frames, and takes 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 , so it has few zero crossings.
Lines L2 and L3 give and , and . Since is below , and . The fricative frames have energies between about 0.73 and 0.82, below ITL, so lines L4 and L5 find only the tone: and . 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 have , so moves to 30. In line L7, the 8 frames 90 to 97 qualify, so moves to 97. The result is , which is the whole word. The same recording without the fricatives gives , the tone alone, because the refinement finds no frames with high .
Correctness
Whether the frames to 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 and . The full proofs are below.
- The thresholds are ordered. If , then when , and always (theorem).
- The interval holds every loud frame. If line L4 finds , then line L5 finds an , every frame with lies between and after lines L4 and L5, and the refinement only widens the interval (theorem).
- The ends are word-like. After line L5, and , and each connects to a frame above ITU through frames above ITL. After lines L6 and L7, a moved endpoint is a frame with (theorem).
- Gain does not matter. Multiplying the recording by multiplies every and every threshold of line L3 by and leaves every 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 and . We work in the real RAM with frames, and we use the words of lines L1 to L8.
Call a frame high if and active if . 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 , then and . If also , then .
Proof. Since is the mean of the first 10 energies and is the maximum of all of them, . So , and . Their minimum is at least , and strictly above it when . Finally because .
By Lemma 1, a high frame is active when , so every high frame lies in a strong run. If (digital silence), then , 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 . At a frame that is not active it clears . At an active frame with no candidate it sets to that frame, so is always the first frame of the run that contains the current frame. At a high frame it returns . 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.
Theorem 1 (the interval holds every loud frame). If line L4 returns , then line L5 returns some , every high frame satisfies , and lines L6 and L7 only lower and raise .
Proof. If L4 returns, a strong run exists, so L5 returns too. By Lemma 2, is the start of the first strong run and the end of the last one, so , and every high frame lies in some strong run, between the start of the first and the end of the last. Line L6 replaces only by a frame among the 25 before it, and line L7 replaces only by a frame among the 25 after it.
Theorem 2 (the ends are word-like). After line L5, and , and the frames from to the first high frame, and from the last high frame to , are all active. If line L6 changes , then , was at most 25 frames before the old value, and at least 3 frames in that span have ; the same holds for line L7 and .
Proof. The first part is Lemma 2: and are ends of strong runs, so they are active, and the frames of a run are active. Line L6 moves only when at least 3 of the 25 frames before it have , and then to the earliest of those frames, which has . Line L7 is symmetric.
Theorem 3 (gain does not matter). Let with . Then the algorithm returns the same result for as for .
Proof. Each , and the sign of is the sign of (with counted as positive in both), so and . Then and , and since factors out of the minimum, and . Every comparison or has the same answer as for , so lines L4 to L7 make the same choices.
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 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, time. Lines L2 and L3 cost , lines L4 and L5 each scan at most frames, and lines L6 and L7 look at 25 frames each. The total is time, and the arrays and take 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 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 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 , 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.
# 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
- 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
- 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.
| 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 B6AHEG Edit this page History Report an error Markdown