Skip to main content

rtci_interceptor/nack/
generator.rs

1//! NACK Generator Interceptor - Generates NACK requests for missing packets.
2
3use super::receive_log::ReceiveLog;
4use super::stream_supports_nack;
5use crate::Interceptor;
6use crate::stream_info::StreamInfo;
7use crate::{AttributedPacket, Packet, TaggedPacket};
8use sansio::Protocol;
9use shared::TransportContext;
10use shared::error::Error;
11use std::collections::{HashMap, VecDeque};
12use std::time::{Duration, Instant};
13
14/// Builder for the NackGeneratorInterceptor.
15///
16/// # Example
17///
18/// ```
19/// use rtci_interceptor::{Slot, Registry, NackGeneratorBuilder};
20/// use std::time::Duration;
21///
22/// let chain = Registry::new()
23///     .with(Slot::NackGenerator, NackGeneratorBuilder::new()
24///         .with_size(512)
25///         .with_interval(Duration::from_millis(100))
26///         .with_skip_last_n(2)
27///         .build())
28///     .build();
29/// ```
30pub struct NackGeneratorBuilder {
31    /// Size of the receive log (must be power of 2: 64, 128, ..., 32768).
32    size: u16,
33    /// Interval between NACK generation cycles.
34    interval: Duration,
35    /// Number of most recent packets to skip when generating NACKs.
36    skip_last_n: u16,
37    /// Maximum number of NACKs to send per missing packet (0 = unlimited).
38    max_nacks_per_packet: u16,
39    /// How long a packet is asked for, counted from when it was found missing.
40    max_packet_age: Option<Duration>,
41    /// How long a packet has to be missing before it is first asked for.
42    reorder_delay: Duration,
43    /// The round-trip time assumed until one is measured.
44    round_trip_time: Option<Duration>,
45}
46
47/// A limit for [`NackGeneratorBuilder::with_max_nacks_per_packet`]: ten requests, the
48/// generator's default from v0.22.0+brainwires.6 until requests became unlimited. Not
49/// libwebrtc's: its `kMaxNackRetries` is 100 (`modules/video_coding/nack_requester.cc` at
50/// a222406d, line 39), the limit of the `Chrome` behaviour profile. Not the default (see the
51/// method).
52pub const SUGGESTED_MAX_NACKS_PER_PACKET: u16 = 10;
53/// A limit for [`NackGeneratorBuilder::with_max_packet_age`], for a receiver that plays a
54/// packet out within two seconds of its loss. Not the default (see the method).
55pub const SUGGESTED_MAX_PACKET_AGE: Duration = Duration::from_secs(2);
56
57/// How far back the reordering a stream showed is remembered for its allowance.
58const REORDERING_WINDOW: Duration = Duration::from_secs(10);
59/// The most the learned reordering allowance holds a first request back.
60const MAX_REORDERING_ALLOWANCE: Duration = Duration::from_millis(500);
61/// How many of a stream's newest advances of the highest sequence number are kept, to tell
62/// when the gap a late packet fills was opened.
63const ADVANCES_KEPT: usize = 512;
64
65/// The reordering a stream has shown: how late its out-of-order packets came, against when
66/// the first packet that overtook each arrived (RFC 4588 6.3: the first request waits for
67/// reordering to be ruled out).
68#[derive(Default)]
69struct Reordering {
70    /// The highest sequence number received, and when each newer one first arrived.
71    highest: Option<u16>,
72    advances: VecDeque<(u16, Instant)>,
73    /// When each late packet arrived and how long after its gap opened.
74    late: VecDeque<(Instant, Duration)>,
75}
76
77impl Reordering {
78    fn on_packet(&mut self, now: Instant, seq: u16, asked_for: bool) {
79        let newer = |a: u16, b: u16| (1..0x8000).contains(&a.wrapping_sub(b));
80        match self.highest {
81            Some(highest) if !newer(seq, highest) => {
82                // Out of order. A packet that was asked for may be its retransmission: that
83                // says nothing about the path's reordering.
84                if seq != highest
85                    && !asked_for
86                    && let Some((_, opened)) = self
87                        .advances
88                        .iter()
89                        .find(|(advanced, _)| newer(*advanced, seq))
90                {
91                    self.late
92                        .push_back((now, now.saturating_duration_since(*opened)));
93                }
94            }
95            _ => {
96                self.highest = Some(seq);
97                self.advances.push_back((seq, now));
98                while self.advances.len() > ADVANCES_KEPT {
99                    self.advances.pop_front();
100                }
101            }
102        }
103        while let Some((at, _)) = self.late.front() {
104            if now.saturating_duration_since(*at) <= REORDERING_WINDOW {
105                break;
106            }
107            self.late.pop_front();
108        }
109    }
110
111    /// How long a missing packet of this stream may still be on its way: the latest a
112    /// reordered packet came in the last ten seconds, with a quarter on top, at most
113    /// [`MAX_REORDERING_ALLOWANCE`].
114    fn allowance(&self, now: Instant) -> Duration {
115        self.late
116            .iter()
117            .filter(|(at, _)| now.saturating_duration_since(*at) <= REORDERING_WINDOW)
118            .map(|(_, late)| *late)
119            .max()
120            .map_or(Duration::ZERO, |late| {
121                late.mul_f64(1.25).min(MAX_REORDERING_ALLOWANCE)
122            })
123    }
124}
125
126impl Default for NackGeneratorBuilder {
127    fn default() -> Self {
128        Self {
129            size: 512,
130            interval: Duration::from_millis(100),
131            skip_last_n: 0,
132            max_nacks_per_packet: 0,
133            max_packet_age: None,
134            reorder_delay: Duration::ZERO,
135            round_trip_time: None,
136        }
137    }
138}
139
140impl NackGeneratorBuilder {
141    /// Create a new builder with default settings.
142    pub fn new() -> Self {
143        Self::default()
144    }
145
146    /// Set the size of the receive log.
147    ///
148    /// Size must be a power of 2 between 64 and 32768 (inclusive).
149    pub fn with_size(mut self, size: u16) -> Self {
150        self.size = size;
151        self
152    }
153
154    /// Set the interval between NACK generation cycles.
155    pub fn with_interval(mut self, interval: Duration) -> Self {
156        self.interval = interval;
157        self
158    }
159
160    /// Set the number of most recent packets to skip when generating NACKs.
161    ///
162    /// This helps avoid generating NACKs for packets that are simply delayed
163    /// and haven't arrived yet.
164    pub fn with_skip_last_n(mut self, skip_last_n: u16) -> Self {
165        self.skip_last_n = skip_last_n;
166        self
167    }
168
169    /// Set the maximum number of NACKs to send per missing packet (RFC 4588 Appendix A: a
170    /// receiver limits how often it asks again).
171    ///
172    /// Default: 0, unlimited: a missing packet is asked for again a round trip after each
173    /// request (RFC 4588 6.3) for as long as it is missing and the receive log holds it. RFC
174    /// 4588 gives no number ("the absolute minimum should be one", Appendix A). A limit makes a
175    /// packet that the limit's requests did not bring lost for good, and a receiver that holds
176    /// later frames back for it (a sample builder, a jitter buffer) freezes until it gives the
177    /// packet up as well: in `tests/capacity_cap_video_rtc2rtc.rs`, with retransmissions not held
178    /// to the target, ten requests (and no age limit) left the picture frozen for 4.8 to 5.4 s on
179    /// every seed, against 1.0 to 1.6 s without a limit. [`SUGGESTED_MAX_NACKS_PER_PACKET`] is
180    /// those ten; libwebrtc gives a packet up after 100 requests (`kMaxNackRetries`,
181    /// `modules/video_coding/nack_requester.cc` at a222406d, line 39), a request at most every
182    /// round trip, and counts its other limits in packets: a packet more than 10,000 sequence
183    /// numbers behind the newest is not asked for (`kMaxPacketAge`), and a NACK list that would
184    /// pass 1000 entries is cleared and a key frame requested instead (`kMaxNackPackets`).
185    pub fn with_max_nacks_per_packet(mut self, max: u16) -> Self {
186        self.max_nacks_per_packet = max;
187        self
188    }
189
190    /// Set how long a missing packet is asked for (RFC 4588 6.3: a retransmission is only
191    /// requested while it can still be of use). Give the sender's `rtx-time` (RFC 4588 8.1)
192    /// when it signals one: past it the sender no longer has the packet.
193    ///
194    /// Default: `None`, unlimited, unless the sender signals `rtx-time`. How long a packet stays
195    /// useful is the receiving application's playout (RFC 4588 6.3), which this interceptor
196    /// does not know: a fixed two seconds left a call frozen for 5.9 to 6.8 s after a capacity
197    /// drop in `tests/capacity_cap_video_rtc2rtc.rs`, packets whose requests stopped at two
198    /// seconds staying lost while the receiver still waited for them. An application that plays
199    /// out within a known time gives that time here ([`SUGGESTED_MAX_PACKET_AGE`] is two
200    /// seconds).
201    pub fn with_max_packet_age(mut self, max_packet_age: Option<Duration>) -> Self {
202        self.max_packet_age = max_packet_age;
203        self
204    }
205
206    /// Set how long a packet has to be missing before the first NACK for it (RFC 4588 6.3:
207    /// the request is delayed to allow for reordering). Default: zero.
208    ///
209    /// On top of it the generator learns each stream's reordering: a first request also
210    /// waits for as long as the stream's out-of-order packets arrived late in the last ten
211    /// seconds (a quarter more, at most 500 ms), so a path that reorders does not have every
212    /// overtaken packet asked for and retransmitted.
213    pub fn with_reorder_delay(mut self, reorder_delay: Duration) -> Self {
214        self.reorder_delay = reorder_delay;
215        self
216    }
217
218    /// Set the round-trip time assumed until the RTCP session measures one
219    /// ([`RtcpSessionEvent::RoundTripTime`](crate::RtcpSessionEvent::RoundTripTime)). A
220    /// packet is not asked for again before a round trip has passed since the last request
221    /// (RFC 4588 6.3: "the timer value shall be based on the observed round-trip time"): the
222    /// retransmission could not have arrived sooner.
223    pub fn with_round_trip_time(mut self, round_trip_time: Duration) -> Self {
224        self.round_trip_time = Some(round_trip_time);
225        self
226    }
227
228    /// Build the interceptor.
229    pub fn build(self) -> NackGeneratorInterceptor {
230        let mut interceptor = NackGeneratorInterceptor::new(
231            self.size,
232            self.interval,
233            self.skip_last_n,
234            self.max_nacks_per_packet,
235        );
236        interceptor.max_packet_age = self.max_packet_age;
237        interceptor.reorder_delay = self.reorder_delay;
238        interceptor.round_trip_time = self.round_trip_time;
239        interceptor
240    }
241}
242
243/// Interceptor that generates NACK requests for missing RTP packets.
244///
245/// This interceptor monitors incoming RTP packets on remote streams,
246/// tracks which sequence numbers have been received, and periodically
247/// generates RTCP TransportLayerNack packets for missing sequences.
248pub struct NackGeneratorInterceptor {
249    /// Configuration
250    size: u16,
251    interval: Duration,
252    skip_last_n: u16,
253    max_nacks_per_packet: u16,
254
255    /// Next timeout for NACK generation
256    next_timeout: Option<Instant>,
257
258    /// Sender SSRC for NACK packets
259    sender_ssrc: u32,
260
261    /// Receive logs per remote stream SSRC
262    receive_logs: HashMap<u32, ReceiveLog>,
263
264    max_packet_age: Option<Duration>,
265    /// The retransmission payload type of each bound stream that has one, by SSRC.
266    rtx_payload_types: HashMap<u32, u8>,
267    /// The `rtx-time` the remote endpoint announced, by retransmission payload type
268    /// ([`NackControl::RemoteRtxTime`](super::NackControl::RemoteRtxTime)).
269    remote_rtx_times: HashMap<u8, Duration>,
270    reorder_delay: Duration,
271    /// The round-trip time to the senders, measured by the RTCP session when there is one.
272    round_trip_time: Option<Duration>,
273
274    /// What has been asked for, per SSRC and missing sequence number.
275    requests: HashMap<u32, HashMap<u16, Request>>,
276    /// The reordering each stream showed.
277    reordering: HashMap<u32, Reordering>,
278
279    /// Queue for outgoing NACK packets
280    write_queue: VecDeque<TaggedPacket>,
281    /// Inbound packets ready for the next interceptor.
282    read_queue: VecDeque<TaggedPacket>,
283}
284
285impl NackGeneratorInterceptor {
286    fn new(size: u16, interval: Duration, skip_last_n: u16, max_nacks_per_packet: u16) -> Self {
287        Self {
288            read_queue: VecDeque::new(),
289            size,
290            interval,
291            skip_last_n,
292            max_nacks_per_packet,
293            next_timeout: None,
294            sender_ssrc: rand::random(),
295            receive_logs: HashMap::new(),
296            max_packet_age: None,
297            rtx_payload_types: HashMap::new(),
298            remote_rtx_times: HashMap::new(),
299            reorder_delay: Duration::ZERO,
300            round_trip_time: None,
301            requests: HashMap::new(),
302            reordering: HashMap::new(),
303            write_queue: VecDeque::new(),
304        }
305    }
306
307    /// Generate NACKs for all streams with missing packets.
308    fn generate_nacks(&mut self, now: Instant) {
309        for (&ssrc, receive_log) in &self.receive_logs {
310            let missing = receive_log.missing_seq_numbers(self.skip_last_n);
311            if missing.is_empty() {
312                self.requests.remove(&ssrc);
313                continue;
314            }
315
316            // RFC 4588 8.1: past the sender's `rtx-time` it no longer has the packet. The
317            // shorter of that and the configured age is how long a packet is asked for.
318            let rtx_time = self
319                .rtx_payload_types
320                .get(&ssrc)
321                .and_then(|payload_type_rtx| self.remote_rtx_times.get(payload_type_rtx))
322                .copied();
323            let max_packet_age = match (self.max_packet_age, rtx_time) {
324                (Some(age), Some(rtx_time)) => Some(age.min(rtx_time)),
325                (age, rtx_time) => age.or(rtx_time),
326            };
327
328            let reorder_delay = self.reorder_delay.max(
329                self.reordering
330                    .get(&ssrc)
331                    .map_or(Duration::ZERO, |reordering| reordering.allowance(now)),
332            );
333            let requests = self.requests.entry(ssrc).or_default();
334            // A packet that arrived, or that the log no longer covers, is forgotten.
335            requests.retain(|sequence_number, _| missing.contains(sequence_number));
336
337            let due: Vec<u16> = missing
338                .iter()
339                .copied()
340                .filter(|sequence_number| {
341                    let request = requests.entry(*sequence_number).or_insert(Request {
342                        missing_since: now,
343                        last_asked: None,
344                        asked: 0,
345                    });
346                    // Give up: asked often enough, or too old to be of use.
347                    if self.max_nacks_per_packet > 0 && request.asked >= self.max_nacks_per_packet {
348                        return false;
349                    }
350                    let missing_for = now.saturating_duration_since(request.missing_since);
351                    if max_packet_age.is_some_and(|max| missing_for > max) {
352                        return false;
353                    }
354                    let due = match request.last_asked {
355                        // The first request waits out the reordering allowance.
356                        None => missing_for >= reorder_delay,
357                        // The next waits for the retransmission to have had a round trip.
358                        Some(last_asked) => self
359                            .round_trip_time
360                            .is_none_or(|rtt| now.saturating_duration_since(last_asked) >= rtt),
361                    };
362                    if due {
363                        request.last_asked = Some(now);
364                        request.asked = request.asked.saturating_add(1);
365                    }
366                    due
367                })
368                .collect();
369
370            if due.is_empty() {
371                continue;
372            }
373
374            // Create NACK packet
375            let nack = rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack {
376                sender_ssrc: self.sender_ssrc,
377                media_ssrc: ssrc,
378                nacks: rtcp::transport_feedbacks::transport_layer_nack::nack_pairs_from_sequence_numbers(
379                    &due,
380                ),
381            };
382
383            self.write_queue.push_back(TaggedPacket {
384                now,
385                transport: TransportContext::default(),
386                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(nack)])),
387            });
388        }
389    }
390}
391
392/// A missing packet and what has been done about it.
393struct Request {
394    /// When the generator first found it missing.
395    missing_since: Instant,
396    /// When it was last asked for.
397    last_asked: Option<Instant>,
398    /// How often it has been asked for.
399    asked: u16,
400}
401
402impl Protocol<TaggedPacket, TaggedPacket, ()> for NackGeneratorInterceptor {
403    type Rout = TaggedPacket;
404    type Wout = TaggedPacket;
405    type Eout = ();
406    type Error = Error;
407    type Time = Instant;
408
409    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
410        // RFC 4588 5.3: "a receiver MUST stop requesting retransmissions for an SSRC on
411        // receiving its BYE" (RFC 3550 6.6: the source has left). Its receive log goes, and
412        // with it every gap still open; packets arriving later under that SSRC are not tracked.
413        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
414            for rtcp_packet in rtcp_packets {
415                if let Some(goodbye) = rtcp_packet
416                    .as_any()
417                    .downcast_ref::<rtcp::goodbye::Goodbye>()
418                {
419                    for source in &goodbye.sources {
420                        self.receive_logs.remove(source);
421                        self.requests.remove(source);
422                        self.reordering.remove(source);
423                    }
424                }
425            }
426        }
427
428        // The round-trip time the RTCP session measured, for the pace of repeated requests.
429        if let Some(crate::RtcpSessionEvent::RoundTripTime { rtt, .. }) =
430            msg.message.custom::<crate::RtcpSessionEvent>()
431        {
432            self.round_trip_time = Some(*rtt);
433        }
434
435        // Track incoming RTP packets
436        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
437            && let Some(receive_log) = self.receive_logs.get_mut(&rtp_packet.header.ssrc)
438        {
439            receive_log.add(rtp_packet.header.sequence_number);
440            let ssrc = rtp_packet.header.ssrc;
441            let seq = rtp_packet.header.sequence_number;
442            let asked_for = self
443                .requests
444                .get(&ssrc)
445                .and_then(|requests| requests.get(&seq))
446                .is_some_and(|request| request.last_asked.is_some());
447            self.reordering
448                .entry(ssrc)
449                .or_default()
450                .on_packet(msg.now, seq, asked_for);
451
452            // Arm the NACK timer from the first tracked packet's instant. `None` means nothing is
453            // scheduled, so the interceptor asks for no wake-up until a stream is actually flowing.
454            if self.next_timeout.is_none() {
455                self.next_timeout = Some(msg.now + self.interval);
456            }
457        }
458
459        self.read_queue.push_back(msg);
460
461        Ok(())
462    }
463
464    fn poll_read(&mut self) -> Option<Self::Rout> {
465        self.read_queue.pop_front()
466    }
467
468    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
469        if let Some(super::NackControl::RemoteRtxTime {
470            payload_type_rtx,
471            rtx_time,
472        }) = msg.message.custom::<super::NackControl>()
473        {
474            match rtx_time {
475                Some(rtx_time) => self.remote_rtx_times.insert(*payload_type_rtx, *rtx_time),
476                None => self.remote_rtx_times.remove(payload_type_rtx),
477            };
478        }
479        self.write_queue.push_back(msg);
480        Ok(())
481    }
482
483    fn poll_write(&mut self) -> Option<TaggedPacket> {
484        // First drain generated NACK packets
485        if let Some(pkt) = self.write_queue.pop_front() {
486            return Some(pkt);
487        }
488        None
489    }
490
491    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
492        if let Some(next_timeout) = self.next_timeout
493            && now >= next_timeout
494        {
495            self.next_timeout = Some(now + self.interval);
496            self.generate_nacks(now);
497        }
498        Ok(())
499    }
500
501    fn poll_timeout(&mut self) -> Option<Instant> {
502        self.next_timeout
503    }
504}
505
506impl Interceptor for NackGeneratorInterceptor {
507    fn bind_remote_stream(&mut self, info: &StreamInfo) {
508        if stream_supports_nack(info)
509            && let Some(receive_log) = ReceiveLog::new(self.size)
510        {
511            self.receive_logs.insert(info.ssrc, receive_log);
512            match info.payload_type_rtx {
513                Some(payload_type_rtx) => {
514                    self.rtx_payload_types.insert(info.ssrc, payload_type_rtx)
515                }
516                None => self.rtx_payload_types.remove(&info.ssrc),
517            };
518        }
519    }
520
521    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
522        self.receive_logs.remove(&info.ssrc);
523        self.requests.remove(&info.ssrc);
524        self.reordering.remove(&info.ssrc);
525        self.rtx_payload_types.remove(&info.ssrc);
526    }
527
528    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
529
530    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
531}