Skip to main content

lib_jsl_dsp/discrete/digital_communications/
fm.rs

1//! Frequency modulation (FM) and demodulation of complex baseband signals.
2//!
3//! In FM the message `m[n]` sets the *instantaneous frequency* of a constant-envelope carrier:
4//! `f[n] = k_f · m[n]` Hz, so the baseband signal is `y[n] = e^{jφ[n]}` with
5//! `φ[n] = 2π Σ_{i≤n} f[i] / fs`. The peak deviation is `k_f · max|m|`, and Carson's rule
6//! estimates the occupied bandwidth as `2 (Δf + f_m)`.
7//!
8//! The modulator accumulates phase in the same fixed-point [`Nco`] used by the signal sources, so
9//! the phase never drifts, however long the stream runs. The demodulator is the classic
10//! quadrature (phase-difference) discriminator `arg(y[n] · conj(y[n-1]))`, which needs no carrier
11//! recovery and recovers the message exactly in the absence of noise, as long as the deviation
12//! stays below `fs / 2`. An optional single-pole de-emphasis filter models the broadcast
13//! treble-boost compensation.
14//!
15//! See the book entry [Modulation: constellations, OFDM and FM](https://jwkunz.github.io/lib_jsl/book/comms/modulation.html#frequency-modulation).
16
17use crate::discrete::{
18    sources::{
19        nco::{Nco, Waveform},
20        quadrature::{Polarity, QuadratureWave},
21        sinusoid::SineKernel,
22    },
23    stream_operator::{StreamOperator, StreamOperatorManagement},
24};
25use lib_jsl_core::ErrorsJSL;
26use num_complex::Complex;
27use std::f64::consts::TAU;
28
29fn check_params(sample_rate: f64, sensitivity: f64) -> Result<(), ErrorsJSL> {
30    if !(sample_rate.is_finite() && sample_rate > 0.0) || !(sensitivity.is_finite() && sensitivity > 0.0) {
31        return Err(ErrorsJSL::InvalidInputRange("Sample rate and frequency sensitivity must be positive and finite"));
32    }
33    Ok(())
34}
35
36/// Carson's rule for the bandwidth (Hz) containing nearly all of an FM signal's power.
37pub fn carson_bandwidth(peak_deviation_hz: f64, max_message_frequency_hz: f64) -> f64 {
38    2.0 * (peak_deviation_hz + max_message_frequency_hz)
39}
40
41/// A streaming FM modulator: real message samples in, unit-amplitude complex baseband out.
42#[derive(Clone, Debug)]
43pub struct FmModulator {
44    nco: Nco,
45    wave: QuadratureWave,
46    sensitivity: f64,
47}
48
49impl FmModulator {
50    /// `sensitivity` is `k_f` in Hz per message unit; `sample_rate` in Hz.
51    pub fn new(sensitivity_hz_per_unit: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
52        check_params(sample_rate, sensitivity_hz_per_unit)?;
53        Ok(FmModulator {
54            nco: Nco::new(0.0, sample_rate)?,
55            wave: QuadratureWave::new(SineKernel::Direct, Polarity::Positive),
56            sensitivity: sensitivity_hz_per_unit,
57        })
58    }
59
60    /// Modulates one message sample.
61    pub fn modulate_sample(&mut self, m: f64) -> Complex<f64> {
62        self.nco.next_phase_modulated(self.sensitivity * m);
63        self.wave.sample(self.nco.phase())
64    }
65}
66
67impl StreamOperatorManagement for FmModulator {
68    fn reset(&mut self) -> Result<(), ErrorsJSL> {
69        self.nco.reset();
70        Ok(())
71    }
72
73    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
74        Ok(())
75    }
76}
77
78impl StreamOperator<f64, Complex<f64>> for FmModulator {
79    fn process(&mut self, data_in: &[f64]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
80        if data_in.is_empty() {
81            return Ok(None);
82        }
83        Ok(Some(data_in.iter().map(|&m| self.modulate_sample(m)).collect()))
84    }
85
86    fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
87        Ok(None)
88    }
89}
90
91/// Modulates a whole message: `k_f` in Hz per message unit, `sample_rate` in Hz.
92pub fn fm_modulate(message: &[f64], sensitivity_hz_per_unit: f64, sample_rate: f64) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
93    let mut m = FmModulator::new(sensitivity_hz_per_unit, sample_rate)?;
94    Ok(message.iter().map(|&x| m.modulate_sample(x)).collect())
95}
96
97/// A streaming quadrature FM demodulator: complex baseband in, recovered message out.
98#[derive(Clone, Debug)]
99pub struct FmDemodulator {
100    scale: f64,
101    previous: Complex<f64>,
102    deemphasis_alpha: Option<f64>,
103    deemphasis_state: f64,
104}
105
106impl FmDemodulator {
107    /// `sensitivity` is the modulator's `k_f` in Hz per message unit.
108    pub fn new(sensitivity_hz_per_unit: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
109        check_params(sample_rate, sensitivity_hz_per_unit)?;
110        Ok(FmDemodulator { scale: sample_rate / (TAU * sensitivity_hz_per_unit), previous: Complex::new(1.0, 0.0), deemphasis_alpha: None, deemphasis_state: 0.0 })
111    }
112
113    /// Adds a single-pole de-emphasis low-pass with time constant `tau` seconds (50 or 75 µs for
114    /// broadcast FM). `sample_rate` must match the one given to [`new`](Self::new).
115    pub fn with_deemphasis(mut self, tau_seconds: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
116        if !(tau_seconds > 0.0) || !(sample_rate > 0.0) {
117            return Err(ErrorsJSL::InvalidInputRange("De-emphasis time constant and sample rate must be positive"));
118        }
119        self.deemphasis_alpha = Some(1.0 - (-1.0 / (sample_rate * tau_seconds)).exp());
120        Ok(self)
121    }
122
123    /// Demodulates one baseband sample. The first output compares against a unit-phase reference.
124    // ANCHOR: fm_discriminator
125    pub fn demodulate_sample(&mut self, y: Complex<f64>) -> f64 {
126        let d = (y * self.previous.conj()).arg();
127        self.previous = y;
128        let m = d * self.scale;
129        match self.deemphasis_alpha {
130            Some(a) => {
131                self.deemphasis_state += a * (m - self.deemphasis_state);
132                self.deemphasis_state
133            }
134            None => m,
135        }
136    }
137    // ANCHOR_END: fm_discriminator
138}
139
140impl StreamOperatorManagement for FmDemodulator {
141    fn reset(&mut self) -> Result<(), ErrorsJSL> {
142        self.previous = Complex::new(1.0, 0.0);
143        self.deemphasis_state = 0.0;
144        Ok(())
145    }
146
147    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
148        Ok(())
149    }
150}
151
152impl StreamOperator<Complex<f64>, f64> for FmDemodulator {
153    fn process(&mut self, data_in: &[Complex<f64>]) -> Result<Option<Vec<f64>>, ErrorsJSL> {
154        if data_in.is_empty() {
155            return Ok(None);
156        }
157        Ok(Some(data_in.iter().map(|&y| self.demodulate_sample(y)).collect()))
158    }
159
160    fn flush(&mut self) -> Result<Option<Vec<f64>>, ErrorsJSL> {
161        Ok(None)
162    }
163}
164
165/// Demodulates a whole baseband record (no de-emphasis). `k_f` is the modulator's sensitivity.
166pub fn fm_demodulate(baseband: &[Complex<f64>], sensitivity_hz_per_unit: f64, sample_rate: f64) -> Result<Vec<f64>, ErrorsJSL> {
167    let mut d = FmDemodulator::new(sensitivity_hz_per_unit, sample_rate)?;
168    Ok(baseband.iter().map(|&y| d.demodulate_sample(y)).collect())
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn lcg(seed: &mut u64) -> f64 {
176        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
177        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
178    }
179
180    fn gauss(seed: &mut u64) -> f64 {
181        (0..12).map(|_| lcg(seed)).sum::<f64>()
182    }
183
184    fn tone(n: usize, f: f64, fs: f64, amp: f64) -> Vec<f64> {
185        (0..n).map(|i| amp * (TAU * f * i as f64 / fs).sin()).collect()
186    }
187
188    #[test]
189    fn noise_free_round_trip_is_exact() {
190        let (fs, kf) = (48_000.0, 5_000.0);
191        let m: Vec<f64> = tone(4800, 1000.0, fs, 0.8).iter().zip(tone(4800, 2300.0, fs, 0.15)).map(|(a, b)| a + b).collect();
192        let y = fm_modulate(&m, kf, fs).unwrap();
193        let back = fm_demodulate(&y, kf, fs).unwrap();
194        for (a, b) in m.iter().zip(&back) {
195            assert!((a - b).abs() < 1e-9, "{a} vs {b}");
196        }
197    }
198
199    #[test]
200    fn the_envelope_is_constant_and_the_frequency_follows_the_message() {
201        let (fs, kf) = (8000.0, 1000.0);
202        let y = fm_modulate(&vec![0.5; 200], kf, fs).unwrap();
203        assert!(y.iter().all(|v| (v.norm() - 1.0).abs() < 1e-12));
204        // A constant message of 0.5 is a pure tone at 500 Hz: 36 degrees per sample.
205        let step = (y[100] * y[99].conj()).arg();
206        assert!((step - TAU * 500.0 / fs).abs() < 1e-12);
207        // The phase after n samples is 2 pi 500 n / fs.
208        let want = Complex::from_polar(1.0, TAU * 500.0 * 51.0 / fs);
209        assert!((y[50] - want).norm() < 1e-9);
210    }
211
212    #[test]
213    fn no_phase_drift_over_a_long_stream() {
214        let (fs, kf) = (1000.0, 1.0);
215        let mut m = FmModulator::new(kf, fs).unwrap();
216        let mut last = Complex::new(0.0, 0.0);
217        for _ in 0..2_000_000 {
218            last = m.modulate_sample(1.0);
219        }
220        // 2e6 samples of a constant 1 Hz offset at 1 kHz: exactly 2000 cycles, back to phase 0.
221        assert!((last - Complex::new(1.0, 0.0)).norm() < 1e-9, "{last}");
222    }
223
224    #[test]
225    fn streaming_in_chunks_equals_one_shot_and_reset_restarts() {
226        let (fs, kf) = (16_000.0, 3_000.0);
227        let msg = tone(1000, 440.0, fs, 1.0);
228        let whole = fm_modulate(&msg, kf, fs).unwrap();
229        let mut m = FmModulator::new(kf, fs).unwrap();
230        let mut chunked = Vec::new();
231        for c in msg.chunks(77) {
232            chunked.extend(m.process(c).unwrap().unwrap());
233        }
234        assert_eq!(whole, chunked);
235        StreamOperatorManagement::reset(&mut m).unwrap();
236        assert_eq!(m.process(&msg).unwrap().unwrap(), whole);
237        let mut d = FmDemodulator::new(kf, fs).unwrap();
238        let mut got = Vec::new();
239        for c in whole.chunks(123) {
240            got.extend(d.process(c).unwrap().unwrap());
241        }
242        assert!(got.iter().zip(&msg).all(|(a, b)| (a - b).abs() < 1e-9));
243        assert!(m.process(&[]).unwrap().is_none() && d.process(&[]).unwrap().is_none());
244    }
245
246    #[test]
247    fn demodulation_error_grows_with_noise_but_stays_small_at_high_cnr() {
248        let (fs, kf) = (48_000.0, 5_000.0);
249        let msg = tone(20_000, 700.0, fs, 1.0);
250        let clean = fm_modulate(&msg, kf, fs).unwrap();
251        let mut seed = 3;
252        let mut rms_err = Vec::new();
253        for sigma in [0.01, 0.05] {
254            let noisy: Vec<Complex<f64>> = clean.iter().map(|&c| c + Complex::new(gauss(&mut seed), gauss(&mut seed)) * sigma).collect();
255            let out = fm_demodulate(&noisy, kf, fs).unwrap();
256            rms_err.push((out.iter().zip(&msg).map(|(a, b)| (a - b).powi(2)).sum::<f64>() / msg.len() as f64).sqrt());
257        }
258        assert!(rms_err[0] < rms_err[1], "{rms_err:?}");
259        assert!(rms_err[0] < 0.1, "{rms_err:?}");
260    }
261
262    #[test]
263    fn deemphasis_attenuates_high_frequencies() {
264        let (fs, kf) = (48_000.0, 5_000.0);
265        let tau = 75e-6; // corner at 2.12 kHz
266        let amp = |f: f64| {
267            let y = fm_modulate(&tone(9600, f, fs, 1.0), kf, fs).unwrap();
268            let mut d = FmDemodulator::new(kf, fs).unwrap().with_deemphasis(tau, fs).unwrap();
269            let out = d.process(&y).unwrap().unwrap();
270            out[4800..].iter().fold(0.0f64, |a, v| a.max(v.abs()))
271        };
272        let (low, high) = (amp(200.0), amp(8000.0));
273        assert!((low - 1.0).abs() < 0.03, "low-frequency gain {low}");
274        let expect = 1.0 / (1.0 + (TAU * 8000.0 * tau).powi(2)).sqrt();
275        assert!((high - expect).abs() < 0.03, "8 kHz gain {high}, single-pole prediction {expect}");
276    }
277
278    #[test]
279    fn carson_rule_and_parameter_validation() {
280        assert_eq!(carson_bandwidth(75_000.0, 15_000.0), 180_000.0);
281        assert!(FmModulator::new(0.0, 8000.0).is_err());
282        assert!(FmModulator::new(100.0, -1.0).is_err());
283        assert!(FmDemodulator::new(100.0, 0.0).is_err());
284        assert!(FmDemodulator::new(100.0, 8000.0).unwrap().with_deemphasis(0.0, 8000.0).is_err());
285        assert!(fm_modulate(&[0.1], f64::NAN, 8000.0).is_err());
286    }
287}