Skip to main content

lib_jsl_dsp/discrete/digital_communications/
mueller_timing_detector.rs

1//! Mueller & Müller timing error detector and symbol timing recovery.
2//!
3//! A receiver samples at a rate that is a multiple of the symbol rate, but with an unknown timing
4//! phase and a slightly wrong clock. The Mueller & Müller detector measures the timing error from
5//! just *one sample per symbol* and the receiver's own decisions:
6//!
7//! `e[n] = Re{ conj(d[n-1]) · y[n] − conj(d[n]) · y[n-1] }`
8//!
9//! where `y[n]` is the interpolated sample at symbol `n` and `d[n]` the symbol nearest to it. For
10//! a Nyquist pulse the expected value of `e` is proportional to the timing error and zero at the
11//! ideal instant, so it can drive a feedback loop. [`mueller_timing_detector`] is that detector;
12//! [`MuellerTimingRecovery`] wraps it into a complete second-order loop:
13//!
14//! - a [`FarrowFilter`] interpolates the oversampled input at the current (fractional) instant;
15//! - the error nudges the symbol-time estimate `μ` directly (proportional path) and the symbol
16//!   period estimate `ω` (integral path), so the loop tracks both a timing offset and a
17//!   clock-frequency error;
18//! - `ω` is limited to a small band around its nominal value so noise cannot drag it away.
19//!
20//! The loop consumes the oversampled stream and emits one sample per symbol.
21//!
22//! See the book entry [Synchronisation: phase-locked loops, Costas loops and timing recovery](https://jwkunz.github.io/lib_jsl/book/comms/synchronisation.html#timing-recovery).
23
24use super::{constellations::Constellation, farrow_filter::FarrowFilter};
25use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
26use lib_jsl_core::ErrorsJSL;
27use num_complex::Complex;
28
29/// The Mueller & Müller timing error for consecutive symbol-rate samples `y_prev`, `y_curr` with
30/// decisions `d_prev`, `d_curr`. The sign convention is that of the loop in this module: a positive
31/// error moves the sampling instant later (it is added to the symbol-time estimate), a negative
32/// error moves it earlier, and zero means the instants are ideal.
33pub fn mueller_timing_detector(y_prev: Complex<f64>, y_curr: Complex<f64>, d_prev: Complex<f64>, d_curr: Complex<f64>) -> f64 {
34    (d_prev.conj() * y_curr - d_curr.conj() * y_prev).re
35}
36
37/// Symbol timing recovery with a Mueller & Müller detector.
38#[derive(Clone, Debug)]
39pub struct MuellerTimingRecovery {
40    constellation: Constellation,
41    interpolator: FarrowFilter<Complex<f64>>,
42    nominal_omega: f64,
43    omega: f64,
44    omega_limit: f64,
45    gain_mu: f64,
46    gain_omega: f64,
47    /// Input history; `pos` indexes into it (integer part + fractional position).
48    buffer: Vec<Complex<f64>>,
49    pos: f64,
50    prev_sample: Complex<f64>,
51    prev_decision: Complex<f64>,
52    last_error: f64,
53}
54
55impl MuellerTimingRecovery {
56    /// A loop for a signal with `samples_per_symbol` (>= 2, may be fractional) samples per symbol
57    /// and the given constellation for decisions, with the usual gains: `gain_mu = 0.175`,
58    /// `gain_omega = 0.25 · gain_mu²` and `ω` limited to ±0.5% of nominal.
59    pub fn new(samples_per_symbol: f64, constellation: Constellation) -> Result<Self, ErrorsJSL> {
60        let gain_mu = 0.175;
61        Self::with_gains(samples_per_symbol, constellation, gain_mu, 0.25 * gain_mu * gain_mu, 0.005)
62    }
63
64    /// Like [`new`](Self::new) with explicit loop gains and the relative limit on `ω`.
65    pub fn with_gains(samples_per_symbol: f64, constellation: Constellation, gain_mu: f64, gain_omega: f64, omega_relative_limit: f64) -> Result<Self, ErrorsJSL> {
66        if !(samples_per_symbol >= 2.0) || !samples_per_symbol.is_finite() {
67            return Err(ErrorsJSL::InvalidInputRange("Samples per symbol must be at least 2"));
68        }
69        if !(gain_mu > 0.0) || !(gain_omega >= 0.0) || !(omega_relative_limit >= 0.0) {
70            return Err(ErrorsJSL::InvalidInputRange("Loop gains must be non-negative (gain_mu positive)"));
71        }
72        let interpolator = FarrowFilter::new(3)?;
73        let mut s = MuellerTimingRecovery {
74            constellation,
75            interpolator,
76            nominal_omega: samples_per_symbol,
77            omega: samples_per_symbol,
78            omega_limit: omega_relative_limit * samples_per_symbol,
79            gain_mu,
80            gain_omega,
81            buffer: Vec::new(),
82            pos: 0.0,
83            prev_sample: Complex::new(0.0, 0.0),
84            prev_decision: Complex::new(0.0, 0.0),
85            last_error: 0.0,
86        };
87        s.restart();
88        Ok(s)
89    }
90
91    fn restart(&mut self) {
92        self.omega = self.nominal_omega;
93        self.buffer.clear();
94        // Start with the first interpolation window centred on the first samples.
95        self.pos = 1.0;
96        self.prev_sample = Complex::new(0.0, 0.0);
97        self.prev_decision = Complex::new(0.0, 0.0);
98        self.last_error = 0.0;
99    }
100
101    /// The current estimate of the symbol period in samples.
102    pub fn symbol_period(&self) -> f64 {
103        self.omega
104    }
105
106    /// The most recent timing error from the detector.
107    pub fn last_error(&self) -> f64 {
108        self.last_error
109    }
110}
111
112impl StreamOperatorManagement for MuellerTimingRecovery {
113    fn reset(&mut self) -> Result<(), ErrorsJSL> {
114        self.restart();
115        Ok(())
116    }
117
118    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
119        Ok(())
120    }
121}
122
123impl StreamOperator<Complex<f64>, Complex<f64>> for MuellerTimingRecovery {
124    fn process(&mut self, data_in: &[Complex<f64>]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
125        if data_in.is_empty() {
126            return Ok(None);
127        }
128        self.buffer.extend_from_slice(data_in);
129        let mut out = Vec::new();
130        // The cubic window needs samples floor(pos)-1 ..= floor(pos)+2.
131        // ANCHOR: mueller
132        while (self.pos.floor() as usize) + 2 < self.buffer.len() {
133            let i = self.pos.floor() as usize;
134            let mu = self.pos - i as f64;
135            let y = self.interpolator.interpolate_window(&self.buffer[i - 1..=i + 2], mu)?;
136            let d = self.constellation.slice(y);
137            let err = mueller_timing_detector(self.prev_sample, y, self.prev_decision, d).clamp(-1.0, 1.0);
138            self.omega = (self.omega + self.gain_omega * err).clamp(self.nominal_omega - self.omega_limit, self.nominal_omega + self.omega_limit);
139            self.pos += self.omega + self.gain_mu * err;
140            self.prev_sample = y;
141            self.prev_decision = d;
142            self.last_error = err;
143            out.push(y);
144        }
145        // ANCHOR_END: mueller
146        // Drop consumed history, keeping the samples the next window will need.
147        let keep_from = (self.pos.floor() as usize).saturating_sub(1).min(self.buffer.len());
148        if keep_from > 0 {
149            self.buffer.drain(..keep_from);
150            self.pos -= keep_from as f64;
151        }
152        Ok(if out.is_empty() { None } else { Some(out) })
153    }
154
155    fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
156        Ok(None)
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use std::f64::consts::PI;
164
165    fn lcg(seed: &mut u64) -> f64 {
166        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
167        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
168    }
169
170    fn gauss(seed: &mut u64) -> f64 {
171        (0..12).map(|_| lcg(seed)).sum::<f64>()
172    }
173
174    /// Raised-cosine pulse (roll-off `beta`, symbol period 1), a Nyquist pulse.
175    fn raised_cosine(t: f64, beta: f64) -> f64 {
176        let sinc = if t.abs() < 1e-12 { 1.0 } else { (PI * t).sin() / (PI * t) };
177        let denom = 1.0 - (2.0 * beta * t).powi(2);
178        if denom.abs() < 1e-9 {
179            return PI / 4.0 * if beta > 0.0 { (PI / (2.0 * beta)).sin() / (PI / (2.0 * beta)) } else { 1.0 };
180        }
181        sinc * (PI * beta * t).cos() / denom
182    }
183
184    /// Samples the pulse-shaped signal at times `t_k = (k / sps)(1 + clock_error) + offset` symbol
185    /// periods, evaluating the pulse analytically (no interpolation error).
186    fn received(symbols: &[Complex<f64>], sps: f64, offset: f64, clock_error: f64, num_samples: usize) -> Vec<Complex<f64>> {
187        (0..num_samples)
188            .map(|k| {
189                let t = k as f64 / sps * (1.0 + clock_error) + offset;
190                let centre = t.round() as isize;
191                (centre - 10..=centre + 10)
192                    .filter(|&n| n >= 0 && (n as usize) < symbols.len())
193                    .map(|n| symbols[n as usize] * raised_cosine(t - n as f64, 0.35))
194                    .sum()
195            })
196            .collect()
197    }
198
199    fn random_symbols(c: &Constellation, n: usize, seed: &mut u64) -> Vec<Complex<f64>> {
200        (0..n).map(|_| c.points()[((lcg(seed) + 0.5) * c.size() as f64) as usize % c.size()]).collect()
201    }
202
203    /// Symbol errors between recovered samples and the sent symbols, trying every alignment
204    /// (recovered sample `i` corresponds to sent symbol `i + shift`, with a possible phase flip
205    /// ambiguity ruled out because timing recovery does not rotate the signal).
206    fn best_symbol_errors(c: &Constellation, recovered: &[Complex<f64>], sent: &[Complex<f64>], skip: usize) -> usize {
207        (0..8usize)
208            .map(|shift| {
209                recovered
210                    .iter()
211                    .enumerate()
212                    .skip(skip)
213                    .filter(|(i, _)| i + shift < sent.len())
214                    .filter(|(i, y)| c.slice(**y) != sent[i + shift])
215                    .count()
216            })
217            .min()
218            .unwrap()
219    }
220
221    #[test]
222    fn detector_vanishes_at_the_ideal_sampling_instants() {
223        let (a, b) = (Complex::new(1.0, 0.0), Complex::new(-1.0, 0.0));
224        assert_eq!(mueller_timing_detector(a, b, a, b), 0.0);
225        let q = Complex::new(0.7, -0.7);
226        assert!(mueller_timing_detector(q, q, q, q).abs() < 1e-15);
227        // A sample that has leaked a bit of its neighbour produces a nonzero error.
228        assert!(mueller_timing_detector(a, b * 0.9 + a * 0.1, a, b).abs() > 0.05);
229    }
230
231    #[test]
232    fn recovers_symbols_despite_a_fractional_timing_offset() {
233        let c = Constellation::qpsk();
234        let mut seed = 4;
235        let sent = random_symbols(&c, 3000, &mut seed);
236        for offset in [0.0, 0.13, 0.37, 0.5, 0.81] {
237            let rx = received(&sent, 4.0, offset, 0.0, 4 * 2900);
238            let mut rec = MuellerTimingRecovery::new(4.0, c.clone()).unwrap();
239            let out = rec.process(&rx).unwrap().unwrap();
240            assert!(out.len() > 2800 && out.len() < 2950, "got {} symbols", out.len());
241            assert_eq!(best_symbol_errors(&c, &out, &sent, 400), 0, "offset {offset}");
242            assert!((rec.symbol_period() - 4.0).abs() < 0.01, "omega {}", rec.symbol_period());
243        }
244    }
245
246    #[test]
247    fn tracks_a_clock_frequency_error() {
248        let c = Constellation::qpsk();
249        let mut seed = 6;
250        let sent = random_symbols(&c, 6000, &mut seed);
251        for ppm in [-400.0, 250.0] {
252            let eps = ppm * 1e-6;
253            let rx = received(&sent, 4.0, 0.3, eps, 4 * 5800);
254            let mut rec = MuellerTimingRecovery::new(4.0, c.clone()).unwrap();
255            let out = rec.process(&rx).unwrap().unwrap();
256            assert_eq!(best_symbol_errors(&c, &out, &sent, 800), 0, "{ppm} ppm");
257            // The recovered symbol period follows the true one, 4/(1+eps).
258            let true_period = 4.0 / (1.0 + eps);
259            assert!((rec.symbol_period() - true_period).abs() < 0.002, "{ppm} ppm: omega {} vs {true_period}", rec.symbol_period());
260        }
261    }
262
263    #[test]
264    fn works_for_bpsk_and_with_noise_and_in_chunks() {
265        let c = Constellation::bpsk();
266        let mut seed = 8;
267        let sent = random_symbols(&c, 4000, &mut seed);
268        let mut rx = received(&sent, 8.0, 0.6, 100e-6, 8 * 3900);
269        for v in rx.iter_mut() {
270            *v += Complex::new(gauss(&mut seed), gauss(&mut seed)) * 0.05;
271        }
272        let mut rec = MuellerTimingRecovery::new(8.0, c.clone()).unwrap();
273        let mut out = Vec::new();
274        for chunk in rx.chunks(1000) {
275            if let Some(o) = rec.process(chunk).unwrap() {
276                out.extend(o);
277            }
278        }
279        assert!(out.len() > 3800);
280        assert_eq!(best_symbol_errors(&c, &out, &sent, 500), 0);
281    }
282
283    #[test]
284    fn chunking_does_not_change_the_output() {
285        let c = Constellation::qpsk();
286        let mut seed = 10;
287        let sent = random_symbols(&c, 500, &mut seed);
288        let rx = received(&sent, 4.0, 0.2, 0.0, 4 * 480);
289        let whole = MuellerTimingRecovery::new(4.0, c.clone()).unwrap().process(&rx).unwrap().unwrap();
290        let mut rec = MuellerTimingRecovery::new(4.0, c).unwrap();
291        let mut parts = Vec::new();
292        for chunk in rx.chunks(37) {
293            if let Some(o) = rec.process(chunk).unwrap() {
294                parts.extend(o);
295            }
296        }
297        assert_eq!(whole.len(), parts.len());
298        assert!(whole.iter().zip(&parts).all(|(a, b)| (a - b).norm() < 1e-9));
299        StreamOperatorManagement::reset(&mut rec).unwrap();
300        assert_eq!(rec.symbol_period(), 4.0);
301        assert!(rec.process(&[]).unwrap().is_none() && rec.flush().unwrap().is_none());
302    }
303
304    #[test]
305    fn invalid_parameters() {
306        let c = Constellation::bpsk();
307        assert!(MuellerTimingRecovery::new(1.5, c.clone()).is_err());
308        assert!(MuellerTimingRecovery::new(f64::NAN, c.clone()).is_err());
309        assert!(MuellerTimingRecovery::with_gains(4.0, c.clone(), 0.0, 0.01, 0.01).is_err());
310        assert!(MuellerTimingRecovery::with_gains(4.0, c, 0.1, -1.0, 0.01).is_err());
311    }
312}