bandsaunter/bandsaunter/demod.py
The Dust Council 2aa8739f25 Tune SSB to the carrier, and read the sideband from the signal
An SSB capture was tuned to the centroid of the detected energy, which is
what every other mode wants and the one thing SSB cannot use. Its
demodulator is a filter that opens at the suppressed carrier, so centring
on the middle of the voice filtered off its lower half and shifted the
rest down by the error. Measured against known transmitters that error was
+2445 Hz on 20 m and -2486 Hz on 80 m, against 35 Hz for NFM and 9 Hz for
AM, which do not care either way. On real speech the difference is a clean
transcript versus nothing recognisable at all.

Speech puts most of its power just above the carrier, so the occupied band
leans towards it. ssb_alignment() reads that lean: it locates the carrier
to within about 100 Hz and names the sideband at the same time, without
recourse to any convention. The offset is applied inside the demodulator
at the IF rate, where it costs a fraction of what shifting the full-rate
stream would, and the reported frequency becomes the carrier -- the
frequency an operator would dial in.

The sideband was also decided by "LSB below 10 MHz, USB above", which
overrode a band plan that already knew better and demodulated 60 m as LSB.
The measurement decides now, the band plan when the signal has no lean to
read, and the convention only when neither has anything to say.

The simulator was transmitting SSB unfiltered, several times wider than
anything on the air, because it applied no transmit audio filter -- and
that filter is what makes a signal single-sideband. Its absence hid the
whole problem from the tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 23:09:44 -07:00

344 lines
11 KiB
Python
Executable file

