Skip to main content

rtci_interceptor/jitterbuffer/
discards.rs

1//! What a receive-side jitter buffer discards, for the discard rate of the RFC 3611 VoIP
2//! Metrics block (section 4.7.1).
3//!
4//! RFC 3611 section 4.7.1, discard rate: "The fraction of RTP data packets from the source that
5//! have been discarded since the beginning of reception, due to late or early arrival,
6//! under-run or overflow at the receiving jitter buffer", "calculated by dividing the total
7//! number of packets discarded (excluding duplicate packet discards) by the total number of
8//! packets expected". The jitter buffers ([`JitterBufferInterceptor`] and the adaptive one)
9//! know what they discard; the XR generator, wire-ward of them, knows what was expected. A
10//! [`JitterBufferDiscards`] given to both builders carries the count across.
11//!
12//! [`JitterBufferInterceptor`]: crate::JitterBufferInterceptor
13
14use std::collections::{HashMap, VecDeque};
15use std::sync::{Arc, Mutex};
16
17/// The packets each remote stream's jitter buffer discarded, shared by a jitter buffer and the
18/// XR generator: give the same handle to [`JitterBufferBuilder::with_discard_count`] (or
19/// [`AdaptiveJitterBufferBuilder::with_discard_count`]) and to
20/// [`XrReportBuilder::with_jitter_buffer_discards`], and the VoIP Metrics block's discard rate
21/// is the buffer's (RFC 3611 section 4.7.1). Without it the generator reports 0, which is
22/// true only when nothing in the chain discards.
23///
24/// Counted per SSRC since the stream was bound: packets that arrived after their turn to be
25/// played out had passed, that a full buffer dropped, and that a stream restart (a timestamp
26/// discontinuity) dropped unplayed. A second copy of a packet, held or already played out, is
27/// not counted ("excluding duplicate packet discards").
28///
29/// ```
30/// use rtci_interceptor::{
31///     JitterBufferBuilder, JitterBufferDiscards, Registry, Slot, XrReportBuilder,
32/// };
33///
34/// let discards = JitterBufferDiscards::new();
35/// let chain = Registry::new()
36///     .with(
37///         Slot::ExtendedReports,
38///         XrReportBuilder::new().with_jitter_buffer_discards(&discards).build(),
39///     )
40///     .with(
41///         Slot::JitterBuffer,
42///         JitterBufferBuilder::new().with_discard_count(&discards).build(),
43///     )
44///     .build();
45/// # let _ = chain;
46/// assert_eq!(0, discards.discarded(0x1234));
47/// ```
48///
49/// [`JitterBufferBuilder::with_discard_count`]: crate::JitterBufferBuilder::with_discard_count
50/// [`AdaptiveJitterBufferBuilder::with_discard_count`]: crate::AdaptiveJitterBufferBuilder::with_discard_count
51/// [`XrReportBuilder::with_jitter_buffer_discards`]: crate::XrReportBuilder::with_jitter_buffer_discards
52#[derive(Debug, Clone, Default)]
53pub struct JitterBufferDiscards {
54    streams: Arc<Mutex<HashMap<u32, StreamDiscards>>>,
55}
56
57/// How many of a stream's discarded sequence numbers wait for the XR generator: it takes them
58/// at each report (once a second by default), so this is room for far more than one interval.
59pub(crate) const PENDING_DISCARDS: usize = 4096;
60
61#[derive(Debug, Default)]
62struct StreamDiscards {
63    /// Discarded since the stream was bound.
64    total: u64,
65    /// The sequence numbers discarded since the XR generator last took them, for the burst
66    /// and gap metrics (RFC 3611 section 4.7.2: packets "either lost or discarded").
67    pending: VecDeque<u16>,
68}
69
70impl JitterBufferDiscards {
71    /// A handle with nothing counted.
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// The packets of the remote stream `ssrc` discarded so far, duplicates excluded.
77    pub fn discarded(&self, ssrc: u32) -> u64 {
78        self.lock().get(&ssrc).map_or(0, |stream| stream.total)
79    }
80
81    /// The packets with these sequence numbers were discarded.
82    pub(crate) fn record(&self, ssrc: u32, sequence_numbers: Vec<u16>) {
83        if sequence_numbers.is_empty() {
84            return;
85        }
86        let mut streams = self.lock();
87        let stream = streams.entry(ssrc).or_default();
88        stream.total += sequence_numbers.len() as u64;
89        stream.pending.extend(sequence_numbers);
90        while stream.pending.len() > PENDING_DISCARDS {
91            stream.pending.pop_front();
92        }
93    }
94
95    /// The sequence numbers discarded since the last call, oldest first.
96    pub(crate) fn take_pending(&self, ssrc: u32) -> Vec<u16> {
97        self.lock()
98            .get_mut(&ssrc)
99            .map(|stream| stream.pending.drain(..).collect())
100            .unwrap_or_default()
101    }
102
103    /// A stream bound again starts its count again ("since the beginning of reception").
104    pub(crate) fn reset(&self, ssrc: u32) {
105        self.lock().remove(&ssrc);
106    }
107
108    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<u32, StreamDiscards>> {
109        self.streams
110            .lock()
111            .unwrap_or_else(|poisoned| poisoned.into_inner())
112    }
113}
114
115/// How many played-out positions a buffer remembers, to tell a late copy of a packet already
116/// played out (a duplicate) from a packet whose turn passed without it (a discard).
117pub(crate) const PLAYED_OUT_MEMORY: usize = 1024;
118
119/// The positions (sequence numbers, extended or not) a buffer played out most recently.
120#[derive(Debug, Default)]
121pub(crate) struct PlayedOut {
122    recent: VecDeque<u64>,
123}
124
125impl PlayedOut {
126    pub(crate) fn record(&mut self, position: u64) {
127        if self.recent.len() == PLAYED_OUT_MEMORY {
128            self.recent.pop_front();
129        }
130        self.recent.push_back(position);
131    }
132
133    /// Whether `position` was played out (among the last [`PLAYED_OUT_MEMORY`]). Asked only
134    /// for a packet that arrives after its turn, so the scan is rare.
135    pub(crate) fn contains(&self, position: u64) -> bool {
136        self.recent.contains(&position)
137    }
138
139    pub(crate) fn clear(&mut self) {
140        self.recent.clear();
141    }
142}