Skip to main content

weirdnet_streaming/
stats.rs

1//! Arrival statistics for a subscriber.
2use serde::{Deserialize, Serialize};
3
4/// What a subscriber has seen: frames, loss, and how late and how unevenly frames arrive.
5///
6/// Delay is relative: the sender's and receiver's clocks are not compared, so the delay of a
7/// frame is how much later it arrived than the earliest-arriving frame would predict. Jitter is
8/// the RFC 3550 interarrival jitter estimate.
9#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
10pub struct Stats {
11    /// Frames received.
12    pub frames: u64,
13    /// Bytes of payload received.
14    pub bytes: u64,
15    /// Gaps seen.
16    pub gaps: u64,
17    /// Frames missed in those gaps.
18    pub missed: u64,
19    /// The last sequence number.
20    pub last_seq: Option<u64>,
21    /// Mean relative arrival delay, milliseconds.
22    pub mean_delay_ms: f64,
23    /// Largest relative arrival delay, milliseconds.
24    pub max_delay_ms: f64,
25    /// Interarrival jitter, milliseconds.
26    pub jitter_ms: f64,
27    #[serde(skip)]
28    min_transit: Option<f64>,
29    #[serde(skip)]
30    prev_transit: Option<f64>,
31    #[serde(skip)]
32    delay_sum: f64,
33}
34
35impl Stats {
36    /// Count a frame that arrived at `arrival_ms` (any monotonic clock), with the stream's
37    /// `clock_rate`. Returns the number of frames missed before it.
38    pub fn observe(&mut self, seq: u64, pts: u64, payload_len: usize, clock_rate: u32, arrival_ms: f64) -> u64 {
39        let missed = match self.last_seq {
40            Some(last) if seq > last + 1 => seq - last - 1,
41            _ => 0,
42        };
43        if missed > 0 {
44            self.gaps += 1;
45            self.missed += missed;
46        }
47        if self.last_seq.is_none_or(|l| seq > l) {
48            self.last_seq = Some(seq);
49        }
50        self.frames += 1;
51        self.bytes += payload_len as u64;
52        let pts_ms = pts as f64 * 1000.0 / clock_rate.max(1) as f64;
53        let transit = arrival_ms - pts_ms;
54        if let Some(prev) = self.prev_transit {
55            let d = (transit - prev).abs();
56            self.jitter_ms += (d - self.jitter_ms) / 16.0;
57        }
58        self.prev_transit = Some(transit);
59        let min = self.min_transit.map_or(transit, |m: f64| m.min(transit));
60        self.min_transit = Some(min);
61        let delay = transit - min;
62        self.delay_sum += delay;
63        self.mean_delay_ms = self.delay_sum / self.frames as f64;
64        self.max_delay_ms = self.max_delay_ms.max(delay);
65        missed
66    }
67}