"""Streaming demodulators.
Each demodulator consumes consecutive blocks of complex baseband at the
device sample rate and emits float32 audio in [-1, 1]. All internal filters
are stateful, so a recording assembled from many blocks has no seams.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import numpy as np
from scipy import signal as sps
from .dsp import DecimationChain, Mixer
__all__ = ["make_demodulator", "Demodulator", "MODES", "plan_rates",
"DEEMPHASIS_US"]
MODES = ("nfm", "wfm", "am", "usb", "lsb", "cw", "dsb", "raw")
DEEMPHASIS_US = 75e-6 # North America; Europe uses 50 us
def _small_prime_divisors(n: int, limit: int = 8192) -> list[int]:
"""Divisors of ``n`` built only from 2/3/5 -- the ones that decimate cleanly."""
out = {1}
for p in (2, 3, 5):
cur = set(out)
for v in cur:
m = v
while m * p <= limit and n % (m * p) == 0:
m *= p
out.add(m)
return sorted(out)
def plan_rates(sample_rate: int, bandwidth: float, audio_rate: int,
min_if_factor: float = 2.5) -> tuple[int, int, int, int]:
"""Choose IF and audio decimation for one demod chain.
Returns ``(if_decim, audio_decim, if_rate, actual_audio_rate)``. The IF
rate is kept at least ``min_if_factor`` times the signal bandwidth so the
discriminator is not clipped by its own anti-alias filter.
"""
sample_rate = int(sample_rate)
divisors = _small_prime_divisors(sample_rate)
total = min(divisors, key=lambda d: abs(sample_rate / d - audio_rate))
actual_audio = int(round(sample_rate / total))
need_if = max(bandwidth * min_if_factor, actual_audio * 2.0)
if_decim = 1
for d in divisors:
if d > total:
break
if sample_rate / d >= need_if and total % d == 0:
if_decim = d
audio_decim = max(1, total // if_decim)
if_rate = int(round(sample_rate / if_decim))
return if_decim, audio_decim, if_rate, actual_audio
class _DCBlock:
"""One-pole DC blocker, keeps voice from riding on a slow offset."""
def __init__(self, r: float = 0.995):
self.r = r
self._x1 = 0.0
self._y1 = 0.0
def __call__(self, x: np.ndarray) -> np.ndarray:
y, zf = sps.lfilter([1.0, -1.0], [1.0, -self.r], x,
zi=[self.r * self._y1 - self._x1])
self._x1 = float(x[-1]) if x.size else self._x1
self._y1 = float(y[-1]) if y.size else self._y1
return y
class _AGC:
"""Slow level control so quiet and loud transmissions land at similar volume."""
def __init__(self, target: float = 0.25, attack: float = 0.02,
release: float = 0.002, max_gain: float = 200.0):
self.target = target
self.attack = attack
self.release = release
self.max_gain = max_gain
self.gain = 1.0
def __call__(self, x: np.ndarray) -> np.ndarray:
if x.size == 0:
return x
level = float(np.sqrt(np.mean(x.astype(np.float64) ** 2))) + 1e-9
want = min(self.max_gain, self.target / level)
a = self.attack if want < self.gain else self.release
self.gain = (1.0 - a) * self.gain + a * want
return x * self.gain
@dataclass
class Demodulator:
"""Base class -- subclasses implement :meth:`_demod`."""
sample_rate: int
bandwidth: float
audio_rate: int = 16_000
mode: str = "raw"
def __post_init__(self):
self.if_decim, self.audio_decim, self.if_rate, self.audio_rate = plan_rates(
self.sample_rate, self.bandwidth, self.audio_rate,
min_if_factor=self._min_if_factor()
)
self.if_chain = DecimationChain(self.if_decim, complex_input=True)
self.audio_chain = DecimationChain(self.audio_decim, complex_input=False)
self.dc = _DCBlock()
self.agc = _AGC()
self._setup()
def _min_if_factor(self) -> float:
return 2.5
def _setup(self) -> None:
pass
def reset(self) -> None:
self.if_chain.reset()
self.audio_chain.reset()
self.dc = _DCBlock()
self.agc = _AGC()
self._setup()
# -- pipeline ------------------------------------------------------
def to_if(self, x: np.ndarray) -> np.ndarray:
"""Complex baseband at the IF rate -- also what the classifier sees."""
return self.if_chain(x)
def _demod(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
def _post(self, audio: np.ndarray) -> np.ndarray:
return audio
def step(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Return ``(audio, if_iq)``.
The recorder wants both: audio to write, and the IF-rate complex
baseband to hand to the classifier.
"""
empty_a = np.zeros(0, dtype=np.float32)
empty_i = np.zeros(0, dtype=np.complex64)
if x.size == 0:
return empty_a, empty_i
iq = self.to_if(x)
if iq.size == 0:
return empty_a, empty_i
audio = self._demod(iq)
audio = self._post(audio)
audio = self.audio_chain(audio)
if audio.size == 0:
return empty_a, iq
audio = self.dc(audio)
audio = self.agc(audio)
return np.clip(audio, -1.0, 1.0).astype(np.float32), iq
def process(self, x: np.ndarray) -> np.ndarray:
return self.step(x)[0]
class FMDemod(Demodulator):
"""Quadrature discriminator with optional de-emphasis."""
deemphasis: float | None = DEEMPHASIS_US
def _min_if_factor(self) -> float:
return 2.0
def _setup(self) -> None:
self._last = np.complex64(0)
tau = getattr(self, "deemphasis", DEEMPHASIS_US)
if tau:
a = math.exp(-1.0 / (tau * self.if_rate))
self._de_b = [1.0 - a]
self._de_a = [1.0, -a]
self._de_zi = np.zeros(1)
else:
self._de_b = None
def _demod(self, x: np.ndarray) -> np.ndarray:
prev = np.empty(x.size, dtype=np.complex64)
prev[0] = self._last
prev[1:] = x[:-1]
self._last = x[-1]
# Scale so full deviation maps to roughly +-1.
gain = self.if_rate / (2.0 * math.pi * max(1.0, self.bandwidth / 2.0))
return np.angle(x * np.conj(prev)).astype(np.float64) * gain
def _post(self, audio: np.ndarray) -> np.ndarray:
if self._de_b is None:
return audio
out, self._de_zi = sps.lfilter(self._de_b, self._de_a, audio, zi=self._de_zi)
return out
class NFMDemod(FMDemod):
pass
class WFMDemod(FMDemod):
def _min_if_factor(self) -> float:
return 1.4 # 180 kHz signal in a 256 kHz IF is normal for broadcast FM
class AMDemod(Demodulator):
"""Envelope detector. Works for airband, shortwave and CB AM."""
def _demod(self, x: np.ndarray) -> np.ndarray:
return np.abs(x).astype(np.float64)
class SSBDemod(Demodulator):
"""Single-sideband via a one-sided complex band-pass, then take the real part."""
upper: bool = True
# Where the suppressed carrier sits relative to the tuned centre. The
# filter below opens at the carrier and everything under it is discarded,
# so this is the one demodulator that has to be told exactly where the
# signal begins; the scanner measures it and passes it in. Shifting here,
# at the IF rate, costs a fraction of what shifting the full-rate stream
# would, and the IF passband is far wider than any plausible offset.
carrier_offset_hz: float = 0.0
def _setup(self) -> None:
self._zi = None
self._taps = None
self._carrier = (Mixer(self.carrier_offset_hz, self.if_rate)
if self.carrier_offset_hz else None)
def _sideband_taps(self):
if self._taps is None:
lo, hi = (200.0, self.bandwidth) if getattr(self, "upper", True) \
else (-self.bandwidth, -200.0)
centre = 0.5 * (lo + hi)
half = 0.5 * abs(hi - lo)
proto = sps.firwin(129, min(half / (self.if_rate / 2.0), 0.99))
n = np.arange(proto.size) - proto.size // 2
self._taps = (proto * np.exp(2j * math.pi * centre * n / self.if_rate))
self._zi = np.zeros(self._taps.size - 1, dtype=np.complex128)
return self._taps
def _demod(self, x: np.ndarray) -> np.ndarray:
if self._carrier is not None:
x = self._carrier(x)
taps = self._sideband_taps()
y, self._zi = sps.lfilter(taps, [1.0], x, zi=self._zi)
return 2.0 * y.real
class USBDemod(SSBDemod):
upper = True
class LSBDemod(SSBDemod):
upper = False
class CWDemod(SSBDemod):
"""SSB with a narrow filter and a beat-frequency offset, so CW is audible."""
upper = True
bfo_hz: float = 700.0
def _setup(self) -> None:
self._zi = None
self._taps = None
self._mixer = Mixer(-getattr(self, "bfo_hz", 700.0), self.if_rate)
def _sideband_taps(self):
if self._taps is None:
bfo = getattr(self, "bfo_hz", 700.0)
half = max(150.0, self.bandwidth / 2.0)
lo, hi = bfo - half, bfo + half
centre = 0.5 * (lo + hi)
proto = sps.firwin(255, min((0.5 * (hi - lo)) / (self.if_rate / 2.0), 0.99))
n = np.arange(proto.size) - proto.size // 2
self._taps = (proto * np.exp(2j * math.pi * centre * n / self.if_rate))
self._zi = np.zeros(self._taps.size - 1, dtype=np.complex128)
return self._taps
def _demod(self, x: np.ndarray) -> np.ndarray:
# Shift the (near-DC) carrier up to the BFO pitch before filtering.
x = self._mixer(x)
taps = self._sideband_taps()
y, self._zi = sps.lfilter(taps, [1.0], x, zi=self._zi)
return 2.0 * y.real
class DSBDemod(Demodulator):
"""Coherent-ish DSB / product detector; also a usable fallback for raw IQ."""
def _demod(self, x: np.ndarray) -> np.ndarray:
return x.real.astype(np.float64) * 2.0
class RawDemod(Demodulator):
"""No demodulation -- magnitude only, so 'listening' to data still shows activity."""
def _demod(self, x: np.ndarray) -> np.ndarray:
return np.abs(x).astype(np.float64)
_CLASSES = {
"nfm": NFMDemod,
"wfm": WFMDemod,
"fm": NFMDemod,
"am": AMDemod,
"usb": USBDemod,
"lsb": LSBDemod,
"ssb": USBDemod,
"cw": CWDemod,
"dsb": DSBDemod,
"raw": RawDemod,
}
# Broadcast FM carries content well past the 8 kHz a 16 kHz audio rate can
# hold, so it gets a higher floor than the narrowband modes.
_MIN_AUDIO_RATE = {"wfm": 32_000}
def make_demodulator(mode: str, sample_rate: int, bandwidth: float,
audio_rate: int = 16_000, **kw) -> Demodulator:
mode = (mode or "nfm").lower()
audio_rate = max(audio_rate, _MIN_AUDIO_RATE.get(mode, 0))
cls = _CLASSES.get(mode, RawDemod)
obj = cls(sample_rate=sample_rate, bandwidth=bandwidth,
audio_rate=audio_rate, mode=mode)
for k, v in kw.items():
setattr(obj, k, v)
if kw:
obj.reset()
return obj