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::{older_than, 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    /// The oldest sequence number the application can still use, per SSRC
274    /// ([`NackControl::Horizon`](super::NackControl::Horizon)).
275    horizons: HashMap<u32, u16>,
276
277    /// What has been asked for, per SSRC and missing sequence number.
278    requests: HashMap<u32, HashMap<u16, Request>>,
279    /// The reordering each stream showed.
280    reordering: HashMap<u32, Reordering>,
281
282    /// Queue for outgoing NACK packets
283    write_queue: VecDeque<TaggedPacket>,
284    /// Inbound packets ready for the next interceptor.
285    read_queue: VecDeque<TaggedPacket>,
286}
287
288impl NackGeneratorInterceptor {
289    fn new(size: u16, interval: Duration, skip_last_n: u16, max_nacks_per_packet: u16) -> Self {
290        Self {
291            read_queue: VecDeque::new(),
292            size,
293            interval,
294            skip_last_n,
295            max_nacks_per_packet,
296            next_timeout: None,
297            sender_ssrc: rand::random(),
298            receive_logs: HashMap::new(),
299            max_packet_age: None,
300            rtx_payload_types: HashMap::new(),
301            remote_rtx_times: HashMap::new(),
302            reorder_delay: Duration::ZERO,
303            round_trip_time: None,
304            horizons: HashMap::new(),
305            requests: HashMap::new(),
306            reordering: HashMap::new(),
307            write_queue: VecDeque::new(),
308        }
309    }
310
311    /// Generate NACKs for all streams with missing packets.
312    fn generate_nacks(&mut self, now: Instant) {
313        for (&ssrc, receive_log) in &self.receive_logs {
314            let mut missing = receive_log.missing_seq_numbers(self.skip_last_n);
315            // RFC 4588 6.3: a packet older than what the application can still use is not
316            // asked for (and its request is forgotten below).
317            if let Some(&horizon) = self.horizons.get(&ssrc) {
318                missing.retain(|&sequence_number| !older_than(sequence_number, horizon));
319            }
320            if missing.is_empty() {
321                self.requests.remove(&ssrc);
322                continue;
323            }
324
325            // RFC 4588 8.1: past the sender's `rtx-time` it no longer has the packet. The
326            // shorter of that and the configured age is how long a packet is asked for.
327            let rtx_time = self
328                .rtx_payload_types
329                .get(&ssrc)
330                .and_then(|payload_type_rtx| self.remote_rtx_times.get(payload_type_rtx))
331                .copied();
332            let max_packet_age = match (self.max_packet_age, rtx_time) {
333                (Some(age), Some(rtx_time)) => Some(age.min(rtx_time)),
334                (age, rtx_time) => age.or(rtx_time),
335            };
336
337            let reorder_delay = self.reorder_delay.max(
338                self.reordering
339                    .get(&ssrc)
340                    .map_or(Duration::ZERO, |reordering| reordering.allowance(now)),
341            );
342            let requests = self.requests.entry(ssrc).or_default();
343            // A packet that arrived, or that the log no longer covers, is forgotten.
344            requests.retain(|sequence_number, _| missing.contains(sequence_number));
345
346            let due: Vec<u16> = missing
347                .iter()
348                .copied()
349                .filter(|sequence_number| {
350                    let request = requests.entry(*sequence_number).or_insert(Request {
351                        missing_since: now,
352                        last_asked: None,
353                        asked: 0,
354                    });
355                    // Give up: asked often enough, or too old to be of use.
356                    if self.max_nacks_per_packet > 0 && request.asked >= self.max_nacks_per_packet {
357                        return false;
358                    }
359                    let missing_for = now.saturating_duration_since(request.missing_since);
360                    if max_packet_age.is_some_and(|max| missing_for > max) {
361                        return false;
362                    }
363                    let due = match request.last_asked {
364                        // The first request waits out the reordering allowance.
365                        None => missing_for >= reorder_delay,
366                        // The next waits for the retransmission to have had a round trip.
367                        Some(last_asked) => self
368                            .round_trip_time
369                            .is_none_or(|rtt| now.saturating_duration_since(last_asked) >= rtt),
370                    };
371                    if due {
372                        request.last_asked = Some(now);
373                        request.asked = request.asked.saturating_add(1);
374                    }
375                    due
376                })
377                .collect();
378
379            if due.is_empty() {
380                continue;
381            }
382
383            // Create NACK packet
384            let nack = rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack {
385                sender_ssrc: self.sender_ssrc,
386                media_ssrc: ssrc,
387                nacks: rtcp::transport_feedbacks::transport_layer_nack::nack_pairs_from_sequence_numbers(
388                    &due,
389                ),
390            };
391
392            self.write_queue.push_back(TaggedPacket {
393                now,
394                transport: TransportContext::default(),
395                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(nack)])),
396            });
397        }
398    }
399}
400
401/// A missing packet and what has been done about it.
402struct Request {
403    /// When the generator first found it missing.
404    missing_since: Instant,
405    /// When it was last asked for.
406    last_asked: Option<Instant>,
407    /// How often it has been asked for.
408    asked: u16,
409}
410
411impl Protocol<TaggedPacket, TaggedPacket, ()> for NackGeneratorInterceptor {
412    type Rout = TaggedPacket;
413    type Wout = TaggedPacket;
414    type Eout = ();
415    type Error = Error;
416    type Time = Instant;
417
418    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
419        // RFC 4588 5.3: "a receiver MUST stop requesting retransmissions for an SSRC on
420        // receiving its BYE" (RFC 3550 6.6: the source has left). Its receive log goes, and
421        // with it every gap still open; packets arriving later under that SSRC are not tracked.
422        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
423            for rtcp_packet in rtcp_packets {
424                if let Some(goodbye) = rtcp_packet
425                    .as_any()
426                    .downcast_ref::<rtcp::goodbye::Goodbye>()
427                {
428                    for source in &goodbye.sources {
429                        self.receive_logs.remove(source);
430                        self.horizons.remove(source);
431                        self.requests.remove(source);
432                        self.reordering.remove(source);
433                    }
434                }
435            }
436        }
437
438        // The round-trip time the RTCP session measured, for the pace of repeated requests.
439        if let Some(crate::RtcpSessionEvent::RoundTripTime { rtt, .. }) =
440            msg.message.custom::<crate::RtcpSessionEvent>()
441        {
442            self.round_trip_time = Some(*rtt);
443        }
444
445        // Track incoming RTP packets
446        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
447            && let Some(receive_log) = self.receive_logs.get_mut(&rtp_packet.header.ssrc)
448        {
449            receive_log.add(rtp_packet.header.sequence_number);
450            let ssrc = rtp_packet.header.ssrc;
451            let seq = rtp_packet.header.sequence_number;
452            let asked_for = self
453                .requests
454                .get(&ssrc)
455                .and_then(|requests| requests.get(&seq))
456                .is_some_and(|request| request.last_asked.is_some());
457            self.reordering
458                .entry(ssrc)
459                .or_default()
460                .on_packet(msg.now, seq, asked_for);
461
462            // Arm the NACK timer from the first tracked packet's instant. `None` means nothing is
463            // scheduled, so the interceptor asks for no wake-up until a stream is actually flowing.
464            if self.next_timeout.is_none() {
465                self.next_timeout = Some(msg.now + self.interval);
466            }
467        }
468
469        self.read_queue.push_back(msg);
470
471        Ok(())
472    }
473
474    fn poll_read(&mut self) -> Option<Self::Rout> {
475        self.read_queue.pop_front()
476    }
477
478    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
479        if let Some(super::NackControl::RemoteRtxTime {
480            payload_type_rtx,
481            rtx_time,
482        }) = msg.message.custom::<super::NackControl>()
483        {
484            match rtx_time {
485                Some(rtx_time) => self.remote_rtx_times.insert(*payload_type_rtx, *rtx_time),
486                None => self.remote_rtx_times.remove(payload_type_rtx),
487            };
488        }
489        if let Some(super::NackControl::Horizon {
490            media_ssrc,
491            oldest_useful,
492        }) = msg.message.custom::<super::NackControl>()
493        {
494            match oldest_useful {
495                Some(oldest_useful) => self.horizons.insert(*media_ssrc, *oldest_useful),
496                None => self.horizons.remove(media_ssrc),
497            };
498        }
499        self.write_queue.push_back(msg);
500        Ok(())
501    }
502
503    fn poll_write(&mut self) -> Option<TaggedPacket> {
504        // First drain generated NACK packets
505        if let Some(pkt) = self.write_queue.pop_front() {
506            return Some(pkt);
507        }
508        None
509    }
510
511    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
512        if let Some(next_timeout) = self.next_timeout
513            && now >= next_timeout
514        {
515            self.next_timeout = Some(now + self.interval);
516            self.generate_nacks(now);
517        }
518        Ok(())
519    }
520
521    fn poll_timeout(&mut self) -> Option<Instant> {
522        self.next_timeout
523    }
524}
525
526impl Interceptor for NackGeneratorInterceptor {
527    fn bind_remote_stream(&mut self, info: &StreamInfo) {
528        if stream_supports_nack(info)
529            && let Some(receive_log) = ReceiveLog::new(self.size)
530        {
531            self.receive_logs.insert(info.ssrc, receive_log);
532            match info.payload_type_rtx {
533                Some(payload_type_rtx) => {
534                    self.rtx_payload_types.insert(info.ssrc, payload_type_rtx)
535                }
536                None => self.rtx_payload_types.remove(&info.ssrc),
537            };
538        }
539    }
540
541    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
542        self.receive_logs.remove(&info.ssrc);
543        self.requests.remove(&info.ssrc);
544        self.reordering.remove(&info.ssrc);
545        self.rtx_payload_types.remove(&info.ssrc);
546        self.horizons.remove(&info.ssrc);
547    }
548
549    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
550
551    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
552}