rtci-interceptor 0.5.0

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
Documentation
//! What a receive-side jitter buffer discards, for the discard rate of the RFC 3611 VoIP
//! Metrics block (section 4.7.1).
//!
//! RFC 3611 section 4.7.1, discard rate: "The fraction of RTP data packets from the source that
//! have been discarded since the beginning of reception, due to late or early arrival,
//! under-run or overflow at the receiving jitter buffer", "calculated by dividing the total
//! number of packets discarded (excluding duplicate packet discards) by the total number of
//! packets expected". The jitter buffers ([`JitterBufferInterceptor`] and the adaptive one)
//! know what they discard; the XR generator, wire-ward of them, knows what was expected. A
//! [`JitterBufferDiscards`] given to both builders carries the count across.
//!
//! [`JitterBufferInterceptor`]: crate::JitterBufferInterceptor

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};

/// The packets each remote stream's jitter buffer discarded, shared by a jitter buffer and the
/// XR generator: give the same handle to [`JitterBufferBuilder::with_discard_count`] (or
/// [`AdaptiveJitterBufferBuilder::with_discard_count`]) and to
/// [`XrReportBuilder::with_jitter_buffer_discards`], and the VoIP Metrics block's discard rate
/// is the buffer's (RFC 3611 section 4.7.1). Without it the generator reports 0, which is
/// true only when nothing in the chain discards.
///
/// Counted per SSRC since the stream was bound: packets that arrived after their turn to be
/// played out had passed, that a full buffer dropped, and that a stream restart (a timestamp
/// discontinuity) dropped unplayed. A second copy of a packet, held or already played out, is
/// not counted ("excluding duplicate packet discards").
///
/// ```
/// use rtci_interceptor::{
///     JitterBufferBuilder, JitterBufferDiscards, Registry, Slot, XrReportBuilder,
/// };
///
/// let discards = JitterBufferDiscards::new();
/// let chain = Registry::new()
///     .with(
///         Slot::ExtendedReports,
///         XrReportBuilder::new().with_jitter_buffer_discards(&discards).build(),
///     )
///     .with(
///         Slot::JitterBuffer,
///         JitterBufferBuilder::new().with_discard_count(&discards).build(),
///     )
///     .build();
/// # let _ = chain;
/// assert_eq!(0, discards.discarded(0x1234));
/// ```
///
/// [`JitterBufferBuilder::with_discard_count`]: crate::JitterBufferBuilder::with_discard_count
/// [`AdaptiveJitterBufferBuilder::with_discard_count`]: crate::AdaptiveJitterBufferBuilder::with_discard_count
/// [`XrReportBuilder::with_jitter_buffer_discards`]: crate::XrReportBuilder::with_jitter_buffer_discards
#[derive(Debug, Clone, Default)]
pub struct JitterBufferDiscards {
    streams: Arc<Mutex<HashMap<u32, StreamDiscards>>>,
}

/// How many of a stream's discarded sequence numbers wait for the XR generator: it takes them
/// at each report (once a second by default), so this is room for far more than one interval.
pub(crate) const PENDING_DISCARDS: usize = 4096;

#[derive(Debug, Default)]
struct StreamDiscards {
    /// Discarded since the stream was bound.
    total: u64,
    /// The sequence numbers discarded since the XR generator last took them, for the burst
    /// and gap metrics (RFC 3611 section 4.7.2: packets "either lost or discarded").
    pending: VecDeque<u16>,
}

impl JitterBufferDiscards {
    /// A handle with nothing counted.
    pub fn new() -> Self {
        Self::default()
    }

    /// The packets of the remote stream `ssrc` discarded so far, duplicates excluded.
    pub fn discarded(&self, ssrc: u32) -> u64 {
        self.lock().get(&ssrc).map_or(0, |stream| stream.total)
    }

    /// The packets with these sequence numbers were discarded.
    pub(crate) fn record(&self, ssrc: u32, sequence_numbers: Vec<u16>) {
        if sequence_numbers.is_empty() {
            return;
        }
        let mut streams = self.lock();
        let stream = streams.entry(ssrc).or_default();
        stream.total += sequence_numbers.len() as u64;
        stream.pending.extend(sequence_numbers);
        while stream.pending.len() > PENDING_DISCARDS {
            stream.pending.pop_front();
        }
    }

    /// The sequence numbers discarded since the last call, oldest first.
    pub(crate) fn take_pending(&self, ssrc: u32) -> Vec<u16> {
        self.lock()
            .get_mut(&ssrc)
            .map(|stream| stream.pending.drain(..).collect())
            .unwrap_or_default()
    }

    /// A stream bound again starts its count again ("since the beginning of reception").
    pub(crate) fn reset(&self, ssrc: u32) {
        self.lock().remove(&ssrc);
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<u32, StreamDiscards>> {
        self.streams
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

/// How many played-out positions a buffer remembers, to tell a late copy of a packet already
/// played out (a duplicate) from a packet whose turn passed without it (a discard).
pub(crate) const PLAYED_OUT_MEMORY: usize = 1024;

/// The positions (sequence numbers, extended or not) a buffer played out most recently.
#[derive(Debug, Default)]
pub(crate) struct PlayedOut {
    recent: VecDeque<u64>,
}

impl PlayedOut {
    pub(crate) fn record(&mut self, position: u64) {
        if self.recent.len() == PLAYED_OUT_MEMORY {
            self.recent.pop_front();
        }
        self.recent.push_back(position);
    }

    /// Whether `position` was played out (among the last [`PLAYED_OUT_MEMORY`]). Asked only
    /// for a packet that arrives after its turn, so the scan is rare.
    pub(crate) fn contains(&self, position: u64) -> bool {
        self.recent.contains(&position)
    }

    pub(crate) fn clear(&mut self) {
        self.recent.clear();
    }
}