"""Simulate a narrowband telephone line. Wideband speech goes through what a PSTN call does to it: resample to 8 kHz, band-limit to 300-3400 Hz, G.711 mu-law companding, then back to 16 kHz because that is what the recognizers expect (and what a voice agent feeds them). """ from __future__ import annotations import numpy as np from scipy.signal import butter, resample_poly, sosfilt WIDEBAND_RATE = 16_000 NARROWBAND_RATE = 8_000 _BIAS = 0x84 _CLIP = 32_635 _SEGMENT_STARTS = np.array([0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000], dtype=np.int32) _VOICE_BAND = butter(4, [300, 3400], btype="bandpass", fs=NARROWBAND_RATE, output="sos") def ulaw_encode(pcm16: np.ndarray) -> np.ndarray: """16-bit linear PCM -> 8-bit G.711 mu-law (same result as the Sun g711.c reference).""" x = pcm16.astype(np.int32) sign = np.where(x < 0, 0x80, 0) magnitude = np.minimum(np.abs(x), _CLIP) + _BIAS segment = np.searchsorted(_SEGMENT_STARTS, magnitude, side="right").astype(np.int32) mantissa = (magnitude >> (segment + 3)) & 0x0F return (~(sign | (segment << 4) | mantissa) & 0xFF).astype(np.uint8) def ulaw_decode(ulaw: np.ndarray) -> np.ndarray: """8-bit G.711 mu-law -> 16-bit linear PCM.""" u = ~ulaw.astype(np.int32) & 0xFF segment = (u >> 4) & 0x07 mantissa = u & 0x0F magnitude = (((mantissa << 3) + _BIAS) << segment) - _BIAS return np.where(u & 0x80, -magnitude, magnitude).astype(np.int16) def telephone_channel(audio: np.ndarray, sample_rate: int = WIDEBAND_RATE) -> np.ndarray: """Pass 16 kHz float audio in [-1, 1] through a simulated phone line; returns 16 kHz float32.""" if sample_rate != WIDEBAND_RATE: raise ValueError(f"expected {WIDEBAND_RATE} Hz audio, got {sample_rate} Hz") narrow = resample_poly(audio.astype(np.float64), 1, 2) narrow = sosfilt(_VOICE_BAND, narrow) pcm = np.clip(np.round(narrow * 32768.0), -32768, 32767).astype(np.int16) pcm = ulaw_decode(ulaw_encode(pcm)) wide = resample_poly(pcm.astype(np.float64) / 32768.0, 2, 1) return wide[: len(audio)].astype(np.float32)