Skip to main content

frenz_export/
timing.rs

1//! Estimating sample acquisition times from packet arrival times.
2//!
3//! A packet carrying samples `n .. n+k` cannot arrive before its last sample was acquired, and
4//! Bluetooth only adds delay. So, for a stream sampled at a steady rate, the true clock
5//! `t(n) = a + b·n` is the *lower envelope* of `(index of last sample, arrival time)`: arrivals lie
6//! on or above it. [`fit_lower_envelope`] finds that line by iteratively refitting least squares to
7//! the earliest-arriving packets. `1/b` is the measured sample rate; residuals are the delivery
8//! latency beyond the minimum (jitter).
9
10use serde_json::json;
11
12/// A fitted clock for one uninterrupted segment of one stream.
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct ClockFit {
15    /// Time of sample index 0 (Unix seconds, host clock).
16    pub offset: f64,
17    /// Seconds per sample.
18    pub period: f64,
19    /// Median arrival delay above the envelope (s).
20    pub jitter_p50: f64,
21    /// 95th-percentile arrival delay above the envelope (s).
22    pub jitter_p95: f64,
23    /// Packets used.
24    pub packets: usize,
25    /// True if there were too few packets to fit and the nominal rate was used.
26    pub nominal: bool,
27}
28
29impl ClockFit {
30    /// Estimated acquisition time of sample `n`.
31    pub fn time(&self, n: f64) -> f64 {
32        self.offset + self.period * n
33    }
34
35    /// JSON description for session metadata.
36    pub fn to_json(&self) -> serde_json::Value {
37        json!({
38            "rate_hz": 1.0 / self.period, "offset_unix_s": self.offset, "packets": self.packets,
39            "jitter_p50_s": self.jitter_p50, "jitter_p95_s": self.jitter_p95, "nominal_rate_used": self.nominal,
40        })
41    }
42}
43
44/// Where a packet's samples sit within a stream: which uninterrupted segment, and the index of
45/// its first sample in that segment.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Placed {
48    /// Segment number, from 0.
49    pub segment: i64,
50    /// Index within the segment of the packet's first sample.
51    pub first_sample: i64,
52}
53
54#[derive(Debug, Clone, Copy)]
55struct Previous {
56    arrival: f64,
57    device_time: u32,
58    sequence: Option<u8>,
59    samples: usize,
60}
61
62/// Assigns packets of one stream to segments and sample indices, one packet at a time.
63///
64/// The rules use only the packets seen so far, so the exporter and live readers place packets
65/// identically. A new segment starts after a silence of more than a second, after a jump in the
66/// sequence counter that the elapsed time does not explain, and, for streams without a counter,
67/// after a step in the band's clock or a burst of packets.
68#[derive(Debug, Clone)]
69pub struct Segmenter {
70    rate_hz: f64,
71    packet_period: f64,
72    per_second: usize,
73    previous: Option<Previous>,
74    segment: i64,
75    next: i64,
76    same_second: usize,
77    /// Frames missing inside segments (counted from sequence numbers).
78    pub lost_frames: u64,
79    /// Sequence counter restarts that followed a stream-start command.
80    pub restarts: u64,
81}
82
83impl Segmenter {
84    /// A segmenter for a stream sampled at `rate_hz`.
85    pub fn new(rate_hz: f64) -> Self {
86        Self {
87            rate_hz,
88            packet_period: 0.0,
89            per_second: 0,
90            previous: None,
91            segment: 0,
92            next: 0,
93            same_second: 0,
94            lost_frames: 0,
95            restarts: 0,
96        }
97    }
98
99    /// Places the next packet. `arrival` is in seconds, `sequence` is the frame counter if the
100    /// stream has one, `samples` the number of samples in the packet. `forced` starts a new
101    /// segment regardless (an undecodable frame came before this one). `after_start` says a
102    /// stream-start command was written within the last second, which explains a counter restart.
103    pub fn push(
104        &mut self,
105        arrival: f64,
106        device_time: u32,
107        sequence: Option<u8>,
108        samples: usize,
109        forced: bool,
110        after_start: bool,
111    ) -> Placed {
112        let Some(prev) = self.previous else {
113            self.packet_period = samples as f64 / self.rate_hz;
114            // Sequence-less streams send a fixed number of packets per device second (2 observed);
115            // more means a burst (seen during PPG freezes), after which the sample count no longer
116            // tracks time.
117            self.per_second = (1.0 / self.packet_period.max(1e-9)).round() as usize;
118            self.same_second = 1;
119            self.previous = Some(Previous {
120                arrival,
121                device_time,
122                sequence,
123                samples,
124            });
125            return Placed {
126                segment: self.segment,
127                first_sample: self.next,
128            };
129        };
130        let packet_period = self.packet_period;
131        let step = match (prev.sequence, sequence) {
132            (Some(a), Some(b)) => {
133                let d = i64::from(b.wrapping_sub(a));
134                if d == 1 {
135                    Some(1)
136                } else if b == 0 && after_start {
137                    // Continuous only if data kept flowing; after a pause it is a new segment.
138                    self.restarts += 1;
139                    (arrival - prev.arrival < 4.0 * packet_period + 0.5).then_some(1)
140                } else if d > 1 && arrival - prev.arrival < (d as f64 + 4.0) * packet_period + 1.0 {
141                    self.lost_frames += (d - 1) as u64;
142                    Some(d)
143                } else {
144                    None
145                }
146            }
147            // Streams without a sequence counter: a long silence or a device clock jump starts a
148            // new segment, because lost packets cannot be counted.
149            _ => {
150                let gap = arrival - prev.arrival;
151                let clock_step = i64::from(device_time) - i64::from(prev.device_time);
152                self.same_second = if clock_step == 0 { self.same_second + 1 } else { 1 };
153                let burst = self.same_second > self.per_second;
154                (gap < 2.0 * packet_period.max(0.5) && (0..=1).contains(&clock_step) && !burst).then_some(1)
155            }
156        };
157        // Any silence of more than a second starts a new segment, whatever the counters say.
158        let paused = arrival - prev.arrival > 1.0 + 2.0 * packet_period;
159        match step {
160            Some(d) if !forced && !paused => self.next += d * prev.samples as i64,
161            _ => {
162                self.segment += 1;
163                self.next = 0;
164                self.same_second = 1;
165            }
166        }
167        self.previous = Some(Previous {
168            arrival,
169            device_time,
170            sequence,
171            samples,
172        });
173        Placed {
174            segment: self.segment,
175            first_sample: self.next,
176        }
177    }
178}
179
180fn least_squares(points: &[(f64, f64)]) -> Option<(f64, f64)> {
181    let n = points.len() as f64;
182    if points.len() < 2 {
183        return None;
184    }
185    let (sx, sy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| (a + x, b + y));
186    let (mx, my) = (sx / n, sy / n);
187    let (sxx, sxy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| {
188        (a + (x - mx).powi(2), b + (x - mx) * (y - my))
189    });
190    if sxx <= 0.0 {
191        return None;
192    }
193    let slope = sxy / sxx;
194    Some((my - slope * mx, slope))
195}
196
197fn percentile(sorted: &[f64], q: f64) -> f64 {
198    if sorted.is_empty() {
199        return 0.0;
200    }
201    let idx = ((sorted.len() - 1) as f64 * q).round() as usize;
202    sorted.get(idx).copied().unwrap_or(0.0)
203}
204
205/// Fits the lower envelope of `(last_sample_index, arrival_unix_s)` pairs. With fewer than 20
206/// packets, the nominal period is used and only the offset is fitted.
207pub fn fit_lower_envelope(points: &[(f64, f64)], nominal_rate_hz: f64) -> ClockFit {
208    let nominal_period = 1.0 / nominal_rate_hz;
209    let (offset, period, nominal) = if points.len() >= 20 {
210        let mut fit = least_squares(points).unwrap_or((0.0, nominal_period));
211        for _ in 0..4 {
212            let mut residuals: Vec<f64> = points.iter().map(|(x, y)| y - (fit.0 + fit.1 * x)).collect();
213            residuals.sort_by(f64::total_cmp);
214            let cut = percentile(&residuals, 0.10);
215            let low: Vec<(f64, f64)> = points
216                .iter()
217                .copied()
218                .filter(|(x, y)| y - (fit.0 + fit.1 * x) <= cut)
219                .collect();
220            match least_squares(&low) {
221                // Reject fits that are physically implausible (> 5 % off nominal).
222                Some(f) if (f.1 / nominal_period - 1.0).abs() < 0.05 => fit = f,
223                _ => break,
224            }
225        }
226        (fit.0, fit.1, false)
227    } else {
228        (0.0, nominal_period, true)
229    };
230    place_on_envelope(points, offset, period, nominal_period, nominal)
231}
232
233/// Fits only the offset, taking the sample rate as `nominal_rate_hz`. For when there is too
234/// little data to trust a fitted rate.
235pub fn fit_nominal(points: &[(f64, f64)], nominal_rate_hz: f64) -> ClockFit {
236    let nominal_period = 1.0 / nominal_rate_hz;
237    place_on_envelope(points, 0.0, nominal_period, nominal_period, true)
238}
239
240fn place_on_envelope(
241    points: &[(f64, f64)],
242    mut offset: f64,
243    mut period: f64,
244    nominal_period: f64,
245    nominal: bool,
246) -> ClockFit {
247    // Shift the line down so no packet arrives before its last sample was acquired.
248    let min_residual = points
249        .iter()
250        .map(|(x, y)| y - (offset + period * x))
251        .fold(f64::INFINITY, f64::min);
252    if min_residual.is_finite() {
253        offset += min_residual;
254    }
255    if !period.is_finite() || period <= 0.0 {
256        period = nominal_period;
257    }
258    let mut delays: Vec<f64> = points.iter().map(|(x, y)| y - (offset + period * x)).collect();
259    delays.sort_by(f64::total_cmp);
260    ClockFit {
261        offset,
262        period,
263        jitter_p50: percentile(&delays, 0.5),
264        jitter_p95: percentile(&delays, 0.95),
265        packets: points.len(),
266        nominal,
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn recovers_rate_and_offset_under_one_sided_jitter() {
276        // 125.3 Hz true rate, 9 samples per packet, delays 5–150 ms (deterministic pseudo-random).
277        let true_period = 1.0 / 125.3;
278        let mut state = 7u64;
279        let points: Vec<(f64, f64)> = (0..2000)
280            .map(|k| {
281                state = state
282                    .wrapping_mul(6364136223846793005)
283                    .wrapping_add(1442695040888963407);
284                let delay = 0.005 + 0.145 * ((state >> 33) as f64 / (1u64 << 31) as f64).powi(3);
285                let n = (9 * k + 8) as f64;
286                (n, 1_800_000_000.0 + true_period * n + delay)
287            })
288            .collect();
289        let fit = fit_lower_envelope(&points, 125.0);
290        assert!((1.0 / fit.period - 125.3).abs() < 0.01, "rate {}", 1.0 / fit.period);
291        assert!(
292            (fit.offset - 1_800_000_000.005).abs() < 0.003,
293            "offset error {}",
294            fit.offset - 1_800_000_000.005
295        );
296        assert!(points.iter().all(|(x, y)| *y >= fit.time(*x) - 1e-9));
297    }
298
299    #[test]
300    fn short_segments_use_nominal_rate() {
301        let points = [(8.0, 10.1), (17.0, 10.2)];
302        let fit = fit_lower_envelope(&points, 125.0);
303        assert!(fit.nominal);
304        assert!((fit.period - 0.008).abs() < 1e-12);
305    }
306}