weirdnet-audio-stream 0.2.0

General-purpose audio streaming for Weirdnet: publish and subscribe to live or recorded streams of codec-agnostic frames, many listeners with their own bounded queues, seeking, arrival statistics and per-subscription authorisation.
Documentation
//! Arrival statistics for a subscriber.
use serde::{Deserialize, Serialize};

/// What a subscriber has seen: frames, loss, and how late and how unevenly frames arrive.
///
/// Delay is relative: the sender's and receiver's clocks are not compared, so the delay of a
/// frame is how much later it arrived than the earliest-arriving frame would predict. Jitter is
/// the RFC 3550 interarrival jitter estimate.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Stats {
    /// Frames received.
    pub frames: u64,
    /// Bytes of payload received.
    pub bytes: u64,
    /// Gaps seen.
    pub gaps: u64,
    /// Frames missed in those gaps.
    pub missed: u64,
    /// The last sequence number.
    pub last_seq: Option<u64>,
    /// Mean relative arrival delay, milliseconds.
    pub mean_delay_ms: f64,
    /// Largest relative arrival delay, milliseconds.
    pub max_delay_ms: f64,
    /// Interarrival jitter, milliseconds.
    pub jitter_ms: f64,
    #[serde(skip)]
    min_transit: Option<f64>,
    #[serde(skip)]
    prev_transit: Option<f64>,
    #[serde(skip)]
    delay_sum: f64,
}

impl Stats {
    /// Count a frame that arrived at `arrival_ms` (any monotonic clock), with the stream's
    /// `clock_rate`. Returns the number of frames missed before it.
    pub fn observe(&mut self, seq: u64, pts: u64, payload_len: usize, clock_rate: u32, arrival_ms: f64) -> u64 {
        let missed = match self.last_seq {
            Some(last) if seq > last + 1 => seq - last - 1,
            _ => 0,
        };
        if missed > 0 {
            self.gaps += 1;
            self.missed += missed;
        }
        if self.last_seq.is_none_or(|l| seq > l) {
            self.last_seq = Some(seq);
        }
        self.frames += 1;
        self.bytes += payload_len as u64;
        let pts_ms = pts as f64 * 1000.0 / clock_rate.max(1) as f64;
        let transit = arrival_ms - pts_ms;
        if let Some(prev) = self.prev_transit {
            let d = (transit - prev).abs();
            self.jitter_ms += (d - self.jitter_ms) / 16.0;
        }
        self.prev_transit = Some(transit);
        let min = self.min_transit.map_or(transit, |m: f64| m.min(transit));
        self.min_transit = Some(min);
        let delay = transit - min;
        self.delay_sum += delay;
        self.mean_delay_ms = self.delay_sum / self.frames as f64;
        self.max_delay_ms = self.max_delay_ms.max(delay);
        missed
    }
}