Skip to main content

rtci_interceptor/jitterbuffer/
receiver.rs

1//! Receive-side jitter buffer interceptor: a time-based playout policy over [`JitterBufferInterceptor`].
2//!
3//! # Why this does not follow upstream
4//!
5//! `pion/interceptor`'s `ReceiverInterceptor` buffers a *packet count* and is pull-driven: its
6//! `BindRemoteStream` reader pushes the packet it just read and immediately pops one back, so the
7//! buffer is a fixed-length delay line of 50 packets rather than a span of time. webrtc#846 asks
8//! for the other thing — a depth measured in milliseconds, drained on a timer — because what a
9//! jitter buffer has to absorb is variation in *arrival time*, and a packet count only stands in
10//! for that while the bitrate is constant.
11//!
12//! The differences that follow from that:
13//!
14//! | | upstream | here |
15//! |---|---|---|
16//! | depth | 50 packets | a [`Duration`] |
17//! | emission | inside the read path, one in one out | on `handle_timeout`, everything now due |
18//! | not ready yet | `ErrPopWhileBuffering` | `poll_read` simply yields nothing |
19//! | per stream | one buffer for all of them | one per SSRC |
20//! | unbind | clears every stream's packets | drops only that stream |
21
22use super::buffer::{JitterBuffer as Buffer, Rejected, State};
23use super::discards::JitterBufferDiscards;
24use super::sequence::TimestampExtender;
25use crate::Interceptor;
26use crate::stream_info::StreamInfo;
27use crate::{Packet, TaggedPacket};
28use sansio::Protocol;
29use shared::error::Error;
30use std::collections::{HashMap, VecDeque};
31use std::time::{Duration, Instant};
32
33/// Default playout depth: enough to absorb ordinary network jitter without adding audible delay.
34pub const DEFAULT_DEPTH: Duration = Duration::from_millis(120);
35
36/// Default cap on packets held per stream, so a stalled or hostile stream cannot grow without
37/// bound while its deadline is still in the future.
38pub const DEFAULT_CAPACITY: usize = 512;
39
40/// A timestamp jump this large is read as a stream restart rather than a gap to wait out.
41///
42/// Ten seconds of media: far beyond any real inter-packet spacing, and small enough that a genuine
43/// restart is noticed promptly.
44const DISCONTINUITY: Duration = Duration::from_secs(10);
45
46/// Builder for [`JitterBufferInterceptor`].
47///
48/// # Example
49///
50/// ```
51/// use rtci_interceptor::{Slot, JitterBufferBuilder, Registry};
52/// use std::time::Duration;
53///
54/// let chain = Registry::new()
55///     .with(Slot::JitterBuffer, JitterBufferBuilder::new().with_depth(Duration::from_millis(80)).build())
56///     .build();
57/// ```
58pub struct JitterBufferBuilder {
59    depth: Duration,
60    capacity: usize,
61    discards: Option<JitterBufferDiscards>,
62}
63
64impl Default for JitterBufferBuilder {
65    fn default() -> Self {
66        Self {
67            depth: DEFAULT_DEPTH,
68            capacity: DEFAULT_CAPACITY,
69            discards: None,
70        }
71    }
72}
73
74impl JitterBufferBuilder {
75    /// Create a builder with the default depth and capacity.
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// How long a packet is held to absorb arrival-time variation.
81    ///
82    /// # Its relationship with NACK
83    ///
84    /// This is the delay the buffer adds, and it is also the window in which a retransmission is
85    /// still useful. A lost packet cannot come back before
86    ///
87    /// ```text
88    ///     detection (up to one NACK interval) + round trip + the sender's response
89    /// ```
90    ///
91    /// has elapsed, and the buffer plays a position out one depth after that position is due. So
92    /// **a depth shallower than that sum means every retransmission arrives too late** — its slot
93    /// has already been played past, so it is dropped rather than emitted out of order, and the
94    /// NACK traffic was spent for nothing.
95    ///
96    /// The two are deliberately not coupled: a mechanism for the jitter buffer and the NACK
97    /// generator to negotiate would tie together interceptors that are otherwise independent, and
98    /// an application that configures both can honour the inequality itself.
99    /// `tests/jitter_buffer_nack_depth.rs` holds it to that — the same loss recovered under a
100    /// depth chosen to accommodate it and lost under one chosen not to.
101    pub fn with_depth(mut self, depth: Duration) -> Self {
102        self.depth = depth;
103        self
104    }
105
106    /// Maximum packets held per stream, independently of the time depth.
107    pub fn with_capacity(mut self, capacity: usize) -> Self {
108        self.capacity = capacity;
109        self
110    }
111
112    /// Counts what each stream's buffer discards into `discards`, for the discard rate of the
113    /// XR VoIP Metrics block (RFC 3611 section 4.7.1): give the same handle to
114    /// [`XrReportBuilder::with_jitter_buffer_discards`](crate::XrReportBuilder::with_jitter_buffer_discards).
115    pub fn with_discard_count(mut self, discards: &JitterBufferDiscards) -> Self {
116        self.discards = Some(discards.clone());
117        self
118    }
119
120    /// Build the interceptor.
121    pub fn build(self) -> JitterBufferInterceptor {
122        let mut interceptor = JitterBufferInterceptor::new(self.depth, self.capacity);
123        interceptor.discards = self.discards;
124        interceptor
125    }
126}
127
128/// Where a stream's RTP timeline was pinned to the wall clock.
129///
130/// Playout instants are derived from this: a packet's deadline is the anchor's arrival instant
131/// plus the depth, plus however far the packet's RTP timestamp is beyond the anchor's. Anchoring
132/// on the first packet, rather than waiting for the buffered span to reach the full depth, is what
133/// lets a single-packet or paused stream start at all.
134#[derive(Debug, Clone, Copy)]
135struct Anchor {
136    arrived: Instant,
137    timestamp: u64,
138}
139
140#[cfg(test)]
141#[path = "receiver_deadlines_test.rs"]
142mod receiver_deadlines_test;
143
144/// Everything tracked for one remote stream.
145struct Stream {
146    buffer: Buffer,
147    timestamps: TimestampExtender,
148    /// RTP timestamp units per second, from the negotiated codec.
149    clock_rate: u32,
150    anchor: Option<Anchor>,
151    /// Playout instant per held packet, keyed by extended sequence number.
152    deadlines: HashMap<u64, Instant>,
153}
154
155impl Stream {
156    fn new(clock_rate: u32, capacity: usize) -> Self {
157        Self {
158            buffer: Buffer::new(capacity),
159            timestamps: TimestampExtender::new(),
160            // A zero clock rate would make every deadline a division by zero; treat an
161            // unnegotiated rate as the RTP video default rather than refusing to buffer.
162            clock_rate: if clock_rate == 0 { 90_000 } else { clock_rate },
163            anchor: None,
164            deadlines: HashMap::new(),
165        }
166    }
167
168    /// How far `timestamp` is beyond the anchor, in wall-clock terms.
169    fn offset_from_anchor(&self, anchor: &Anchor, timestamp: u64) -> Duration {
170        let ticks = timestamp.saturating_sub(anchor.timestamp);
171        Duration::from_secs_f64(ticks as f64 / f64::from(self.clock_rate))
172    }
173
174    /// Start the timeline again at this packet, dropping what was held *and* the ordering state.
175    ///
176    /// Only for a timestamp discontinuity: the old anchor no longer describes where this stream is
177    /// in time, and deriving deadlines from it would put every subsequent packet either
178    /// immediately overdue or hours away. Resetting the buffer also clears its extended-sequence
179    /// origin, which is why running dry must not come through here — a fresh origin measured
180    /// against a stale played-out watermark would reject everything.
181    fn restart(&mut self, arrived: Instant, timestamp: u64) {
182        self.buffer.reset();
183        self.deadlines.clear();
184        self.anchor = Some(Anchor { arrived, timestamp });
185    }
186}
187
188/// Holds each stream's packets for a fixed span of time, then releases them in order.
189///
190/// The `jitterbuffer::receiver` module documentation covers how this differs from upstream.
191pub struct JitterBufferInterceptor {
192    depth: Duration,
193    capacity: usize,
194    streams: HashMap<u32, Stream>,
195    /// Where each stream's discards are counted, when the application asked for them.
196    discards: Option<JitterBufferDiscards>,
197    /// Packets whose playout instant has come, waiting to join the belt.
198    due: VecDeque<TaggedPacket>,
199    /// Inbound packets ready for the next interceptor.
200    read_queue: VecDeque<TaggedPacket>,
201    /// Outbound packets ready for the next interceptor: what passed through, plus
202    /// anything this one generated.
203    write_queue: VecDeque<TaggedPacket>,
204}
205
206impl JitterBufferInterceptor {
207    fn new(depth: Duration, capacity: usize) -> Self {
208        Self {
209            read_queue: VecDeque::new(),
210            write_queue: VecDeque::new(),
211            due: VecDeque::new(),
212            depth,
213            capacity,
214            streams: HashMap::new(),
215            discards: None,
216        }
217    }
218
219    /// The playout instant of the packet nearest release on `stream`.
220    fn next_deadline(stream: &Stream) -> Option<Instant> {
221        let front = stream.buffer.front_sequence()?;
222        stream.deadlines.get(&front).copied()
223    }
224}
225
226impl Protocol<TaggedPacket, TaggedPacket, ()> for JitterBufferInterceptor {
227    type Rout = TaggedPacket;
228    type Wout = TaggedPacket;
229    type Eout = ();
230    type Error = Error;
231    type Time = Instant;
232
233    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
234        let Packet::Rtp(rtp) = &msg.message.packet else {
235            // RTCP has no sequence number to order by and no playout deadline; it must not be
236            // delayed behind media either, since feedback is only useful while it is fresh.
237            self.read_queue.push_back(msg);
238            return Ok(());
239        };
240
241        let ssrc = rtp.header.ssrc;
242        let timestamp = rtp.header.timestamp;
243        let arrived = msg.now;
244
245        let Some(stream) = self.streams.get_mut(&ssrc) else {
246            // Not a stream we were told about: pass it straight through rather than buffering
247            // packets nobody will ever come to collect.
248            self.read_queue.push_back(msg);
249            return Ok(());
250        };
251
252        let extended_timestamp = stream.timestamps.extend(timestamp);
253
254        // Anchor the timeline on the first packet, or re-anchor across a discontinuity.
255        //
256        // Re-anchoring is not the same as restarting: a stream that merely ran dry keeps its
257        // ordering state, because `released_through` is what stops a straggler from the previous
258        // run being emitted behind packets that already left. Only a discontinuity — where the
259        // timeline genuinely no longer relates to the old one — wipes it.
260        match stream.anchor {
261            None => {
262                stream.anchor = Some(Anchor {
263                    arrived,
264                    timestamp: extended_timestamp,
265                })
266            }
267            Some(anchor) => {
268                let ticks = extended_timestamp.abs_diff(anchor.timestamp);
269                let elapsed = Duration::from_secs_f64(ticks as f64 / f64::from(stream.clock_rate));
270                if elapsed > DISCONTINUITY {
271                    stream.restart(arrived, extended_timestamp);
272                }
273            }
274        }
275
276        let anchor = stream.anchor.expect("just anchored");
277        let deadline =
278            anchor.arrived + self.depth + stream.offset_from_anchor(&anchor, extended_timestamp);
279
280        let pushed = stream.buffer.push(msg);
281        // RFC 3611 section 4.7.1: what this arrival made the buffer discard (a restart's
282        // unplayed packets, an overflow, the arrival itself when its turn has passed).
283        let discarded = stream.buffer.take_discards();
284        if let Some(discards) = &self.discards {
285            discards.record(ssrc, discarded);
286        }
287        match pushed {
288            Ok(extended) => {
289                stream.deadlines.insert(extended, deadline);
290                // A full buffer evicts its oldest packet to take this one; that packet's deadline
291                // goes with it, or the map grows by one per eviction for the stream's life.
292                if stream.deadlines.len() > stream.buffer.len()
293                    && let Some(front) = stream.buffer.front_sequence()
294                {
295                    stream.deadlines.retain(|held, _| *held >= front);
296                }
297                // Held: it leaves later, from `poll_read`, at its playout instant.
298                Ok(())
299            }
300            // Dropped on purpose — a duplicate, a straggler past its position, a foreign SSRC, or
301            // the capacity cap. None of these may be forwarded: doing so would emit a packet twice
302            // or out of order, which is exactly what this interceptor exists to prevent.
303            Err(
304                Rejected::Duplicate | Rejected::Late | Rejected::Overflow | Rejected::ForeignSsrc,
305            ) => Ok(()),
306        }
307    }
308
309    fn poll_read(&mut self) -> Option<TaggedPacket> {
310        // What passed straight through goes first: RTCP must not wait behind buffered media.
311        self.read_queue.pop_front().or_else(|| self.due.pop_front())
312    }
313
314    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
315        self.write_queue.push_back(msg);
316        Ok(())
317    }
318
319    fn poll_write(&mut self) -> Option<Self::Wout> {
320        self.write_queue.pop_front()
321    }
322
323    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
324        // Collected first so the borrow of `self.streams` ends before the queue is extended.
325        let mut due: Vec<TaggedPacket> = Vec::new();
326
327        for stream in self.streams.values_mut() {
328            // The first packet's deadline is what starts playout; before that the stream is still
329            // filling, and `pop` yields nothing.
330            if stream.buffer.state() == State::Buffering
331                && Self::next_deadline(stream).is_some_and(|deadline| deadline <= now)
332            {
333                stream.buffer.begin_emitting();
334            }
335
336            while let Some(front) = stream.buffer.front_sequence() {
337                let Some(&deadline) = stream.deadlines.get(&front) else {
338                    break;
339                };
340                if deadline > now {
341                    break;
342                }
343                let Some(mut packet) = stream.buffer.pop() else {
344                    break;
345                };
346                stream.deadlines.remove(&front);
347                // Rule 3 of the chain contract: the packet carries the instant it was released,
348                // not the instant it arrived, so nothing downstream counts this buffer's own
349                // holding time as network delay.
350                packet.now = now;
351                due.push(packet);
352            }
353
354            // Run dry: fill again before playout resumes, so the next packet is not emitted the
355            // moment it lands with no cushion behind it.
356            if stream.buffer.is_empty() && stream.buffer.state() == State::Emitting {
357                stream.buffer.begin_buffering();
358                // Timeline anchor only: ordering state survives, so a straggler from the run that
359                // just ended is still rejected rather than emitted out of order.
360                stream.anchor = None;
361            }
362        }
363
364        // Queued for `poll_read`, which puts them back on the belt, so a released packet
365        // traverses every interceptor ahead of this one exactly as a live one would. The nested design
366        // did this by re-injecting through `inner` by hand.
367        self.due.extend(due);
368        Ok(())
369    }
370
371    fn poll_timeout(&mut self) -> Option<Instant> {
372        self.streams.values().filter_map(Self::next_deadline).min()
373    }
374}
375
376impl Interceptor for JitterBufferInterceptor {
377    fn bind_remote_stream(&mut self, info: &StreamInfo) {
378        // Keyed by SSRC, unlike upstream, whose single buffer interleaves every remote stream
379        // into one sequence-number ordering.
380        if !self.streams.contains_key(&info.ssrc) {
381            if let Some(discards) = &self.discards {
382                discards.reset(info.ssrc);
383            }
384            self.streams
385                .insert(info.ssrc, Stream::new(info.clock_rate, self.capacity));
386        }
387    }
388
389    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
390        // Only this stream. Upstream's `UnbindRemoteStream` clears the shared buffer, discarding
391        // every other stream's packets along with it.
392        self.streams.remove(&info.ssrc);
393    }
394
395    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
396
397    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
398}