Skip to main content

rtci_interceptor/nack/
responder.rs

1//! NACK Responder Interceptor - Responds to NACK requests by retransmitting packets.
2
3use super::send_buffer::SendBuffer;
4use super::stream_supports_nack;
5use crate::Interceptor;
6use crate::cc::probe::{ProbePacket, ProbeRequest};
7use crate::stream_info::StreamInfo;
8use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
9use sansio::Protocol;
10use shared::TransportContext;
11use shared::error::Error;
12use shared::marshal::MarshalSize;
13use std::collections::{HashMap, VecDeque};
14use std::time::{Duration, Instant};
15
16/// Builder for the NackResponderInterceptor.
17///
18/// # Example
19///
20/// ```
21/// use rtci_interceptor::{Slot, Registry, NackResponderBuilder};
22///
23/// let chain = Registry::new()
24///     .with(Slot::NackResponder, NackResponderBuilder::new()
25///         .with_size(1024)
26///         .build())
27///     .build();
28/// ```
29pub struct NackResponderBuilder {
30    /// Size of the send buffer (must be power of 2: 1, 2, 4, ..., 32768).
31    size: u16,
32    /// How long a sent packet stays available for retransmission.
33    max_packet_age: Option<Duration>,
34    /// How retransmissions are held to the congestion controller's target.
35    rate_limit: RetransmissionRateLimit,
36    /// The most of the target the retransmission reserve takes.
37    max_reserve_fraction: f64,
38    /// A packet written longer ago is not repaired.
39    max_repair_age: Option<Duration>,
40    /// Repairs waiting that would take this long or more at the target, after it halved, are
41    /// given up.
42    repair_backlog_bound: Option<Duration>,
43}
44
45impl Default for NackResponderBuilder {
46    fn default() -> Self {
47        Self {
48            size: 1024,
49            max_packet_age: None,
50            rate_limit: RetransmissionRateLimit::default(),
51            max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
52            max_repair_age: Some(MAX_REPAIR_AGE),
53            repair_backlog_bound: Some(REPAIR_BACKLOG_BOUND),
54        }
55    }
56}
57
58/// How the NACK responder holds its retransmissions to the congestion controller's target
59/// (RFC 4588 section 7), read from [`Attribute::TargetBitrateChanged`] as it passes on the read
60/// leg. Until a target has passed, and in a chain without a congestion controller, nothing is
61/// held back.
62///
63/// The rate is counted over the last [`RETRANSMISSION_RATE_WINDOW`]. A NACKed packet that
64/// does not fit now waits, oldest request first, and leaves when the window has room for it
65/// ([`poll_timeout`](sansio::Protocol::poll_timeout) is that instant), for as long as the
66/// receiver keeps asking for it ([`PENDING_REQUEST_LIFETIME`]). Section 7 lets the sender
67/// "selectively retransmit only the packets that it deems important and ignore NACK messages
68/// for other packets in order to limit the bitrate": a packet still asked for is the one
69/// deemed important, one the receiver stopped asking for is dropped.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71#[non_exhaustive]
72pub enum RetransmissionRateLimit {
73    /// RFC 4588 section 7, both halves: "the acceptable packet rate and bitrate include both
74    /// the original and retransmitted data", and "the sender SHOULD NOT send retransmission
75    /// packets without reducing the packet rate and bitrate of the original stream (for
76    /// example, by encoding the data at a lower rate)".
77    ///
78    /// Retransmissions take what the original packets of every local stream leave of the
79    /// target. While retransmissions wait or were sent within the window, the target reported
80    /// for the original media is the congestion controller's less a **retransmission
81    /// reserve**: on the read leg [`Attribute::TargetBitrateChanged`] is lowered by it on its
82    /// way to the application, and [`RetransmissionReserve`] rides down the write leg to the
83    /// congestion controller, whose handle (`GccHandle::target_bitrate_bps`,
84    /// `CongestionControlHandle::target_bitrate`) reports the lowered target and keeps the
85    /// estimate itself readable (`estimate_bps`, `estimate_bitrate`). An encoder that follows
86    /// the target leaves the reserve free, so the repairs have room.
87    ///
88    /// The reserve is what the waiting requests need to leave within about one round trip
89    /// (their octets over the round-trip time the RTCP session measured, at most
90    /// [`RETRANSMISSION_RATE_WINDOW`]), or the retransmission rate of the window when that is
91    /// more, and never more than [`MAX_RETRANSMISSION_RESERVE`] of the target
92    /// ([`NackResponderBuilder::with_max_reserve_fraction`]). It is released as the requests
93    /// are served and the retransmissions leave the window: with nothing waiting and nothing
94    /// retransmitted within the last window it is zero.
95    ///
96    /// **At the congestion controller's floor.** The controller's minimum bit rate is this
97    /// engine's setting, not the RFC's, and the controller announces it with its target
98    /// ([`MinimumTarget`]). The original media is never told less than that minimum (the least
99    /// the application set its media to need). When lowering the original media by the reserve
100    /// would take it under that floor (target − reserve < minimum), it cannot make the room:
101    /// an encoder at its own minimum already fills the floor (in the capacity-cap test, 30
102    /// kbit/s of video and 80 kbit/s of audio against a 100 kbit/s target), and the rule above
103    /// would leave the repairs nothing for as long as the estimate stays near the floor. There
104    /// the retransmissions of packets still asked for take the window's room first: they may
105    /// send up to the target within the window, whatever the original packets took, and the
106    /// original media is told the target less the reserve. Section 7 lets the sender
107    /// "selectively retransmit only the packets that it deems important"; a packet still asked
108    /// for is the one deemed important. An application at its minimum adds its own excess
109    /// over the floor; the retransmissions never go over the target.
110    ///
111    /// What holds the sum on the wire when the application ignores the lowered target: with
112    /// a pacer in the chain (the default interceptor set) the pacer sends at the controller's
113    /// target, retransmissions and media alike; without one (a chain of NACK, TWCC and GCC
114    /// alone) it is this rule: above the floor the retransmissions take only what the
115    /// original packets leave, so the engine never adds to an application's excess; near the
116    /// floor (target under the minimum plus the reserve, at most twice the minimum with the
117    /// default reserve) they take at most the target.
118    #[default]
119    WithinTarget,
120    /// A rate limiter on the retransmissions alone, its maximum the target (the form of
121    /// libwebrtc's `RtpSender` when it is given a `retransmission_rate_limiter`,
122    /// `modules/rtp_rtcp/source/rtp_sender.cc`): the retransmissions stay under the target
123    /// whatever the original packets take, and the target reported for the original media is
124    /// not lowered, so the sum may reach twice the target. A setting in no behaviour profile:
125    /// libwebrtc gives its video senders no such limiter (`call/rtp_video_sender.cc:292-354`
126    /// at a222406d; `rtp_rtcp_interface.h:92` defaults it to null) and lowers the encoder
127    /// target by the protection share instead. Measured in
128    /// `tests/capacity_cap_video_rtc2rtc.rs` against the default: longest freeze 0.84 to
129    /// 1.29 s against 0.83 to 1.24 s, 17 to 27 retransmissions dropped at the capped link
130    /// against 14 to 17.
131    UpToTarget,
132    /// No limit beyond the per-stream budget (one retransmission per original packet sent): the
133    /// fork's behaviour before. Retransmissions are then not congestion controlled.
134    Unlimited,
135}
136
137/// The window [`RetransmissionRateLimit`] measures the rates over (libwebrtc's
138/// `kRetransmitWindowSizeMs`).
139pub const RETRANSMISSION_RATE_WINDOW: Duration = Duration::from_secs(1);
140
141/// The most of the congestion controller's target the retransmission reserve of
142/// [`RetransmissionRateLimit::WithinTarget`] takes, by default: half.
143pub const MAX_RETRANSMISSION_RESERVE: f64 = 0.5;
144
145/// A request that waits for room is dropped when the receiver has not asked for the packet
146/// again within this long, or within two round trips when that is longer: a receiver asks
147/// again every round trip while the packet is missing, so one that stopped asking has the
148/// packet or no longer wants it.
149pub const PENDING_REQUEST_LIFETIME: Duration = Duration::from_secs(1);
150
151/// The shortest round trip the reserve spreads the waiting requests over.
152const MIN_RESERVE_HORIZON: Duration = Duration::from_millis(10);
153
154/// The retransmission reserve of [`RetransmissionRateLimit::WithinTarget`], in bits per
155/// second: the part of the congestion controller's target kept for retransmissions, which the
156/// target reported for the original media leaves out.
157///
158/// The NACK responder sends it down the write leg (on a packet of its own, an empty RTCP
159/// carrier, when it changes), so a congestion controller wire-ward of it reports the lowered
160/// target through its handle. Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
161#[derive(Debug, Clone, Copy, PartialEq)]
162pub struct RetransmissionReserve {
163    /// The reserve, bits per second.
164    pub bits_per_second: f64,
165}
166
167/// Rides with [`Attribute::TargetBitrateChanged`]: the congestion controller's minimum bit
168/// rate, the floor its target never goes under. Where lowering the original media by the
169/// retransmission reserve would take it under this floor the NACK responder lets the
170/// retransmissions take the window's room first ([`RetransmissionRateLimit::WithinTarget`]).
171/// Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct MinimumTarget {
174    /// The minimum, bits per second.
175    pub bits_per_second: f64,
176}
177
178/// The target for the original media: the controller's `target` less the `reserve`, never
179/// under the controller's `minimum` (the least the application set its media to need; near it
180/// the retransmissions take the room first instead, see [`RetransmissionRateLimit::WithinTarget`]).
181fn media_target(target: f64, reserve: f64, minimum: f64) -> f64 {
182    (target - reserve).max(minimum.min(target)).max(0.0)
183}
184
185/// How much the reported reserve may move before a new one is announced: 5 % of the target,
186/// at least 5 kbit/s, and any change to or from zero.
187fn reserve_moved(announced: f64, reserve: f64, target_bps: f64) -> bool {
188    (announced == 0.0) != (reserve == 0.0)
189        || (reserve - announced).abs() >= (0.05 * target_bps).max(5_000.0)
190}
191
192/// Octets sent within the last [`RETRANSMISSION_RATE_WINDOW`].
193#[derive(Default)]
194struct RateWindow {
195    sent: VecDeque<(Instant, usize)>,
196    octets: usize,
197}
198
199/// The instant at which the entries of `windows` leaving [`RETRANSMISSION_RATE_WINDOW`] have
200/// freed `deficit` octets, oldest first; `None` if all of them together free less.
201fn freed_at(windows: &[&RateWindow], deficit: usize) -> Option<Instant> {
202    let mut cursors = vec![0usize; windows.len()];
203    let mut freed = 0usize;
204    loop {
205        let (index, &(at, octets)) = windows
206            .iter()
207            .zip(&cursors)
208            .enumerate()
209            .filter_map(|(index, (window, &cursor))| window.sent.get(cursor).map(|e| (index, e)))
210            .min_by_key(|(_, (at, _))| *at)?;
211        cursors[index] += 1;
212        freed += octets;
213        if freed >= deficit {
214            return Some(at + RETRANSMISSION_RATE_WINDOW);
215        }
216    }
217}
218
219/// A NACKed packet waiting for room in the rate limit.
220struct PendingRetransmission {
221    ssrc: u32,
222    sequence_number: u16,
223    /// The packet asked for: its serial in the stream. The request is for that packet, not
224    /// for whichever has the sequence number when there is room.
225    packet: u64,
226    /// The size its retransmission has on the wire.
227    octets: usize,
228}
229
230impl RateWindow {
231    fn expire(&mut self, now: Instant) {
232        while let Some(&(at, octets)) = self.sent.front() {
233            if now.saturating_duration_since(at) < RETRANSMISSION_RATE_WINDOW {
234                break;
235            }
236            self.sent.pop_front();
237            self.octets -= octets;
238        }
239    }
240
241    fn add(&mut self, now: Instant, octets: usize) {
242        self.sent.push_back((now, octets));
243        self.octets += octets;
244    }
245
246    /// Takes back `octets` added at `at`, if the entry is still in the window.
247    fn forget(&mut self, at: Instant, octets: usize) {
248        if let Some(entry) = self
249            .sent
250            .iter_mut()
251            .rev()
252            .find(|(sent, size)| *sent == at && *size == octets)
253        {
254            entry.1 = 0;
255            self.octets -= octets;
256        }
257    }
258}
259
260impl NackResponderBuilder {
261    /// Create a new builder with default settings.
262    pub fn new() -> Self {
263        Self::default()
264    }
265
266    /// Set the size of the send buffer.
267    ///
268    /// Size must be a power of 2 between 1 and 32768 (inclusive).
269    /// Larger buffers can retransmit older packets but use more memory.
270    pub fn with_size(mut self, size: u16) -> Self {
271        self.size = size;
272        self
273    }
274
275    /// Set how long a sent packet is kept for retransmission: the `rtx-time` of RFC 4588
276    /// 8.1, when one is signalled. A NACK for a packet sent longer ago is not answered.
277    ///
278    /// Default: `None`, a packet is available for as long as the buffer holds it.
279    pub fn with_max_packet_age(mut self, max_packet_age: Option<Duration>) -> Self {
280        self.max_packet_age = max_packet_age;
281        self
282    }
283
284    /// Set how retransmissions are held to the congestion controller's target (RFC 4588
285    /// section 7). Default: [`RetransmissionRateLimit::WithinTarget`], the RFC's form;
286    /// [`RetransmissionRateLimit::UpToTarget`] is the limiter libwebrtc's `RtpSender` has
287    /// when it is given one.
288    pub fn with_rate_limit(mut self, rate_limit: RetransmissionRateLimit) -> Self {
289        self.rate_limit = rate_limit;
290        self
291    }
292
293    /// Set the most of the congestion controller's target the retransmission reserve of
294    /// [`RetransmissionRateLimit::WithinTarget`] takes, from 0 (no reserve: the target is
295    /// never lowered) to 1. Default: [`MAX_RETRANSMISSION_RESERVE`].
296    pub fn with_max_reserve_fraction(mut self, fraction: f64) -> Self {
297        self.max_reserve_fraction = if fraction.is_finite() {
298            fraction.clamp(0.0, 1.0)
299        } else {
300            MAX_RETRANSMISSION_RESERVE
301        };
302        self
303    }
304
305    /// Set how old a packet may be and still be repaired: a NACK for a packet written to the
306    /// responder longer ago is declined (RFC 8834 section 6.1: "the likelihood of them
307    /// arriving in time to be useful need[s] to be considered before RTP retransmission is
308    /// used"; RFC 4588 section 7: the sender "MAY selectively retransmit only the packets that
309    /// it deems important and ignore NACK messages for other packets").
310    ///
311    /// A receiver that still asks for a video packet that old is waiting for a picture
312    /// nobody can use, so the first such request **gives the stream up**: everything sent on
313    /// it so far is forgotten (its buffer, the requests waiting), the retransmission reserve
314    /// they held is released at once, and the application is asked for a key frame (a Picture
315    /// Loss Indication with sender SSRC 0, `RTCPeerConnectionEvent::OnKeyFrameRequest`, as at
316    /// the pacer's flush). What is written afterwards is buffered and repaired as ever. An
317    /// audio packet that old is not retransmitted and nothing else happens.
318    ///
319    /// Default: [`MAX_REPAIR_AGE`]. `None`: a packet is repaired for as long as the buffer
320    /// holds it. This is the sender's own judgement and is not announced.
321    ///
322    /// **An `rtx-time` takes its place.** RFC 4588 section 8.1: `rtx-time` is "the maximum
323    /// time a sender will keep an original RTP packet in its buffers available for
324    /// retransmission". Where one is in force for a stream (announced in the session
325    /// description or set by the application for its retransmission format,
326    /// [`NackControl::LocalRtxTime`](super::NackControl::LocalRtxTime), or configured with
327    /// [`with_max_packet_age`](Self::with_max_packet_age)), that is how old a packet of the
328    /// stream may be and still be repaired, whether shorter or longer than this setting, and
329    /// this setting does nothing for the stream: a packet older than the `rtx-time` is not
330    /// retransmitted and nothing else happens (the stream is not given up, no key frame is
331    /// asked for: the receiver was told the time and "should take into account the signalled
332    /// sender retransmission buffer length", section 8.8).
333    ///
334    /// The `rtx-time` is that of the packet's own retransmission format (RFC 4588 section 8.6:
335    /// a parameter of each RTX payload type, which `apt` ties to one original payload type):
336    /// a RED packet's is the one announced for the RTX of `red`, a plain packet's the one of
337    /// its codec's RTX. That one value decides all three for the packet: the cut at the time,
338    /// this setting where there is no time, and whether the packet's age gives the stream up.
339    /// A packet that is never sent again (a FEC packet in RED on a stream without RTX, a
340    /// payload type without an RTX format on a stream that has RTX) gives nothing up by its
341    /// age: the receiver is not waiting for a picture because of it.
342    pub fn with_max_repair_age(mut self, max_repair_age: Option<Duration>) -> Self {
343        self.max_repair_age = max_repair_age;
344        self
345    }
346
347    /// Set the backlog of repairs past which they are given up when the path's capacity has
348    /// collapsed: the requests waiting would take this long or more to leave at the congestion
349    /// controller's whole target, and the target is at most half of the highest in force
350    /// within the last two seconds. Every video stream with a request waiting is then given
351    /// up as [`with_max_repair_age`](Self::with_max_repair_age) describes (forgotten, the
352    /// reserve released, a key frame asked for). The targets from before a give-up no longer
353    /// count: the next one needs the target to halve again. RFC 4588 section 7: "If
354    /// congestion is not kept under control, then retransmission SHOULD NOT be used": such a
355    /// backlog is repaired at a rate the path drops again, for seconds, while the original
356    /// media is held at the reserve's floor.
357    ///
358    /// A backlog at a steady target (ordinary loss, however heavy) is never given up: it
359    /// is repaired within the target. Audio requests count toward the backlog and are never
360    /// given up. Without a congestion controller's target there is no such rule. An
361    /// `rtx-time` does not change it: the time is the most a packet is kept, and a collapse
362    /// ends the repairs of what was sent before it as the pacer's flush does.
363    ///
364    /// Default: [`REPAIR_BACKLOG_BOUND`]. `None`: every request is served in order.
365    pub fn with_repair_backlog_bound(mut self, bound: Option<Duration>) -> Self {
366        self.repair_backlog_bound = bound;
367        self
368    }
369
370    /// Build the interceptor.
371    pub fn build(self) -> NackResponderInterceptor {
372        let mut interceptor = NackResponderInterceptor::new(self.size);
373        interceptor.max_packet_age = self.max_packet_age;
374        interceptor.rate_limit = self.rate_limit;
375        interceptor.max_reserve_fraction = self.max_reserve_fraction;
376        interceptor.max_repair_age = self.max_repair_age;
377        interceptor.repair_backlog_bound = self.repair_backlog_bound;
378        interceptor
379    }
380}
381
382/// The RID header extension (RFC 8852 3.1).
383const RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id";
384/// The repaired-RID header extension (RFC 8852 3.2), which an RTX packet carries instead.
385const REPAIRED_RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
386
387/// The one-byte or two-byte id `info` negotiated for `uri`.
388fn extension_id(info: &StreamInfo, uri: &str) -> Option<u8> {
389    info.rtp_header_extensions
390        .iter()
391        .find(|extension| extension.uri == uri)
392        .and_then(|extension| u8::try_from(extension.id).ok())
393}
394
395/// The subtype of a MIME type (`video/rtx` -> `rtx`).
396fn subtype(mime_type: &str) -> &str {
397    mime_type
398        .rsplit_once('/')
399        .map_or(mime_type, |(_, subtype)| subtype)
400}
401
402/// The `(apt, rtx)` pairs of the retransmission formats of `info`'s m= section: every format
403/// whose MIME subtype is `rtx` and whose fmtp names an associated payload type (RFC 4588
404/// section 8.1: "apt (associated payload type) ... the value of this parameter is the
405/// payload type of the associated original stream").
406fn section_rtx_payload_types(info: &StreamInfo) -> Vec<(u8, u8)> {
407    info.section_mime_types
408        .iter()
409        .filter(|(_, mime_type)| subtype(mime_type).eq_ignore_ascii_case("rtx"))
410        .filter_map(|(rtx, _)| {
411            let (_, fmtp) = info.section_fmtp_lines.iter().find(|(pt, _)| pt == rtx)?;
412            let apt = fmtp
413                .split(';')
414                .filter_map(|parameter| parameter.trim().strip_prefix("apt="))
415                .find_map(|value| value.trim().parse::<u8>().ok())?;
416            Some((apt, *rtx))
417        })
418        .collect()
419}
420
421/// The `red` and `ulpfec` payload types of `info`'s m= section, when it has both: FEC is
422/// then sent as RED packets of the media stream (RFC 5109 section 14.2).
423fn section_fec_in_red(info: &StreamInfo) -> Option<(u8, u8)> {
424    let payload_type = |name: &str| {
425        info.section_mime_types
426            .iter()
427            .find(|(_, mime_type)| subtype(mime_type).eq_ignore_ascii_case(name))
428            .map(|(payload_type, _)| *payload_type)
429    };
430    Some((payload_type("red")?, payload_type("ulpfec")?))
431}
432
433/// How a packet asked for again is sent.
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435enum RepairForm {
436    /// As a retransmission packet (RFC 4588 section 4) of this payload type on the stream's
437    /// RTX SSRC.
438    Rtx(u8),
439    /// A FEC packet ([`LocalStream::is_fec`]): a retransmission packet of this payload type
440    /// on the stream's RTX SSRC that carries the packet's sequence number and its RED block
441    /// header and none of its FEC data. See [`LocalStream::repair_form`].
442    RtxWithoutFec(u8),
443    /// The stream negotiated no retransmission format: the packet again as it was sent, on
444    /// the media SSRC under its sequence number (RFC 4585 section 6.2.1 leaves the form of a
445    /// retransmission to the sender).
446    Original,
447}
448
449/// Per-stream state for the responder.
450struct LocalStream {
451    /// Buffer of sent packets for retransmission.
452    send_buffer: SendBuffer,
453    /// RTX SSRC for RFC4588 retransmission (if configured).
454    ssrc_rtx: Option<u32>,
455    /// RTX payload type for RFC4588 retransmission (if configured).
456    payload_type_rtx: Option<u8>,
457    /// The payload type the stream was bound with: the one `payload_type_rtx` repairs.
458    payload_type: u8,
459    /// The retransmission payload type of each payload type of the stream's m= section that
460    /// has one: `(apt, rtx)` for every `rtx` format the binder listed
461    /// ([`StreamInfo::section_mime_types`], [`StreamInfo::section_fmtp_lines`]). Empty when
462    /// the binder did not list the section's formats: `payload_type_rtx` then stands for
463    /// every packet. See [`LocalStream::repair_form`].
464    rtx_payload_types: Vec<(u8, u8)>,
465    /// The section's `red` and `ulpfec` payload types, when FEC is sent in RED packets of
466    /// this stream. See [`LocalStream::is_fec`].
467    fec_in_red: Option<(u8, u8)>,
468    /// Sequence number counter for RTX packets.
469    rtx_sequence_number: u16,
470    /// The sequence number of the packet sent last, and when.
471    last_sent: Option<(u16, Instant)>,
472    /// When each sequence number was last retransmitted, so a repeated NACK within
473    /// [`MIN_RETRANSMIT_INTERVAL`] does not resend it again.
474    last_retransmit: HashMap<u16, Instant>,
475    /// The RID extension id, if negotiated.
476    rid_extension_id: Option<u8>,
477    /// The repaired-RID extension id, if negotiated.
478    repaired_rid_extension_id: Option<u8>,
479    /// Retransmissions this stream may still send: one more for each original packet sent, up
480    /// to the send buffer's size, and one less per retransmission. A NACK naming the whole buffer
481    /// may be answered once in full, but repeated NACKs cannot make the stream retransmit faster
482    /// than it sends, so the peer cannot turn its NACKs into a multiple of our send rate.
483    retransmit_budget: usize,
484    /// The budget's ceiling: the send buffer's size.
485    retransmit_budget_max: usize,
486    /// When each buffered packet was sent, by its place in the send buffer (the sequence
487    /// number modulo the buffer size), with the sequence number the entry is for and the
488    /// packet's serial (see `written`).
489    sent_at: Vec<Option<(u16, Instant, u64)>>,
490    /// How many packets of the stream were written: each packet's serial, its place in the
491    /// order written, which no later packet of the stream has again whatever its 16-bit
492    /// sequence number (the extended sequence number, without trusting the application's
493    /// numbering to be continuous).
494    written: u64,
495    /// What is remembered of the latest retransmission of a packet, by its sequence number.
496    /// Each entry names its packet by the serial, so the packet that has the 16-bit number a
497    /// cycle later does not inherit it, and each ends by the clock (see [`RepairState`]).
498    /// Never more entries than the send buffer has places.
499    repairs: HashMap<u16, Repair>,
500    /// The sequence number each recent RTX packet of this stream was given → the packet it
501    /// repairs and when the retransmission was made, oldest first in `repairs_order`: how
502    /// RFC 8888 feedback, which reports the RTX stream under its own sequence numbers, names
503    /// a retransmission.
504    repairs_by_rtx: HashMap<u16, (u16, Instant)>,
505    repairs_order: VecDeque<(u16, Instant)>,
506    /// Whether the stream is video (not audio): a key frame can be asked for it.
507    video: bool,
508    /// The newest packet the buffer held when it was last emptied (a give-up, the pacer's
509    /// flush): the header of a probe's padding until the next packet is written.
510    probe_template: Option<rtp::Packet>,
511}
512
513/// What is remembered of the retransmissions of one packet.
514#[derive(Debug, Clone, Copy)]
515struct Repair {
516    /// The packet: its serial in the stream.
517    packet: u64,
518    /// When the first retransmission of the packet that is still remembered was made: a
519    /// report on a retransmission made before it is about an earlier packet of the same
520    /// 16-bit number.
521    first_made: Instant,
522    /// When the latest retransmission was made.
523    made: Instant,
524    state: RepairState,
525}
526
527/// Where the latest retransmission of a packet is, as far as the sender knows. Every state
528/// ends by the engine's clock (the instant of the request, write, notice or timeout at hand),
529/// whether or not another report ever comes.
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531enum RepairState {
532    /// Waiting in the pacer since it was made, for [`IN_PACER_LIFETIME`] at most. The pacer
533    /// holds one retransmission per (SSRC, 16-bit sequence number), so this one state holds
534    /// for whatever packet has the number: nothing is made for it meanwhile.
535    InPacer,
536    /// Left toward the wire at `left`, no report yet: a request is held until two round trips
537    /// and [`REPAIR_REPORT_MARGIN`] after.
538    Unreported { left: Instant },
539    /// Left at `left`, and the wait for its report ran out: requests are answered. A report
540    /// still counts until [`RETRANSMISSION_REPORT_HORIZON`](crate::RETRANSMISSION_REPORT_HORIZON)
541    /// after it left.
542    Overdue { left: Instant },
543    /// Reported received at `reported`: requests are declined for [`DELIVERED_MEMORY`].
544    Delivered { reported: Instant },
545}
546
547impl LocalStream {
548    /// Whether `packet` is a FEC packet: a RED packet of the stream whose one block is the
549    /// section's `ulpfec` format (RFC 2198 section 3: the last block header is one octet,
550    /// F = 0 and the block's payload type; RFC 5109 section 14.2).
551    ///
552    /// FEC data is not retransmitted: it repairs media that the receiver also asks for by
553    /// NACK, and the media's own retransmission is what answers the NACK. libwebrtc does not
554    /// keep FEC packets for retransmission at all (modules/rtp_rtcp/source/ulpfec_generator.cc:233
555    /// at a222406d, `red_packet->set_allow_retransmission(false)`; rtp_sender_egress.cc:316
556    /// puts a packet in the history only `if (options.is_media &&
557    /// packet->allow_retransmission())`), so a NACK that names one finds nothing
558    /// (rtp_sender.cc:348-351, `ReSendPacket`: "Packet not found or already queued for
559    /// retransmission, ignore.") and its receiver asks until the request ages out
560    /// (modules/video_coding/nack_requester.cc:34-39: 10 000 sequence numbers, 100 requests).
561    /// The sequence number is answered here all the same: see [`Self::repair_form`].
562    fn is_fec(&self, packet: &rtp::Packet) -> bool {
563        self.fec_in_red.is_some_and(|(red, ulpfec)| {
564            packet.header.payload_type == red && packet.payload.first() == Some(&ulpfec)
565        })
566    }
567
568    /// How `packet`, sent on this stream, is sent again; `None` when it is not.
569    ///
570    /// RFC 4588 section 8.1 ties a retransmission format to ONE original payload type: "apt
571    /// (associated payload type) ... the value of this parameter is the payload type of the
572    /// associated original stream", and section 8.6: "the retransmission payload type is
573    /// mapped to the payload type of the original stream with the apt parameter". A stream
574    /// does not always leave under the payload type it was bound with: a FEC encoder
575    /// application-ward of this interceptor rewrites video into RED packets (RFC 2198), whose
576    /// retransmission format is the one whose `apt` names the `red` payload type
577    /// (`a=fmtp:117 apt=116`), not the media format's; a source may switch between the
578    /// formats of its section (RFC 7160). A receiver restores the payload type from the
579    /// `apt` of the payload type the retransmission arrives under, so a RED packet
580    /// retransmitted under the media format's RTX is restored as media with a RED header in
581    /// front of it. libwebrtc looks the RTX payload type up by the payload type of the packet
582    /// it retransmits and sends nothing when there is none
583    /// (modules/rtp_rtcp/source/rtp_sender.cc, `BuildRtxPacket`:
584    /// `rtx_payload_type_map_.find(packet.PayloadType())`).
585    ///
586    /// - A FEC packet ([`Self::is_fec`]) is answered with its sequence number alone
587    ///   ([`RepairForm::RtxWithoutFec`]): the retransmission packet of the RED packet cut
588    ///   down to its one-octet block header, three octets of payload with the original
589    ///   sequence number. A FEC packet in RED has a sequence number of the media stream, and a
590    ///   receiver that puts frames together in sequence-number order cannot tell a lost one
591    ///   from a lost one-packet frame: it waits for it and then asks for a key frame.
592    ///   Restored, the answer is a RED packet whose FEC block is empty, which a receiver
593    ///   takes as it takes any FEC packet (present, no media; libwebrtc:
594    ///   video/rtp_video_stream_receiver2.cc:1603-1612, a RED packet whose first octet is the
595    ///   `ulpfec` payload type is an empty packet to its packet buffer and NACK module). On a
596    ///   stream without retransmission a FEC packet is not sent again: the packet as it was
597    ///   is all that can leave under its sequence number.
598    /// - A stream without retransmission (no RTX SSRC or no RTX payload type): the packet as
599    ///   it was.
600    /// - Otherwise the RTX format whose `apt` is the packet's payload type, among the
601    ///   section's formats and the stream's own pair. A payload type without one is not sent
602    ///   again: never as a duplicate on the media SSRC of a stream that negotiated RTX (the
603    ///   receiver of such a stream expects its repairs on the RTX stream, and a duplicate is
604    ///   one more packet of the media stream's own sequence space on a path that just lost
605    ///   packets).
606    /// - When the binder listed no `rtx` format for the section, the stream's one RTX payload
607    ///   type stands for every packet.
608    fn repair_form(&self, packet: &rtp::Packet) -> Option<RepairForm> {
609        let fec = self.is_fec(packet);
610        let (Some(_), Some(stream_rtx)) = (self.ssrc_rtx, self.payload_type_rtx) else {
611            return (!fec).then_some(RepairForm::Original);
612        };
613        let payload_type = packet.header.payload_type;
614        let rtx = if self.rtx_payload_types.is_empty() {
615            Some(stream_rtx)
616        } else {
617            self.rtx_payload_types
618                .iter()
619                .find(|(apt, _)| *apt == payload_type)
620                .map(|(_, rtx)| *rtx)
621                .or_else(|| (payload_type == self.payload_type).then_some(stream_rtx))
622        };
623        rtx.map(|rtx| {
624            if fec {
625                RepairForm::RtxWithoutFec(rtx)
626            } else {
627                RepairForm::Rtx(rtx)
628            }
629        })
630    }
631
632    /// The serial of the packet now held under `sequence_number`.
633    fn packet(&self, sequence_number: u16) -> Option<u64> {
634        self.sent_at[usize::from(sequence_number) % self.sent_at.len()]
635            .filter(|(held, _, _)| *held == sequence_number)
636            .map(|(_, _, serial)| serial)
637    }
638
639    /// Remembers `repair` of the packet under `sequence_number`. The entries stay within the
640    /// send buffer's places: when they are all taken, those whose packet the buffer no longer
641    /// holds go (there is one, since a packet the buffer holds is being added).
642    fn remember_repair(&mut self, sequence_number: u16, repair: Repair) {
643        if self.repairs.len() >= self.sent_at.len() && !self.repairs.contains_key(&sequence_number)
644        {
645            let sent_at = &self.sent_at;
646            self.repairs.retain(|sequence_number, repair| {
647                sent_at[usize::from(*sequence_number) % sent_at.len()].is_some_and(
648                    |(held, _, serial)| held == *sequence_number && serial == repair.packet,
649                )
650            });
651        }
652        if self.repairs.len() < self.sent_at.len() || self.repairs.contains_key(&sequence_number) {
653            self.repairs.insert(sequence_number, repair);
654        }
655    }
656}
657
658/// The most octets one probe cluster is filled with.
659const MAX_PROBE_FILL_OCTETS: usize = crate::cc::probe::PROBE_MAX_OCTETS;
660
661/// The most packets one probe cluster is filled with.
662const MAX_PROBE_FILL_PACKETS: usize = 128;
663
664/// The padding octets of one probe packet: the most RFC 3550 section 5.1 padding holds (its
665/// count is one octet).
666pub const PROBE_PADDING_OCTETS: u8 = 255;
667
668/// A sequence number is retransmitted at most once per this interval, however often it is
669/// NACKed. Receivers repeat NACKs while the repair is in flight; without this a peer can make
670/// us resend the same packets as fast as it can send RTCP (an amplifier).
671pub const MIN_RETRANSMIT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(20);
672
673/// How long after its retransmission a packet is not retransmitted again however often it is
674/// asked for: [`MIN_RETRANSMIT_INTERVAL`]. libwebrtc waits a round trip
675/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`, `VerifyRtt`); measured here that loses
676/// repairs: when a retransmission is itself lost, the receiver's next request can fall inside
677/// that round trip and be ignored, and the one after waits for RFC 4585's early-feedback hold
678/// (`tests/vp8_nack_jitter_buffer_rtc2rtc.rs`, seed 4: packet 1272 retransmitted again 1.42 s
679/// after the lost copy, after the 2 s jitter buffer had played past it). A request that
680/// crossed a repair in flight costs one duplicate instead.
681fn resend_interval(round_trip_time: Option<Duration>) -> Duration {
682    let _ = round_trip_time;
683    MIN_RETRANSMIT_INTERVAL
684}
685
686/// How long after a retransmission left the transport-wide feedback on it is waited for, beyond
687/// two round trips, before a request for the same packet is answered without it: the receiver's
688/// feedback interval (100 ms by default, `TwccReceiverBuilder`).
689pub const REPAIR_REPORT_MARGIN: Duration = Duration::from_millis(100);
690
691/// How long a retransmission the feedback reported received is remembered: a request for its
692/// packet within this long of the report crossed it and is not answered. The time is the
693/// request's own (the engine's clock), so the memory ends whether or not another report
694/// comes: a request after it is answered, which is also what bounds a receiver whose feedback
695/// reports retransmissions it did not get. It is the memory of one packet (SSRC and extended
696/// sequence number): it ends with the packet's place in the send buffer, its `rtx-time` or
697/// its repair age, past which no request for it is answered anyway, and the packet that has
698/// the same 16-bit number a cycle later starts without it.
699///
700/// Longer than the default repair age ([`MAX_REPAIR_AGE`]), under which no request for the
701/// packet is answered once it is two seconds old whatever is remembered of it. The memory is
702/// the bound for the configurations where a packet is repaired longer: an `rtx-time` over two
703/// seconds, the repair age off (`PacerBacklog::Keep`, the `Chrome` profile). There a shorter
704/// memory would answer a request that crossed its repair behind a deep queue.
705pub const DELIVERED_MEMORY: Duration = Duration::from_secs(4);
706
707/// What a request for a packet that was retransmitted before gets
708/// ([`RetransmissionsReported`](crate::RetransmissionsReported)).
709#[derive(Debug, Clone, Copy, PartialEq, Eq)]
710enum Repeat {
711    /// Answered as any request.
712    Answer,
713    /// Kept waiting until the feedback on the earlier retransmission comes, at most until then.
714    Hold(Instant),
715    /// Not answered: the earlier retransmission arrived.
716    Decline,
717}
718
719/// How long a retransmission is taken to wait in the pacer at most: longer than the pacer's
720/// queue time bound (2 s by default), past which the pacer drops it and says so. Not tied to
721/// the repair age: it bounds a state (a pacer that never reports), and a retransmission made
722/// of a packet just under the repair age may wait the pacer's bound after that.
723const IN_PACER_LIFETIME: Duration = Duration::from_secs(4);
724
725/// How old a packet may be and still be repaired, by default
726/// ([`NackResponderBuilder::with_max_repair_age`]): two seconds, the pacer's queue time bound,
727/// past which the pacer itself drops what waits as stale. One second (libwebrtc's shortest
728/// packet history) was measured and is too short: behind a path queue of a second a NACK for a
729/// packet still wanted arrives later than that.
730pub const MAX_REPAIR_AGE: Duration = Duration::from_secs(2);
731
732/// The backlog of repairs given up after the target halved, by default
733/// ([`NackResponderBuilder::with_repair_backlog_bound`]): what would take two seconds or more
734/// to leave at the target. One second was measured and gives up too early: the key frame asked
735/// for goes into a path queue that is still full (200 calls per cell: 8 and 24 with no frame
736/// for over 2 s behind queues of 100 ms and 1 s, against none with two seconds).
737pub const REPAIR_BACKLOG_BOUND: Duration = Duration::from_secs(2);
738
739/// How far back the highest target counts when a backlog of repairs is judged a collapse
740/// (the pacer's queue time bound).
741const COLLAPSE_LOOK_BACK: Duration = Duration::from_secs(2);
742
743/// A backlog of repairs is a collapse when the target is at most this share of the highest
744/// in force within [`COLLAPSE_LOOK_BACK`] (the pacer's `COLLAPSE_AT`).
745const COLLAPSE_AT: f64 = 0.5;
746
747/// The most target changes remembered.
748const MAX_TARGETS_KEPT: usize = 256;
749
750/// Most retransmissions queued and not yet taken by `poll_write`. Past it further NACKed
751/// packets are not queued until the queue drains.
752pub const MAX_QUEUED_RETRANSMISSIONS: usize = 1024;
753
754/// The most retransmission SSRCs whose next sequence number is remembered after their stream
755/// was unbound.
756const MAX_REMEMBERED_RTX_SSRCS: usize = 1024;
757
758/// Interceptor that responds to NACK requests by retransmitting packets.
759///
760/// This interceptor buffers outgoing RTP packets on local streams and
761/// retransmits them when RTCP TransportLayerNack packets are received.
762pub struct NackResponderInterceptor {
763    /// Configuration
764    size: u16,
765
766    /// How long a sent packet stays available for retransmission (`rtx-time`).
767    max_packet_age: Option<Duration>,
768    /// The `rtx-time` this endpoint announced, by retransmission payload type
769    /// ([`NackControl::LocalRtxTime`](super::NackControl::LocalRtxTime)): it replaces
770    /// `max_packet_age` for the streams repaired under that payload type.
771    local_rtx_times: HashMap<u8, Duration>,
772
773    /// Send buffers per local stream SSRC
774    streams: HashMap<u32, LocalStream>,
775
776    /// The next sequence number of each retransmission SSRC this interceptor has sent on,
777    /// kept when its stream is unbound: a stream bound again with the same RTX SSRC (a
778    /// renegotiation re-binding it) carries on from here. Starting over would repeat sequence
779    /// numbers on a live SSRC, which SRTP refuses to protect twice (the packet index is the
780    /// SSRC's rollover counter and sequence number).
781    rtx_sequence_numbers: HashMap<u32, u16>,
782
783    /// Queue for retransmitted packets
784    write_queue: VecDeque<TaggedPacket>,
785    /// Retransmissions in `write_queue` not yet taken by `poll_write`.
786    retransmissions_queued: usize,
787    /// Inbound packets ready for the next interceptor.
788    read_queue: VecDeque<TaggedPacket>,
789    /// The RTP session (transport) of each SSRC, from the peer connection's
790    /// [`RtpSessionAssignment`](crate::RtpSessionAssignment)s; empty while there is one.
791    sessions: HashMap<u32, usize>,
792
793    /// See [`NackResponderBuilder::with_rate_limit`].
794    rate_limit: RetransmissionRateLimit,
795    /// The congestion controller's latest target, bits per second.
796    target_bps: Option<f64>,
797    /// The controller's minimum ([`MinimumTarget`]), bits per second.
798    minimum_bps: Option<f64>,
799    /// The original packets of the local streams, and the retransmissions, sent lately.
800    originals: RateWindow,
801    retransmitted: RateWindow,
802    /// See [`NackResponderBuilder::with_max_reserve_fraction`].
803    max_reserve_fraction: f64,
804    /// The round trip the RTCP session measured last.
805    round_trip_time: Option<Duration>,
806    /// NACKed packets waiting for room, oldest request first.
807    pending: VecDeque<PendingRetransmission>,
808    /// When each waiting packet was last asked for, and which packet it is (its serial).
809    pending_asked: HashMap<(u32, u16), (Instant, u64)>,
810    /// The octets of `pending`.
811    pending_octets: usize,
812    /// The reserve last announced, bits per second.
813    announced_reserve: f64,
814    /// When the next waiting retransmission can leave, worked out since the last change:
815    /// `None` when it has to be worked out again.
816    release_at: Option<Option<Instant>>,
817    /// Whether a pacer wire-ward reports its retransmissions' departures (it has once).
818    pacer_reports: bool,
819    /// Whether the pacer tells the source to pause ([`PacerPause`](crate::PacerPause)): the
820    /// target the application reads is zero.
821    paused: bool,
822    /// Whether transport-wide feedback reports on the retransmissions
823    /// ([`RetransmissionsReported`](crate::RetransmissionsReported)): it has once.
824    repairs_reported: bool,
825    /// See [`NackResponderBuilder::with_max_repair_age`].
826    max_repair_age: Option<Duration>,
827    /// See [`NackResponderBuilder::with_repair_backlog_bound`].
828    repair_backlog_bound: Option<Duration>,
829    /// The targets set within [`COLLAPSE_LOOK_BACK`] (and the one in force before), oldest
830    /// first; cleared when repairs are given up.
831    targets: VecDeque<(Instant, f64)>,
832    /// Retransmissions made before this instant no longer hold the reserve: what they
833    /// repaired was given up.
834    reserve_since: Option<Instant>,
835}
836
837impl NackResponderInterceptor {
838    fn new(size: u16) -> Self {
839        Self {
840            read_queue: VecDeque::new(),
841            size,
842            max_packet_age: None,
843            local_rtx_times: HashMap::new(),
844            streams: HashMap::new(),
845            rtx_sequence_numbers: HashMap::new(),
846            write_queue: VecDeque::new(),
847            retransmissions_queued: 0,
848            sessions: HashMap::new(),
849            rate_limit: RetransmissionRateLimit::default(),
850            target_bps: None,
851            minimum_bps: None,
852            originals: RateWindow::default(),
853            retransmitted: RateWindow::default(),
854            max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
855            round_trip_time: None,
856            pending: VecDeque::new(),
857            pending_asked: HashMap::new(),
858            pending_octets: 0,
859            announced_reserve: 0.0,
860            release_at: None,
861            pacer_reports: false,
862            paused: false,
863            repairs_reported: false,
864            max_repair_age: Some(MAX_REPAIR_AGE),
865            repair_backlog_bound: Some(REPAIR_BACKLOG_BOUND),
866            targets: VecDeque::new(),
867            reserve_since: None,
868        }
869    }
870
871    /// Octets at `bits_per_second` over the window.
872    fn window_octets(bits_per_second: f64) -> usize {
873        (bits_per_second / 8.0 * RETRANSMISSION_RATE_WINDOW.as_secs_f64()) as usize
874    }
875
876    /// The octets retransmissions may still take within the window, `None` for no limit.
877    fn retransmission_allowance(&mut self, now: Instant) -> Option<usize> {
878        let target_bps = self.target_bps?;
879        self.originals.expire(now);
880        self.retransmitted.expire(now);
881        let target = Self::window_octets(target_bps);
882        let limit = match self.rate_limit {
883            RetransmissionRateLimit::WithinTarget => {
884                if self.at_floor() {
885                    // Near the floor the retransmissions take the window's room first.
886                    target
887                } else {
888                    // What the originals leave, or the reserve the original media has already
889                    // been lowered by, whichever is more.
890                    target
891                        .saturating_sub(self.originals.octets)
892                        .max(Self::window_octets(self.announced_reserve))
893                }
894            }
895            RetransmissionRateLimit::UpToTarget => target,
896            RetransmissionRateLimit::Unlimited => return None,
897        };
898        Some(limit.saturating_sub(self.retransmitted.octets))
899    }
900
901    /// Whether lowering the original media by the reserve would take it under the
902    /// controller's minimum (see [`RetransmissionRateLimit::WithinTarget`]).
903    fn at_floor(&self) -> bool {
904        self.rate_limit == RetransmissionRateLimit::WithinTarget
905            && self.announced_reserve > 0.0
906            && match (self.target_bps, self.minimum_bps) {
907                (Some(target), Some(minimum)) => target - self.announced_reserve < minimum,
908                _ => false,
909            }
910    }
911
912    /// The retransmission reserve at `now`, bits per second (see
913    /// [`RetransmissionRateLimit::WithinTarget`]); zero under the other rules.
914    fn reserve(&mut self, now: Instant) -> f64 {
915        let Some(target_bps) = self.target_bps else {
916            return 0.0;
917        };
918        if self.rate_limit != RetransmissionRateLimit::WithinTarget {
919            return 0.0;
920        }
921        self.retransmitted.expire(now);
922        // Retransmissions of what was given up since hold no reserve: nothing follows them.
923        let retransmitted = match self.reserve_since {
924            Some(since) => self
925                .retransmitted
926                .sent
927                .iter()
928                .filter(|(at, _)| *at >= since)
929                .map(|(_, octets)| *octets)
930                .sum(),
931            None => self.retransmitted.octets,
932        };
933        if self.pending.is_empty() && retransmitted == 0 {
934            return 0.0;
935        }
936        let horizon = self
937            .round_trip_time
938            .unwrap_or(RETRANSMISSION_RATE_WINDOW)
939            .clamp(MIN_RESERVE_HORIZON, RETRANSMISSION_RATE_WINDOW);
940        let needed = self.pending_octets as f64 * 8.0 / horizon.as_secs_f64();
941        let in_use = retransmitted as f64 * 8.0 / RETRANSMISSION_RATE_WINDOW.as_secs_f64();
942        needed
943            .max(in_use)
944            .min(self.max_reserve_fraction * target_bps)
945    }
946
947    /// How long a waiting request stays without being asked for again.
948    fn pending_lifetime(&self) -> Duration {
949        self.round_trip_time
950            .map_or(PENDING_REQUEST_LIFETIME, |rtt| {
951                (rtt * 2).max(PENDING_REQUEST_LIFETIME)
952            })
953    }
954
955    /// Drops the waiting requests nobody asked for again within their lifetime.
956    fn expire_pending(&mut self, now: Instant) {
957        let lifetime = self.pending_lifetime();
958        let before = self.pending.len();
959        let asked = &mut self.pending_asked;
960        let octets = &mut self.pending_octets;
961        self.pending.retain(|entry| {
962            let key = (entry.ssrc, entry.sequence_number);
963            let fresh = asked
964                .get(&key)
965                .is_some_and(|(at, _)| now.saturating_duration_since(*at) <= lifetime);
966            if !fresh {
967                asked.remove(&key);
968                *octets -= entry.octets;
969            }
970            fresh
971        });
972        if self.pending.len() != before {
973            self.release_at = None;
974        }
975    }
976
977    /// The wire size of the retransmission of `packet` in `form`: an RTX packet carries the
978    /// original sequence number ahead of the payload (RFC 4588 section 4).
979    fn retransmission_size(form: RepairForm, packet: &rtp::Packet) -> usize {
980        match form {
981            RepairForm::Rtx(_) => packet.marshal_size() + 2,
982            // The header, the original sequence number and the RED block header.
983            RepairForm::RtxWithoutFec(_) => packet.marshal_size() - packet.payload.len() + 3,
984            RepairForm::Original => packet.marshal_size(),
985        }
986    }
987
988    /// The `rtx-time` in force for a packet of `stream` sent again in `form` (RFC 4588 8.1: a
989    /// packet is kept for retransmission that long): what the session description announced
990    /// for the packet's retransmission format, the RTX payload type whose `apt` is the
991    /// packet's payload type (RED's RTX for a RED packet; the stream's own, for a packet sent
992    /// again as it was); without one, the configured age. RFC 4588 section 8.6 makes
993    /// `rtx-time` a parameter of each retransmission payload type, so two formats of one
994    /// stream may announce different times, or one and not the other.
995    fn rtx_time(&self, stream: &LocalStream, form: RepairForm) -> Option<Duration> {
996        let payload_type_rtx = match form {
997            RepairForm::Rtx(payload_type_rtx) | RepairForm::RtxWithoutFec(payload_type_rtx) => {
998                Some(payload_type_rtx)
999            }
1000            RepairForm::Original => stream.payload_type_rtx,
1001        };
1002        payload_type_rtx
1003            .and_then(|payload_type_rtx| self.local_rtx_times.get(&payload_type_rtx))
1004            .copied()
1005            .or(self.max_packet_age)
1006    }
1007
1008    /// How long ago `seq` of `stream` was written, if the stream holds it.
1009    fn age(stream: &LocalStream, seq: u16, now: Instant) -> Option<Duration> {
1010        stream.sent_at[usize::from(seq) % stream.sent_at.len()]
1011            .filter(|(sequence_number, _, _)| *sequence_number == seq)
1012            .map(|(_, sent, _)| now.saturating_duration_since(sent))
1013    }
1014
1015    /// Whether `seq` of `stream` may be retransmitted at `now` (it is still held, it has a
1016    /// form to be sent again in, see [`LocalStream::repair_form`], and it is not older than
1017    /// the `rtx-time` of that form or, without one, than the repair age), and its
1018    /// retransmission's size.
1019    fn retransmittable(&self, stream: &LocalStream, seq: u16, now: Instant) -> Option<usize> {
1020        let original_packet = stream.send_buffer.get(seq)?;
1021        let form = stream.repair_form(original_packet)?;
1022        if let Some(rtx_time) = self.rtx_time(stream, form)
1023            && Self::age(stream, seq, now).is_some_and(|age| age > rtx_time)
1024        {
1025            return None;
1026        }
1027        if self.too_old(stream, form, seq, now) {
1028            return None;
1029        }
1030        Some(Self::retransmission_size(form, original_packet))
1031    }
1032
1033    /// Sends the waiting retransmissions the rate limit has room for, oldest request first.
1034    fn release(&mut self, now: Instant) {
1035        let mut allowance = self.retransmission_allowance(now);
1036        let resend_interval = resend_interval(self.round_trip_time);
1037        // Waits for the feedback that ended are over, reached below or not.
1038        self.expire_repairs(now);
1039        // A request held for the feedback on an earlier retransmission keeps its place; the
1040        // ones behind it are served meanwhile.
1041        let mut index = 0;
1042        while let Some(entry) = self.pending.get(index) {
1043            if self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
1044                break;
1045            }
1046            let (ssrc, seq) = (entry.ssrc, entry.sequence_number);
1047            if !self.holds(ssrc, seq, entry.packet) {
1048                // The packet asked for is gone; the one that has its number was not asked for.
1049                self.remove_pending(index);
1050                continue;
1051            }
1052            match self.repeat_state((ssrc, seq), now) {
1053                Repeat::Hold(_) => {
1054                    index += 1;
1055                    continue;
1056                }
1057                Repeat::Decline => {
1058                    self.remove_pending(index);
1059                    continue;
1060                }
1061                Repeat::Answer => {}
1062            }
1063            let in_pacer = self.in_pacer(ssrc, seq, now);
1064            let current = self.streams.get(&ssrc).and_then(|stream| {
1065                let recently = stream
1066                    .last_retransmit
1067                    .get(&seq)
1068                    .is_some_and(|at| now.saturating_duration_since(*at) < resend_interval)
1069                    || in_pacer;
1070                if recently {
1071                    None
1072                } else {
1073                    self.retransmittable(stream, seq, now)
1074                        .map(|size| (size, stream.retransmit_budget))
1075                }
1076            });
1077            let Some((size, budget)) = current else {
1078                // Gone from the buffer, too old, its stream unbound, or just sent.
1079                self.remove_pending(index);
1080                continue;
1081            };
1082            if budget == 0 {
1083                // Waits for the next original packet, which adds to the budget.
1084                break;
1085            }
1086            if let Some(left) = allowance.as_mut() {
1087                if size > *left {
1088                    break;
1089                }
1090                *left -= size;
1091            }
1092            self.remove_pending(index);
1093            self.retransmit(now, ssrc, seq, size);
1094        }
1095    }
1096
1097    fn remove_pending(&mut self, index: usize) {
1098        if let Some(entry) = self.pending.remove(index) {
1099            self.pending_asked
1100                .remove(&(entry.ssrc, entry.sequence_number));
1101            self.pending_octets -= entry.octets;
1102            self.release_at = None;
1103        }
1104    }
1105
1106    /// Queues the retransmission of `seq` of the stream `ssrc`.
1107    fn retransmit(&mut self, now: Instant, ssrc: u32, seq: u16, size: usize) {
1108        let earlier = self.repair(ssrc, seq, now);
1109        let Some(stream) = self.streams.get_mut(&ssrc) else {
1110            return;
1111        };
1112        // Held, and with a form to be sent again in (`retransmittable` said so already).
1113        let Some(form) = stream
1114            .send_buffer
1115            .get(seq)
1116            .and_then(|packet| stream.repair_form(packet))
1117        else {
1118            return;
1119        };
1120        stream.last_retransmit.insert(seq, now);
1121        if let Some(packet) = stream.packet(seq) {
1122            // An earlier retransmission of this same packet still remembered: reports on it
1123            // go on counting.
1124            let first_made = earlier
1125                .filter(|earlier| earlier.packet == packet)
1126                .map_or(now, |earlier| earlier.first_made);
1127            let state = if self.pacer_reports {
1128                RepairState::InPacer
1129            } else {
1130                // Without a pacer it leaves now.
1131                RepairState::Unreported { left: now }
1132            };
1133            stream.remember_repair(
1134                seq,
1135                Repair {
1136                    packet,
1137                    first_made,
1138                    made: now,
1139                    state,
1140                },
1141            );
1142        }
1143        stream.retransmit_budget -= 1;
1144        self.retransmissions_queued += 1;
1145        let Some(original_packet) = stream.send_buffer.get(seq) else {
1146            return;
1147        };
1148
1149        let without_fec;
1150        let original_packet = if matches!(form, RepairForm::RtxWithoutFec(_)) {
1151            // The RED block header (RFC 2198 section 3: one octet, the block's payload
1152            // type), without the FEC data behind it.
1153            without_fec = rtp::Packet {
1154                header: original_packet.header.clone(),
1155                payload: original_packet
1156                    .payload
1157                    .slice(..original_packet.payload.len().min(1)),
1158            };
1159            &without_fec
1160        } else {
1161            original_packet
1162        };
1163        let packet =
1164            if let (RepairForm::Rtx(pt_rtx) | RepairForm::RtxWithoutFec(pt_rtx), Some(ssrc_rtx)) =
1165                (form, stream.ssrc_rtx)
1166            {
1167                if stream.repairs_order.len() >= usize::from(self.size).max(1)
1168                    && let Some((oldest, made)) = stream.repairs_order.pop_front()
1169                    && stream
1170                        .repairs_by_rtx
1171                        .get(&oldest)
1172                        .is_some_and(|(_, at)| *at == made)
1173                {
1174                    stream.repairs_by_rtx.remove(&oldest);
1175                }
1176                stream
1177                    .repairs_by_rtx
1178                    .insert(stream.rtx_sequence_number, (seq, now));
1179                stream
1180                    .repairs_order
1181                    .push_back((stream.rtx_sequence_number, now));
1182                rtx_packet(
1183                    &mut stream.rtx_sequence_number,
1184                    (stream.rid_extension_id, stream.repaired_rid_extension_id),
1185                    original_packet,
1186                    ssrc_rtx,
1187                    pt_rtx,
1188                )
1189            } else {
1190                // No RTX negotiated for the stream: retransmit the original packet as-is
1191                original_packet.clone()
1192            };
1193        self.retransmitted.add(now, size);
1194        self.release_at = None;
1195
1196        // Tagged so a send history downstream counts it as new bytes on the wire rather
1197        // than as the original transmission. A bandwidth estimator that cannot tell the two
1198        // apart under-counts exactly when the path is lossy — it sees fewer bytes than are
1199        // really being sent, infers headroom, and raises the target during loss.
1200        self.write_queue.push_back(TaggedPacket {
1201            now,
1202            transport: TransportContext::default(),
1203            message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
1204        });
1205    }
1206
1207    /// When the oldest waiting retransmission fits the rate limit: the instant enough of the
1208    /// window's packets have left it. `None` with nothing waiting, without a target to wait
1209    /// for, or while the stream's budget waits for an original packet (the write of that
1210    /// packet tries again).
1211    pub fn next_release(&mut self) -> Option<Instant> {
1212        if let Some(at) = self.release_at {
1213            return at;
1214        }
1215        let at = self.work_out_release();
1216        self.release_at = Some(at);
1217        at
1218    }
1219
1220    fn work_out_release(&self) -> Option<Instant> {
1221        // A request held for the feedback on an earlier retransmission is due when its wait
1222        // ends (the feedback itself comes on the read leg); the first one not held is the
1223        // head. `release` forgets the waits that ended, so these are all ahead.
1224        let wait = self.report_wait();
1225        let held = |entry: &PendingRetransmission| {
1226            if !self.repairs_reported {
1227                return None;
1228            }
1229            let stream = self.streams.get(&entry.ssrc)?;
1230            let repair = stream.repairs.get(&entry.sequence_number)?;
1231            match repair.state {
1232                RepairState::Unreported { left }
1233                    if stream.packet(entry.sequence_number) == Some(repair.packet) =>
1234                {
1235                    Some(left + wait)
1236                }
1237                _ => None,
1238            }
1239        };
1240        let hold_ends = self.pending.iter().filter_map(held).min();
1241        let Some(target_bps) = self.target_bps else {
1242            return hold_ends;
1243        };
1244        // With nothing waiting, the reserve falls to zero when the last retransmission leaves
1245        // the window.
1246        if self.pending.is_empty() {
1247            return (self.announced_reserve > 0.0)
1248                .then(|| self.retransmitted.sent.back())
1249                .flatten()
1250                .map(|(at, _)| *at + RETRANSMISSION_RATE_WINDOW);
1251        }
1252        // The lifetime of the oldest request ends: due then, to drop it.
1253        let lifetime = self.pending_lifetime();
1254        let stale = self
1255            .pending
1256            .iter()
1257            .filter_map(|entry| self.pending_asked.get(&(entry.ssrc, entry.sequence_number)))
1258            .map(|(asked, _)| *asked)
1259            .min()
1260            .map(|asked| asked + lifetime + Duration::from_micros(1));
1261        let stale = stale.into_iter().chain(hold_ends).min();
1262        let Some(entry) = self.pending.iter().find(|entry| held(entry).is_none()) else {
1263            return stale;
1264        };
1265        if self
1266            .streams
1267            .get(&entry.ssrc)
1268            .is_none_or(|stream| stream.retransmit_budget == 0)
1269        {
1270            return stale;
1271        }
1272        let size = entry.octets;
1273        let target = Self::window_octets(target_bps);
1274        let (originals, retransmitted) = (self.originals.octets, self.retransmitted.octets);
1275        let fits = match self.rate_limit {
1276            RetransmissionRateLimit::WithinTarget if !self.at_floor() => {
1277                let by_share = freed_at(
1278                    &[&self.originals, &self.retransmitted],
1279                    (originals + retransmitted + size)
1280                        .saturating_sub(target)
1281                        .max(1),
1282                )
1283                .filter(|_| size <= target);
1284                // The reserve frees as the retransmissions leave the window.
1285                let reserve = Self::window_octets(self.announced_reserve);
1286                let by_reserve = freed_at(
1287                    &[&self.retransmitted],
1288                    (retransmitted + size).saturating_sub(reserve).max(1),
1289                )
1290                .filter(|_| size <= reserve);
1291                by_share.into_iter().chain(by_reserve).min()
1292            }
1293            // Near the floor the room is the retransmissions' first: only they leaving the
1294            // window frees it.
1295            RetransmissionRateLimit::WithinTarget | RetransmissionRateLimit::UpToTarget => {
1296                freed_at(
1297                    &[&self.retransmitted],
1298                    (retransmitted + size).saturating_sub(target).max(1),
1299                )
1300                .filter(|_| size <= target)
1301            }
1302            RetransmissionRateLimit::Unlimited => None,
1303        };
1304        fits.into_iter().chain(stale).min()
1305    }
1306
1307    /// Announces a reserve that moved: down the write leg for the congestion controller, and
1308    /// up the read leg as the lowered target for the application.
1309    /// The carrier that tells the application its target when only the reserve moved: the
1310    /// controller's target less the reserve, or, while the pacer has the source paused, zero
1311    /// with the controller's target riding along as the pacer's own announcement of a pause
1312    /// has it ([`PacerPause`](crate::PacerPause)). Without it a reader of the carrier takes
1313    /// the zero for the congestion controller's estimate (`availableOutgoingBitrate` read
1314    /// nothing until the next target from the pacer).
1315    fn target_carrier(&self, now: Instant, target_bps: f64, reserve: f64) -> TaggedPacket {
1316        let mut message = AttributedPacket::new(Packet::Rtcp(vec![]));
1317        if self.paused {
1318            message.add(Attribute::TargetBitrateChanged {
1319                bits_per_second: 0.0,
1320            });
1321            message.add(Attribute::Custom(std::sync::Arc::new(crate::PacerPause {
1322                target_bits_per_second: target_bps,
1323            })));
1324        } else {
1325            message.add(Attribute::TargetBitrateChanged {
1326                bits_per_second: media_target(target_bps, reserve, self.minimum_bps.unwrap_or(0.0)),
1327            });
1328        }
1329        TaggedPacket {
1330            now,
1331            transport: TransportContext::default(),
1332            message,
1333        }
1334    }
1335
1336    fn announce_reserve(&mut self, now: Instant, carrier: bool) {
1337        let Some(target_bps) = self.target_bps else {
1338            return;
1339        };
1340        let reserve = self.reserve(now);
1341        if !reserve_moved(self.announced_reserve, reserve, target_bps) {
1342            return;
1343        }
1344        self.announced_reserve = reserve;
1345        self.release_at = None;
1346        self.write_queue.push_back(TaggedPacket {
1347            now,
1348            transport: TransportContext::default(),
1349            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
1350                std::sync::Arc::new(RetransmissionReserve {
1351                    bits_per_second: reserve,
1352                }),
1353            )),
1354        });
1355        if carrier {
1356            let carrier = self.target_carrier(now, target_bps, reserve);
1357            self.read_queue.push_back(carrier);
1358        }
1359        if self.at_floor() {
1360            // Near the floor the window's room is the retransmissions': use it now.
1361            self.release(now);
1362        }
1363    }
1364
1365    /// Fills a probe cluster ([`ProbeRequest`]) with padding-only packets on the RTX stream of
1366    /// the media stream that sent most recently.
1367    ///
1368    /// A probe needs a burst of packets at a multiple of the target rate, and an application
1369    /// that follows the target does not have one waiting. Each packet is an RTP packet of the
1370    /// RTX stream with no payload and [`PROBE_PADDING_OCTETS`] of padding (RFC 3550 section
1371    /// 5.1): an RTX packet too short to hold the original sequence number of RFC 4588 section
1372    /// 4 carries no media, and every receiver drops it after its transport-wide sequence
1373    /// number has been recorded (this crate's endpoint, libwebrtc's `RtxReceiveStream`). A
1374    /// retransmission of a packet already delivered would be a duplicate the receiving
1375    /// application may play twice. The header is the newest packet's, with its extensions
1376    /// (MID, the repaired RID in place of the RID), so the packet is demultiplexed as that
1377    /// stream's repair flow. Without RTX negotiated nothing is added: padding under the media
1378    /// SSRC would take sequence numbers the application owns. Not charged to the NACK budget:
1379    /// it answers no NACK.
1380    ///
1381    /// In a chain without a pacer (the request carries no [`ProbeFill`](crate::ProbeFill)) the
1382    /// padding is the whole cluster and leaves as one burst, marked here with the cluster's
1383    /// [`ProbePacket`]: without the mark the congestion controller would count no packet for
1384    /// the cluster and wait for a result that cannot come.
1385    ///
1386    /// With several RTP sessions (transports) a cluster is the session's that asked for it
1387    /// (the request carries its [`RtpSession`](crate::RtpSession)): it is filled on a stream of
1388    /// that session only, so the probe travels the path whose capacity it measures (RFC 8836
1389    /// section 2: each path its own capacity).
1390    fn fill_probe(
1391        &mut self,
1392        now: Instant,
1393        request: &ProbeRequest,
1394        fill: Option<usize>,
1395        session: Option<usize>,
1396    ) {
1397        let sessions = &self.sessions;
1398        let Some(stream) = self
1399            .streams
1400            .iter_mut()
1401            .filter(|(ssrc, _)| match session {
1402                Some(session) if !sessions.is_empty() => sessions.get(ssrc) == Some(&session),
1403                _ => true,
1404            })
1405            .map(|(_, stream)| stream)
1406            .filter(|stream| stream.ssrc_rtx.is_some() && stream.payload_type_rtx.is_some())
1407            .filter(|stream| stream.last_sent.is_some())
1408            .max_by_key(|stream| stream.last_sent.map(|(_, at)| at))
1409        else {
1410            return;
1411        };
1412        let (Some(ssrc_rtx), Some(pt_rtx), Some((newest, _))) =
1413            (stream.ssrc_rtx, stream.payload_type_rtx, stream.last_sent)
1414        else {
1415            return;
1416        };
1417
1418        // The newest packet still held gives the header; after the buffer was emptied (a
1419        // give-up, the pacer's flush) and before the next packet is written, the newest it
1420        // held then.
1421        let Some(template) = stream
1422            .send_buffer
1423            .get(newest)
1424            .cloned()
1425            .or_else(|| stream.probe_template.clone())
1426        else {
1427            return;
1428        };
1429
1430        // The pacer says how much padding the cluster needs beyond the media it holds
1431        // ([`ProbeFill`](crate::ProbeFill)); without a pacer, the whole cluster.
1432        let wanted = fill
1433            .map_or(request.octets, |octets| octets.min(request.octets))
1434            .min(MAX_PROBE_FILL_OCTETS);
1435        let mut filled = 0usize;
1436        for _ in 0..MAX_PROBE_FILL_PACKETS {
1437            if filled >= wanted || self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
1438                break;
1439            }
1440            let packet = padding_packet(
1441                &mut stream.rtx_sequence_number,
1442                (stream.rid_extension_id, stream.repaired_rid_extension_id),
1443                &template,
1444                ssrc_rtx,
1445                pt_rtx,
1446            );
1447            filled += packet.marshal_size();
1448            self.retransmissions_queued += 1;
1449            let mut message =
1450                AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission);
1451            if fill.is_none() {
1452                // No pacer took the request on its way here: nothing below releases this
1453                // padding at the cluster's rate or marks it, so it leaves as one burst and
1454                // carries the cluster's mark from here. The congestion controller measures
1455                // such a cluster by how the path spread it (`burst_estimate`).
1456                message.add(Attribute::Custom(std::sync::Arc::new(ProbePacket {
1457                    cluster: request.cluster,
1458                })));
1459            }
1460            self.write_queue.push_back(TaggedPacket {
1461                now,
1462                transport: TransportContext::default(),
1463                message,
1464            });
1465        }
1466    }
1467
1468    /// Forgets the packets the pacer discarded ([`PacerDiscard`](crate::PacerDiscard)): out of
1469    /// the retransmission buffer, so a NACK for one is answered by nothing (RFC 4588 section 7:
1470    /// the sender "MAY selectively retransmit only the packets that it deems important"; a frame
1471    /// the pacer gave up is not), out of the requests waiting, and out of the original packets
1472    /// counted against the target, since they never used the link.
1473    fn forget_discarded(&mut self, discard: &crate::PacerDiscard) {
1474        if let Some(stream) = self.streams.get_mut(&discard.ssrc) {
1475            for &seq in &discard.sequence_numbers {
1476                let Some(packet) = stream.send_buffer.remove(seq) else {
1477                    continue;
1478                };
1479                let slot = usize::from(seq) % stream.sent_at.len();
1480                if let Some((sequence_number, at, _)) = stream.sent_at[slot]
1481                    && sequence_number == seq
1482                {
1483                    self.originals.forget(at, packet.marshal_size());
1484                    stream.sent_at[slot] = None;
1485                }
1486                stream.repairs.remove(&seq);
1487            }
1488        }
1489        let before = self.pending.len();
1490        let asked = &mut self.pending_asked;
1491        let octets = &mut self.pending_octets;
1492        self.pending.retain(|entry| {
1493            let discarded = entry.ssrc == discard.ssrc
1494                && discard.sequence_numbers.contains(&entry.sequence_number);
1495            if discarded {
1496                asked.remove(&(entry.ssrc, entry.sequence_number));
1497                *octets -= entry.octets;
1498            }
1499            !discarded
1500        });
1501        if self.pending.len() != before {
1502            self.release_at = None;
1503        }
1504    }
1505
1506    /// The pacer gave its queue up at a collapse of the target
1507    /// ([`PacerFlush`](crate::PacerFlush)): everything sent before on the streams it names is
1508    /// forgotten (the retransmission buffer, the requests waiting, the retransmissions
1509    /// counted as waiting in the pacer), so a NACK for any of it is answered by nothing.
1510    /// Those packets belong to frames sized for a rate the path no longer carries, and the
1511    /// stream restarts at the key frame the pacer asks the application for (RFC 8834 section
1512    /// 6.1: "the likelihood of them arriving in time to be useful need[s] to be considered";
1513    /// RFC 4588 section 7: the sender "MAY selectively retransmit only the packets that it
1514    /// deems important"). What is written after it is buffered and repaired as ever.
1515    fn forget_flushed(&mut self, flush: &crate::PacerFlush) {
1516        self.forget_streams(&flush.ssrcs);
1517    }
1518
1519    /// Forgets everything sent so far on the streams `ssrcs`: their retransmission buffers,
1520    /// what is remembered of their repairs, the requests waiting.
1521    fn forget_streams(&mut self, ssrcs: &[u32]) {
1522        let size = self.size;
1523        for ssrc in ssrcs {
1524            let Some(stream) = self.streams.get_mut(ssrc) else {
1525                continue;
1526            };
1527            // A probe cluster asked for before the next packet is written still needs a
1528            // header to pad under: without one no padding leaves, the cluster goes
1529            // unanswered and a chain without a pacer stops asking.
1530            if let Some(newest) = stream
1531                .last_sent
1532                .and_then(|(newest, _)| stream.send_buffer.get(newest))
1533            {
1534                stream.probe_template = Some(newest.clone());
1535            }
1536            if let Some(buffer) = SendBuffer::new(size) {
1537                stream.send_buffer = buffer;
1538            }
1539            stream.sent_at.iter_mut().for_each(|sent| *sent = None);
1540            stream.last_retransmit.clear();
1541            // What was remembered of the repairs of those packets goes with them. Not needed
1542            // for what is sent: with the buffer emptied no flushed packet can be retransmitted
1543            // again whatever this memory says (`retransmittable` finds none), and the entries
1544            // would age out (`expire_repairs`). Cleared so that a report still in flight on
1545            // one of those repairs finds nothing to hold a later request against, and the
1546            // stream's memory starts empty with the key frame, as its buffer does.
1547            stream.repairs.clear();
1548            stream.repairs_by_rtx.clear();
1549            stream.repairs_order.clear();
1550        }
1551        let before = self.pending.len();
1552        let asked = &mut self.pending_asked;
1553        let octets = &mut self.pending_octets;
1554        self.pending.retain(|entry| {
1555            let flushed = ssrcs.contains(&entry.ssrc);
1556            if flushed {
1557                asked.remove(&(entry.ssrc, entry.sequence_number));
1558                *octets -= entry.octets;
1559            }
1560            !flushed
1561        });
1562        if self.pending.len() != before {
1563            self.release_at = None;
1564        }
1565    }
1566
1567    /// Gives up the repair of everything sent so far on the video streams among `ssrcs` and
1568    /// asks the application for a key frame of each (a Picture Loss Indication with sender
1569    /// SSRC 0 marked [`Attribute::DeliverToApplication`], as the pacer's flush does). The
1570    /// reserve those repairs held is released: the retransmissions made so far no longer count
1571    /// as in use. Audio streams are left as they are.
1572    fn give_up(&mut self, now: Instant, ssrcs: &[u32]) {
1573        let mut ssrcs: Vec<u32> = ssrcs
1574            .iter()
1575            .copied()
1576            .filter(|ssrc| self.streams.get(ssrc).is_some_and(|stream| stream.video))
1577            .collect();
1578        ssrcs.sort_unstable();
1579        ssrcs.dedup();
1580        if ssrcs.is_empty() {
1581            return;
1582        }
1583        self.forget_streams(&ssrcs);
1584        self.reserve_since = Some(now);
1585        self.release_at = None;
1586        // No target from before counts again: what is written from here on (the key frame)
1587        // is written for the target now.
1588        if let Some(target) = self.target_bps {
1589            self.targets.clear();
1590            self.targets.push_back((now, target));
1591        }
1592        for ssrc in ssrcs {
1593            self.read_queue.push_back(TaggedPacket {
1594                now,
1595                transport: TransportContext::default(),
1596                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1597                    rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication {
1598                        sender_ssrc: 0,
1599                        media_ssrc: ssrc,
1600                    },
1601                )]))
1602                .with(Attribute::DeliverToApplication),
1603            });
1604        }
1605    }
1606
1607    /// Notes the target `target` set at `now` (for [`Self::backlog_collapsed`]).
1608    fn note_target(&mut self, now: Instant, target: f64) {
1609        if self.targets.back().is_some_and(|(_, last)| *last == target) {
1610            return;
1611        }
1612        self.targets.push_back((now, target));
1613        while self.targets.len() > 1
1614            && now.saturating_duration_since(self.targets[1].0) >= COLLAPSE_LOOK_BACK
1615        {
1616            self.targets.pop_front();
1617        }
1618        while self.targets.len() > MAX_TARGETS_KEPT {
1619            self.targets.pop_front();
1620        }
1621    }
1622
1623    /// Whether the requests waiting are a backlog the path will not carry in time
1624    /// ([`NackResponderBuilder::with_repair_backlog_bound`]): they would take the bound or
1625    /// more to leave if they had the whole target, and the target is at most [`COLLAPSE_AT`]
1626    /// of the highest in force within [`COLLAPSE_LOOK_BACK`].
1627    fn backlog_collapsed(&self, now: Instant) -> bool {
1628        let (Some(bound), Some(target)) = (self.repair_backlog_bound, self.target_bps) else {
1629            return false;
1630        };
1631        if self.pending.is_empty() || target <= 0.0 {
1632            return false;
1633        }
1634        if (self.pending_octets as f64 * 8.0 / target) < bound.as_secs_f64() {
1635            return false;
1636        }
1637        let mut highest: f64 = 0.0;
1638        for (index, (_, in_force)) in self.targets.iter().enumerate() {
1639            let superseded = self.targets.get(index + 1).is_some_and(|(next, _)| {
1640                now.saturating_duration_since(*next) >= COLLAPSE_LOOK_BACK
1641            });
1642            if !superseded {
1643                highest = highest.max(*in_force);
1644            }
1645        }
1646        highest > 0.0 && target <= COLLAPSE_AT * highest
1647    }
1648
1649    /// Gives up a collapsed backlog at `now`: the video streams with requests waiting. The
1650    /// give-up forgets the targets from before it ([`Self::give_up`]), so the key frame that
1651    /// answers it is not given up in its turn unless the target halves again.
1652    fn give_up_a_backlog(&mut self, now: Instant) {
1653        if !self.backlog_collapsed(now) {
1654            return;
1655        }
1656        let ssrcs: Vec<u32> = self.pending.iter().map(|entry| entry.ssrc).collect();
1657        self.give_up(now, &ssrcs);
1658    }
1659
1660    /// Whether `seq` of `stream`, sent again in `form`, was written longer ago than the
1661    /// sender's own judgement repairs ([`NackResponderBuilder::with_max_repair_age`]). Never
1662    /// with an `rtx-time` in force for that form ([`Self::rtx_time`]): that time is then the
1663    /// one that counts ([`Self::retransmittable`]). One rule per packet: the same per-form
1664    /// value is the age cut, this switch, and the switch of the give-up in the NACK handler.
1665    fn too_old(&self, stream: &LocalStream, form: RepairForm, seq: u16, now: Instant) -> bool {
1666        self.rtx_time(stream, form).is_none()
1667            && self
1668                .max_repair_age
1669                .is_some_and(|bound| Self::age(stream, seq, now).is_some_and(|age| age > bound))
1670    }
1671
1672    /// The pacer's report of retransmissions that left it or were dropped
1673    /// ([`RetransmissionsLeft`](crate::RetransmissionsLeft)): no longer on their way. One that
1674    /// left counts its resend interval from now, the instant it went toward the wire, not from
1675    /// when it was made (libwebrtc's `RtpPacketHistory` sets the send time when the pacer sends
1676    /// it); one that was dropped may be asked for again.
1677    fn retransmissions_left(&mut self, now: Instant, notice: &crate::RetransmissionsLeft) {
1678        self.pacer_reports = true;
1679        for &(ssrc, seq) in &notice.departed {
1680            let Some(stream) = self
1681                .media_ssrc(ssrc)
1682                .and_then(|media| self.streams.get_mut(&media))
1683            else {
1684                continue;
1685            };
1686            let packet = stream.packet(seq);
1687            if let Some(repair) = stream.repairs.get_mut(&seq)
1688                && repair.state == RepairState::InPacer
1689            {
1690                if packet == Some(repair.packet) {
1691                    repair.state = RepairState::Unreported { left: now };
1692                    stream.last_retransmit.insert(seq, now);
1693                } else {
1694                    // The packet it repaired is no longer held: nothing of it is asked for
1695                    // again, and the packet that has the number now starts afresh.
1696                    stream.repairs.remove(&seq);
1697                }
1698            }
1699        }
1700        for &(ssrc, seq) in &notice.dropped {
1701            if let Some(stream) = self
1702                .media_ssrc(ssrc)
1703                .and_then(|media| self.streams.get_mut(&media))
1704                && stream
1705                    .repairs
1706                    .get(&seq)
1707                    .is_some_and(|repair| repair.state == RepairState::InPacer)
1708            {
1709                stream.repairs.remove(&seq);
1710            }
1711        }
1712        // A pacer drops what waited its queue time bound and says so; anything older than
1713        // that is no longer there.
1714        self.expire_repairs(now);
1715        self.release_at = None;
1716    }
1717
1718    /// What is remembered at `now` of the latest retransmission under `seq` of the stream
1719    /// `ssrc`. A state that ran out by the clock is ended here (a wait for the report becomes
1720    /// [`RepairState::Overdue`], anything else is forgotten), and so is what is remembered of
1721    /// a packet the stream no longer holds under that number, except a retransmission still
1722    /// in the pacer (see [`RepairState::InPacer`]).
1723    fn repair(&mut self, ssrc: u32, seq: u16, now: Instant) -> Option<Repair> {
1724        let wait = self.report_wait();
1725        let stream = self.streams.get_mut(&ssrc)?;
1726        let packet = stream.packet(seq);
1727        let repair = stream.repairs.get_mut(&seq)?;
1728        if Self::repair_ended(repair, packet, now, wait) {
1729            stream.repairs.remove(&seq);
1730            return None;
1731        }
1732        Some(*repair)
1733    }
1734
1735    /// Brings `repair`, of the packet `packet` holds now, up to `now`; whether it is over.
1736    fn repair_ended(
1737        repair: &mut Repair,
1738        packet: Option<u64>,
1739        now: Instant,
1740        wait: Duration,
1741    ) -> bool {
1742        let same = packet == Some(repair.packet);
1743        let horizon = crate::RETRANSMISSION_REPORT_HORIZON.max(wait);
1744        match repair.state {
1745            RepairState::InPacer => now.saturating_duration_since(repair.made) >= IN_PACER_LIFETIME,
1746            RepairState::Unreported { left } => {
1747                if same && now >= left + wait {
1748                    repair.state = RepairState::Overdue { left };
1749                }
1750                !same || now.saturating_duration_since(left) >= horizon
1751            }
1752            RepairState::Overdue { left } => {
1753                !same || now.saturating_duration_since(left) >= horizon
1754            }
1755            RepairState::Delivered { reported } => {
1756                !same || now.saturating_duration_since(reported) >= DELIVERED_MEMORY
1757            }
1758        }
1759    }
1760
1761    /// Ends everything remembered of retransmissions that ran out by `now` (see
1762    /// [`Self::repair`]), and the RTX sequence numbers too old for a report to count.
1763    fn expire_repairs(&mut self, now: Instant) {
1764        let wait = self.report_wait();
1765        let horizon = IN_PACER_LIFETIME + crate::RETRANSMISSION_REPORT_HORIZON.max(wait);
1766        for stream in self.streams.values_mut() {
1767            let sent_at = &stream.sent_at;
1768            stream.repairs.retain(|seq, repair| {
1769                let packet = sent_at[usize::from(*seq) % sent_at.len()]
1770                    .filter(|(held, _, _)| held == seq)
1771                    .map(|(_, _, serial)| serial);
1772                !Self::repair_ended(repair, packet, now, wait)
1773            });
1774            while let Some(&(rtx_sequence, made)) = stream.repairs_order.front() {
1775                if now.saturating_duration_since(made) < horizon {
1776                    break;
1777                }
1778                stream.repairs_order.pop_front();
1779                if stream
1780                    .repairs_by_rtx
1781                    .get(&rtx_sequence)
1782                    .is_some_and(|(_, at)| *at == made)
1783                {
1784                    stream.repairs_by_rtx.remove(&rtx_sequence);
1785                }
1786            }
1787        }
1788    }
1789
1790    /// Whether the stream `ssrc` holds the packet `packet` under `seq`.
1791    fn holds(&self, ssrc: u32, seq: u16, packet: u64) -> bool {
1792        self.streams
1793            .get(&ssrc)
1794            .is_some_and(|stream| stream.packet(seq) == Some(packet))
1795    }
1796
1797    /// Whether a retransmission under `seq` of the stream `ssrc` waits in the pacer at `now`.
1798    fn in_pacer(&mut self, ssrc: u32, seq: u16, now: Instant) -> bool {
1799        self.repair(ssrc, seq, now)
1800            .is_some_and(|repair| repair.state == RepairState::InPacer)
1801    }
1802
1803    /// How long a request waits for the feedback on an earlier retransmission of its packet:
1804    /// two round trips and [`REPAIR_REPORT_MARGIN`], or [`PENDING_REQUEST_LIFETIME`] before a
1805    /// round trip is known.
1806    fn report_wait(&self) -> Duration {
1807        self.round_trip_time
1808            .map_or(PENDING_REQUEST_LIFETIME, |rtt| {
1809                rtt * 2 + REPAIR_REPORT_MARGIN
1810            })
1811    }
1812
1813    /// What a request for `key` gets at `now`, given what the feedback reported on its earlier
1814    /// retransmission (see [`RetransmissionsReported`](crate::RetransmissionsReported)). Without
1815    /// such reports every request is answered as before. A wait that ran out is forgotten.
1816    fn repeat_state(&mut self, key: (u32, u16), now: Instant) -> Repeat {
1817        if !self.repairs_reported {
1818            return Repeat::Answer;
1819        }
1820        let (ssrc, seq) = key;
1821        match self.repair(ssrc, seq, now).map(|repair| repair.state) {
1822            Some(RepairState::Delivered { .. }) => Repeat::Decline,
1823            Some(RepairState::Unreported { left }) => Repeat::Hold(left + self.report_wait()),
1824            // In the pacer: not asked here (nothing is made while it waits there).
1825            Some(RepairState::InPacer | RepairState::Overdue { .. }) | None => Repeat::Answer,
1826        }
1827    }
1828
1829    /// The media SSRC of `ssrc`: itself, or the stream whose retransmission SSRC it is.
1830    fn media_ssrc(&self, ssrc: u32) -> Option<u32> {
1831        if self.streams.contains_key(&ssrc) {
1832            Some(ssrc)
1833        } else {
1834            self.streams
1835                .iter()
1836                .find(|(_, stream)| stream.ssrc_rtx == Some(ssrc))
1837                .map(|(media, _)| *media)
1838        }
1839    }
1840
1841    /// The transport-wide feedback on retransmissions
1842    /// ([`RetransmissionsReported`](crate::RetransmissionsReported)). RFC 4588 section 7: the
1843    /// sender "MAY selectively retransmit only the packets that it deems important and ignore
1844    /// NACK messages for other packets"; RFC 8834 section 6.1: "It is not appropriate to blindly
1845    /// retransmit RTP packets in response to a NACK." A request for a packet whose
1846    /// retransmission the receiver got crossed that retransmission on the way (the receiver
1847    /// asks again while the packet is missing, and it waited in the path's queue): it is not
1848    /// answered. One whose retransmission was lost is answered at once.
1849    fn repairs_reported(&mut self, now: Instant, report: &crate::RetransmissionsReported) {
1850        self.repairs_reported = true;
1851        // The clock first: a report counts only for what is still remembered at `now`.
1852        self.expire_repairs(now);
1853        let mut delivered = Vec::new();
1854        for reported in &report.received {
1855            let Some(media) = self.media_ssrc(reported.ssrc) else {
1856                continue;
1857            };
1858            let seq = reported.sequence_number;
1859            // Of this packet (not an earlier one of the same number), and not known already:
1860            // a report that comes again does not begin the memory again.
1861            if let Some(repair) = self.repair(media, seq, now)
1862                && self.holds(media, seq, repair.packet)
1863                && reported.sent >= repair.first_made
1864                && !matches!(repair.state, RepairState::Delivered { .. })
1865                && let Some(repair) = self
1866                    .streams
1867                    .get_mut(&media)
1868                    .and_then(|stream| stream.repairs.get_mut(&seq))
1869            {
1870                repair.state = RepairState::Delivered { reported: now };
1871                delivered.push((media, seq));
1872            }
1873        }
1874        for reported in &report.lost {
1875            let Some(media) = self.media_ssrc(reported.ssrc) else {
1876                continue;
1877            };
1878            let seq = reported.sequence_number;
1879            // The latest retransmission of this packet was lost: asked for again, it is
1880            // answered. The loss of an earlier one says nothing of the one on its way.
1881            if let Some(repair) = self.repair(media, seq, now)
1882                && reported.sent >= repair.made
1883                && matches!(
1884                    repair.state,
1885                    RepairState::Unreported { .. } | RepairState::Overdue { .. }
1886                )
1887                && let Some(stream) = self.streams.get_mut(&media)
1888            {
1889                stream.repairs.remove(&seq);
1890            }
1891        }
1892        if !delivered.is_empty() {
1893            let asked = &mut self.pending_asked;
1894            let octets = &mut self.pending_octets;
1895            self.pending.retain(|entry| {
1896                let key = (entry.ssrc, entry.sequence_number);
1897                let keep = !delivered.contains(&key);
1898                if !keep {
1899                    asked.remove(&key);
1900                    *octets -= entry.octets;
1901                }
1902                keep
1903            });
1904        }
1905        self.release_at = None;
1906    }
1907
1908    /// What RFC 8888 congestion control feedback (`CcFeedbackReport`) in `rtcp_packets` says
1909    /// of the retransmissions: it reports the packets of the RTX stream under their own
1910    /// sequence numbers, each mapped back to the packet it repaired. The counterpart of the
1911    /// TWCC sender's [`RetransmissionsReported`](crate::RetransmissionsReported) for streams
1912    /// whose feedback is RFC 8888.
1913    fn ccfb_report(
1914        &self,
1915        rtcp_packets: &[Box<dyn rtcp::Packet>],
1916    ) -> crate::RetransmissionsReported {
1917        let mut report = crate::RetransmissionsReported::default();
1918        for feedback in rtcp_packets.iter().filter_map(|packet| {
1919            packet
1920                .as_any()
1921                .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>()
1922        }) {
1923            let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
1924            for (ssrc, acknowledgements) in per_stream {
1925                let Some(stream) = self
1926                    .streams
1927                    .values()
1928                    .find(|stream| stream.ssrc_rtx == Some(ssrc))
1929                else {
1930                    continue;
1931                };
1932                for acknowledgement in acknowledgements {
1933                    if let Some(&(sequence_number, sent)) =
1934                        stream.repairs_by_rtx.get(&acknowledgement.sequence_number)
1935                    {
1936                        let reported = crate::ReportedRetransmission {
1937                            ssrc,
1938                            sequence_number,
1939                            sent,
1940                        };
1941                        if acknowledgement.arrived {
1942                            report.received.push(reported);
1943                        } else {
1944                            report.lost.push(reported);
1945                        }
1946                    }
1947                }
1948            }
1949        }
1950        report
1951    }
1952
1953    /// Handle a NACK request by queuing retransmissions.
1954    fn handle_nack(
1955        &mut self,
1956        now: Instant,
1957        nack: &rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack,
1958    ) {
1959        // Collect sequence numbers to retransmit
1960        let mut seqs_to_retransmit = Vec::new();
1961
1962        for nack_pair in &nack.nacks {
1963            // Check the base packet ID
1964            seqs_to_retransmit.push(nack_pair.packet_id);
1965
1966            // Check each bit in lost_packets bitmap
1967            for i in 0..16 {
1968                if nack_pair.lost_packets & (1 << i) != 0 {
1969                    let seq = nack_pair.packet_id.wrapping_add(i + 1);
1970                    seqs_to_retransmit.push(seq);
1971                }
1972            }
1973        }
1974
1975        let ssrc = nack.media_ssrc;
1976        let resend_interval = resend_interval(self.round_trip_time);
1977        let Some(stream) = self.streams.get_mut(&ssrc) else {
1978            return;
1979        };
1980
1981        // A NACK may name the same packet in several pairs; resend each once.
1982        seqs_to_retransmit.sort_unstable();
1983        seqs_to_retransmit.dedup();
1984        // Forget suppression entries old enough not to matter.
1985        stream
1986            .last_retransmit
1987            .retain(|_, at| now.saturating_duration_since(*at) < resend_interval);
1988
1989        // A packet asked for that was written too long ago to be of use
1990        // (`with_max_repair_age`). For a video stream the repair of everything sent so far
1991        // is given up and a key frame asked for; an audio packet is simply not retransmitted
1992        // (`retransmittable`). Only a packet that would be answered counts: one without a
1993        // repair form (a FEC packet in RED on a stream without RTX, a payload type without
1994        // an RTX format on a stream that has RTX) is never sent again, so the receiver is
1995        // not kept waiting for a picture by it, and it is skipped here as it is below.
1996        if let Some(stream) = self.streams.get(&ssrc)
1997            && stream.video
1998            && seqs_to_retransmit.iter().any(|seq| {
1999                stream
2000                    .send_buffer
2001                    .get(*seq)
2002                    .and_then(|packet| stream.repair_form(packet))
2003                    .is_some_and(|form| self.too_old(stream, form, *seq, now))
2004            })
2005        {
2006            self.give_up(now, &[ssrc]);
2007            return;
2008        }
2009
2010        // Every packet asked for joins the requests waiting, oldest request first (one asked
2011        // for again keeps its place and is asked for afresh), and leaves as the rate limit has
2012        // room (RFC 4588 section 7): what does not fit now leaves when the window has room.
2013        for seq in seqs_to_retransmit {
2014            let Some(stream) = self.streams.get(&ssrc) else {
2015                return;
2016            };
2017            if stream.last_retransmit.contains_key(&seq) {
2018                continue;
2019            }
2020            let Some(octets) = self.retransmittable(stream, seq, now) else {
2021                continue;
2022            };
2023            if self.in_pacer(ssrc, seq, now)
2024                || self.repeat_state((ssrc, seq), now) == Repeat::Decline
2025            {
2026                continue;
2027            }
2028            let Some(stream) = self.streams.get(&ssrc) else {
2029                return;
2030            };
2031            let budget = stream.retransmit_budget;
2032            let Some(packet) = stream.packet(seq) else {
2033                continue;
2034            };
2035            // A request still waiting under this number for a packet since replaced ends here.
2036            if self
2037                .pending_asked
2038                .get(&(ssrc, seq))
2039                .is_some_and(|(_, waiting)| *waiting != packet)
2040                && let Some(waiting) = self
2041                    .pending
2042                    .iter()
2043                    .position(|waiting| waiting.ssrc == ssrc && waiting.sequence_number == seq)
2044            {
2045                self.remove_pending(waiting);
2046            }
2047            match self.pending_asked.get_mut(&(ssrc, seq)) {
2048                Some((asked, _)) => *asked = now,
2049                None => {
2050                    // The budget (one retransmission per original sent) refuses it: not
2051                    // kept, the receiver asks again. Only the rate limit makes a request wait.
2052                    if budget == 0 || self.pending.len() >= MAX_QUEUED_RETRANSMISSIONS {
2053                        break;
2054                    }
2055                    self.pending_asked.insert((ssrc, seq), (now, packet));
2056                    // A stream's oldest packet first, whenever it was asked for: a receiver
2057                    // that plays in order waits for its oldest gap, and a packet asked for
2058                    // again (its repair was lost) would otherwise wait behind every newer one.
2059                    let at = self
2060                        .pending
2061                        .iter()
2062                        .position(|waiting| {
2063                            waiting.ssrc == ssrc
2064                                && waiting.sequence_number.wrapping_sub(seq) < 0x8000
2065                        })
2066                        .unwrap_or(self.pending.len());
2067                    self.pending.insert(
2068                        at,
2069                        PendingRetransmission {
2070                            ssrc,
2071                            sequence_number: seq,
2072                            packet,
2073                            octets,
2074                        },
2075                    );
2076                    self.pending_octets += octets;
2077                }
2078            }
2079        }
2080        self.release_at = None;
2081        self.expire_pending(now);
2082        // The original media is lowered by the reserve before any of these is sent (RFC 4588
2083        // section 7: "the sender SHOULD NOT send retransmission packets without reducing the
2084        // packet rate and bitrate of the original stream"); the retransmissions may then use it.
2085        // A backlog the collapsed path will not carry in time is given up instead (the same
2086        // section: "If congestion is not kept under control, then retransmission SHOULD NOT
2087        // be used").
2088        self.give_up_a_backlog(now);
2089        self.announce_reserve(now, false);
2090        self.release(now);
2091    }
2092}
2093
2094/// The RTX packet (RFC 4588 section 4) that carries `original` again: the RTX SSRC and
2095/// payload type, the next sequence number of the RTX stream, and the original sequence number
2096/// ahead of the payload.
2097fn rtx_packet(
2098    rtx_sequence_number: &mut u16,
2099    rid_extension_ids: (Option<u8>, Option<u8>),
2100    original_packet: &rtp::Packet,
2101    ssrc_rtx: u32,
2102    pt_rtx: u8,
2103) -> rtp::Packet {
2104    let (rid_extension_id, repaired_rid_extension_id) = rid_extension_ids;
2105    let original_seq = original_packet.header.sequence_number;
2106    let mut rtx_payload = Vec::with_capacity(2 + original_packet.payload.len());
2107    rtx_payload.extend_from_slice(&original_seq.to_be_bytes());
2108    rtx_payload.extend_from_slice(&original_packet.payload);
2109
2110    let rtx_seq = *rtx_sequence_number;
2111    *rtx_sequence_number = rtx_sequence_number.wrapping_add(1);
2112
2113    // RFC 4588 4: the RTX packet carries the original's header "as is" apart from the SSRC,
2114    // payload type and sequence number, so its CSRCs and header extensions (audio level,
2115    // abs-send-time, mid, ...) go with it. Building a fresh header used to drop them. Version
2116    // is set explicitly: a buffered packet built with a defaulted header is version 0, which
2117    // receivers discard on arrival. Padding is not carried: the RTX payload is the original
2118    // payload alone.
2119    let mut header = original_packet.header.clone();
2120    header.version = 2;
2121    header.ssrc = ssrc_rtx;
2122    header.payload_type = pt_rtx;
2123    header.sequence_number = rtx_seq;
2124    header.padding = false;
2125    header.padding_size = 0;
2126    // RFC 8852 3.2: a repair packet names the stream it repairs with the repaired-RID, not
2127    // the RID, so a receiver never takes the RTX SSRC for a simulcast layer of its own.
2128    if let Some(rid_id) = rid_extension_id
2129        && let Some(rid) = header.get_extension(rid_id)
2130    {
2131        let _ = header.del_extension(rid_id);
2132        if let Some(repaired_id) = repaired_rid_extension_id {
2133            let _ = header.set_extension(repaired_id, rid);
2134        }
2135    }
2136
2137    rtp::Packet {
2138        header,
2139        payload: rtx_payload.into(),
2140    }
2141}
2142
2143/// A padding-only packet of the RTX stream (a bandwidth probe): `template`'s header on the RTX
2144/// SSRC and payload type with the next RTX sequence number, no payload, and
2145/// [`PROBE_PADDING_OCTETS`] of padding.
2146fn padding_packet(
2147    rtx_sequence_number: &mut u16,
2148    rid_extension_ids: (Option<u8>, Option<u8>),
2149    template: &rtp::Packet,
2150    ssrc_rtx: u32,
2151    pt_rtx: u8,
2152) -> rtp::Packet {
2153    let mut packet = rtx_packet(
2154        rtx_sequence_number,
2155        rid_extension_ids,
2156        template,
2157        ssrc_rtx,
2158        pt_rtx,
2159    );
2160    packet.payload = bytes::Bytes::new();
2161    packet.header.marker = false;
2162    packet.header.padding = true;
2163    packet.header.padding_size = PROBE_PADDING_OCTETS;
2164    packet
2165}
2166
2167impl Protocol<TaggedPacket, TaggedPacket, ()> for NackResponderInterceptor {
2168    type Rout = TaggedPacket;
2169    type Wout = TaggedPacket;
2170    type Eout = ();
2171    type Error = Error;
2172    type Time = Instant;
2173
2174    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
2175        let now = msg.now;
2176        let announced_before = self.announced_reserve;
2177        // The congestion controller's target, which the retransmissions are held to.
2178        let carries_target = if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
2179            msg.message.get(&Attribute::TargetBitrateChanged {
2180                bits_per_second: 0.0,
2181            }) {
2182            if bits_per_second.is_finite() && *bits_per_second >= 0.0 {
2183                self.target_bps = Some(*bits_per_second);
2184                self.minimum_bps = msg
2185                    .message
2186                    .custom::<MinimumTarget>()
2187                    .map(|minimum| minimum.bits_per_second)
2188                    .filter(|minimum| minimum.is_finite());
2189                self.release_at = None;
2190            }
2191            true
2192        } else {
2193            false
2194        };
2195
2196        // The round trip the RTCP session measured: the reserve's horizon.
2197        if let Some(crate::RtcpSessionEvent::RoundTripTime { rtt, .. }) =
2198            msg.message.custom::<crate::RtcpSessionEvent>()
2199        {
2200            self.round_trip_time = Some(*rtt);
2201            self.release_at = None;
2202        }
2203
2204        // While the pacer tells the source to pause, the target on the packet is zero and the
2205        // congestion controller's rides with it: the rate the retransmissions are held to.
2206        if carries_target {
2207            let pause = msg.message.custom::<crate::PacerPause>().copied();
2208            self.paused = pause.is_some();
2209            if let Some(pause) = pause
2210                && pause.target_bits_per_second.is_finite()
2211                && pause.target_bits_per_second >= 0.0
2212            {
2213                self.target_bps = Some(pause.target_bits_per_second);
2214            }
2215        }
2216
2217        if carries_target && let Some(target) = self.target_bps {
2218            self.note_target(now, target);
2219            // The target fell under what the waiting repairs need.
2220            self.give_up_a_backlog(now);
2221        }
2222
2223        // Retransmissions that left the pacer (or were dropped there).
2224        if let Some(notice) = msg.message.custom::<crate::RetransmissionsLeft>() {
2225            let notice = notice.clone();
2226            self.retransmissions_left(now, &notice);
2227        }
2228
2229        // What RFC 8888 feedback reports on the RTX streams: read here, where the sequence
2230        // number each RTX packet was given is known.
2231        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
2232            let report = self.ccfb_report(rtcp_packets);
2233            if !report.received.is_empty() || !report.lost.is_empty() {
2234                self.repairs_reported(now, &report);
2235                self.release(now);
2236            }
2237        }
2238
2239        // What transport-wide feedback reported on the retransmissions.
2240        if let Some(report) = msg.message.custom::<crate::RetransmissionsReported>() {
2241            let report = report.clone();
2242            self.repairs_reported(now, &report);
2243            // A request held for a retransmission now reported lost leaves at once.
2244            self.release(now);
2245        }
2246
2247        // Packets the pacer (wire-ward of here) discarded: never resent.
2248        if let Some(discard) = msg.message.custom::<crate::PacerDiscard>() {
2249            let discard = discard.clone();
2250            self.forget_discarded(&discard);
2251        }
2252
2253        // The pacer gave its queue up at a collapse: nothing sent before is repaired.
2254        if let Some(flush) = msg.message.custom::<crate::PacerFlush>() {
2255            let flush = flush.clone();
2256            self.forget_flushed(&flush);
2257        }
2258
2259        // A probe cluster the congestion controller asks for: fill it.
2260        if let Some(request) = msg.message.custom::<ProbeRequest>().copied() {
2261            let session = crate::RtpSession::of(&msg.message);
2262            let fill = msg
2263                .message
2264                .custom::<crate::ProbeFill>()
2265                .filter(|fill| fill.cluster == request.cluster)
2266                .map(|fill| fill.octets);
2267            self.fill_probe(now, &request, fill, session);
2268        }
2269
2270        // Process NACK packets
2271        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
2272            for rtcp_packet in rtcp_packets {
2273                if let Some(nack) = rtcp_packet
2274                    .as_any()
2275                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
2276                {
2277                    self.handle_nack(now, nack);
2278                }
2279            }
2280        }
2281        if carries_target {
2282            // A new target may leave room for what waits.
2283            self.release(now);
2284        }
2285
2286        // The application's target is the controller's less the reserve (RFC 4588 section
2287        // 7): lowered on the packet that carries it, or announced on a carrier of its own when
2288        // only the reserve moved.
2289        if !carries_target
2290            && self.announced_reserve != announced_before
2291            && let Some(target_bps) = self.target_bps
2292        {
2293            // Moved while the NACK was read: the application hears of it here.
2294            let carrier = self.target_carrier(now, target_bps, self.announced_reserve);
2295            self.read_queue.push_back(carrier);
2296        }
2297        self.announce_reserve(now, !carries_target);
2298        if carries_target && self.announced_reserve > 0.0 {
2299            let (reserve, minimum) = (self.announced_reserve, self.minimum_bps.unwrap_or(0.0));
2300            for attribute in &mut msg.message.attributes {
2301                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
2302                    *bits_per_second = media_target(*bits_per_second, reserve, minimum);
2303                }
2304            }
2305        }
2306
2307        self.read_queue.push_back(msg);
2308
2309        Ok(())
2310    }
2311
2312    fn poll_read(&mut self) -> Option<Self::Rout> {
2313        self.read_queue.pop_front()
2314    }
2315
2316    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
2317        if let Some(assignment) = msg.message.custom::<crate::RtpSessionAssignment>() {
2318            for ssrc in &assignment.ssrcs {
2319                self.sessions.insert(*ssrc, assignment.session);
2320            }
2321        }
2322        if let Some(super::NackControl::LocalRtxTime {
2323            payload_type_rtx,
2324            rtx_time,
2325        }) = msg.message.custom::<super::NackControl>()
2326        {
2327            match rtx_time {
2328                Some(rtx_time) => self.local_rtx_times.insert(*payload_type_rtx, *rtx_time),
2329                None => self.local_rtx_times.remove(payload_type_rtx),
2330            };
2331        }
2332        // Every original packet counts against the target (RFC 4588 section 7), whether or
2333        // not its stream is repaired.
2334        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
2335            && !msg.message.has(&Attribute::Retransmission)
2336        {
2337            self.originals.expire(msg.now);
2338            self.originals.add(msg.now, rtp_packet.marshal_size());
2339        }
2340        // Buffer outgoing RTP packets
2341        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
2342            && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
2343        {
2344            stream.send_buffer.add(rtp_packet.clone());
2345            stream.last_sent = Some((rtp_packet.header.sequence_number, msg.now));
2346            stream.written += 1;
2347            let slot = usize::from(rtp_packet.header.sequence_number) % stream.sent_at.len();
2348            stream.sent_at[slot] =
2349                Some((rtp_packet.header.sequence_number, msg.now, stream.written));
2350            stream.retransmit_budget =
2351                (stream.retransmit_budget + 1).min(stream.retransmit_budget_max);
2352        }
2353        if matches!(msg.message.packet, Packet::Rtp(_)) {
2354            self.release_at = None;
2355            if !self.pending.is_empty() {
2356                // The budget may have room again.
2357                self.release(msg.now);
2358            }
2359            if !self.pending.is_empty() || self.announced_reserve > 0.0 {
2360                self.announce_reserve(msg.now, true);
2361            }
2362        }
2363
2364        self.write_queue.push_back(msg);
2365
2366        Ok(())
2367    }
2368
2369    fn poll_write(&mut self) -> Option<TaggedPacket> {
2370        // First drain retransmitted packets
2371        let packet = self.write_queue.pop_front()?;
2372        if packet.message.has(&Attribute::Retransmission) {
2373            self.retransmissions_queued = self.retransmissions_queued.saturating_sub(1);
2374        }
2375        Some(packet)
2376    }
2377
2378    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
2379        // What is remembered of retransmissions ends by this clock, with or without a
2380        // request or a report to end it.
2381        self.expire_repairs(now);
2382        if !self.pending.is_empty() || self.announced_reserve > 0.0 {
2383            // Worked out afresh: a deadline that passed without a change must not be handed
2384            // back again (a driver would spin on it).
2385            self.release_at = None;
2386            self.expire_pending(now);
2387            self.give_up_a_backlog(now);
2388            self.release(now);
2389            self.announce_reserve(now, true);
2390        }
2391        Ok(())
2392    }
2393
2394    /// Due at once while packets wait in the write queue. A retransmission or a probe cluster's
2395    /// padding is made on the read leg (a NACK, a [`ProbeRequest`]), which a driver reaches
2396    /// after its `poll_write` (`poll_write`, `poll_event`, `poll_read`, then `poll_timeout`
2397    /// and sleep, as the crate's event loop has it): without a deadline the packets would wait
2398    /// for whatever wakes the driver next, a timer or an incoming datagram, which can be a
2399    /// long time on a connection with little traffic. The deadline is the instant they were
2400    /// made, so the driver's `handle_timeout` and the `poll_write` after it take them out at
2401    /// once; it is gone when the queue is drained.
2402    ///
2403    /// A retransmission the rate limit holds back is not in the write queue: its deadline is
2404    /// the instant the limit next has room for it ([`Self::next_release`]), never earlier (a
2405    /// driver woken at once would spin), and the same for a waiting request running out and
2406    /// the reserve falling back to zero.
2407    fn poll_timeout(&mut self) -> Option<Self::Time> {
2408        let queued = self.write_queue.front().map(|packet| packet.now);
2409        queued.into_iter().chain(self.next_release()).min()
2410    }
2411}
2412
2413impl Interceptor for NackResponderInterceptor {
2414    fn bind_local_stream(&mut self, info: &StreamInfo) {
2415        if stream_supports_nack(info)
2416            && let Some(send_buffer) = SendBuffer::new(self.size)
2417        {
2418            // RFC 4588 4: the initial sequence number of the retransmission stream is random
2419            // (RFC 3550 5.1), and the stream is the RTX SSRC's, not the binding's: a stream
2420            // bound again continues where the SSRC left off.
2421            let rtx_sequence_number = info
2422                .ssrc_rtx
2423                .and_then(|ssrc_rtx| self.rtx_sequence_numbers.get(&ssrc_rtx).copied())
2424                .unwrap_or_else(rand::random::<u16>);
2425            self.streams.insert(
2426                info.ssrc,
2427                LocalStream {
2428                    send_buffer,
2429                    ssrc_rtx: info.ssrc_rtx,
2430                    payload_type_rtx: info.payload_type_rtx,
2431                    payload_type: info.payload_type,
2432                    rtx_payload_types: section_rtx_payload_types(info),
2433                    fec_in_red: section_fec_in_red(info),
2434                    rtx_sequence_number,
2435                    last_sent: None,
2436                    last_retransmit: HashMap::new(),
2437                    rid_extension_id: extension_id(info, RTP_STREAM_ID_URI),
2438                    repaired_rid_extension_id: extension_id(info, REPAIRED_RTP_STREAM_ID_URI),
2439                    retransmit_budget: usize::from(self.size),
2440                    retransmit_budget_max: usize::from(self.size),
2441                    sent_at: vec![None; usize::from(self.size).max(1)],
2442                    written: 0,
2443                    repairs: HashMap::new(),
2444                    repairs_by_rtx: HashMap::new(),
2445                    repairs_order: VecDeque::new(),
2446                    video: !info.mime_type.to_ascii_lowercase().starts_with("audio/"),
2447                    probe_template: None,
2448                },
2449            );
2450        }
2451    }
2452
2453    fn unbind_local_stream(&mut self, info: &StreamInfo) {
2454        if let Some(stream) = self.streams.remove(&info.ssrc)
2455            && let Some(ssrc_rtx) = stream.ssrc_rtx
2456        {
2457            if self.rtx_sequence_numbers.len() >= MAX_REMEMBERED_RTX_SSRCS
2458                && !self.rtx_sequence_numbers.contains_key(&ssrc_rtx)
2459            {
2460                self.rtx_sequence_numbers.clear();
2461            }
2462            self.rtx_sequence_numbers
2463                .insert(ssrc_rtx, stream.rtx_sequence_number);
2464        }
2465    }
2466
2467    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
2468
2469    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
2470}
2471
2472#[cfg(test)]
2473mod tests {
2474    use super::*;
2475    use crate::stream_info::RTCPFeedback;
2476    use rtcp::transport_feedbacks::transport_layer_nack::{
2477        TransportLayerNack, nack_pairs_from_sequence_numbers,
2478    };
2479    use std::sync::Arc;
2480
2481    const SSRC: u32 = 0x1234;
2482    const RTX_SSRC: u32 = 0x5678;
2483    const SIZE: u16 = 64;
2484
2485    fn responder() -> NackResponderInterceptor {
2486        let mut responder = NackResponderBuilder::new()
2487            .with_size(SIZE)
2488            .with_rate_limit(RetransmissionRateLimit::Unlimited)
2489            .build();
2490        responder.bind_local_stream(&StreamInfo {
2491            ssrc: SSRC,
2492            ssrc_rtx: Some(RTX_SSRC),
2493            payload_type_rtx: Some(97),
2494            payload_type: 96,
2495            rtcp_feedback: vec![RTCPFeedback {
2496                typ: "nack".to_string(),
2497                parameter: String::new(),
2498            }],
2499            ..Default::default()
2500        });
2501        responder
2502    }
2503
2504    fn tagged(now: Instant, message: AttributedPacket) -> TaggedPacket {
2505        TaggedPacket {
2506            now,
2507            transport: TransportContext::default(),
2508            message,
2509        }
2510    }
2511
2512    fn original(responder: &mut NackResponderInterceptor, now: Instant, sequence_number: u16) {
2513        let packet = rtp::Packet {
2514            header: rtp::header::Header {
2515                version: 2,
2516                payload_type: 96,
2517                sequence_number,
2518                ssrc: SSRC,
2519                ..Default::default()
2520            },
2521            payload: vec![0u8; 100].into(),
2522        };
2523        responder
2524            .handle_write(tagged(now, AttributedPacket::new(Packet::Rtp(packet))))
2525            .unwrap();
2526    }
2527
2528    /// The sizes of everything the responder remembers of repairs and requests.
2529    fn remembered(responder: &NackResponderInterceptor) -> [usize; 5] {
2530        let stream = &responder.streams[&SSRC];
2531        [
2532            stream.repairs.len(),
2533            stream.repairs_by_rtx.len(),
2534            stream.repairs_order.len(),
2535            responder.pending.len(),
2536            responder.pending_asked.len(),
2537        ]
2538    }
2539
2540    /// A receiver that asks for everything, over and over, and reports whatever it likes of
2541    /// the retransmissions (received, lost, both, for packets retransmitted or not, with any
2542    /// instant) cannot make the responder remember more than its send buffer has places:
2543    /// what is kept of repairs is at most one entry per packet held. And the engine's clock
2544    /// alone empties it: with no further request or report, a timeout past the longest
2545    /// memory leaves nothing.
2546    #[test]
2547    fn requests_and_reports_without_end_do_not_grow_what_is_remembered() {
2548        let mut responder = responder();
2549        let base = Instant::now();
2550        let size = usize::from(SIZE);
2551        let mut now = base;
2552        let mut most = 0;
2553        // Reports come and a pacer is there, so every state is in use. From step 10 000 the
2554        // pacer says nothing more, and from step 20 000 no report comes either: every
2555        // retransmission then stays "in the pacer", the one state kept for whatever packet has
2556        // the number, for four seconds (8 000 steps) while the buffer turns over every 64.
2557        for step in 0..30_000u32 {
2558            now = base + Duration::from_micros(500) * step;
2559            let sequence_number = step as u16;
2560            original(&mut responder, now, sequence_number);
2561            // Ask for the whole buffer, and for numbers far outside it.
2562            let mut asked: Vec<u16> = (0..SIZE)
2563                .map(|back| sequence_number.wrapping_sub(back))
2564                .collect();
2565            asked.extend((0..SIZE).map(|far| sequence_number.wrapping_add(0x4000 + far * 97)));
2566            asked.sort_unstable();
2567            responder
2568                .handle_read(tagged(
2569                    now,
2570                    AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerNack {
2571                        sender_ssrc: 1,
2572                        media_ssrc: SSRC,
2573                        nacks: nack_pairs_from_sequence_numbers(&asked),
2574                    })])),
2575                ))
2576                .unwrap();
2577            // Reports on every sequence number there is, a different mix each time.
2578            let reported = |sequence_number: u16| crate::ReportedRetransmission {
2579                ssrc: RTX_SSRC,
2580                sequence_number,
2581                sent: now,
2582            };
2583            let numbers =
2584                (0..512u16).map(|index| index.wrapping_mul(128).wrapping_add(step as u16));
2585            let report = match step % 3 {
2586                0 => crate::RetransmissionsReported {
2587                    received: numbers.map(reported).collect(),
2588                    lost: vec![],
2589                },
2590                1 => crate::RetransmissionsReported {
2591                    received: vec![],
2592                    lost: numbers.map(reported).collect(),
2593                },
2594                _ => crate::RetransmissionsReported {
2595                    received: asked.iter().copied().map(reported).collect(),
2596                    lost: asked.iter().copied().map(reported).collect(),
2597                },
2598            };
2599            let mut message = AttributedPacket::new(Packet::Rtcp(vec![]))
2600                .with(Attribute::Custom(Arc::new(report)));
2601            if step < 10_000 && step % 7 == 0 {
2602                // The pacer's notices, as arbitrary.
2603                message.add(Attribute::Custom(Arc::new(crate::RetransmissionsLeft {
2604                    departed: asked.iter().map(|seq| (RTX_SSRC, *seq)).collect(),
2605                    dropped: vec![(RTX_SSRC, sequence_number)],
2606                })));
2607            }
2608            if step < 20_000 {
2609                responder.handle_read(tagged(now, message)).unwrap();
2610            }
2611            while responder.poll_write().is_some() {}
2612            while responder.poll_read().is_some() {}
2613            let [repairs, by_rtx, order, pending, asked] = remembered(&responder);
2614            assert!(
2615                repairs <= size && by_rtx <= size && order <= size,
2616                "step {step}: {repairs} repairs, {by_rtx} RTX numbers ({order}) remembered, \
2617                 the buffer holds {size}"
2618            );
2619            assert!(pending <= MAX_QUEUED_RETRANSMISSIONS && asked == pending);
2620            most = most.max(repairs);
2621        }
2622        assert!(
2623            most > size / 2,
2624            "most of the buffer's places were remembered at some point: {most} of {size}"
2625        );
2626        // Nothing more arrives. The clock alone:
2627        responder
2628            .handle_timeout(now + Duration::from_secs(30))
2629            .unwrap();
2630        assert_eq!([0; 5], remembered(&responder));
2631    }
2632
2633    /// What is remembered of a repair ends with the engine's clock at a timeout, with no
2634    /// request and no report to end it: a retransmission reported received is forgotten four
2635    /// seconds after the report.
2636    #[test]
2637    fn a_timeout_alone_ends_the_memory_of_a_delivered_retransmission() {
2638        let mut responder = responder();
2639        let base = Instant::now();
2640        for sequence_number in 0..10 {
2641            original(&mut responder, base, sequence_number);
2642        }
2643        let at = |milliseconds: u64| base + Duration::from_millis(milliseconds);
2644        responder
2645            .handle_read(tagged(
2646                at(100),
2647                AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerNack {
2648                    sender_ssrc: 1,
2649                    media_ssrc: SSRC,
2650                    nacks: nack_pairs_from_sequence_numbers(&[3]),
2651                })])),
2652            ))
2653            .unwrap();
2654        responder
2655            .handle_read(tagged(
2656                at(200),
2657                AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(
2658                    crate::RetransmissionsReported {
2659                        received: vec![crate::ReportedRetransmission {
2660                            ssrc: RTX_SSRC,
2661                            sequence_number: 3,
2662                            sent: at(100),
2663                        }],
2664                        lost: vec![],
2665                    },
2666                ))),
2667            ))
2668            .unwrap();
2669        let state = |responder: &NackResponderInterceptor| {
2670            responder.streams[&SSRC]
2671                .repairs
2672                .get(&3)
2673                .map(|repair| repair.state)
2674        };
2675        assert_eq!(
2676            Some(RepairState::Delivered { reported: at(200) }),
2677            state(&responder)
2678        );
2679        responder.handle_timeout(at(4_199)).unwrap();
2680        assert!(state(&responder).is_some(), "1 ms before the memory ends");
2681        responder.handle_timeout(at(4_200)).unwrap();
2682        assert_eq!(None, state(&responder));
2683    }
2684}