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