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, ProbeUnsent};
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::{BTreeSet, HashMap, HashSet, 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    /// Whether probe clusters are filled with padding-only packets.
44    probe_padding: bool,
45}
46
47impl Default for NackResponderBuilder {
48    fn default() -> Self {
49        Self {
50            size: 1024,
51            max_packet_age: None,
52            rate_limit: RetransmissionRateLimit::default(),
53            max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
54            max_repair_age: Some(MAX_REPAIR_AGE),
55            repair_backlog_bound: Some(REPAIR_BACKLOG_BOUND),
56            probe_padding: true,
57        }
58    }
59}
60
61/// How the NACK responder holds its retransmissions to the congestion controller's target
62/// (RFC 4588 section 7), read from [`Attribute::TargetBitrateChanged`] as it passes on the read
63/// leg. Until a target has passed, and in a chain without a congestion controller, nothing is
64/// held back.
65///
66/// The rate is counted over the last [`RETRANSMISSION_RATE_WINDOW`]. A NACKed packet that
67/// does not fit now waits, oldest request first, and leaves when the window has room for it
68/// ([`poll_timeout`](sansio::Protocol::poll_timeout) is that instant), for as long as the
69/// receiver keeps asking for it ([`PENDING_REQUEST_LIFETIME`]). Section 7 lets the sender
70/// "selectively retransmit only the packets that it deems important and ignore NACK messages
71/// for other packets in order to limit the bitrate": a packet still asked for is the one
72/// deemed important, one the receiver stopped asking for is dropped.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74#[non_exhaustive]
75pub enum RetransmissionRateLimit {
76    /// RFC 4588 section 7, both halves: "the acceptable packet rate and bitrate include both
77    /// the original and retransmitted data", and "the sender SHOULD NOT send retransmission
78    /// packets without reducing the packet rate and bitrate of the original stream (for
79    /// example, by encoding the data at a lower rate)".
80    ///
81    /// Retransmissions take what the original packets of every local stream leave of the
82    /// target. While retransmissions wait or were sent within the window, the target reported
83    /// for the original media is the congestion controller's less a **retransmission
84    /// reserve**: on the read leg [`Attribute::TargetBitrateChanged`] is lowered by it on its
85    /// way to the application, and [`RetransmissionReserve`] rides down the write leg to the
86    /// congestion controller, whose handle (`GccHandle::target_bitrate_bps`,
87    /// `CongestionControlHandle::target_bitrate`) reports the lowered target and keeps the
88    /// estimate itself readable (`estimate_bps`, `estimate_bitrate`). An encoder that follows
89    /// the target leaves the reserve free, so the repairs have room.
90    ///
91    /// The reserve is what the waiting requests need to leave within about one round trip
92    /// (their octets over the round-trip time the RTCP session measured, at most
93    /// [`RETRANSMISSION_RATE_WINDOW`]), or the retransmission rate of the window when that is
94    /// more, and never more than [`MAX_RETRANSMISSION_RESERVE`] of the target
95    /// ([`NackResponderBuilder::with_max_reserve_fraction`]). It is released as the requests
96    /// are served and the retransmissions leave the window: with nothing waiting and nothing
97    /// retransmitted within the last window it is zero.
98    ///
99    /// **At the congestion controller's floor.** The controller's minimum bit rate is this
100    /// engine's setting, not the RFC's, and the controller announces it with its target
101    /// ([`MinimumTarget`]). The original media is never told less than that minimum (the least
102    /// the application set its media to need). When lowering the original media by the reserve
103    /// would take it under that floor (target − reserve < minimum), it cannot make the room:
104    /// an encoder at its own minimum already fills the floor (in the capacity-cap test, 30
105    /// kbit/s of video and 80 kbit/s of audio against a 100 kbit/s target), and the rule above
106    /// would leave the repairs nothing for as long as the estimate stays near the floor. There
107    /// the retransmissions of packets still asked for take the window's room first: they may
108    /// send up to the target within the window, whatever the original packets took, and the
109    /// original media is told the target less the reserve. Section 7 lets the sender
110    /// "selectively retransmit only the packets that it deems important"; a packet still asked
111    /// for is the one deemed important. An application at its minimum adds its own excess
112    /// over the floor; the retransmissions never go over the target.
113    ///
114    /// What holds the sum on the wire when the application ignores the lowered target: with
115    /// a pacer in the chain (the default interceptor set) the pacer sends at the controller's
116    /// target, retransmissions and media alike; without one (a chain of NACK, TWCC and GCC
117    /// alone) it is this rule: above the floor the retransmissions take only what the
118    /// original packets leave, so the engine never adds to an application's excess; near the
119    /// floor (target under the minimum plus the reserve, at most twice the minimum with the
120    /// default reserve) they take at most the target.
121    #[default]
122    WithinTarget,
123    /// A rate limiter on the retransmissions alone, its maximum the target (the form of
124    /// libwebrtc's `RtpSender` when it is given a `retransmission_rate_limiter`,
125    /// `modules/rtp_rtcp/source/rtp_sender.cc`): the retransmissions stay under the target
126    /// whatever the original packets take, and the target reported for the original media is
127    /// not lowered, so the sum may reach twice the target. A setting in no behaviour profile:
128    /// libwebrtc gives its video senders no such limiter (`call/rtp_video_sender.cc:292-354`
129    /// at a222406d; `rtp_rtcp_interface.h:92` defaults it to null) and lowers the encoder
130    /// target by the protection share instead. Measured in
131    /// `tests/capacity_cap_video_rtc2rtc.rs` against the default: longest freeze 0.84 to
132    /// 1.29 s against 0.83 to 1.24 s, 17 to 27 retransmissions dropped at the capped link
133    /// against 14 to 17.
134    UpToTarget,
135    /// No limit beyond the per-stream budget (one retransmission per original packet sent): the
136    /// fork's behaviour before. Retransmissions are then not congestion controlled.
137    Unlimited,
138}
139
140/// The window [`RetransmissionRateLimit`] measures the rates over (libwebrtc's
141/// `kRetransmitWindowSizeMs`).
142pub const RETRANSMISSION_RATE_WINDOW: Duration = Duration::from_secs(1);
143
144/// The most of the congestion controller's target the retransmission reserve of
145/// [`RetransmissionRateLimit::WithinTarget`] takes, by default: half.
146pub const MAX_RETRANSMISSION_RESERVE: f64 = 0.5;
147
148/// A request that waits for room is dropped when the receiver has not asked for the packet
149/// again within this long, or within two round trips when that is longer: a receiver asks
150/// again every round trip while the packet is missing, so one that stopped asking has the
151/// packet or no longer wants it.
152pub const PENDING_REQUEST_LIFETIME: Duration = Duration::from_secs(1);
153
154/// The shortest round trip the reserve spreads the waiting requests over.
155const MIN_RESERVE_HORIZON: Duration = Duration::from_millis(10);
156
157/// The retransmission reserve of [`RetransmissionRateLimit::WithinTarget`], in bits per
158/// second: the part of the congestion controller's target kept for retransmissions, which the
159/// target reported for the original media leaves out.
160///
161/// The NACK responder sends it down the write leg (on a packet of its own, an empty RTCP
162/// carrier, when it changes), so a congestion controller wire-ward of it reports the lowered
163/// target through its handle. Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub struct RetransmissionReserve {
166    /// The reserve, bits per second.
167    pub bits_per_second: f64,
168}
169
170/// Rides with [`Attribute::TargetBitrateChanged`]: the congestion controller's minimum bit
171/// rate, the floor its target never goes under. Where lowering the original media by the
172/// retransmission reserve would take it under this floor the NACK responder lets the
173/// retransmissions take the window's room first ([`RetransmissionRateLimit::WithinTarget`]).
174/// Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
175#[derive(Debug, Clone, Copy, PartialEq)]
176pub struct MinimumTarget {
177    /// The minimum, bits per second.
178    pub bits_per_second: f64,
179}
180
181/// The target for the original media: the controller's `target` less the `reserve`, never
182/// under the controller's `minimum` (the least the application set its media to need; near it
183/// the retransmissions take the room first instead, see [`RetransmissionRateLimit::WithinTarget`]).
184fn media_target(target: f64, reserve: f64, minimum: f64) -> f64 {
185    (target - reserve).max(minimum.min(target)).max(0.0)
186}
187
188/// How much the reported reserve may move before a new one is announced: 5 % of the target,
189/// at least 5 kbit/s, and any change to or from zero.
190fn reserve_moved(announced: f64, reserve: f64, target_bps: f64) -> bool {
191    (announced == 0.0) != (reserve == 0.0)
192        || (reserve - announced).abs() >= (0.05 * target_bps).max(5_000.0)
193}
194
195/// Octets sent within the last [`RETRANSMISSION_RATE_WINDOW`].
196#[derive(Default)]
197struct RateWindow {
198    sent: VecDeque<(Instant, usize)>,
199    octets: usize,
200}
201
202/// The instant at which the entries of `windows` leaving [`RETRANSMISSION_RATE_WINDOW`] have
203/// freed `deficit` octets, oldest first; `None` if all of them together free less.
204fn freed_at(windows: &[&RateWindow], deficit: usize) -> Option<Instant> {
205    let mut cursors = vec![0usize; windows.len()];
206    let mut freed = 0usize;
207    loop {
208        let (index, &(at, octets)) = windows
209            .iter()
210            .zip(&cursors)
211            .enumerate()
212            .filter_map(|(index, (window, &cursor))| window.sent.get(cursor).map(|e| (index, e)))
213            .min_by_key(|(_, (at, _))| *at)?;
214        cursors[index] += 1;
215        freed += octets;
216        if freed >= deficit {
217            return Some(at + RETRANSMISSION_RATE_WINDOW);
218        }
219    }
220}
221
222/// A NACKed packet waiting for room in the rate limit.
223struct PendingRetransmission {
224    ssrc: u32,
225    sequence_number: u16,
226    /// The packet asked for: its serial in the stream. The request is for that packet, not
227    /// for whichever has the sequence number when there is room.
228    packet: u64,
229    /// The size its retransmission has on the wire.
230    octets: usize,
231}
232
233impl RateWindow {
234    fn expire(&mut self, now: Instant) {
235        while let Some(&(at, octets)) = self.sent.front() {
236            if now.saturating_duration_since(at) < RETRANSMISSION_RATE_WINDOW {
237                break;
238            }
239            self.sent.pop_front();
240            self.octets -= octets;
241        }
242    }
243
244    fn add(&mut self, now: Instant, octets: usize) {
245        self.sent.push_back((now, octets));
246        self.octets += octets;
247    }
248
249    /// Takes back `octets` added at `at`, if the entry is still in the window.
250    fn forget(&mut self, at: Instant, octets: usize) {
251        if let Some(entry) = self
252            .sent
253            .iter_mut()
254            .rev()
255            .find(|(sent, size)| *sent == at && *size == octets)
256        {
257            entry.1 = 0;
258            self.octets -= octets;
259        }
260    }
261}
262
263impl NackResponderBuilder {
264    /// Create a new builder with default settings.
265    pub fn new() -> Self {
266        Self::default()
267    }
268
269    /// Set the size of the send buffer.
270    ///
271    /// Size must be a power of 2 between 1 and 32768 (inclusive).
272    /// Larger buffers can retransmit older packets but use more memory.
273    pub fn with_size(mut self, size: u16) -> Self {
274        self.size = size;
275        self
276    }
277
278    /// Set how long a sent packet is kept for retransmission: the `rtx-time` of RFC 4588
279    /// 8.1, when one is signalled. A NACK for a packet sent longer ago is not answered.
280    ///
281    /// Default: `None`, a packet is available for as long as the buffer holds it.
282    pub fn with_max_packet_age(mut self, max_packet_age: Option<Duration>) -> Self {
283        self.max_packet_age = max_packet_age;
284        self
285    }
286
287    /// Set how retransmissions are held to the congestion controller's target (RFC 4588
288    /// section 7). Default: [`RetransmissionRateLimit::WithinTarget`], the RFC's form;
289    /// [`RetransmissionRateLimit::UpToTarget`] is the limiter libwebrtc's `RtpSender` has
290    /// when it is given one.
291    pub fn with_rate_limit(mut self, rate_limit: RetransmissionRateLimit) -> Self {
292        self.rate_limit = rate_limit;
293        self
294    }
295
296    /// Set the most of the congestion controller's target the retransmission reserve of
297    /// [`RetransmissionRateLimit::WithinTarget`] takes, from 0 (no reserve: the target is
298    /// never lowered) to 1. Default: [`MAX_RETRANSMISSION_RESERVE`].
299    pub fn with_max_reserve_fraction(mut self, fraction: f64) -> Self {
300        self.max_reserve_fraction = if fraction.is_finite() {
301            fraction.clamp(0.0, 1.0)
302        } else {
303            MAX_RETRANSMISSION_RESERVE
304        };
305        self
306    }
307
308    /// Set how old a packet may be and still be repaired: a NACK for a packet written to the
309    /// responder longer ago is declined (RFC 8834 section 6.1: "the likelihood of them
310    /// arriving in time to be useful need[s] to be considered before RTP retransmission is
311    /// used"; RFC 4588 section 7: the sender "MAY selectively retransmit only the packets that
312    /// it deems important and ignore NACK messages for other packets").
313    ///
314    /// A receiver that still asks for a video packet that old is waiting for a picture
315    /// nobody can use, so the first such request **gives the stream up**: everything sent on
316    /// it so far is forgotten (its buffer, the requests waiting), the retransmission reserve
317    /// they held is released at once, and the application is asked for a key frame (a Picture
318    /// Loss Indication with sender SSRC 0, `RTCPeerConnectionEvent::OnKeyFrameRequest`, as at
319    /// the pacer's flush). What is written afterwards is buffered and repaired as ever. An
320    /// audio packet that old is not retransmitted and nothing else happens.
321    ///
322    /// Default: [`MAX_REPAIR_AGE`]. `None`: a packet is repaired for as long as the buffer
323    /// holds it. This is the sender's own judgement and is not announced.
324    ///
325    /// **An `rtx-time` takes its place.** RFC 4588 section 8.1: `rtx-time` is "the maximum
326    /// time a sender will keep an original RTP packet in its buffers available for
327    /// retransmission". Where one is in force for a stream (announced in the session
328    /// description or set by the application for its retransmission format,
329    /// [`NackControl::LocalRtxTime`](super::NackControl::LocalRtxTime), or configured with
330    /// [`with_max_packet_age`](Self::with_max_packet_age)), that is how old a packet of the
331    /// stream may be and still be repaired, whether shorter or longer than this setting, and
332    /// this setting does nothing for the stream: a packet older than the `rtx-time` is not
333    /// retransmitted and nothing else happens (the stream is not given up, no key frame is
334    /// asked for: the receiver was told the time and "should take into account the signalled
335    /// sender retransmission buffer length", section 8.8).
336    ///
337    /// The `rtx-time` is that of the packet's own retransmission format (RFC 4588 section 8.6:
338    /// a parameter of each RTX payload type, which `apt` ties to one original payload type):
339    /// a RED packet's is the one announced for the RTX of `red`, a plain packet's the one of
340    /// its codec's RTX. That one value decides all three for the packet: the cut at the time,
341    /// this setting where there is no time, and whether the packet's age gives the stream up.
342    /// A packet that is never sent again (a FEC packet in RED on a stream without RTX, a
343    /// payload type without an RTX format on a stream that has RTX) gives nothing up by its
344    /// age: the receiver is not waiting for a picture because of it.
345    pub fn with_max_repair_age(mut self, max_repair_age: Option<Duration>) -> Self {
346        self.max_repair_age = max_repair_age;
347        self
348    }
349
350    /// Set the backlog of repairs past which they are given up when the path's capacity has
351    /// collapsed: the requests waiting would take this long or more to leave at the congestion
352    /// controller's whole target, and the target is at most half of the highest in force
353    /// within the last two seconds. Every video stream with a request waiting is then given
354    /// up as [`with_max_repair_age`](Self::with_max_repair_age) describes (forgotten, the
355    /// reserve released, a key frame asked for). The targets from before a give-up no longer
356    /// count: the next one needs the target to halve again. RFC 4588 section 7: "If
357    /// congestion is not kept under control, then retransmission SHOULD NOT be used": such a
358    /// backlog is repaired at a rate the path drops again, for seconds, while the original
359    /// media is held at the reserve's floor.
360    ///
361    /// A backlog at a steady target (ordinary loss, however heavy) is never given up: it
362    /// is repaired within the target. Audio requests count toward the backlog and are never
363    /// given up. Without a congestion controller's target there is no such rule. An
364    /// `rtx-time` does not change it: the time is the most a packet is kept, and a collapse
365    /// ends the repairs of what was sent before it as the pacer's flush does.
366    ///
367    /// Default: [`REPAIR_BACKLOG_BOUND`]. `None`: every request is served in order.
368    pub fn with_repair_backlog_bound(mut self, bound: Option<Duration>) -> Self {
369        self.repair_backlog_bound = bound;
370        self
371    }
372
373    /// Whether a probe cluster ([`ProbeRequest`]) that the pacer's media and the FEC encoder
374    /// leave unfilled is filled with padding-only packets on the RTX stream.
375    ///
376    /// `true` by default, as libwebrtc (`modules/rtp_rtcp/source/rtp_sender.cc`,
377    /// `RTPSender::GeneratePadding`, lines 451-456 @ a222406d: what its RTX payload padding
378    /// leaves is sent as padding-only packets). `false` is RFC 7714 section 7.2's form: "It
379    /// is RECOMMENDED that the RTP padding mechanism not be used unless it is necessary to
380    /// disguise the length of the underlying Plaintext", and a probe's padding hides no
381    /// length. The cluster then carries only the media and FEC repair packets it was filled
382    /// with (RFC 8854 section 8: FEC as the probe's additional data); with nothing else to
383    /// fill it and no pacer, it is reported to the congestion controller as unsent, as
384    /// without RTX.
385    pub fn with_probe_padding(mut self, probe_padding: bool) -> Self {
386        self.probe_padding = probe_padding;
387        self
388    }
389
390    /// Build the interceptor.
391    pub fn build(self) -> NackResponderInterceptor {
392        let mut interceptor = NackResponderInterceptor::new(self.size);
393        interceptor.max_packet_age = self.max_packet_age;
394        interceptor.rate_limit = self.rate_limit;
395        interceptor.max_reserve_fraction = self.max_reserve_fraction;
396        interceptor.max_repair_age = self.max_repair_age;
397        interceptor.repair_backlog_bound = self.repair_backlog_bound;
398        interceptor.probe_padding = self.probe_padding;
399        interceptor
400    }
401}
402
403/// The RID header extension (RFC 8852 3.1).
404const RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id";
405/// The repaired-RID header extension (RFC 8852 3.2), which an RTX packet carries instead.
406const REPAIRED_RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
407/// The MID header extension (RFC 9143 section 15).
408const MID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:mid";
409
410/// The one-byte or two-byte id `info` negotiated for `uri`.
411fn extension_id(info: &StreamInfo, uri: &str) -> Option<u8> {
412    info.rtp_header_extensions
413        .iter()
414        .find(|extension| extension.uri == uri)
415        .and_then(|extension| u8::try_from(extension.id).ok())
416}
417
418/// The subtype of a MIME type (`video/rtx` -> `rtx`).
419fn subtype(mime_type: &str) -> &str {
420    mime_type
421        .rsplit_once('/')
422        .map_or(mime_type, |(_, subtype)| subtype)
423}
424
425/// The `(apt, rtx)` pairs of the retransmission formats of `info`'s m= section: every format
426/// whose MIME subtype is `rtx` and whose fmtp names an associated payload type (RFC 4588
427/// section 8.1: "apt (associated payload type) ... the value of this parameter is the
428/// payload type of the associated original stream").
429fn section_rtx_payload_types(info: &StreamInfo) -> Vec<(u8, u8)> {
430    info.section_mime_types
431        .iter()
432        .filter(|(_, mime_type)| subtype(mime_type).eq_ignore_ascii_case("rtx"))
433        .filter_map(|(rtx, _)| {
434            let (_, fmtp) = info.section_fmtp_lines.iter().find(|(pt, _)| pt == rtx)?;
435            let apt = fmtp
436                .split(';')
437                .filter_map(|parameter| parameter.trim().strip_prefix("apt="))
438                .find_map(|value| value.trim().parse::<u8>().ok())?;
439            Some((apt, *rtx))
440        })
441        .collect()
442}
443
444/// The `red` and `ulpfec` payload types of `info`'s m= section, when it has both: FEC is
445/// then sent as RED packets of the media stream (RFC 5109 section 14.2).
446fn section_fec_in_red(info: &StreamInfo) -> Option<(u8, u8)> {
447    let payload_type = |name: &str| {
448        info.section_mime_types
449            .iter()
450            .find(|(_, mime_type)| subtype(mime_type).eq_ignore_ascii_case(name))
451            .map(|(payload_type, _)| *payload_type)
452    };
453    Some((payload_type("red")?, payload_type("ulpfec")?))
454}
455
456/// How a packet asked for again is sent.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458enum RepairForm {
459    /// As a retransmission packet (RFC 4588 section 4) of this payload type on the stream's
460    /// RTX SSRC.
461    Rtx(u8),
462    /// A FEC packet ([`LocalStream::is_fec`]): a retransmission packet of this payload type
463    /// on the stream's RTX SSRC that carries the packet's sequence number and its RED block
464    /// header and none of its FEC data. See [`LocalStream::repair_form`].
465    RtxWithoutFec(u8),
466    /// The stream negotiated no retransmission format: the packet again as it was sent, on
467    /// the media SSRC under its sequence number (RFC 4585 section 6.2.1 leaves the form of a
468    /// retransmission to the sender).
469    Original,
470    /// The stream negotiated RFC 8627 FlexFEC and no RTX (section 1.1.7: an answer to an
471    /// offer of both keeps FlexFEC alone, its own retransmission in RTX's place): a FlexFEC
472    /// retransmission packet (R=1, F=0, section 4.2.2.3) on the repair stream.
473    FlexFec,
474}
475
476/// Per-stream state for the responder.
477struct LocalStream {
478    /// Buffer of sent packets for retransmission.
479    send_buffer: SendBuffer,
480    /// RTX SSRC for RFC4588 retransmission (if configured).
481    ssrc_rtx: Option<u32>,
482    /// RTX payload type for RFC4588 retransmission (if configured).
483    payload_type_rtx: Option<u8>,
484    /// The payload type the stream was bound with: the one `payload_type_rtx` repairs.
485    payload_type: u8,
486    /// The retransmission payload type of each payload type of the stream's m= section that
487    /// has one: `(apt, rtx)` for every `rtx` format the binder listed
488    /// ([`StreamInfo::section_mime_types`], [`StreamInfo::section_fmtp_lines`]). Empty when
489    /// the binder did not list the section's formats: `payload_type_rtx` then stands for
490    /// every packet. See [`LocalStream::repair_form`].
491    rtx_payload_types: Vec<(u8, u8)>,
492    /// The section's `red` and `ulpfec` payload types, when FEC is sent in RED packets of
493    /// this stream. See [`LocalStream::is_fec`].
494    fec_in_red: Option<(u8, u8)>,
495    /// Sequence number counter for RTX packets.
496    rtx_sequence_number: u16,
497    /// The sequence number of the packet sent last, and when.
498    last_sent: Option<(u16, Instant)>,
499    /// When each sequence number was last retransmitted, so a repeated NACK within
500    /// [`MIN_RETRANSMIT_INTERVAL`] does not resend it again.
501    last_retransmit: HashMap<u16, Instant>,
502    /// The RID extension id, if negotiated.
503    rid_extension_id: Option<u8>,
504    /// The repaired-RID extension id, if negotiated.
505    repaired_rid_extension_id: Option<u8>,
506    /// The MID extension id, if negotiated.
507    mid_extension_id: Option<u8>,
508    /// The MID and RID elements (id, value) of the newest packet written that carried them.
509    /// The sender stops putting them on its packets once the receiver has reported on the
510    /// stream (RFC 7941 section 4.2.3), but its RTX stream is a new SSRC to the receiver
511    /// (section 4.2.4.1): each RTX packet carries them (the RID as the repaired RID), also
512    /// when the packet it repairs went without them.
513    identifiers: Vec<(u8, bytes::Bytes)>,
514    /// Retransmissions this stream may still send: one more for each original packet sent, up
515    /// to the send buffer's size, and one less per retransmission. A NACK naming the whole buffer
516    /// may be answered once in full, but repeated NACKs cannot make the stream retransmit faster
517    /// than it sends, so the peer cannot turn its NACKs into a multiple of our send rate.
518    retransmit_budget: usize,
519    /// The budget's ceiling: the send buffer's size.
520    retransmit_budget_max: usize,
521    /// When each buffered packet was sent, by its place in the send buffer (the sequence
522    /// number modulo the buffer size), with the sequence number the entry is for and the
523    /// packet's serial (see `written`).
524    sent_at: Vec<Option<(u16, Instant, u64)>>,
525    /// How many packets of the stream were written: each packet's serial, its place in the
526    /// order written, which no later packet of the stream has again whatever its 16-bit
527    /// sequence number (the extended sequence number, without trusting the application's
528    /// numbering to be continuous).
529    written: u64,
530    /// What is remembered of the latest retransmission of a packet, by its sequence number.
531    /// Each entry names its packet by the serial, so the packet that has the 16-bit number a
532    /// cycle later does not inherit it, and each ends by the clock (see [`RepairState`]).
533    /// Never more entries than the send buffer has places.
534    repairs: Repairs,
535    /// The sequence number each recent RTX packet of this stream was given → the packet it
536    /// repairs and when the retransmission was made, oldest first in `repairs_order`: how
537    /// RFC 8888 feedback, which reports the RTX stream under its own sequence numbers, names
538    /// a retransmission.
539    repairs_by_rtx: HashMap<u16, (u16, Instant)>,
540    repairs_order: VecDeque<(u16, Instant)>,
541    /// Whether the stream is video (not audio): a key frame can be asked for it.
542    video: bool,
543    /// The RFC 8627 FlexFEC repair stream (SSRC, payload type) when the stream negotiated
544    /// FlexFEC and no RTX: its retransmissions go there in FlexFEC's retransmission form.
545    flexfec: Option<(u32, u8)>,
546    /// The newest packet the buffer held when it was last emptied (a give-up, the pacer's
547    /// flush): the header of a probe's padding until the next packet is written.
548    probe_template: Option<rtp::Packet>,
549}
550
551/// What is remembered of the retransmissions of one packet.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553struct Repair {
554    /// The packet: its serial in the stream.
555    packet: u64,
556    /// When the first retransmission of the packet that is still remembered was made: a
557    /// report on a retransmission made before it is about an earlier packet of the same
558    /// 16-bit number.
559    first_made: Instant,
560    /// When the latest retransmission was made.
561    made: Instant,
562    state: RepairState,
563}
564
565/// Where the latest retransmission of a packet is, as far as the sender knows. Every state
566/// ends by the engine's clock (the instant of the request, write, notice or timeout at hand),
567/// whether or not another report ever comes.
568#[derive(Debug, Clone, Copy, PartialEq, Eq)]
569enum RepairState {
570    /// Waiting in the pacer since it was made, for [`IN_PACER_LIFETIME`] at most. The pacer
571    /// holds one retransmission per (SSRC, 16-bit sequence number), so this one state holds
572    /// for whatever packet has the number: nothing is made for it meanwhile.
573    InPacer,
574    /// Left toward the wire at `left`, no report yet: a request is held until two round trips
575    /// and [`REPAIR_REPORT_MARGIN`] after.
576    Unreported { left: Instant },
577    /// Left at `left`, and the wait for its report ran out: requests are answered. A report
578    /// still counts until [`RETRANSMISSION_REPORT_HORIZON`](crate::RETRANSMISSION_REPORT_HORIZON)
579    /// after it left.
580    Overdue { left: Instant },
581    /// Reported received at `reported`: requests are declined for [`DELIVERED_MEMORY`].
582    Delivered { reported: Instant },
583}
584
585/// The packet the send buffer holds under `seq` (its serial), if any.
586fn held_packet(sent_at: &[Option<(u16, Instant, u64)>], seq: u16) -> Option<u64> {
587    sent_at[usize::from(seq) % sent_at.len()]
588        .filter(|(held, _, _)| *held == seq)
589        .map(|(_, _, serial)| serial)
590}
591
592/// What is remembered of the retransmissions of a stream's packets ([`Repair`] by sequence
593/// number), kept so that what ends by the clock or with its packet is ended without a pass over
594/// every entry.
595///
596/// An entry ends ([`NackResponderInterceptor::repair_ended`]) either by the clock, at an
597/// instant its state counts from plus a duration the same for every entry in that state at a
598/// given moment (the made instant plus [`IN_PACER_LIFETIME`], the departure plus the report
599/// wait or horizon, the report plus [`DELIVERED_MEMORY`]), or, outside the pacer, when the send
600/// buffer's place of its packet is written again. So each state keeps its entries ordered by
601/// that instant, and expiry takes them from the front while they are due: an entry is visited
602/// when it ends or changes state, not at every request. The entries whose place was written
603/// again are noted when it is ([`Repairs::written_over`]) and ended at the next expiry; one
604/// still in the pacer stays until its time (the pacer holds one retransmission per number,
605/// whatever packet has it) and is noted apart, for [`Repairs::retain_held`]. What expiry leaves
606/// is exactly what a pass over every entry left (review perf-1 item H2: that pass cost about
607/// 22 us per NACK with a full memory of 1024 entries, and a datagram can carry 75 NACKs).
608#[derive(Default)]
609struct Repairs {
610    entries: HashMap<u16, Repair>,
611    /// `(made, seq)` of the entries [`RepairState::InPacer`].
612    in_pacer: BTreeSet<(Instant, u16)>,
613    /// `(left, seq)` of the entries [`RepairState::Unreported`].
614    unreported: BTreeSet<(Instant, u16)>,
615    /// `(left, seq)` of the entries [`RepairState::Overdue`].
616    overdue: BTreeSet<(Instant, u16)>,
617    /// `(reported, seq)` of the entries [`RepairState::Delivered`].
618    delivered: BTreeSet<(Instant, u16)>,
619    /// Entries whose packet's place in the send buffer was written again since the last expiry.
620    written_over: Vec<u16>,
621    /// Entries in the pacer whose packet's place was written again: no longer of a packet held.
622    stale_in_pacer: HashSet<u16>,
623    /// Entries visited by [`Repairs::expire`]: the work expiry costs, which tests bound.
624    expiry_visits: u64,
625}
626
627impl Repairs {
628    fn len(&self) -> usize {
629        self.entries.len()
630    }
631
632    fn contains_key(&self, seq: u16) -> bool {
633        self.entries.contains_key(&seq)
634    }
635
636    fn get(&self, seq: u16) -> Option<&Repair> {
637        self.entries.get(&seq)
638    }
639
640    /// The queue of entries in `state`, and the instant the entry counts from there.
641    fn queue(&mut self, repair: &Repair) -> (&mut BTreeSet<(Instant, u16)>, Instant) {
642        match repair.state {
643            RepairState::InPacer => (&mut self.in_pacer, repair.made),
644            RepairState::Unreported { left } => (&mut self.unreported, left),
645            RepairState::Overdue { left } => (&mut self.overdue, left),
646            RepairState::Delivered { reported } => (&mut self.delivered, reported),
647        }
648    }
649
650    fn unqueue(&mut self, seq: u16, repair: &Repair) {
651        let (queue, at) = self.queue(repair);
652        queue.remove(&(at, seq));
653    }
654
655    fn enqueue(&mut self, seq: u16, repair: &Repair) {
656        let (queue, at) = self.queue(repair);
657        queue.insert((at, seq));
658    }
659
660    fn insert(&mut self, seq: u16, repair: Repair) {
661        if let Some(old) = self.entries.insert(seq, repair) {
662            self.unqueue(seq, &old);
663        }
664        self.stale_in_pacer.remove(&seq);
665        self.enqueue(seq, &repair);
666    }
667
668    fn remove(&mut self, seq: u16) -> Option<Repair> {
669        let repair = self.entries.remove(&seq)?;
670        self.unqueue(seq, &repair);
671        self.stale_in_pacer.remove(&seq);
672        Some(repair)
673    }
674
675    fn set_state(&mut self, seq: u16, state: RepairState) {
676        let Some(repair) = self.entries.get(&seq).copied() else {
677            return;
678        };
679        self.unqueue(seq, &repair);
680        let repair = Repair { state, ..repair };
681        self.entries.insert(seq, repair);
682        self.enqueue(seq, &repair);
683    }
684
685    fn clear(&mut self) {
686        let visits = self.expiry_visits;
687        *self = Repairs {
688            expiry_visits: visits,
689            ..Repairs::default()
690        };
691    }
692
693    /// The send buffer's place of `seq`, which held the packet `serial`, is written again: an
694    /// entry of that packet is no longer of a packet held.
695    fn written_over(&mut self, seq: u16, serial: u64) {
696        if let Some(repair) = self.entries.get(&seq)
697            && repair.packet == serial
698        {
699            self.written_over.push(seq);
700            if repair.state == RepairState::InPacer {
701                self.stale_in_pacer.insert(seq);
702            }
703        }
704    }
705
706    /// `repair` of `seq` brought up to `now` ([`NackResponderInterceptor::repair_ended`]):
707    /// ended (removed, `None`) or kept, in the state it is in now.
708    fn bring_up_to_date(
709        &mut self,
710        seq: u16,
711        packet: Option<u64>,
712        now: Instant,
713        wait: Duration,
714    ) -> Option<Repair> {
715        let mut repair = *self.entries.get(&seq)?;
716        let before = repair.state;
717        if NackResponderInterceptor::repair_ended(&mut repair, packet, now, wait) {
718            self.remove(seq);
719            return None;
720        }
721        if repair.state != before {
722            self.set_state(seq, repair.state);
723        }
724        Some(repair)
725    }
726
727    /// Takes from the front of `queue` the entries due at `now`: counted from `at`, `after`
728    /// has passed.
729    fn due(queue: &mut BTreeSet<(Instant, u16)>, now: Instant, after: Duration) -> Vec<u16> {
730        let mut due = Vec::new();
731        while let Some(&(at, seq)) = queue.first() {
732            // `now.saturating_duration_since(at) >= after`, for a positive `after`.
733            if at.checked_add(after).is_none_or(|end| now < end) {
734                break;
735            }
736            queue.pop_first();
737            due.push(seq);
738        }
739        due
740    }
741
742    /// Ends every entry that ran out by `now` ([`NackResponderInterceptor::repair_ended`] with
743    /// the report wait `wait`), and turns the waits for a report that ran out into
744    /// [`RepairState::Overdue`]: what a pass over every entry did, visiting only these.
745    fn expire(&mut self, sent_at: &[Option<(u16, Instant, u64)>], now: Instant, wait: Duration) {
746        // Outside the pacer an entry ends with its packet.
747        for seq in std::mem::take(&mut self.written_over) {
748            self.expiry_visits += 1;
749            if let Some(repair) = self.entries.get(&seq)
750                && repair.state != RepairState::InPacer
751                && held_packet(sent_at, seq) != Some(repair.packet)
752            {
753                self.remove(seq);
754            }
755        }
756        let horizon = crate::RETRANSMISSION_REPORT_HORIZON.max(wait);
757        let queues = [
758            (Self::due(&mut self.in_pacer, now, IN_PACER_LIFETIME), false),
759            // The wait for the report is never longer than the horizon: an entry not due here
760            // has not ended by the clock either.
761            (Self::due(&mut self.unreported, now, wait), true),
762            (Self::due(&mut self.overdue, now, horizon), false),
763            (Self::due(&mut self.delivered, now, DELIVERED_MEMORY), false),
764        ];
765        for (due, may_go_on) in queues {
766            for seq in due {
767                self.expiry_visits += 1;
768                // Out of its queue already; back in the right one if it goes on.
769                let Some(mut repair) = self.entries.get(&seq).copied() else {
770                    continue;
771                };
772                if may_go_on
773                    && !NackResponderInterceptor::repair_ended(
774                        &mut repair,
775                        held_packet(sent_at, seq),
776                        now,
777                        wait,
778                    )
779                {
780                    self.entries.insert(seq, repair);
781                    self.enqueue(seq, &repair);
782                } else {
783                    self.entries.remove(&seq);
784                    self.stale_in_pacer.remove(&seq);
785                }
786            }
787        }
788    }
789
790    /// Drops every entry whose packet the send buffer no longer holds under its number,
791    /// whatever its state.
792    fn retain_held(&mut self, sent_at: &[Option<(u16, Instant, u64)>]) {
793        let candidates: Vec<u16> = std::mem::take(&mut self.written_over)
794            .into_iter()
795            .chain(self.stale_in_pacer.iter().copied())
796            .collect();
797        for seq in candidates {
798            if let Some(repair) = self.entries.get(&seq)
799                && held_packet(sent_at, seq) != Some(repair.packet)
800            {
801                self.remove(seq);
802            }
803        }
804        self.stale_in_pacer.clear();
805    }
806
807    /// Every entry, in no order (tests).
808    #[cfg(test)]
809    fn iter(&self) -> impl Iterator<Item = (&u16, &Repair)> {
810        self.entries.iter()
811    }
812
813    /// Whether every entry is in the queue of its state under its instant, and nothing else is.
814    #[cfg(test)]
815    fn consistent(&self) -> bool {
816        let queued =
817            self.in_pacer.len() + self.unreported.len() + self.overdue.len() + self.delivered.len();
818        queued == self.entries.len()
819            && self.entries.iter().all(|(seq, repair)| {
820                let key = |at: Instant| (at, *seq);
821                match repair.state {
822                    RepairState::InPacer => self.in_pacer.contains(&key(repair.made)),
823                    RepairState::Unreported { left } => self.unreported.contains(&key(left)),
824                    RepairState::Overdue { left } => self.overdue.contains(&key(left)),
825                    RepairState::Delivered { reported } => self.delivered.contains(&key(reported)),
826                }
827            })
828    }
829}
830
831impl LocalStream {
832    /// Whether `packet` is a FEC packet: a RED packet of the stream whose one block is the
833    /// section's `ulpfec` format (RFC 2198 section 3: the last block header is one octet,
834    /// F = 0 and the block's payload type; RFC 5109 section 14.2).
835    ///
836    /// FEC data is not retransmitted: it repairs media that the receiver also asks for by
837    /// NACK, and the media's own retransmission is what answers the NACK. libwebrtc does not
838    /// keep FEC packets for retransmission at all (modules/rtp_rtcp/source/ulpfec_generator.cc:233
839    /// at a222406d, `red_packet->set_allow_retransmission(false)`; rtp_sender_egress.cc:316
840    /// puts a packet in the history only `if (options.is_media &&
841    /// packet->allow_retransmission())`), so a NACK that names one finds nothing
842    /// (rtp_sender.cc:348-351, `ReSendPacket`: "Packet not found or already queued for
843    /// retransmission, ignore.") and its receiver asks until the request ages out
844    /// (modules/video_coding/nack_requester.cc:34-39: 10 000 sequence numbers, 100 requests).
845    /// The sequence number is answered here all the same: see [`Self::repair_form`].
846    fn is_fec(&self, packet: &rtp::Packet) -> bool {
847        self.fec_in_red.is_some_and(|(red, ulpfec)| {
848            packet.header.payload_type == red && packet.payload.first() == Some(&ulpfec)
849        })
850    }
851
852    /// How `packet`, sent on this stream, is sent again; `None` when it is not.
853    ///
854    /// RFC 4588 section 8.1 ties a retransmission format to ONE original payload type: "apt
855    /// (associated payload type) ... the value of this parameter is the payload type of the
856    /// associated original stream", and section 8.6: "the retransmission payload type is
857    /// mapped to the payload type of the original stream with the apt parameter". A stream
858    /// does not always leave under the payload type it was bound with: a FEC encoder
859    /// application-ward of this interceptor rewrites video into RED packets (RFC 2198), whose
860    /// retransmission format is the one whose `apt` names the `red` payload type
861    /// (`a=fmtp:117 apt=116`), not the media format's; a source may switch between the
862    /// formats of its section (RFC 7160). A receiver restores the payload type from the
863    /// `apt` of the payload type the retransmission arrives under, so a RED packet
864    /// retransmitted under the media format's RTX is restored as media with a RED header in
865    /// front of it. libwebrtc looks the RTX payload type up by the payload type of the packet
866    /// it retransmits and sends nothing when there is none
867    /// (modules/rtp_rtcp/source/rtp_sender.cc, `BuildRtxPacket`:
868    /// `rtx_payload_type_map_.find(packet.PayloadType())`).
869    ///
870    /// - A FEC packet ([`Self::is_fec`]) is answered with its sequence number alone
871    ///   ([`RepairForm::RtxWithoutFec`]): the retransmission packet of the RED packet cut
872    ///   down to its one-octet block header, three octets of payload with the original
873    ///   sequence number. A FEC packet in RED has a sequence number of the media stream, and a
874    ///   receiver that puts frames together in sequence-number order cannot tell a lost one
875    ///   from a lost one-packet frame: it waits for it and then asks for a key frame.
876    ///   Restored, the answer is a RED packet whose FEC block is empty, which a receiver
877    ///   takes as it takes any FEC packet (present, no media; libwebrtc:
878    ///   video/rtp_video_stream_receiver2.cc:1603-1612, a RED packet whose first octet is the
879    ///   `ulpfec` payload type is an empty packet to its packet buffer and NACK module). On a
880    ///   stream without retransmission a FEC packet is not sent again: the packet as it was
881    ///   is all that can leave under its sequence number.
882    /// - A stream without retransmission (no RTX SSRC or no RTX payload type): the packet as
883    ///   it was.
884    /// - Otherwise the RTX format whose `apt` is the packet's payload type, among the
885    ///   section's formats and the stream's own pair. A payload type without one is not sent
886    ///   again: never as a duplicate on the media SSRC of a stream that negotiated RTX (the
887    ///   receiver of such a stream expects its repairs on the RTX stream, and a duplicate is
888    ///   one more packet of the media stream's own sequence space on a path that just lost
889    ///   packets).
890    /// - When the binder listed no `rtx` format for the section, the stream's one RTX payload
891    ///   type stands for every packet.
892    fn repair_form(&self, packet: &rtp::Packet) -> Option<RepairForm> {
893        let fec = self.is_fec(packet);
894        let (Some(_), Some(stream_rtx)) = (self.ssrc_rtx, self.payload_type_rtx) else {
895            if self.flexfec.is_some() {
896                return (!fec).then_some(RepairForm::FlexFec);
897            }
898            return (!fec).then_some(RepairForm::Original);
899        };
900        let payload_type = packet.header.payload_type;
901        let rtx = if self.rtx_payload_types.is_empty() {
902            Some(stream_rtx)
903        } else {
904            self.rtx_payload_types
905                .iter()
906                .find(|(apt, _)| *apt == payload_type)
907                .map(|(_, rtx)| *rtx)
908                .or_else(|| (payload_type == self.payload_type).then_some(stream_rtx))
909        };
910        rtx.map(|rtx| {
911            if fec {
912                RepairForm::RtxWithoutFec(rtx)
913            } else {
914                RepairForm::Rtx(rtx)
915            }
916        })
917    }
918
919    /// The serial of the packet now held under `sequence_number`.
920    fn packet(&self, sequence_number: u16) -> Option<u64> {
921        self.sent_at[usize::from(sequence_number) % self.sent_at.len()]
922            .filter(|(held, _, _)| *held == sequence_number)
923            .map(|(_, _, serial)| serial)
924    }
925
926    /// Remembers `repair` of the packet under `sequence_number`. The entries stay within the
927    /// send buffer's places: when they are all taken, those whose packet the buffer no longer
928    /// holds go (there is one, since a packet the buffer holds is being added).
929    fn remember_repair(&mut self, sequence_number: u16, repair: Repair) {
930        if self.repairs.len() >= self.sent_at.len() && !self.repairs.contains_key(sequence_number) {
931            self.repairs.retain_held(&self.sent_at);
932        }
933        if self.repairs.len() < self.sent_at.len() || self.repairs.contains_key(sequence_number) {
934            self.repairs.insert(sequence_number, repair);
935        }
936    }
937}
938
939/// The most octets one probe cluster is filled with.
940const MAX_PROBE_FILL_OCTETS: usize = crate::cc::probe::PROBE_MAX_OCTETS;
941
942/// The most packets one probe cluster is filled with.
943const MAX_PROBE_FILL_PACKETS: usize = 128;
944
945/// The most probe clusters left to a FEC encoder that are remembered until it says how much of
946/// each it filled.
947const MAX_FEC_PROBE_PENDING: usize = 8;
948
949/// The padding octets of one probe packet: the most RFC 3550 section 5.1 padding holds (its
950/// count is one octet).
951pub const PROBE_PADDING_OCTETS: u8 = 255;
952
953/// A sequence number is retransmitted at most once per this interval, however often it is
954/// NACKed. Receivers repeat NACKs while the repair is in flight; without this a peer can make
955/// us resend the same packets as fast as it can send RTCP (an amplifier).
956pub const MIN_RETRANSMIT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(20);
957
958/// How long after its retransmission a packet is not retransmitted again however often it is
959/// asked for: [`MIN_RETRANSMIT_INTERVAL`]. libwebrtc waits a round trip
960/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`, `VerifyRtt`); measured here that loses
961/// repairs: when a retransmission is itself lost, the receiver's next request can fall inside
962/// that round trip and be ignored, and the one after waits for RFC 4585's early-feedback hold
963/// (`tests/vp8_nack_jitter_buffer_rtc2rtc.rs`, seed 4: packet 1272 retransmitted again 1.42 s
964/// after the lost copy, after the 2 s jitter buffer had played past it). A request that
965/// crossed a repair in flight costs one duplicate instead.
966fn resend_interval(round_trip_time: Option<Duration>) -> Duration {
967    let _ = round_trip_time;
968    MIN_RETRANSMIT_INTERVAL
969}
970
971/// How long after a retransmission left the transport-wide feedback on it is waited for, beyond
972/// two round trips, before a request for the same packet is answered without it: the receiver's
973/// feedback interval (100 ms by default, `TwccReceiverBuilder`).
974pub const REPAIR_REPORT_MARGIN: Duration = Duration::from_millis(100);
975
976/// How long a retransmission the feedback reported received is remembered: a request for its
977/// packet within this long of the report crossed it and is not answered. The time is the
978/// request's own (the engine's clock), so the memory ends whether or not another report
979/// comes: a request after it is answered, which is also what bounds a receiver whose feedback
980/// reports retransmissions it did not get. It is the memory of one packet (SSRC and extended
981/// sequence number): it ends with the packet's place in the send buffer, its `rtx-time` or
982/// its repair age, past which no request for it is answered anyway, and the packet that has
983/// the same 16-bit number a cycle later starts without it.
984///
985/// Longer than the default repair age ([`MAX_REPAIR_AGE`]), under which no request for the
986/// packet is answered once it is two seconds old whatever is remembered of it. The memory is
987/// the bound for the configurations where a packet is repaired longer: an `rtx-time` over two
988/// seconds, the repair age off (`PacerBacklog::Keep`, the `Chrome` profile). There a shorter
989/// memory would answer a request that crossed its repair behind a deep queue.
990pub const DELIVERED_MEMORY: Duration = Duration::from_secs(4);
991
992/// What a request for a packet that was retransmitted before gets
993/// ([`RetransmissionsReported`](crate::RetransmissionsReported)).
994#[derive(Debug, Clone, Copy, PartialEq, Eq)]
995enum Repeat {
996    /// Answered as any request.
997    Answer,
998    /// Kept waiting until the feedback on the earlier retransmission comes, at most until then.
999    Hold(Instant),
1000    /// Not answered: the earlier retransmission arrived.
1001    Decline,
1002}
1003
1004/// How long a retransmission is taken to wait in the pacer at most: longer than the pacer's
1005/// queue time bound (2 s by default), past which the pacer drops it and says so. Not tied to
1006/// the repair age: it bounds a state (a pacer that never reports), and a retransmission made
1007/// of a packet just under the repair age may wait the pacer's bound after that.
1008const IN_PACER_LIFETIME: Duration = Duration::from_secs(4);
1009
1010/// How old a packet may be and still be repaired, by default
1011/// ([`NackResponderBuilder::with_max_repair_age`]): two seconds, the pacer's queue time bound,
1012/// past which the pacer itself drops what waits as stale. One second (libwebrtc's shortest
1013/// packet history) was measured and is too short: behind a path queue of a second a NACK for a
1014/// packet still wanted arrives later than that.
1015pub const MAX_REPAIR_AGE: Duration = Duration::from_secs(2);
1016
1017/// The backlog of repairs given up after the target halved, by default
1018/// ([`NackResponderBuilder::with_repair_backlog_bound`]): what would take two seconds or more
1019/// to leave at the target. One second was measured and gives up too early: the key frame asked
1020/// for goes into a path queue that is still full (200 calls per cell: 8 and 24 with no frame
1021/// for over 2 s behind queues of 100 ms and 1 s, against none with two seconds).
1022pub const REPAIR_BACKLOG_BOUND: Duration = Duration::from_secs(2);
1023
1024/// How far back the highest target counts when a backlog of repairs is judged a collapse
1025/// (the pacer's queue time bound).
1026const COLLAPSE_LOOK_BACK: Duration = Duration::from_secs(2);
1027
1028/// A backlog of repairs is a collapse when the target is at most this share of the highest
1029/// in force within [`COLLAPSE_LOOK_BACK`] (the pacer's `COLLAPSE_AT`).
1030const COLLAPSE_AT: f64 = 0.5;
1031
1032/// The most target changes remembered.
1033const MAX_TARGETS_KEPT: usize = 256;
1034
1035/// Most retransmissions queued and not yet taken by `poll_write`. Past it further NACKed
1036/// packets are not queued until the queue drains.
1037pub const MAX_QUEUED_RETRANSMISSIONS: usize = 1024;
1038
1039/// The most retransmission SSRCs whose next sequence number is remembered after their stream
1040/// was unbound.
1041const MAX_REMEMBERED_RTX_SSRCS: usize = 1024;
1042
1043/// Interceptor that responds to NACK requests by retransmitting packets.
1044///
1045/// This interceptor buffers outgoing RTP packets on local streams and
1046/// retransmits them when RTCP TransportLayerNack packets are received.
1047pub struct NackResponderInterceptor {
1048    /// Configuration
1049    size: u16,
1050
1051    /// How long a sent packet stays available for retransmission (`rtx-time`).
1052    max_packet_age: Option<Duration>,
1053    /// The `rtx-time` this endpoint announced, by retransmission payload type
1054    /// ([`NackControl::LocalRtxTime`](super::NackControl::LocalRtxTime)): it replaces
1055    /// `max_packet_age` for the streams repaired under that payload type.
1056    local_rtx_times: HashMap<u8, Duration>,
1057
1058    /// Send buffers per local stream SSRC
1059    streams: HashMap<u32, LocalStream>,
1060
1061    /// The next sequence number of each retransmission SSRC this interceptor has sent on,
1062    /// kept when its stream is unbound: a stream bound again with the same RTX SSRC (a
1063    /// renegotiation re-binding it) carries on from here. Starting over would repeat sequence
1064    /// numbers on a live SSRC, which SRTP refuses to protect twice (the packet index is the
1065    /// SSRC's rollover counter and sequence number).
1066    rtx_sequence_numbers: HashMap<u32, u16>,
1067    /// The RFC 8627 FlexFEC repair streams this responder retransmits on, by repair SSRC
1068    /// ([`FlexFecRepairStream`]).
1069    flexfec_repair: HashMap<u32, FlexFecRepairStream>,
1070
1071    /// Queue for retransmitted packets
1072    write_queue: VecDeque<TaggedPacket>,
1073    /// Retransmissions in `write_queue` not yet taken by `poll_write`.
1074    retransmissions_queued: usize,
1075    /// Inbound packets ready for the next interceptor.
1076    read_queue: VecDeque<TaggedPacket>,
1077    /// The RTP session (transport) of each SSRC, from the peer connection's
1078    /// [`RtpSessionAssignment`](crate::RtpSessionAssignment)s; empty while there is one.
1079    sessions: HashMap<u32, usize>,
1080    /// The streams that may not send ([`StreamsNotSending`](crate::StreamsNotSending)): no
1081    /// NACK for them is answered and no probe is padded on their RTX streams.
1082    not_sending: HashSet<u32>,
1083    /// The streams a FEC encoder fills probe clusters for
1084    /// ([`FecProbeFiller`](crate::cc::probe::FecProbeFiller)): while one of them sends, a
1085    /// cluster the pacer sends is left to the FEC encoder (RFC 8854 section 8).
1086    fec_probe_streams: HashSet<u32>,
1087    /// The clusters left to the FEC encoder, newest last, until it says how much of each it
1088    /// filled ([`FecProbeFilled`](crate::cc::probe::FecProbeFilled)): the request, the pacer's
1089    /// fill (`None`: no pacer, the whole cluster) and the request's RTP session.
1090    fec_probe_pending: VecDeque<(ProbeRequest, Option<usize>, Option<usize>)>,
1091
1092    /// See [`NackResponderBuilder::with_rate_limit`].
1093    rate_limit: RetransmissionRateLimit,
1094    /// The congestion controller's latest target, bits per second.
1095    target_bps: Option<f64>,
1096    /// The controller's minimum ([`MinimumTarget`]), bits per second.
1097    minimum_bps: Option<f64>,
1098    /// The original packets of the local streams, and the retransmissions, sent lately.
1099    originals: RateWindow,
1100    retransmitted: RateWindow,
1101    /// See [`NackResponderBuilder::with_max_reserve_fraction`].
1102    max_reserve_fraction: f64,
1103    /// The round trip the RTCP session measured last.
1104    round_trip_time: Option<Duration>,
1105    /// NACKed packets waiting for room, oldest request first.
1106    pending: VecDeque<PendingRetransmission>,
1107    /// When each waiting packet was last asked for, and which packet it is (its serial).
1108    pending_asked: HashMap<(u32, u16), (Instant, u64)>,
1109    /// The octets of `pending`.
1110    pending_octets: usize,
1111    /// The reserve last announced, bits per second.
1112    announced_reserve: f64,
1113    /// When the next waiting retransmission can leave, worked out since the last change:
1114    /// `None` when it has to be worked out again.
1115    release_at: Option<Option<Instant>>,
1116    /// Whether a pacer wire-ward reports its retransmissions' departures (it has once).
1117    pacer_reports: bool,
1118    /// Whether the pacer tells the source to pause ([`PacerPause`](crate::PacerPause)): the
1119    /// target the application reads is zero.
1120    paused: bool,
1121    /// Whether transport-wide feedback reports on the retransmissions
1122    /// ([`RetransmissionsReported`](crate::RetransmissionsReported)): it has once.
1123    repairs_reported: bool,
1124    /// See [`NackResponderBuilder::with_max_repair_age`].
1125    max_repair_age: Option<Duration>,
1126    /// See [`NackResponderBuilder::with_repair_backlog_bound`].
1127    repair_backlog_bound: Option<Duration>,
1128    /// See [`NackResponderBuilder::with_probe_padding`].
1129    probe_padding: bool,
1130    /// The targets set within [`COLLAPSE_LOOK_BACK`] (and the one in force before), oldest
1131    /// first; cleared when repairs are given up.
1132    targets: VecDeque<(Instant, f64)>,
1133    /// Retransmissions made before this instant no longer hold the reserve: what they
1134    /// repaired was given up.
1135    reserve_since: Option<Instant>,
1136}
1137
1138impl NackResponderInterceptor {
1139    fn new(size: u16) -> Self {
1140        Self {
1141            read_queue: VecDeque::new(),
1142            size,
1143            max_packet_age: None,
1144            local_rtx_times: HashMap::new(),
1145            streams: HashMap::new(),
1146            rtx_sequence_numbers: HashMap::new(),
1147            flexfec_repair: HashMap::new(),
1148            write_queue: VecDeque::new(),
1149            retransmissions_queued: 0,
1150            sessions: HashMap::new(),
1151            not_sending: HashSet::new(),
1152            fec_probe_streams: HashSet::new(),
1153            fec_probe_pending: VecDeque::new(),
1154            rate_limit: RetransmissionRateLimit::default(),
1155            target_bps: None,
1156            minimum_bps: None,
1157            originals: RateWindow::default(),
1158            retransmitted: RateWindow::default(),
1159            max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
1160            round_trip_time: None,
1161            pending: VecDeque::new(),
1162            pending_asked: HashMap::new(),
1163            pending_octets: 0,
1164            announced_reserve: 0.0,
1165            release_at: None,
1166            pacer_reports: false,
1167            paused: false,
1168            repairs_reported: false,
1169            max_repair_age: Some(MAX_REPAIR_AGE),
1170            repair_backlog_bound: Some(REPAIR_BACKLOG_BOUND),
1171            probe_padding: true,
1172            targets: VecDeque::new(),
1173            reserve_since: None,
1174        }
1175    }
1176
1177    /// Octets at `bits_per_second` over the window.
1178    fn window_octets(bits_per_second: f64) -> usize {
1179        (bits_per_second / 8.0 * RETRANSMISSION_RATE_WINDOW.as_secs_f64()) as usize
1180    }
1181
1182    /// The octets retransmissions may still take within the window, `None` for no limit.
1183    fn retransmission_allowance(&mut self, now: Instant) -> Option<usize> {
1184        let target_bps = self.target_bps?;
1185        self.originals.expire(now);
1186        self.retransmitted.expire(now);
1187        let target = Self::window_octets(target_bps);
1188        let limit = match self.rate_limit {
1189            RetransmissionRateLimit::WithinTarget => {
1190                if self.at_floor() {
1191                    // Near the floor the retransmissions take the window's room first.
1192                    target
1193                } else {
1194                    // What the originals leave, or the reserve the original media has already
1195                    // been lowered by, whichever is more.
1196                    target
1197                        .saturating_sub(self.originals.octets)
1198                        .max(Self::window_octets(self.announced_reserve))
1199                }
1200            }
1201            RetransmissionRateLimit::UpToTarget => target,
1202            RetransmissionRateLimit::Unlimited => return None,
1203        };
1204        Some(limit.saturating_sub(self.retransmitted.octets))
1205    }
1206
1207    /// Whether lowering the original media by the reserve would take it under the
1208    /// controller's minimum (see [`RetransmissionRateLimit::WithinTarget`]).
1209    fn at_floor(&self) -> bool {
1210        self.rate_limit == RetransmissionRateLimit::WithinTarget
1211            && self.announced_reserve > 0.0
1212            && match (self.target_bps, self.minimum_bps) {
1213                (Some(target), Some(minimum)) => target - self.announced_reserve < minimum,
1214                _ => false,
1215            }
1216    }
1217
1218    /// The retransmission reserve at `now`, bits per second (see
1219    /// [`RetransmissionRateLimit::WithinTarget`]); zero under the other rules.
1220    fn reserve(&mut self, now: Instant) -> f64 {
1221        let Some(target_bps) = self.target_bps else {
1222            return 0.0;
1223        };
1224        if self.rate_limit != RetransmissionRateLimit::WithinTarget {
1225            return 0.0;
1226        }
1227        self.retransmitted.expire(now);
1228        // Retransmissions of what was given up since hold no reserve: nothing follows them.
1229        let retransmitted = match self.reserve_since {
1230            Some(since) => self
1231                .retransmitted
1232                .sent
1233                .iter()
1234                .filter(|(at, _)| *at >= since)
1235                .map(|(_, octets)| *octets)
1236                .sum(),
1237            None => self.retransmitted.octets,
1238        };
1239        if self.pending.is_empty() && retransmitted == 0 {
1240            return 0.0;
1241        }
1242        let horizon = self
1243            .round_trip_time
1244            .unwrap_or(RETRANSMISSION_RATE_WINDOW)
1245            .clamp(MIN_RESERVE_HORIZON, RETRANSMISSION_RATE_WINDOW);
1246        let needed = self.pending_octets as f64 * 8.0 / horizon.as_secs_f64();
1247        let in_use = retransmitted as f64 * 8.0 / RETRANSMISSION_RATE_WINDOW.as_secs_f64();
1248        needed
1249            .max(in_use)
1250            .min(self.max_reserve_fraction * target_bps)
1251    }
1252
1253    /// How long a waiting request stays without being asked for again.
1254    fn pending_lifetime(&self) -> Duration {
1255        self.round_trip_time
1256            .map_or(PENDING_REQUEST_LIFETIME, |rtt| {
1257                (rtt * 2).max(PENDING_REQUEST_LIFETIME)
1258            })
1259    }
1260
1261    /// Drops the waiting requests nobody asked for again within their lifetime.
1262    fn expire_pending(&mut self, now: Instant) {
1263        let lifetime = self.pending_lifetime();
1264        let before = self.pending.len();
1265        let asked = &mut self.pending_asked;
1266        let octets = &mut self.pending_octets;
1267        self.pending.retain(|entry| {
1268            let key = (entry.ssrc, entry.sequence_number);
1269            let fresh = asked
1270                .get(&key)
1271                .is_some_and(|(at, _)| now.saturating_duration_since(*at) <= lifetime);
1272            if !fresh {
1273                asked.remove(&key);
1274                *octets -= entry.octets;
1275            }
1276            fresh
1277        });
1278        if self.pending.len() != before {
1279            self.release_at = None;
1280        }
1281    }
1282
1283    /// The wire size of the retransmission of `packet` in `form`: an RTX packet carries the
1284    /// original sequence number ahead of the payload (RFC 4588 section 4).
1285    fn retransmission_size(form: RepairForm, packet: &rtp::Packet) -> usize {
1286        match form {
1287            RepairForm::Rtx(_) => packet.marshal_size() + 2,
1288            // The header, the original sequence number and the RED block header.
1289            RepairForm::RtxWithoutFec(_) => packet.marshal_size() - packet.payload.len() + 3,
1290            RepairForm::Original => packet.marshal_size(),
1291            // The repair stream's 12-octet header ahead of the whole original packet.
1292            RepairForm::FlexFec => packet.marshal_size() + 12,
1293        }
1294    }
1295
1296    /// The `rtx-time` in force for a packet of `stream` sent again in `form` (RFC 4588 8.1: a
1297    /// packet is kept for retransmission that long): what the session description announced
1298    /// for the packet's retransmission format, the RTX payload type whose `apt` is the
1299    /// packet's payload type (RED's RTX for a RED packet; the stream's own, for a packet sent
1300    /// again as it was); without one, the configured age. RFC 4588 section 8.6 makes
1301    /// `rtx-time` a parameter of each retransmission payload type, so two formats of one
1302    /// stream may announce different times, or one and not the other.
1303    fn rtx_time(&self, stream: &LocalStream, form: RepairForm) -> Option<Duration> {
1304        let payload_type_rtx = match form {
1305            RepairForm::Rtx(payload_type_rtx) | RepairForm::RtxWithoutFec(payload_type_rtx) => {
1306                Some(payload_type_rtx)
1307            }
1308            RepairForm::Original | RepairForm::FlexFec => stream.payload_type_rtx,
1309        };
1310        payload_type_rtx
1311            .and_then(|payload_type_rtx| self.local_rtx_times.get(&payload_type_rtx))
1312            .copied()
1313            .or(self.max_packet_age)
1314    }
1315
1316    /// How long ago `seq` of `stream` was written, if the stream holds it.
1317    fn age(stream: &LocalStream, seq: u16, now: Instant) -> Option<Duration> {
1318        stream.sent_at[usize::from(seq) % stream.sent_at.len()]
1319            .filter(|(sequence_number, _, _)| *sequence_number == seq)
1320            .map(|(_, sent, _)| now.saturating_duration_since(sent))
1321    }
1322
1323    /// Whether `seq` of `stream` may be retransmitted at `now` (it is still held, it has a
1324    /// form to be sent again in, see [`LocalStream::repair_form`], and it is not older than
1325    /// the `rtx-time` of that form or, without one, than the repair age), and its
1326    /// retransmission's size.
1327    fn retransmittable(&self, stream: &LocalStream, seq: u16, now: Instant) -> Option<usize> {
1328        let original_packet = stream.send_buffer.get(seq)?;
1329        let form = stream.repair_form(original_packet)?;
1330        if let Some(rtx_time) = self.rtx_time(stream, form)
1331            && Self::age(stream, seq, now).is_some_and(|age| age > rtx_time)
1332        {
1333            return None;
1334        }
1335        if self.too_old(stream, form, seq, now) {
1336            return None;
1337        }
1338        Some(Self::retransmission_size(form, original_packet))
1339    }
1340
1341    /// Sends the waiting retransmissions the rate limit has room for, oldest request first.
1342    fn release(&mut self, now: Instant) {
1343        let mut allowance = self.retransmission_allowance(now);
1344        let resend_interval = resend_interval(self.round_trip_time);
1345        // Waits for the feedback that ended are over, reached below or not.
1346        self.expire_repairs(now);
1347        // A request held for the feedback on an earlier retransmission keeps its place; the
1348        // ones behind it are served meanwhile.
1349        let mut index = 0;
1350        while let Some(entry) = self.pending.get(index) {
1351            if self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
1352                break;
1353            }
1354            let (ssrc, seq) = (entry.ssrc, entry.sequence_number);
1355            if !self.holds(ssrc, seq, entry.packet) {
1356                // The packet asked for is gone; the one that has its number was not asked for.
1357                self.remove_pending(index);
1358                continue;
1359            }
1360            match self.repeat_state((ssrc, seq), now) {
1361                Repeat::Hold(_) => {
1362                    index += 1;
1363                    continue;
1364                }
1365                Repeat::Decline => {
1366                    self.remove_pending(index);
1367                    continue;
1368                }
1369                Repeat::Answer => {}
1370            }
1371            let in_pacer = self.in_pacer(ssrc, seq, now);
1372            let current = self.streams.get(&ssrc).and_then(|stream| {
1373                let recently = stream
1374                    .last_retransmit
1375                    .get(&seq)
1376                    .is_some_and(|at| now.saturating_duration_since(*at) < resend_interval)
1377                    || in_pacer;
1378                if recently {
1379                    None
1380                } else {
1381                    self.retransmittable(stream, seq, now)
1382                        .map(|size| (size, stream.retransmit_budget))
1383                }
1384            });
1385            let Some((size, budget)) = current else {
1386                // Gone from the buffer, too old, its stream unbound, or just sent.
1387                self.remove_pending(index);
1388                continue;
1389            };
1390            if budget == 0 {
1391                // Waits for the next original packet, which adds to the budget.
1392                break;
1393            }
1394            if let Some(left) = allowance.as_mut() {
1395                if size > *left {
1396                    break;
1397                }
1398                *left -= size;
1399            }
1400            self.remove_pending(index);
1401            self.retransmit(now, ssrc, seq, size);
1402        }
1403    }
1404
1405    fn remove_pending(&mut self, index: usize) {
1406        if let Some(entry) = self.pending.remove(index) {
1407            self.pending_asked
1408                .remove(&(entry.ssrc, entry.sequence_number));
1409            self.pending_octets -= entry.octets;
1410            self.release_at = None;
1411        }
1412    }
1413
1414    /// Queues the retransmission of `seq` of the stream `ssrc`.
1415    fn retransmit(&mut self, now: Instant, ssrc: u32, seq: u16, size: usize) {
1416        let earlier = self.repair(ssrc, seq, now);
1417        let Some(stream) = self.streams.get_mut(&ssrc) else {
1418            return;
1419        };
1420        // Held, and with a form to be sent again in (`retransmittable` said so already).
1421        let Some(form) = stream
1422            .send_buffer
1423            .get(seq)
1424            .and_then(|packet| stream.repair_form(packet))
1425        else {
1426            return;
1427        };
1428        stream.last_retransmit.insert(seq, now);
1429        if let Some(packet) = stream.packet(seq) {
1430            // An earlier retransmission of this same packet still remembered: reports on it
1431            // go on counting.
1432            let first_made = earlier
1433                .filter(|earlier| earlier.packet == packet)
1434                .map_or(now, |earlier| earlier.first_made);
1435            let state = if self.pacer_reports {
1436                RepairState::InPacer
1437            } else {
1438                // Without a pacer it leaves now.
1439                RepairState::Unreported { left: now }
1440            };
1441            stream.remember_repair(
1442                seq,
1443                Repair {
1444                    packet,
1445                    first_made,
1446                    made: now,
1447                    state,
1448                },
1449            );
1450        }
1451        stream.retransmit_budget -= 1;
1452        self.retransmissions_queued += 1;
1453        let Some(original_packet) = stream.send_buffer.get(seq) else {
1454            return;
1455        };
1456
1457        let without_fec;
1458        let original_packet = if matches!(form, RepairForm::RtxWithoutFec(_)) {
1459            // The RED block header (RFC 2198 section 3: one octet, the block's payload
1460            // type), without the FEC data behind it.
1461            without_fec = rtp::Packet {
1462                header: original_packet.header.clone(),
1463                payload: original_packet
1464                    .payload
1465                    .slice(..original_packet.payload.len().min(1)),
1466            };
1467            &without_fec
1468        } else {
1469            original_packet
1470        };
1471        let packet =
1472            if let (RepairForm::Rtx(pt_rtx) | RepairForm::RtxWithoutFec(pt_rtx), Some(ssrc_rtx)) =
1473                (form, stream.ssrc_rtx)
1474            {
1475                if stream.repairs_order.len() >= usize::from(self.size).max(1)
1476                    && let Some((oldest, made)) = stream.repairs_order.pop_front()
1477                    && stream
1478                        .repairs_by_rtx
1479                        .get(&oldest)
1480                        .is_some_and(|(_, at)| *at == made)
1481                {
1482                    stream.repairs_by_rtx.remove(&oldest);
1483                }
1484                stream
1485                    .repairs_by_rtx
1486                    .insert(stream.rtx_sequence_number, (seq, now));
1487                stream
1488                    .repairs_order
1489                    .push_back((stream.rtx_sequence_number, now));
1490                rtx_packet(
1491                    &mut stream.rtx_sequence_number,
1492                    (stream.rid_extension_id, stream.repaired_rid_extension_id),
1493                    &stream.identifiers,
1494                    original_packet,
1495                    ssrc_rtx,
1496                    pt_rtx,
1497                )
1498            } else if let (RepairForm::FlexFec, Some((ssrc_fec, pt_fec))) = (form, stream.flexfec) {
1499                let Some(packet) = flexfec_retransmission(
1500                    self.flexfec_repair.entry(ssrc_fec).or_default(),
1501                    now,
1502                    original_packet,
1503                    ssrc_fec,
1504                    pt_fec,
1505                ) else {
1506                    return;
1507                };
1508                // As for RTX: RFC 8888 feedback names the repair stream's packets by their
1509                // own sequence numbers.
1510                if stream.repairs_order.len() >= usize::from(self.size).max(1)
1511                    && let Some((oldest, made)) = stream.repairs_order.pop_front()
1512                    && stream
1513                        .repairs_by_rtx
1514                        .get(&oldest)
1515                        .is_some_and(|(_, at)| *at == made)
1516                {
1517                    stream.repairs_by_rtx.remove(&oldest);
1518                }
1519                stream
1520                    .repairs_by_rtx
1521                    .insert(packet.header.sequence_number, (seq, now));
1522                stream
1523                    .repairs_order
1524                    .push_back((packet.header.sequence_number, now));
1525                packet
1526            } else {
1527                // No RTX negotiated for the stream: retransmit the original packet as-is
1528                original_packet.clone()
1529            };
1530        self.retransmitted.add(now, size);
1531        self.release_at = None;
1532
1533        // Tagged so a send history downstream counts it as new bytes on the wire rather
1534        // than as the original transmission. A bandwidth estimator that cannot tell the two
1535        // apart under-counts exactly when the path is lossy — it sees fewer bytes than are
1536        // really being sent, infers headroom, and raises the target during loss.
1537        self.write_queue.push_back(TaggedPacket {
1538            now,
1539            transport: TransportContext::default(),
1540            message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
1541        });
1542    }
1543
1544    /// When the oldest waiting retransmission fits the rate limit: the instant enough of the
1545    /// window's packets have left it. `None` with nothing waiting, without a target to wait
1546    /// for, or while the stream's budget waits for an original packet (the write of that
1547    /// packet tries again).
1548    pub fn next_release(&mut self) -> Option<Instant> {
1549        if let Some(at) = self.release_at {
1550            return at;
1551        }
1552        let at = self.work_out_release();
1553        self.release_at = Some(at);
1554        at
1555    }
1556
1557    fn work_out_release(&self) -> Option<Instant> {
1558        // A request held for the feedback on an earlier retransmission is due when its wait
1559        // ends (the feedback itself comes on the read leg); the first one not held is the
1560        // head. `release` forgets the waits that ended, so these are all ahead.
1561        let wait = self.report_wait();
1562        let held = |entry: &PendingRetransmission| {
1563            if !self.repairs_reported {
1564                return None;
1565            }
1566            let stream = self.streams.get(&entry.ssrc)?;
1567            let repair = stream.repairs.get(entry.sequence_number)?;
1568            match repair.state {
1569                RepairState::Unreported { left }
1570                    if stream.packet(entry.sequence_number) == Some(repair.packet) =>
1571                {
1572                    Some(left + wait)
1573                }
1574                _ => None,
1575            }
1576        };
1577        let hold_ends = self.pending.iter().filter_map(held).min();
1578        let Some(target_bps) = self.target_bps else {
1579            return hold_ends;
1580        };
1581        // With nothing waiting, the reserve falls to zero when the last retransmission leaves
1582        // the window.
1583        if self.pending.is_empty() {
1584            return (self.announced_reserve > 0.0)
1585                .then(|| self.retransmitted.sent.back())
1586                .flatten()
1587                .map(|(at, _)| *at + RETRANSMISSION_RATE_WINDOW);
1588        }
1589        // The lifetime of the oldest request ends: due then, to drop it.
1590        let lifetime = self.pending_lifetime();
1591        let stale = self
1592            .pending
1593            .iter()
1594            .filter_map(|entry| self.pending_asked.get(&(entry.ssrc, entry.sequence_number)))
1595            .map(|(asked, _)| *asked)
1596            .min()
1597            .map(|asked| asked + lifetime + Duration::from_micros(1));
1598        let stale = stale.into_iter().chain(hold_ends).min();
1599        let Some(entry) = self.pending.iter().find(|entry| held(entry).is_none()) else {
1600            return stale;
1601        };
1602        if self
1603            .streams
1604            .get(&entry.ssrc)
1605            .is_none_or(|stream| stream.retransmit_budget == 0)
1606        {
1607            return stale;
1608        }
1609        let size = entry.octets;
1610        let target = Self::window_octets(target_bps);
1611        let (originals, retransmitted) = (self.originals.octets, self.retransmitted.octets);
1612        let fits = match self.rate_limit {
1613            RetransmissionRateLimit::WithinTarget if !self.at_floor() => {
1614                let by_share = freed_at(
1615                    &[&self.originals, &self.retransmitted],
1616                    (originals + retransmitted + size)
1617                        .saturating_sub(target)
1618                        .max(1),
1619                )
1620                .filter(|_| size <= target);
1621                // The reserve frees as the retransmissions leave the window.
1622                let reserve = Self::window_octets(self.announced_reserve);
1623                let by_reserve = freed_at(
1624                    &[&self.retransmitted],
1625                    (retransmitted + size).saturating_sub(reserve).max(1),
1626                )
1627                .filter(|_| size <= reserve);
1628                by_share.into_iter().chain(by_reserve).min()
1629            }
1630            // Near the floor the room is the retransmissions' first: only they leaving the
1631            // window frees it.
1632            RetransmissionRateLimit::WithinTarget | RetransmissionRateLimit::UpToTarget => {
1633                freed_at(
1634                    &[&self.retransmitted],
1635                    (retransmitted + size).saturating_sub(target).max(1),
1636                )
1637                .filter(|_| size <= target)
1638            }
1639            RetransmissionRateLimit::Unlimited => None,
1640        };
1641        fits.into_iter().chain(stale).min()
1642    }
1643
1644    /// Announces a reserve that moved: down the write leg for the congestion controller, and
1645    /// up the read leg as the lowered target for the application.
1646    /// The carrier that tells the application its target when only the reserve moved: the
1647    /// controller's target less the reserve, or, while the pacer has the source paused, zero
1648    /// with the controller's target riding along as the pacer's own announcement of a pause
1649    /// has it ([`PacerPause`](crate::PacerPause)). Without it a reader of the carrier takes
1650    /// the zero for the congestion controller's estimate (`availableOutgoingBitrate` read
1651    /// nothing until the next target from the pacer).
1652    fn target_carrier(&self, now: Instant, target_bps: f64, reserve: f64) -> TaggedPacket {
1653        let mut message = AttributedPacket::new(Packet::Rtcp(vec![]));
1654        if self.paused {
1655            message.add(Attribute::TargetBitrateChanged {
1656                bits_per_second: 0.0,
1657            });
1658            message.add(Attribute::Custom(std::sync::Arc::new(crate::PacerPause {
1659                target_bits_per_second: target_bps,
1660            })));
1661        } else {
1662            message.add(Attribute::TargetBitrateChanged {
1663                bits_per_second: media_target(target_bps, reserve, self.minimum_bps.unwrap_or(0.0)),
1664            });
1665        }
1666        TaggedPacket {
1667            now,
1668            transport: TransportContext::default(),
1669            message,
1670        }
1671    }
1672
1673    fn announce_reserve(&mut self, now: Instant, carrier: bool) {
1674        let Some(target_bps) = self.target_bps else {
1675            return;
1676        };
1677        let reserve = self.reserve(now);
1678        if !reserve_moved(self.announced_reserve, reserve, target_bps) {
1679            return;
1680        }
1681        self.announced_reserve = reserve;
1682        self.release_at = None;
1683        self.write_queue.push_back(TaggedPacket {
1684            now,
1685            transport: TransportContext::default(),
1686            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
1687                std::sync::Arc::new(RetransmissionReserve {
1688                    bits_per_second: reserve,
1689                }),
1690            )),
1691        });
1692        if carrier {
1693            let carrier = self.target_carrier(now, target_bps, reserve);
1694            self.read_queue.push_back(carrier);
1695        }
1696        if self.at_floor() {
1697            // Near the floor the window's room is the retransmissions': use it now.
1698            self.release(now);
1699        }
1700    }
1701
1702    /// Fills a probe cluster ([`ProbeRequest`]) with padding-only packets on the RTX stream of
1703    /// the media stream that sent most recently.
1704    ///
1705    /// A probe needs a burst of packets at a multiple of the target rate, and an application
1706    /// that follows the target does not have one waiting. Each packet is an RTP packet of the
1707    /// RTX stream with no payload and [`PROBE_PADDING_OCTETS`] of padding (RFC 3550 section
1708    /// 5.1): an RTX packet too short to hold the original sequence number of RFC 4588 section
1709    /// 4 carries no media, and every receiver drops it after its transport-wide sequence
1710    /// number has been recorded (this crate's endpoint, libwebrtc's `RtxReceiveStream`). A
1711    /// retransmission of a packet already delivered would be a duplicate the receiving
1712    /// application may play twice. The header is the newest packet's, with its extensions
1713    /// (MID, the repaired RID in place of the RID), so the packet is demultiplexed as that
1714    /// stream's repair flow. Without RTX negotiated nothing is added: padding under the media
1715    /// SSRC would take sequence numbers the application owns. Not charged to the NACK budget:
1716    /// it answers no NACK.
1717    ///
1718    /// In a chain without a pacer (the request carries no [`ProbeFill`](crate::ProbeFill)) the
1719    /// padding is the whole cluster and leaves as one burst, marked here with the cluster's
1720    /// [`ProbePacket`]: without the mark the congestion controller would count no packet for
1721    /// the cluster and wait for a result that cannot come.
1722    ///
1723    /// With several RTP sessions (transports) a cluster is the session's that asked for it
1724    /// (the request carries its [`RtpSession`](crate::RtpSession)): it is filled on a stream of
1725    /// that session only, so the probe travels the path whose capacity it measures (RFC 8836
1726    /// section 2: each path its own capacity).
1727    fn fill_probe(
1728        &mut self,
1729        now: Instant,
1730        request: &ProbeRequest,
1731        fill: Option<usize>,
1732        session: Option<usize>,
1733    ) {
1734        let sessions = &self.sessions;
1735        let not_sending = &self.not_sending;
1736        let in_session = |ssrc: &u32| match session {
1737            Some(session) if !sessions.is_empty() => sessions.get(ssrc) == Some(&session),
1738            _ => true,
1739        };
1740        // RFC 8854 section 8: "when probing bandwidth ... FEC data SHOULD be used as the
1741        // additional data". A FEC encoder that fills clusters for a stream of the session that
1742        // sends gets the request next and fills it; the pacer (`fill`) sends what it makes, or
1743        // without a pacer it leaves at once, marked by the encoder. What its repair packets
1744        // leave unfilled is padded when it says how much it filled (`fec_probe_filled`): the
1745        // cluster is always the size asked for.
1746        if self
1747            .fec_probe_streams
1748            .iter()
1749            .any(|ssrc| in_session(ssrc) && !not_sending.contains(ssrc))
1750        {
1751            if self.fec_probe_pending.len() == MAX_FEC_PROBE_PENDING {
1752                self.fec_probe_pending.pop_front();
1753            }
1754            self.fec_probe_pending.push_back((*request, fill, session));
1755            return;
1756        }
1757        self.pad_probe(now, request, fill, session);
1758    }
1759
1760    /// The FEC encoder filled `filled.octets` of a cluster left to it: the rest of what the
1761    /// pacer asked to be filled is padded here.
1762    fn fec_probe_filled(&mut self, now: Instant, filled: &crate::cc::probe::FecProbeFilled) {
1763        let Some(at) = self
1764            .fec_probe_pending
1765            .iter()
1766            .position(|(request, _, _)| request.cluster == filled.cluster)
1767        else {
1768            return;
1769        };
1770        let Some((request, fill, session)) = self.fec_probe_pending.remove(at) else {
1771            return;
1772        };
1773        let rest = fill
1774            .unwrap_or(request.octets)
1775            .min(request.octets)
1776            .saturating_sub(filled.octets);
1777        if rest > 0 {
1778            self.pad_probe_octets(
1779                now,
1780                &request,
1781                rest,
1782                fill.is_some(),
1783                filled.octets == 0,
1784                session,
1785            );
1786        }
1787    }
1788
1789    /// Pads `request`'s cluster on the RTX stream of the session's media stream that sent
1790    /// most recently: `fill` octets when a pacer sends it, the whole cluster otherwise (see
1791    /// `fill_probe`).
1792    fn pad_probe(
1793        &mut self,
1794        now: Instant,
1795        request: &ProbeRequest,
1796        fill: Option<usize>,
1797        session: Option<usize>,
1798    ) {
1799        // The pacer says how much padding the cluster needs beyond the media it holds
1800        // ([`ProbeFill`](crate::ProbeFill)); without a pacer, the whole cluster.
1801        let wanted = fill.map_or(request.octets, |octets| octets.min(request.octets));
1802        self.pad_probe_octets(now, request, wanted, fill.is_some(), true, session);
1803    }
1804
1805    /// Pads `wanted` octets of `request`'s cluster (see [`Self::pad_probe`]). `paced`: a pacer
1806    /// sends the cluster (the padding leaves through it); otherwise it leaves at once, marked
1807    /// with the cluster here. `unsent_if_none`: with nothing to pad on and no pacer, the
1808    /// cluster is reported unsent (nothing else left for it).
1809    fn pad_probe_octets(
1810        &mut self,
1811        now: Instant,
1812        request: &ProbeRequest,
1813        wanted: usize,
1814        paced: bool,
1815        unsent_if_none: bool,
1816        session: Option<usize>,
1817    ) {
1818        let fill = paced.then_some(wanted);
1819        let unsent = |this: &mut Self| {
1820            if unsent_if_none {
1821                this.probe_unsent(now, request, fill, session);
1822            }
1823        };
1824        // RFC 7714 section 7.2 (`with_probe_padding(false)`): no padding-only packets; the
1825        // cluster keeps what the pacer's media and the FEC encoder put in it.
1826        if !self.probe_padding {
1827            unsent(self);
1828            return;
1829        }
1830        let sessions = &self.sessions;
1831        let not_sending = &self.not_sending;
1832        let Some(stream) = self
1833            .streams
1834            .iter_mut()
1835            .filter(|(ssrc, _)| match session {
1836                Some(session) if !sessions.is_empty() => sessions.get(ssrc) == Some(&session),
1837                _ => true,
1838            })
1839            .filter(|(ssrc, stream)| {
1840                !not_sending.contains(ssrc)
1841                    && !stream
1842                        .ssrc_rtx
1843                        .is_some_and(|rtx| not_sending.contains(&rtx))
1844            })
1845            .map(|(_, stream)| stream)
1846            .filter(|stream| stream.ssrc_rtx.is_some() && stream.payload_type_rtx.is_some())
1847            .filter(|stream| stream.last_sent.is_some())
1848            .max_by_key(|stream| stream.last_sent.map(|(_, at)| at))
1849        else {
1850            unsent(self);
1851            return;
1852        };
1853        let (Some(ssrc_rtx), Some(pt_rtx), Some((newest, _))) =
1854            (stream.ssrc_rtx, stream.payload_type_rtx, stream.last_sent)
1855        else {
1856            unsent(self);
1857            return;
1858        };
1859
1860        // The newest packet still held gives the header; after the buffer was emptied (a
1861        // give-up, the pacer's flush) and before the next packet is written, the newest it
1862        // held then.
1863        let Some(template) = stream
1864            .send_buffer
1865            .get(newest)
1866            .cloned()
1867            .or_else(|| stream.probe_template.clone())
1868        else {
1869            unsent(self);
1870            return;
1871        };
1872
1873        let wanted = wanted.min(MAX_PROBE_FILL_OCTETS);
1874        let mut filled = 0usize;
1875        for _ in 0..MAX_PROBE_FILL_PACKETS {
1876            if filled >= wanted || self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
1877                break;
1878            }
1879            let packet = padding_packet(
1880                &mut stream.rtx_sequence_number,
1881                (stream.rid_extension_id, stream.repaired_rid_extension_id),
1882                &stream.identifiers,
1883                &template,
1884                ssrc_rtx,
1885                pt_rtx,
1886            );
1887            filled += packet.marshal_size();
1888            self.retransmissions_queued += 1;
1889            let mut message =
1890                AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission);
1891            if fill.is_none() {
1892                // No pacer took the request on its way here: nothing below releases this
1893                // padding at the cluster's rate or marks it, so it leaves as one burst and
1894                // carries the cluster's mark from here. The congestion controller measures
1895                // such a cluster by how the path spread it (`burst_estimate`).
1896                message.add(Attribute::Custom(std::sync::Arc::new(ProbePacket {
1897                    cluster: request.cluster,
1898                })));
1899            }
1900            self.write_queue.push_back(TaggedPacket {
1901                now,
1902                transport: TransportContext::default(),
1903                message,
1904            });
1905        }
1906    }
1907
1908    /// Tells the congestion controller that nothing here could pad `request`'s cluster, when
1909    /// no pacer took it either (`fill` absent: the pacer adds [`ProbeFill`](crate::ProbeFill)
1910    /// to every request and sends a cluster from the media it holds): no packet leaves for the
1911    /// cluster ([`ProbeUnsent`]). The controller then counts it as never asked for and asks
1912    /// again once a stream that can carry it has sent, instead of waiting a second for a
1913    /// result and spending a start-up cluster on it (the first audio packet of a call asks
1914    /// before the video, whose RTX stream carries the padding, has sent).
1915    fn probe_unsent(
1916        &mut self,
1917        now: Instant,
1918        request: &ProbeRequest,
1919        fill: Option<usize>,
1920        session: Option<usize>,
1921    ) {
1922        if fill.is_none() {
1923            self.write_queue.push_back(
1924                ProbeUnsent {
1925                    cluster: request.cluster,
1926                }
1927                .into_packet(now, session),
1928            );
1929        }
1930    }
1931
1932    /// Forgets the packets the pacer discarded ([`PacerDiscard`](crate::PacerDiscard)): out of
1933    /// the retransmission buffer, so a NACK for one is answered by nothing (RFC 4588 section 7:
1934    /// the sender "MAY selectively retransmit only the packets that it deems important"; a frame
1935    /// the pacer gave up is not), out of the requests waiting, and out of the original packets
1936    /// counted against the target, since they never used the link.
1937    fn forget_discarded(&mut self, discard: &crate::PacerDiscard) {
1938        if let Some(stream) = self.streams.get_mut(&discard.ssrc) {
1939            for &seq in &discard.sequence_numbers {
1940                let Some(packet) = stream.send_buffer.remove(seq) else {
1941                    continue;
1942                };
1943                let slot = usize::from(seq) % stream.sent_at.len();
1944                if let Some((sequence_number, at, _)) = stream.sent_at[slot]
1945                    && sequence_number == seq
1946                {
1947                    self.originals.forget(at, packet.marshal_size());
1948                    stream.sent_at[slot] = None;
1949                }
1950                stream.repairs.remove(seq);
1951            }
1952        }
1953        let before = self.pending.len();
1954        let asked = &mut self.pending_asked;
1955        let octets = &mut self.pending_octets;
1956        self.pending.retain(|entry| {
1957            let discarded = entry.ssrc == discard.ssrc
1958                && discard.sequence_numbers.contains(&entry.sequence_number);
1959            if discarded {
1960                asked.remove(&(entry.ssrc, entry.sequence_number));
1961                *octets -= entry.octets;
1962            }
1963            !discarded
1964        });
1965        if self.pending.len() != before {
1966            self.release_at = None;
1967        }
1968    }
1969
1970    /// The pacer gave its queue up at a collapse of the target
1971    /// ([`PacerFlush`](crate::PacerFlush)): everything sent before on the streams it names is
1972    /// forgotten (the retransmission buffer, the requests waiting, the retransmissions
1973    /// counted as waiting in the pacer), so a NACK for any of it is answered by nothing.
1974    /// Those packets belong to frames sized for a rate the path no longer carries, and the
1975    /// stream restarts at the key frame the pacer asks the application for (RFC 8834 section
1976    /// 6.1: "the likelihood of them arriving in time to be useful need[s] to be considered";
1977    /// RFC 4588 section 7: the sender "MAY selectively retransmit only the packets that it
1978    /// deems important"). What is written after it is buffered and repaired as ever.
1979    fn forget_flushed(&mut self, flush: &crate::PacerFlush) {
1980        self.forget_streams(&flush.ssrcs);
1981    }
1982
1983    /// Forgets everything sent so far on the streams `ssrcs`: their retransmission buffers,
1984    /// what is remembered of their repairs, the requests waiting.
1985    fn forget_streams(&mut self, ssrcs: &[u32]) {
1986        let size = self.size;
1987        for ssrc in ssrcs {
1988            let Some(stream) = self.streams.get_mut(ssrc) else {
1989                continue;
1990            };
1991            // A probe cluster asked for before the next packet is written still needs a
1992            // header to pad under: without one no padding leaves, the cluster goes
1993            // unanswered and a chain without a pacer stops asking.
1994            if let Some(newest) = stream
1995                .last_sent
1996                .and_then(|(newest, _)| stream.send_buffer.get(newest))
1997            {
1998                stream.probe_template = Some(newest.clone());
1999            }
2000            if let Some(buffer) = SendBuffer::new(size) {
2001                stream.send_buffer = buffer;
2002            }
2003            stream.sent_at.iter_mut().for_each(|sent| *sent = None);
2004            stream.last_retransmit.clear();
2005            // What was remembered of the repairs of those packets goes with them. Not needed
2006            // for what is sent: with the buffer emptied no flushed packet can be retransmitted
2007            // again whatever this memory says (`retransmittable` finds none), and the entries
2008            // would age out (`expire_repairs`). Cleared so that a report still in flight on
2009            // one of those repairs finds nothing to hold a later request against, and the
2010            // stream's memory starts empty with the key frame, as its buffer does.
2011            stream.repairs.clear();
2012            stream.repairs_by_rtx.clear();
2013            stream.repairs_order.clear();
2014        }
2015        let before = self.pending.len();
2016        let asked = &mut self.pending_asked;
2017        let octets = &mut self.pending_octets;
2018        self.pending.retain(|entry| {
2019            let flushed = ssrcs.contains(&entry.ssrc);
2020            if flushed {
2021                asked.remove(&(entry.ssrc, entry.sequence_number));
2022                *octets -= entry.octets;
2023            }
2024            !flushed
2025        });
2026        if self.pending.len() != before {
2027            self.release_at = None;
2028        }
2029    }
2030
2031    /// Gives up the repair of everything sent so far on the video streams among `ssrcs` and
2032    /// asks the application for a key frame of each (a Picture Loss Indication with sender
2033    /// SSRC 0 marked [`Attribute::DeliverToApplication`], as the pacer's flush does, and
2034    /// carrying [`LocalKeyFrameRequest::RepairGivenUp`](crate::LocalKeyFrameRequest)). The
2035    /// reserve those repairs held is released: the retransmissions made so far no longer count
2036    /// as in use. Audio streams are left as they are.
2037    fn give_up(&mut self, now: Instant, ssrcs: &[u32]) {
2038        let mut ssrcs: Vec<u32> = ssrcs
2039            .iter()
2040            .copied()
2041            .filter(|ssrc| self.streams.get(ssrc).is_some_and(|stream| stream.video))
2042            .collect();
2043        ssrcs.sort_unstable();
2044        ssrcs.dedup();
2045        if ssrcs.is_empty() {
2046            return;
2047        }
2048        self.forget_streams(&ssrcs);
2049        self.reserve_since = Some(now);
2050        self.release_at = None;
2051        // No target from before counts again: what is written from here on (the key frame)
2052        // is written for the target now.
2053        if let Some(target) = self.target_bps {
2054            self.targets.clear();
2055            self.targets.push_back((now, target));
2056        }
2057        for ssrc in ssrcs {
2058            self.read_queue.push_back(TaggedPacket {
2059                now,
2060                transport: TransportContext::default(),
2061                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
2062                    rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication {
2063                        sender_ssrc: 0,
2064                        media_ssrc: ssrc,
2065                    },
2066                )]))
2067                .with(Attribute::DeliverToApplication)
2068                .with(Attribute::Custom(std::sync::Arc::new(
2069                    crate::LocalKeyFrameRequest::RepairGivenUp,
2070                ))),
2071            });
2072        }
2073    }
2074
2075    /// Notes the target `target` set at `now` (for [`Self::backlog_collapsed`]).
2076    fn note_target(&mut self, now: Instant, target: f64) {
2077        if self.targets.back().is_some_and(|(_, last)| *last == target) {
2078            return;
2079        }
2080        self.targets.push_back((now, target));
2081        while self.targets.len() > 1
2082            && now.saturating_duration_since(self.targets[1].0) >= COLLAPSE_LOOK_BACK
2083        {
2084            self.targets.pop_front();
2085        }
2086        while self.targets.len() > MAX_TARGETS_KEPT {
2087            self.targets.pop_front();
2088        }
2089    }
2090
2091    /// Whether the requests waiting are a backlog the path will not carry in time
2092    /// ([`NackResponderBuilder::with_repair_backlog_bound`]): they would take the bound or
2093    /// more to leave if they had the whole target, and the target is at most [`COLLAPSE_AT`]
2094    /// of the highest in force within [`COLLAPSE_LOOK_BACK`].
2095    fn backlog_collapsed(&self, now: Instant) -> bool {
2096        let (Some(bound), Some(target)) = (self.repair_backlog_bound, self.target_bps) else {
2097            return false;
2098        };
2099        if self.pending.is_empty() || target <= 0.0 {
2100            return false;
2101        }
2102        if (self.pending_octets as f64 * 8.0 / target) < bound.as_secs_f64() {
2103            return false;
2104        }
2105        let mut highest: f64 = 0.0;
2106        for (index, (_, in_force)) in self.targets.iter().enumerate() {
2107            let superseded = self.targets.get(index + 1).is_some_and(|(next, _)| {
2108                now.saturating_duration_since(*next) >= COLLAPSE_LOOK_BACK
2109            });
2110            if !superseded {
2111                highest = highest.max(*in_force);
2112            }
2113        }
2114        highest > 0.0 && target <= COLLAPSE_AT * highest
2115    }
2116
2117    /// Gives up a collapsed backlog at `now`: the video streams with requests waiting. The
2118    /// give-up forgets the targets from before it ([`Self::give_up`]), so the key frame that
2119    /// answers it is not given up in its turn unless the target halves again.
2120    fn give_up_a_backlog(&mut self, now: Instant) {
2121        if !self.backlog_collapsed(now) {
2122            return;
2123        }
2124        let ssrcs: Vec<u32> = self.pending.iter().map(|entry| entry.ssrc).collect();
2125        self.give_up(now, &ssrcs);
2126    }
2127
2128    /// Whether `seq` of `stream`, sent again in `form`, was written longer ago than the
2129    /// sender's own judgement repairs ([`NackResponderBuilder::with_max_repair_age`]). Never
2130    /// with an `rtx-time` in force for that form ([`Self::rtx_time`]): that time is then the
2131    /// one that counts ([`Self::retransmittable`]). One rule per packet: the same per-form
2132    /// value is the age cut, this switch, and the switch of the give-up in the NACK handler.
2133    fn too_old(&self, stream: &LocalStream, form: RepairForm, seq: u16, now: Instant) -> bool {
2134        self.rtx_time(stream, form).is_none()
2135            && self
2136                .max_repair_age
2137                .is_some_and(|bound| Self::age(stream, seq, now).is_some_and(|age| age > bound))
2138    }
2139
2140    /// The pacer's report of retransmissions that left it or were dropped
2141    /// ([`RetransmissionsLeft`](crate::RetransmissionsLeft)): no longer on their way. One that
2142    /// left counts its resend interval from now, the instant it went toward the wire, not from
2143    /// when it was made (libwebrtc's `RtpPacketHistory` sets the send time when the pacer sends
2144    /// it); one that was dropped may be asked for again.
2145    fn retransmissions_left(&mut self, now: Instant, notice: &crate::RetransmissionsLeft) {
2146        self.pacer_reports = true;
2147        for &(ssrc, seq) in &notice.departed {
2148            let Some(stream) = self
2149                .media_ssrc(ssrc)
2150                .and_then(|media| self.streams.get_mut(&media))
2151            else {
2152                continue;
2153            };
2154            let packet = stream.packet(seq);
2155            if let Some(repair) = stream.repairs.get(seq).copied()
2156                && repair.state == RepairState::InPacer
2157            {
2158                if packet == Some(repair.packet) {
2159                    stream
2160                        .repairs
2161                        .set_state(seq, RepairState::Unreported { left: now });
2162                    stream.last_retransmit.insert(seq, now);
2163                } else {
2164                    // The packet it repaired is no longer held: nothing of it is asked for
2165                    // again, and the packet that has the number now starts afresh.
2166                    stream.repairs.remove(seq);
2167                }
2168            }
2169        }
2170        for &(ssrc, seq) in &notice.dropped {
2171            if let Some(stream) = self
2172                .media_ssrc(ssrc)
2173                .and_then(|media| self.streams.get_mut(&media))
2174                && stream
2175                    .repairs
2176                    .get(seq)
2177                    .is_some_and(|repair| repair.state == RepairState::InPacer)
2178            {
2179                stream.repairs.remove(seq);
2180            }
2181        }
2182        // A pacer drops what waited its queue time bound and says so; anything older than
2183        // that is no longer there.
2184        self.expire_repairs(now);
2185        self.release_at = None;
2186    }
2187
2188    /// What is remembered at `now` of the latest retransmission under `seq` of the stream
2189    /// `ssrc`. A state that ran out by the clock is ended here (a wait for the report becomes
2190    /// [`RepairState::Overdue`], anything else is forgotten), and so is what is remembered of
2191    /// a packet the stream no longer holds under that number, except a retransmission still
2192    /// in the pacer (see [`RepairState::InPacer`]).
2193    fn repair(&mut self, ssrc: u32, seq: u16, now: Instant) -> Option<Repair> {
2194        let wait = self.report_wait();
2195        let stream = self.streams.get_mut(&ssrc)?;
2196        let packet = stream.packet(seq);
2197        stream.repairs.bring_up_to_date(seq, packet, now, wait)
2198    }
2199
2200    /// Brings `repair`, of the packet `packet` holds now, up to `now`; whether it is over.
2201    fn repair_ended(
2202        repair: &mut Repair,
2203        packet: Option<u64>,
2204        now: Instant,
2205        wait: Duration,
2206    ) -> bool {
2207        let same = packet == Some(repair.packet);
2208        let horizon = crate::RETRANSMISSION_REPORT_HORIZON.max(wait);
2209        match repair.state {
2210            RepairState::InPacer => now.saturating_duration_since(repair.made) >= IN_PACER_LIFETIME,
2211            RepairState::Unreported { left } => {
2212                if same && now >= left + wait {
2213                    repair.state = RepairState::Overdue { left };
2214                }
2215                !same || now.saturating_duration_since(left) >= horizon
2216            }
2217            RepairState::Overdue { left } => {
2218                !same || now.saturating_duration_since(left) >= horizon
2219            }
2220            RepairState::Delivered { reported } => {
2221                !same || now.saturating_duration_since(reported) >= DELIVERED_MEMORY
2222            }
2223        }
2224    }
2225
2226    /// Ends everything remembered of retransmissions that ran out by `now` (see
2227    /// [`Self::repair`]), and the RTX sequence numbers too old for a report to count.
2228    fn expire_repairs(&mut self, now: Instant) {
2229        let wait = self.report_wait();
2230        let horizon = IN_PACER_LIFETIME + crate::RETRANSMISSION_REPORT_HORIZON.max(wait);
2231        for stream in self.streams.values_mut() {
2232            stream.repairs.expire(&stream.sent_at, now, wait);
2233            while let Some(&(rtx_sequence, made)) = stream.repairs_order.front() {
2234                if now.saturating_duration_since(made) < horizon {
2235                    break;
2236                }
2237                stream.repairs_order.pop_front();
2238                if stream
2239                    .repairs_by_rtx
2240                    .get(&rtx_sequence)
2241                    .is_some_and(|(_, at)| *at == made)
2242                {
2243                    stream.repairs_by_rtx.remove(&rtx_sequence);
2244                }
2245            }
2246        }
2247    }
2248
2249    /// Whether the stream `ssrc` holds the packet `packet` under `seq`.
2250    fn holds(&self, ssrc: u32, seq: u16, packet: u64) -> bool {
2251        self.streams
2252            .get(&ssrc)
2253            .is_some_and(|stream| stream.packet(seq) == Some(packet))
2254    }
2255
2256    /// Whether a retransmission under `seq` of the stream `ssrc` waits in the pacer at `now`.
2257    fn in_pacer(&mut self, ssrc: u32, seq: u16, now: Instant) -> bool {
2258        self.repair(ssrc, seq, now)
2259            .is_some_and(|repair| repair.state == RepairState::InPacer)
2260    }
2261
2262    /// How long a request waits for the feedback on an earlier retransmission of its packet:
2263    /// two round trips and [`REPAIR_REPORT_MARGIN`], or [`PENDING_REQUEST_LIFETIME`] before a
2264    /// round trip is known.
2265    fn report_wait(&self) -> Duration {
2266        self.round_trip_time
2267            .map_or(PENDING_REQUEST_LIFETIME, |rtt| {
2268                rtt * 2 + REPAIR_REPORT_MARGIN
2269            })
2270    }
2271
2272    /// What a request for `key` gets at `now`, given what the feedback reported on its earlier
2273    /// retransmission (see [`RetransmissionsReported`](crate::RetransmissionsReported)). Without
2274    /// such reports every request is answered as before. A wait that ran out is forgotten.
2275    fn repeat_state(&mut self, key: (u32, u16), now: Instant) -> Repeat {
2276        if !self.repairs_reported {
2277            return Repeat::Answer;
2278        }
2279        let (ssrc, seq) = key;
2280        match self.repair(ssrc, seq, now).map(|repair| repair.state) {
2281            Some(RepairState::Delivered { .. }) => Repeat::Decline,
2282            Some(RepairState::Unreported { left }) => Repeat::Hold(left + self.report_wait()),
2283            // In the pacer: not asked here (nothing is made while it waits there).
2284            Some(RepairState::InPacer | RepairState::Overdue { .. }) | None => Repeat::Answer,
2285        }
2286    }
2287
2288    /// The media SSRC of `ssrc`: itself, or the stream whose retransmission SSRC it is.
2289    fn media_ssrc(&self, ssrc: u32) -> Option<u32> {
2290        if self.streams.contains_key(&ssrc) {
2291            Some(ssrc)
2292        } else {
2293            self.streams
2294                .iter()
2295                .find(|(_, stream)| stream.ssrc_rtx == Some(ssrc))
2296                .map(|(media, _)| *media)
2297        }
2298    }
2299
2300    /// The transport-wide feedback on retransmissions
2301    /// ([`RetransmissionsReported`](crate::RetransmissionsReported)). RFC 4588 section 7: the
2302    /// sender "MAY selectively retransmit only the packets that it deems important and ignore
2303    /// NACK messages for other packets"; RFC 8834 section 6.1: "It is not appropriate to blindly
2304    /// retransmit RTP packets in response to a NACK." A request for a packet whose
2305    /// retransmission the receiver got crossed that retransmission on the way (the receiver
2306    /// asks again while the packet is missing, and it waited in the path's queue): it is not
2307    /// answered. One whose retransmission was lost is answered at once.
2308    fn repairs_reported(&mut self, now: Instant, report: &crate::RetransmissionsReported) {
2309        self.repairs_reported = true;
2310        // The clock first: a report counts only for what is still remembered at `now`.
2311        self.expire_repairs(now);
2312        let mut delivered = Vec::new();
2313        for reported in &report.received {
2314            let Some(media) = self.media_ssrc(reported.ssrc) else {
2315                continue;
2316            };
2317            let seq = reported.sequence_number;
2318            // Of this packet (not an earlier one of the same number), and not known already:
2319            // a report that comes again does not begin the memory again.
2320            if let Some(repair) = self.repair(media, seq, now)
2321                && self.holds(media, seq, repair.packet)
2322                && reported.sent >= repair.first_made
2323                && !matches!(repair.state, RepairState::Delivered { .. })
2324                && let Some(stream) = self.streams.get_mut(&media)
2325                && stream.repairs.contains_key(seq)
2326            {
2327                stream
2328                    .repairs
2329                    .set_state(seq, RepairState::Delivered { reported: now });
2330                delivered.push((media, seq));
2331            }
2332        }
2333        for reported in &report.lost {
2334            let Some(media) = self.media_ssrc(reported.ssrc) else {
2335                continue;
2336            };
2337            let seq = reported.sequence_number;
2338            // The latest retransmission of this packet was lost: asked for again, it is
2339            // answered. The loss of an earlier one says nothing of the one on its way.
2340            if let Some(repair) = self.repair(media, seq, now)
2341                && reported.sent >= repair.made
2342                && matches!(
2343                    repair.state,
2344                    RepairState::Unreported { .. } | RepairState::Overdue { .. }
2345                )
2346                && let Some(stream) = self.streams.get_mut(&media)
2347            {
2348                stream.repairs.remove(seq);
2349            }
2350        }
2351        if !delivered.is_empty() {
2352            let asked = &mut self.pending_asked;
2353            let octets = &mut self.pending_octets;
2354            self.pending.retain(|entry| {
2355                let key = (entry.ssrc, entry.sequence_number);
2356                let keep = !delivered.contains(&key);
2357                if !keep {
2358                    asked.remove(&key);
2359                    *octets -= entry.octets;
2360                }
2361                keep
2362            });
2363        }
2364        self.release_at = None;
2365    }
2366
2367    /// What RFC 8888 congestion control feedback (`CcFeedbackReport`) in `rtcp_packets` says
2368    /// of the retransmissions: it reports the packets of the RTX stream under their own
2369    /// sequence numbers, each mapped back to the packet it repaired. The counterpart of the
2370    /// TWCC sender's [`RetransmissionsReported`](crate::RetransmissionsReported) for streams
2371    /// whose feedback is RFC 8888.
2372    fn ccfb_report(
2373        &self,
2374        rtcp_packets: &[Box<dyn rtcp::Packet>],
2375    ) -> crate::RetransmissionsReported {
2376        let mut report = crate::RetransmissionsReported::default();
2377        for feedback in rtcp_packets.iter().filter_map(|packet| {
2378            packet
2379                .as_any()
2380                .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>()
2381        }) {
2382            let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
2383            for (ssrc, acknowledgements) in per_stream {
2384                // The RTX stream of one stream, or a FlexFEC repair stream that one or more
2385                // streams retransmit on (named then by the media SSRC).
2386                let streams: Vec<(u32, &LocalStream)> = self
2387                    .streams
2388                    .iter()
2389                    .filter_map(|(media, stream)| {
2390                        if stream.ssrc_rtx == Some(ssrc) {
2391                            Some((ssrc, stream))
2392                        } else if stream.flexfec.is_some_and(|(fec, _)| fec == ssrc) {
2393                            Some((*media, stream))
2394                        } else {
2395                            None
2396                        }
2397                    })
2398                    .collect();
2399                for acknowledgement in acknowledgements {
2400                    if let Some((named, &(sequence_number, sent))) =
2401                        streams.iter().find_map(|(named, stream)| {
2402                            stream
2403                                .repairs_by_rtx
2404                                .get(&acknowledgement.sequence_number)
2405                                .map(|repair| (*named, repair))
2406                        })
2407                    {
2408                        let reported = crate::ReportedRetransmission {
2409                            ssrc: named,
2410                            sequence_number,
2411                            sent,
2412                        };
2413                        if acknowledgement.arrived {
2414                            report.received.push(reported);
2415                        } else {
2416                            report.lost.push(reported);
2417                        }
2418                    }
2419                }
2420            }
2421        }
2422        report
2423    }
2424
2425    /// Handle a NACK request by queuing retransmissions.
2426    fn handle_nack(
2427        &mut self,
2428        now: Instant,
2429        nack: &rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack,
2430    ) {
2431        // Collect sequence numbers to retransmit
2432        let mut seqs_to_retransmit = Vec::new();
2433
2434        for nack_pair in &nack.nacks {
2435            // Check the base packet ID
2436            seqs_to_retransmit.push(nack_pair.packet_id);
2437
2438            // Check each bit in lost_packets bitmap
2439            for i in 0..16 {
2440                if nack_pair.lost_packets & (1 << i) != 0 {
2441                    let seq = nack_pair.packet_id.wrapping_add(i + 1);
2442                    seqs_to_retransmit.push(seq);
2443                }
2444            }
2445        }
2446
2447        let ssrc = nack.media_ssrc;
2448        // A stream that may not send is not repaired either (RFC 8866 section 6.7.4).
2449        if self.not_sending.contains(&ssrc) {
2450            return;
2451        }
2452        let resend_interval = resend_interval(self.round_trip_time);
2453        let Some(stream) = self.streams.get_mut(&ssrc) else {
2454            return;
2455        };
2456
2457        // A NACK may name the same packet in several pairs; resend each once.
2458        seqs_to_retransmit.sort_unstable();
2459        seqs_to_retransmit.dedup();
2460        // Forget suppression entries old enough not to matter.
2461        stream
2462            .last_retransmit
2463            .retain(|_, at| now.saturating_duration_since(*at) < resend_interval);
2464
2465        // A packet asked for that was written too long ago to be of use
2466        // (`with_max_repair_age`). For a video stream the repair of everything sent so far
2467        // is given up and a key frame asked for; an audio packet is simply not retransmitted
2468        // (`retransmittable`). Only a packet that would be answered counts: one without a
2469        // repair form (a FEC packet in RED on a stream without RTX, a payload type without
2470        // an RTX format on a stream that has RTX) is never sent again, so the receiver is
2471        // not kept waiting for a picture by it, and it is skipped here as it is below.
2472        if let Some(stream) = self.streams.get(&ssrc)
2473            && stream.video
2474            && seqs_to_retransmit.iter().any(|seq| {
2475                stream
2476                    .send_buffer
2477                    .get(*seq)
2478                    .and_then(|packet| stream.repair_form(packet))
2479                    .is_some_and(|form| self.too_old(stream, form, *seq, now))
2480            })
2481        {
2482            self.give_up(now, &[ssrc]);
2483            return;
2484        }
2485
2486        // Every packet asked for joins the requests waiting, oldest request first (one asked
2487        // for again keeps its place and is asked for afresh), and leaves as the rate limit has
2488        // room (RFC 4588 section 7): what does not fit now leaves when the window has room.
2489        for seq in seqs_to_retransmit {
2490            let Some(stream) = self.streams.get(&ssrc) else {
2491                return;
2492            };
2493            if stream.last_retransmit.contains_key(&seq) {
2494                continue;
2495            }
2496            let Some(octets) = self.retransmittable(stream, seq, now) else {
2497                continue;
2498            };
2499            if self.in_pacer(ssrc, seq, now)
2500                || self.repeat_state((ssrc, seq), now) == Repeat::Decline
2501            {
2502                continue;
2503            }
2504            let Some(stream) = self.streams.get(&ssrc) else {
2505                return;
2506            };
2507            let budget = stream.retransmit_budget;
2508            let Some(packet) = stream.packet(seq) else {
2509                continue;
2510            };
2511            // A request still waiting under this number for a packet since replaced ends here.
2512            if self
2513                .pending_asked
2514                .get(&(ssrc, seq))
2515                .is_some_and(|(_, waiting)| *waiting != packet)
2516                && let Some(waiting) = self
2517                    .pending
2518                    .iter()
2519                    .position(|waiting| waiting.ssrc == ssrc && waiting.sequence_number == seq)
2520            {
2521                self.remove_pending(waiting);
2522            }
2523            match self.pending_asked.get_mut(&(ssrc, seq)) {
2524                Some((asked, _)) => *asked = now,
2525                None => {
2526                    // The budget (one retransmission per original sent) refuses it: not
2527                    // kept, the receiver asks again. Only the rate limit makes a request wait.
2528                    if budget == 0 || self.pending.len() >= MAX_QUEUED_RETRANSMISSIONS {
2529                        break;
2530                    }
2531                    self.pending_asked.insert((ssrc, seq), (now, packet));
2532                    // A stream's oldest packet first, whenever it was asked for: a receiver
2533                    // that plays in order waits for its oldest gap, and a packet asked for
2534                    // again (its repair was lost) would otherwise wait behind every newer one.
2535                    let at = self
2536                        .pending
2537                        .iter()
2538                        .position(|waiting| {
2539                            waiting.ssrc == ssrc
2540                                && waiting.sequence_number.wrapping_sub(seq) < 0x8000
2541                        })
2542                        .unwrap_or(self.pending.len());
2543                    self.pending.insert(
2544                        at,
2545                        PendingRetransmission {
2546                            ssrc,
2547                            sequence_number: seq,
2548                            packet,
2549                            octets,
2550                        },
2551                    );
2552                    self.pending_octets += octets;
2553                }
2554            }
2555        }
2556        self.release_at = None;
2557        self.expire_pending(now);
2558        // The original media is lowered by the reserve before any of these is sent (RFC 4588
2559        // section 7: "the sender SHOULD NOT send retransmission packets without reducing the
2560        // packet rate and bitrate of the original stream"); the retransmissions may then use it.
2561        // A backlog the collapsed path will not carry in time is given up instead (the same
2562        // section: "If congestion is not kept under control, then retransmission SHOULD NOT
2563        // be used").
2564        self.give_up_a_backlog(now);
2565        self.announce_reserve(now, false);
2566        self.release(now);
2567    }
2568}
2569
2570/// An RFC 8627 FlexFEC repair stream as the NACK responder sees it: the sequence numbers of
2571/// its packets, which the responder owns (the FEC encoder's repair packets pass it on their way
2572/// to the wire and are numbered here, so its retransmissions share one sequence space with
2573/// them), and the timestamp of its last packet, from which a retransmission's is read.
2574#[derive(Debug, Default)]
2575struct FlexFecRepairStream {
2576    /// The next sequence number; `None` until the first packet (the encoder's first, or, for a
2577    /// retransmission before any, a start drawn from the repair SSRC: random as the SSRC is,
2578    /// RFC 3550 section 5.1, and the same in every run of a seeded call).
2579    next: Option<u16>,
2580    /// The last packet's instant and RTP timestamp on the repair stream's clock.
2581    last: Option<(Instant, u32)>,
2582}
2583
2584impl FlexFecRepairStream {
2585    /// The sequence number the next packet on the repair stream takes; `seen` is the one the
2586    /// encoder gave a packet of its own (the start of the space when nothing came before).
2587    fn take(&mut self, seen: Option<u16>, ssrc: u32) -> u16 {
2588        let next = *self
2589            .next
2590            .get_or_insert_with(|| seen.unwrap_or((ssrc >> 16) as u16 ^ ssrc as u16));
2591        self.next = Some(next.wrapping_add(1));
2592        next
2593    }
2594}
2595
2596/// RFC 8627 section 4.2.2.3, a FlexFEC retransmission packet (R=1, F=0) that carries
2597/// `original` again on the repair stream: the repair stream's SSRC, payload type, next sequence
2598/// number and timestamp (its last packet's moved on by the time since, on a 90 kHz clock, or
2599/// the original's when the stream has sent nothing yet), and as payload the original RTP
2600/// packet as it was sent ("The retransmission includes the RTP header of the source packet in
2601/// addition to the payload", section 1.1.7: version 2 reads as R=1 F=0).
2602fn flexfec_retransmission(
2603    repair: &mut FlexFecRepairStream,
2604    now: Instant,
2605    original_packet: &rtp::Packet,
2606    ssrc_fec: u32,
2607    pt_fec: u8,
2608) -> Option<rtp::Packet> {
2609    use shared::marshal::Marshal;
2610    let mut source = original_packet.clone();
2611    source.header.version = 2;
2612    source.header.padding = false;
2613    source.header.padding_size = 0;
2614    let payload = source.marshal().ok()?.freeze();
2615    let timestamp = repair
2616        .last
2617        .map_or(original_packet.header.timestamp, |(at, ts)| {
2618            let ticks = now.saturating_duration_since(at).as_nanos() * 90_000 / 1_000_000_000;
2619            ts.wrapping_add(ticks as u32)
2620        });
2621    repair.last = Some((now, timestamp));
2622    Some(rtp::Packet {
2623        header: rtp::header::Header {
2624            version: 2,
2625            payload_type: pt_fec,
2626            sequence_number: repair.take(None, ssrc_fec),
2627            timestamp,
2628            ssrc: ssrc_fec,
2629            ..Default::default()
2630        },
2631        payload,
2632    })
2633}
2634
2635/// The FlexFEC repair stream (SSRC, payload type) a stream's retransmissions go to: one that
2636/// negotiated RFC 8627 FlexFEC and no RTX (section 1.1.7).
2637fn flexfec_retransmission_stream(info: &StreamInfo) -> Option<(u32, u8)> {
2638    if info.ssrc_rtx.is_some() || !info.fec_is_flexfec() {
2639        return None;
2640    }
2641    Some((info.ssrc_fec?, info.payload_type_fec?))
2642}
2643
2644/// The RTX packet (RFC 4588 section 4) that carries `original` again: the RTX SSRC and
2645/// payload type, the next sequence number of the RTX stream, and the original sequence number
2646/// ahead of the payload.
2647fn rtx_packet(
2648    rtx_sequence_number: &mut u16,
2649    rid_extension_ids: (Option<u8>, Option<u8>),
2650    identifiers: &[(u8, bytes::Bytes)],
2651    original_packet: &rtp::Packet,
2652    ssrc_rtx: u32,
2653    pt_rtx: u8,
2654) -> rtp::Packet {
2655    let (rid_extension_id, repaired_rid_extension_id) = rid_extension_ids;
2656    let original_seq = original_packet.header.sequence_number;
2657    let mut rtx_payload = Vec::with_capacity(2 + original_packet.payload.len());
2658    rtx_payload.extend_from_slice(&original_seq.to_be_bytes());
2659    rtx_payload.extend_from_slice(&original_packet.payload);
2660
2661    let rtx_seq = *rtx_sequence_number;
2662    *rtx_sequence_number = rtx_sequence_number.wrapping_add(1);
2663
2664    // RFC 4588 4: the RTX packet carries the original's header "as is" apart from the SSRC,
2665    // payload type and sequence number, so its CSRCs and header extensions (audio level,
2666    // abs-send-time, mid, ...) go with it. Building a fresh header used to drop them. Version
2667    // is set explicitly: a buffered packet built with a defaulted header is version 0, which
2668    // receivers discard on arrival. Padding is not carried: the RTX payload is the original
2669    // payload alone.
2670    let mut header = original_packet.header.clone();
2671    header.version = 2;
2672    header.ssrc = ssrc_rtx;
2673    header.payload_type = pt_rtx;
2674    header.sequence_number = rtx_seq;
2675    header.padding = false;
2676    header.padding_size = 0;
2677    // RFC 7941 section 4.2.4.1: the stream's MID and RID go on every RTX packet, also when the
2678    // original went without them (its stream was acknowledged).
2679    for (id, value) in identifiers {
2680        if header.get_extension(*id).is_none() {
2681            let _ = header.set_extension_upgrading(*id, value.clone());
2682        }
2683    }
2684    // RFC 8852 3.2: a repair packet names the stream it repairs with the repaired-RID, not
2685    // the RID, so a receiver never takes the RTX SSRC for a simulcast layer of its own.
2686    if let Some(rid_id) = rid_extension_id
2687        && let Some(rid) = header.get_extension(rid_id)
2688    {
2689        let _ = header.del_extension(rid_id);
2690        if let Some(repaired_id) = repaired_rid_extension_id {
2691            let _ = header.set_extension(repaired_id, rid);
2692        }
2693    }
2694
2695    rtp::Packet {
2696        header,
2697        payload: rtx_payload.into(),
2698    }
2699}
2700
2701/// A padding-only packet of the RTX stream (a bandwidth probe): `template`'s header on the RTX
2702/// SSRC and payload type with the next RTX sequence number, no payload, and
2703/// [`PROBE_PADDING_OCTETS`] of padding.
2704fn padding_packet(
2705    rtx_sequence_number: &mut u16,
2706    rid_extension_ids: (Option<u8>, Option<u8>),
2707    identifiers: &[(u8, bytes::Bytes)],
2708    template: &rtp::Packet,
2709    ssrc_rtx: u32,
2710    pt_rtx: u8,
2711) -> rtp::Packet {
2712    let mut packet = rtx_packet(
2713        rtx_sequence_number,
2714        rid_extension_ids,
2715        identifiers,
2716        template,
2717        ssrc_rtx,
2718        pt_rtx,
2719    );
2720    packet.payload = bytes::Bytes::new();
2721    packet.header.marker = false;
2722    packet.header.padding = true;
2723    packet.header.padding_size = PROBE_PADDING_OCTETS;
2724    packet
2725}
2726
2727impl Protocol<TaggedPacket, TaggedPacket, ()> for NackResponderInterceptor {
2728    type Rout = TaggedPacket;
2729    type Wout = TaggedPacket;
2730    type Eout = ();
2731    type Error = Error;
2732    type Time = Instant;
2733
2734    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
2735        let now = msg.now;
2736        let announced_before = self.announced_reserve;
2737        // The congestion controller's target, which the retransmissions are held to.
2738        let carries_target = if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
2739            msg.message.get(&Attribute::TargetBitrateChanged {
2740                bits_per_second: 0.0,
2741            }) {
2742            if bits_per_second.is_finite() && *bits_per_second >= 0.0 {
2743                self.target_bps = Some(*bits_per_second);
2744                self.minimum_bps = msg
2745                    .message
2746                    .custom::<MinimumTarget>()
2747                    .map(|minimum| minimum.bits_per_second)
2748                    .filter(|minimum| minimum.is_finite());
2749                self.release_at = None;
2750            }
2751            true
2752        } else {
2753            false
2754        };
2755
2756        // The round trip the RTCP session measured: the reserve's horizon.
2757        if let Some(crate::RtcpSessionEvent::RoundTripTime { rtt, .. }) =
2758            msg.message.custom::<crate::RtcpSessionEvent>()
2759        {
2760            self.round_trip_time = Some(*rtt);
2761            self.release_at = None;
2762        }
2763
2764        // While the pacer tells the source to pause, the target on the packet is zero and the
2765        // congestion controller's rides with it: the rate the retransmissions are held to.
2766        if carries_target {
2767            let pause = msg.message.custom::<crate::PacerPause>().copied();
2768            self.paused = pause.is_some();
2769            if let Some(pause) = pause
2770                && pause.target_bits_per_second.is_finite()
2771                && pause.target_bits_per_second >= 0.0
2772            {
2773                self.target_bps = Some(pause.target_bits_per_second);
2774            }
2775        }
2776
2777        if carries_target && let Some(target) = self.target_bps {
2778            self.note_target(now, target);
2779            // The target fell under what the waiting repairs need.
2780            self.give_up_a_backlog(now);
2781        }
2782
2783        // Retransmissions that left the pacer (or were dropped there).
2784        if let Some(notice) = msg.message.custom::<crate::RetransmissionsLeft>() {
2785            let notice = notice.clone();
2786            self.retransmissions_left(now, &notice);
2787        }
2788
2789        // What RFC 8888 feedback reports on the RTX streams: read here, where the sequence
2790        // number each RTX packet was given is known.
2791        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
2792            let report = self.ccfb_report(rtcp_packets);
2793            if !report.received.is_empty() || !report.lost.is_empty() {
2794                self.repairs_reported(now, &report);
2795                self.release(now);
2796            }
2797        }
2798
2799        // What transport-wide feedback reported on the retransmissions.
2800        if let Some(report) = msg.message.custom::<crate::RetransmissionsReported>() {
2801            let report = report.clone();
2802            self.repairs_reported(now, &report);
2803            // A request held for a retransmission now reported lost leaves at once.
2804            self.release(now);
2805        }
2806
2807        // Packets the pacer (wire-ward of here) discarded: never resent.
2808        if let Some(discard) = msg.message.custom::<crate::PacerDiscard>() {
2809            let discard = discard.clone();
2810            self.forget_discarded(&discard);
2811        }
2812
2813        // The pacer gave its queue up at a collapse: nothing sent before is repaired.
2814        if let Some(flush) = msg.message.custom::<crate::PacerFlush>() {
2815            let flush = flush.clone();
2816            self.forget_flushed(&flush);
2817        }
2818
2819        // A probe cluster the congestion controller asks for: fill it.
2820        if let Some(request) = msg.message.custom::<ProbeRequest>().copied() {
2821            let session = crate::RtpSession::of(&msg.message);
2822            let fill = msg
2823                .message
2824                .custom::<crate::ProbeFill>()
2825                .filter(|fill| fill.cluster == request.cluster)
2826                .map(|fill| fill.octets);
2827            self.fill_probe(now, &request, fill, session);
2828        }
2829
2830        // Process NACK packets
2831        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
2832            for rtcp_packet in rtcp_packets {
2833                if let Some(nack) = rtcp_packet
2834                    .as_any()
2835                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
2836                {
2837                    self.handle_nack(now, nack);
2838                }
2839            }
2840        }
2841        if carries_target {
2842            // A new target may leave room for what waits.
2843            self.release(now);
2844        }
2845
2846        // The application's target is the controller's less the reserve (RFC 4588 section
2847        // 7): lowered on the packet that carries it, or announced on a carrier of its own when
2848        // only the reserve moved.
2849        if !carries_target
2850            && self.announced_reserve != announced_before
2851            && let Some(target_bps) = self.target_bps
2852        {
2853            // Moved while the NACK was read: the application hears of it here.
2854            let carrier = self.target_carrier(now, target_bps, self.announced_reserve);
2855            self.read_queue.push_back(carrier);
2856        }
2857        self.announce_reserve(now, !carries_target);
2858        if carries_target && self.announced_reserve > 0.0 {
2859            let (reserve, minimum) = (self.announced_reserve, self.minimum_bps.unwrap_or(0.0));
2860            for attribute in &mut msg.message.attributes {
2861                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
2862                    *bits_per_second = media_target(*bits_per_second, reserve, minimum);
2863                }
2864            }
2865        }
2866
2867        self.read_queue.push_back(msg);
2868
2869        Ok(())
2870    }
2871
2872    fn poll_read(&mut self) -> Option<Self::Rout> {
2873        self.read_queue.pop_front()
2874    }
2875
2876    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
2877        // A packet of a FlexFEC repair stream this responder retransmits on (the encoder's
2878        // repair packets): numbered in the one sequence space the retransmissions share.
2879        if let Packet::Rtp(packet) = &mut msg.message.packet
2880            && let Some(repair) = self.flexfec_repair.get_mut(&packet.header.ssrc)
2881        {
2882            packet.header.sequence_number =
2883                repair.take(Some(packet.header.sequence_number), packet.header.ssrc);
2884            repair.last = Some((msg.now, packet.header.timestamp));
2885        }
2886        if let Some(assignment) = msg.message.custom::<crate::RtpSessionAssignment>() {
2887            for ssrc in &assignment.ssrcs {
2888                self.sessions.insert(*ssrc, assignment.session);
2889            }
2890        }
2891        if let Some(filler) = msg.message.custom::<crate::cc::probe::FecProbeFiller>() {
2892            self.fec_probe_streams.insert(filler.ssrc);
2893        }
2894        // How much of a cluster left to it the FEC encoder filled: the rest is padded. The
2895        // carrier ends here.
2896        if let Some(filled) = msg
2897            .message
2898            .custom::<crate::cc::probe::FecProbeFilled>()
2899            .copied()
2900        {
2901            self.fec_probe_filled(msg.now, &filled);
2902            return Ok(());
2903        }
2904        // Streams that may not send from now on: what was sent of them is forgotten, so that
2905        // nothing of it is sent again, now or once they send again.
2906        if let Some(notice) = msg.message.custom::<crate::StreamsNotSending>() {
2907            let stopped: Vec<u32> = notice
2908                .ssrcs
2909                .iter()
2910                .copied()
2911                .filter(|ssrc| !self.not_sending.contains(ssrc))
2912                .collect();
2913            self.not_sending = notice.ssrcs.iter().copied().collect();
2914            self.forget_streams(&stopped);
2915        }
2916        if let Some(super::NackControl::LocalRtxTime {
2917            payload_type_rtx,
2918            rtx_time,
2919        }) = msg.message.custom::<super::NackControl>()
2920        {
2921            match rtx_time {
2922                Some(rtx_time) => self.local_rtx_times.insert(*payload_type_rtx, *rtx_time),
2923                None => self.local_rtx_times.remove(payload_type_rtx),
2924            };
2925        }
2926        // Every original packet counts against the target (RFC 4588 section 7), whether or
2927        // not its stream is repaired.
2928        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
2929            && !msg.message.has(&Attribute::Retransmission)
2930        {
2931            self.originals.expire(msg.now);
2932            self.originals.add(msg.now, rtp_packet.marshal_size());
2933        }
2934        // Buffer outgoing RTP packets
2935        if let Packet::Rtp(ref rtp_packet) = msg.message.packet
2936            && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
2937        {
2938            for id in [stream.mid_extension_id, stream.rid_extension_id]
2939                .into_iter()
2940                .flatten()
2941            {
2942                if let Some(value) = rtp_packet.header.get_extension(id) {
2943                    match stream
2944                        .identifiers
2945                        .iter_mut()
2946                        .find(|(known, _)| *known == id)
2947                    {
2948                        Some(entry) => entry.1 = value,
2949                        None => stream.identifiers.push((id, value)),
2950                    }
2951                }
2952            }
2953            stream.send_buffer.add(rtp_packet.clone());
2954            stream.last_sent = Some((rtp_packet.header.sequence_number, msg.now));
2955            stream.written += 1;
2956            let slot = usize::from(rtp_packet.header.sequence_number) % stream.sent_at.len();
2957            if let Some((held, _, serial)) = stream.sent_at[slot] {
2958                // What is remembered of that packet's repair no longer has a packet.
2959                stream.repairs.written_over(held, serial);
2960            }
2961            stream.sent_at[slot] =
2962                Some((rtp_packet.header.sequence_number, msg.now, stream.written));
2963            stream.retransmit_budget =
2964                (stream.retransmit_budget + 1).min(stream.retransmit_budget_max);
2965        }
2966        if matches!(msg.message.packet, Packet::Rtp(_)) {
2967            self.release_at = None;
2968            if !self.pending.is_empty() {
2969                // The budget may have room again.
2970                self.release(msg.now);
2971            }
2972            if !self.pending.is_empty() || self.announced_reserve > 0.0 {
2973                self.announce_reserve(msg.now, true);
2974            }
2975        }
2976
2977        self.write_queue.push_back(msg);
2978
2979        Ok(())
2980    }
2981
2982    fn poll_write(&mut self) -> Option<TaggedPacket> {
2983        // First drain retransmitted packets
2984        let packet = self.write_queue.pop_front()?;
2985        if packet.message.has(&Attribute::Retransmission) {
2986            self.retransmissions_queued = self.retransmissions_queued.saturating_sub(1);
2987        }
2988        Some(packet)
2989    }
2990
2991    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
2992        // What is remembered of retransmissions ends by this clock, with or without a
2993        // request or a report to end it.
2994        self.expire_repairs(now);
2995        if !self.pending.is_empty() || self.announced_reserve > 0.0 {
2996            // Worked out afresh: a deadline that passed without a change must not be handed
2997            // back again (a driver would spin on it).
2998            self.release_at = None;
2999            self.expire_pending(now);
3000            self.give_up_a_backlog(now);
3001            self.release(now);
3002            self.announce_reserve(now, true);
3003        }
3004        Ok(())
3005    }
3006
3007    /// Due at once while packets wait in the write queue. A retransmission or a probe cluster's
3008    /// padding is made on the read leg (a NACK, a [`ProbeRequest`]), which a driver reaches
3009    /// after its `poll_write` (`poll_write`, `poll_event`, `poll_read`, then `poll_timeout`
3010    /// and sleep, as the crate's event loop has it): without a deadline the packets would wait
3011    /// for whatever wakes the driver next, a timer or an incoming datagram, which can be a
3012    /// long time on a connection with little traffic. The deadline is the instant they were
3013    /// made, so the driver's `handle_timeout` and the `poll_write` after it take them out at
3014    /// once; it is gone when the queue is drained.
3015    ///
3016    /// A retransmission the rate limit holds back is not in the write queue: its deadline is
3017    /// the instant the limit next has room for it ([`Self::next_release`]), never earlier (a
3018    /// driver woken at once would spin), and the same for a waiting request running out and
3019    /// the reserve falling back to zero.
3020    fn poll_timeout(&mut self) -> Option<Self::Time> {
3021        let queued = self.write_queue.front().map(|packet| packet.now);
3022        queued.into_iter().chain(self.next_release()).min()
3023    }
3024}
3025
3026impl Interceptor for NackResponderInterceptor {
3027    fn bind_local_stream(&mut self, info: &StreamInfo) {
3028        if stream_supports_nack(info)
3029            && let Some(send_buffer) = SendBuffer::new(self.size)
3030        {
3031            // RFC 4588 4: the initial sequence number of the retransmission stream is random
3032            // (RFC 3550 5.1), and the stream is the RTX SSRC's, not the binding's: a stream
3033            // bound again continues where the SSRC left off.
3034            let rtx_sequence_number = info
3035                .ssrc_rtx
3036                .and_then(|ssrc_rtx| self.rtx_sequence_numbers.get(&ssrc_rtx).copied())
3037                .unwrap_or_else(rand::random::<u16>);
3038            self.streams.insert(
3039                info.ssrc,
3040                LocalStream {
3041                    send_buffer,
3042                    ssrc_rtx: info.ssrc_rtx,
3043                    payload_type_rtx: info.payload_type_rtx,
3044                    payload_type: info.payload_type,
3045                    rtx_payload_types: section_rtx_payload_types(info),
3046                    fec_in_red: section_fec_in_red(info),
3047                    rtx_sequence_number,
3048                    last_sent: None,
3049                    last_retransmit: HashMap::new(),
3050                    rid_extension_id: extension_id(info, RTP_STREAM_ID_URI),
3051                    repaired_rid_extension_id: extension_id(info, REPAIRED_RTP_STREAM_ID_URI),
3052                    mid_extension_id: extension_id(info, MID_URI),
3053                    identifiers: Vec::new(),
3054                    retransmit_budget: usize::from(self.size),
3055                    retransmit_budget_max: usize::from(self.size),
3056                    sent_at: vec![None; usize::from(self.size).max(1)],
3057                    written: 0,
3058                    repairs: Repairs::default(),
3059                    repairs_by_rtx: HashMap::new(),
3060                    repairs_order: VecDeque::new(),
3061                    video: !info.mime_type.to_ascii_lowercase().starts_with("audio/"),
3062                    probe_template: None,
3063                    flexfec: flexfec_retransmission_stream(info),
3064                },
3065            );
3066            if let Some((ssrc_fec, _)) = flexfec_retransmission_stream(info) {
3067                self.flexfec_repair.entry(ssrc_fec).or_default();
3068            }
3069        }
3070    }
3071
3072    fn unbind_local_stream(&mut self, info: &StreamInfo) {
3073        self.fec_probe_streams.remove(&info.ssrc);
3074        if let Some(stream) = self.streams.remove(&info.ssrc)
3075            && let Some(ssrc_rtx) = stream.ssrc_rtx
3076        {
3077            if self.rtx_sequence_numbers.len() >= MAX_REMEMBERED_RTX_SSRCS
3078                && !self.rtx_sequence_numbers.contains_key(&ssrc_rtx)
3079            {
3080                self.rtx_sequence_numbers.clear();
3081            }
3082            self.rtx_sequence_numbers
3083                .insert(ssrc_rtx, stream.rtx_sequence_number);
3084        }
3085    }
3086
3087    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
3088
3089    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
3090}
3091
3092#[cfg(test)]
3093mod tests {
3094    use super::*;
3095    use crate::stream_info::RTCPFeedback;
3096    use rtcp::transport_feedbacks::transport_layer_nack::{
3097        TransportLayerNack, nack_pairs_from_sequence_numbers,
3098    };
3099    use std::sync::Arc;
3100
3101    const SSRC: u32 = 0x1234;
3102    const RTX_SSRC: u32 = 0x5678;
3103    const SIZE: u16 = 64;
3104
3105    fn responder() -> NackResponderInterceptor {
3106        let mut responder = NackResponderBuilder::new()
3107            .with_size(SIZE)
3108            .with_rate_limit(RetransmissionRateLimit::Unlimited)
3109            .build();
3110        responder.bind_local_stream(&StreamInfo {
3111            ssrc: SSRC,
3112            ssrc_rtx: Some(RTX_SSRC),
3113            payload_type_rtx: Some(97),
3114            payload_type: 96,
3115            rtcp_feedback: vec![RTCPFeedback {
3116                typ: "nack".to_string(),
3117                parameter: String::new(),
3118            }],
3119            ..Default::default()
3120        });
3121        responder
3122    }
3123
3124    fn tagged(now: Instant, message: AttributedPacket) -> TaggedPacket {
3125        TaggedPacket {
3126            now,
3127            transport: TransportContext::default(),
3128            message,
3129        }
3130    }
3131
3132    fn original(responder: &mut NackResponderInterceptor, now: Instant, sequence_number: u16) {
3133        let packet = rtp::Packet {
3134            header: rtp::header::Header {
3135                version: 2,
3136                payload_type: 96,
3137                sequence_number,
3138                ssrc: SSRC,
3139                ..Default::default()
3140            },
3141            payload: vec![0u8; 100].into(),
3142        };
3143        responder
3144            .handle_write(tagged(now, AttributedPacket::new(Packet::Rtp(packet))))
3145            .unwrap();
3146    }
3147
3148    /// The sizes of everything the responder remembers of repairs and requests.
3149    fn remembered(responder: &NackResponderInterceptor) -> [usize; 5] {
3150        let stream = &responder.streams[&SSRC];
3151        [
3152            stream.repairs.len(),
3153            stream.repairs_by_rtx.len(),
3154            stream.repairs_order.len(),
3155            responder.pending.len(),
3156            responder.pending_asked.len(),
3157        ]
3158    }
3159
3160    /// A receiver that asks for everything, over and over, and reports whatever it likes of
3161    /// the retransmissions (received, lost, both, for packets retransmitted or not, with any
3162    /// instant) cannot make the responder remember more than its send buffer has places:
3163    /// what is kept of repairs is at most one entry per packet held. And the engine's clock
3164    /// alone empties it: with no further request or report, a timeout past the longest
3165    /// memory leaves nothing.
3166    #[test]
3167    fn requests_and_reports_without_end_do_not_grow_what_is_remembered() {
3168        let mut responder = responder();
3169        let base = Instant::now();
3170        let size = usize::from(SIZE);
3171        let mut now = base;
3172        let mut most = 0;
3173        // Reports come and a pacer is there, so every state is in use. From step 10 000 the
3174        // pacer says nothing more, and from step 20 000 no report comes either: every
3175        // retransmission then stays "in the pacer", the one state kept for whatever packet has
3176        // the number, for four seconds (8 000 steps) while the buffer turns over every 64.
3177        for step in 0..30_000u32 {
3178            now = base + Duration::from_micros(500) * step;
3179            let sequence_number = step as u16;
3180            original(&mut responder, now, sequence_number);
3181            // Ask for the whole buffer, and for numbers far outside it.
3182            let mut asked: Vec<u16> = (0..SIZE)
3183                .map(|back| sequence_number.wrapping_sub(back))
3184                .collect();
3185            asked.extend((0..SIZE).map(|far| sequence_number.wrapping_add(0x4000 + far * 97)));
3186            asked.sort_unstable();
3187            responder
3188                .handle_read(tagged(
3189                    now,
3190                    AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerNack {
3191                        sender_ssrc: 1,
3192                        media_ssrc: SSRC,
3193                        nacks: nack_pairs_from_sequence_numbers(&asked),
3194                    })])),
3195                ))
3196                .unwrap();
3197            // Reports on every sequence number there is, a different mix each time.
3198            let reported = |sequence_number: u16| crate::ReportedRetransmission {
3199                ssrc: RTX_SSRC,
3200                sequence_number,
3201                sent: now,
3202            };
3203            let numbers =
3204                (0..512u16).map(|index| index.wrapping_mul(128).wrapping_add(step as u16));
3205            let report = match step % 3 {
3206                0 => crate::RetransmissionsReported {
3207                    received: numbers.map(reported).collect(),
3208                    lost: vec![],
3209                },
3210                1 => crate::RetransmissionsReported {
3211                    received: vec![],
3212                    lost: numbers.map(reported).collect(),
3213                },
3214                _ => crate::RetransmissionsReported {
3215                    received: asked.iter().copied().map(reported).collect(),
3216                    lost: asked.iter().copied().map(reported).collect(),
3217                },
3218            };
3219            let mut message = AttributedPacket::new(Packet::Rtcp(vec![]))
3220                .with(Attribute::Custom(Arc::new(report)));
3221            if step < 10_000 && step % 7 == 0 {
3222                // The pacer's notices, as arbitrary.
3223                message.add(Attribute::Custom(Arc::new(crate::RetransmissionsLeft {
3224                    departed: asked.iter().map(|seq| (RTX_SSRC, *seq)).collect(),
3225                    dropped: vec![(RTX_SSRC, sequence_number)],
3226                })));
3227            }
3228            if step < 20_000 {
3229                responder.handle_read(tagged(now, message)).unwrap();
3230            }
3231            while responder.poll_write().is_some() {}
3232            while responder.poll_read().is_some() {}
3233            let [repairs, by_rtx, order, pending, asked] = remembered(&responder);
3234            assert!(
3235                repairs <= size && by_rtx <= size && order <= size,
3236                "step {step}: {repairs} repairs, {by_rtx} RTX numbers ({order}) remembered, \
3237                 the buffer holds {size}"
3238            );
3239            assert!(pending <= MAX_QUEUED_RETRANSMISSIONS && asked == pending);
3240            most = most.max(repairs);
3241        }
3242        assert!(
3243            most > size / 2,
3244            "most of the buffer's places were remembered at some point: {most} of {size}"
3245        );
3246        // Nothing more arrives. The clock alone:
3247        responder
3248            .handle_timeout(now + Duration::from_secs(30))
3249            .unwrap();
3250        assert_eq!([0; 5], remembered(&responder));
3251    }
3252
3253    /// A responder with a send buffer of `size` places, retransmitting without a rate limit.
3254    fn responder_of(size: u16) -> NackResponderInterceptor {
3255        let mut responder = NackResponderBuilder::new()
3256            .with_size(size)
3257            .with_rate_limit(RetransmissionRateLimit::Unlimited)
3258            .build();
3259        responder.bind_local_stream(&StreamInfo {
3260            ssrc: SSRC,
3261            ssrc_rtx: Some(RTX_SSRC),
3262            payload_type_rtx: Some(97),
3263            payload_type: 96,
3264            rtcp_feedback: vec![RTCPFeedback {
3265                typ: "nack".to_string(),
3266                parameter: String::new(),
3267            }],
3268            ..Default::default()
3269        });
3270        responder
3271    }
3272
3273    fn nack_of(now: Instant, asked: &[u16]) -> TaggedPacket {
3274        tagged(
3275            now,
3276            AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerNack {
3277                sender_ssrc: 1,
3278                media_ssrc: SSRC,
3279                nacks: nack_pairs_from_sequence_numbers(asked),
3280            })])),
3281        )
3282    }
3283
3284    /// One datagram with a NACK of its own for each of `asked` (a compound RTCP packet).
3285    fn nacks_of(now: Instant, asked: impl Iterator<Item = u16>) -> TaggedPacket {
3286        tagged(
3287            now,
3288            AttributedPacket::new(Packet::Rtcp(
3289                asked
3290                    .map(|seq| {
3291                        Box::new(TransportLayerNack {
3292                            sender_ssrc: 1,
3293                            media_ssrc: SSRC,
3294                            nacks: nack_pairs_from_sequence_numbers(&[seq]),
3295                        }) as Box<dyn rtcp::Packet>
3296                    })
3297                    .collect(),
3298            )),
3299        )
3300    }
3301
3302    fn expiry_visits(responder: &NackResponderInterceptor) -> u64 {
3303        responder.streams[&SSRC].repairs.expiry_visits
3304    }
3305
3306    /// With what is remembered of repairs filling every place of a 1024-packet send buffer, a
3307    /// datagram of 75 NACKs (about what a 1200-byte compound RTCP packet holds) and timeouts
3308    /// cost expiry no pass over that memory: an entry is visited when it ends or changes state,
3309    /// and only then. Each NACK and each timeout used to visit every entry (review perf-1 H2:
3310    /// about 22 us an answer, 75 x 1024 visits a datagram).
3311    #[test]
3312    fn expiry_visits_an_entry_only_when_it_ends_or_changes_state_however_many_nacks_come() {
3313        const SIZE: u16 = 1024;
3314        let mut responder = responder_of(SIZE);
3315        let base = Instant::now();
3316        let at = |ms: u64| base + Duration::from_millis(ms);
3317        for seq in 0..SIZE {
3318            original(&mut responder, at(0), seq);
3319        }
3320        while responder.poll_write().is_some() {}
3321        // Every packet asked for and retransmitted: a repair remembered in every place.
3322        for chunk in (0..SIZE).collect::<Vec<_>>().chunks(64) {
3323            responder.handle_read(nack_of(at(10), chunk)).unwrap();
3324            while responder.poll_write().is_some() {}
3325        }
3326        let remembered = responder.streams[&SSRC].repairs.len();
3327        assert_eq!(
3328            usize::from(SIZE),
3329            remembered,
3330            "precondition: the memory is full"
3331        );
3332
3333        let before = expiry_visits(&responder);
3334        // 75 NACKs in one datagram, eight times, and timeouts between them: nothing ends.
3335        for round in 0..8u16 {
3336            responder
3337                .handle_read(nacks_of(
3338                    at(20 + u64::from(round)),
3339                    (0..75).map(|i| (i * 13 + round) % SIZE),
3340                ))
3341                .unwrap();
3342            responder.handle_timeout(at(20 + u64::from(round))).unwrap();
3343            while responder.poll_write().is_some() {}
3344        }
3345        assert_eq!(
3346            usize::from(SIZE),
3347            responder.streams[&SSRC].repairs.len(),
3348            "nothing ended yet"
3349        );
3350        let nacks_cost = expiry_visits(&responder) - before;
3351        assert!(
3352            nacks_cost == 0,
3353            "600 NACKs and 8 timeouts visited {nacks_cost} remembered repairs, none of which ended"
3354        );
3355
3356        // The clock: past the wait for a report (1 s without a round trip) every entry becomes
3357        // overdue, past the horizon (4 s) every one ends. Each is visited once for each.
3358        responder.handle_timeout(at(1_500)).unwrap();
3359        responder.handle_timeout(at(10_000)).unwrap();
3360        assert_eq!(0, responder.streams[&SSRC].repairs.len());
3361        let total = expiry_visits(&responder) - before;
3362        assert!(
3363            total <= 2 * u64::from(SIZE),
3364            "{total} visits to end {SIZE} entries"
3365        );
3366    }
3367
3368    /// What a pass over every entry leaves, computed from a copy: the old `expire_repairs`.
3369    fn expired_by_a_full_pass(
3370        responder: &NackResponderInterceptor,
3371        now: Instant,
3372    ) -> HashMap<u16, Repair> {
3373        let wait = responder.report_wait();
3374        let stream = &responder.streams[&SSRC];
3375        let mut entries: HashMap<u16, Repair> = stream
3376            .repairs
3377            .iter()
3378            .map(|(seq, repair)| (*seq, *repair))
3379            .collect();
3380        entries.retain(|seq, repair| {
3381            !NackResponderInterceptor::repair_ended(
3382                repair,
3383                held_packet(&stream.sent_at, *seq),
3384                now,
3385                wait,
3386            )
3387        });
3388        entries
3389    }
3390
3391    /// Expiry leaves exactly what a pass over every entry left, through requests, reports
3392    /// (received and lost, true and not), the pacer's notices, round trips that move the report
3393    /// wait, packets written over and timeouts at any instant: checked against a full pass over
3394    /// a copy before each timeout. And every entry whose packet is no longer held is one expiry
3395    /// or `retain_held` will find.
3396    #[test]
3397    fn expiry_leaves_what_a_pass_over_every_entry_leaves() {
3398        let mut responder = responder_of(SIZE);
3399        let base = Instant::now();
3400        let mut checked = 0;
3401        let mut removed = 0;
3402        for step in 0..6_000u32 {
3403            let now = base + Duration::from_micros(700) * step;
3404            let seq = step as u16;
3405            original(&mut responder, now, seq);
3406            if step % 2 == 0 {
3407                let asked: Vec<u16> = (1..20u16)
3408                    .map(|back| seq.wrapping_sub(back * 3 + (step as u16 % 5)))
3409                    .collect::<std::collections::BTreeSet<_>>()
3410                    .into_iter()
3411                    .collect();
3412                responder.handle_read(nack_of(now, &asked)).unwrap();
3413            }
3414            let mut message = AttributedPacket::new(Packet::Rtcp(vec![]));
3415            let reported = |back: u16| crate::ReportedRetransmission {
3416                ssrc: RTX_SSRC,
3417                sequence_number: seq.wrapping_sub(back),
3418                sent: now - Duration::from_millis(u64::from(back % 7) * 20),
3419            };
3420            if step % 3 == 1 {
3421                message.add(Attribute::Custom(Arc::new(
3422                    crate::RetransmissionsReported {
3423                        received: (5..15).map(reported).collect(),
3424                        lost: (15..25).map(reported).collect(),
3425                    },
3426                )));
3427            }
3428            if step % 5 == 2 && step < 4_000 {
3429                message.add(Attribute::Custom(Arc::new(crate::RetransmissionsLeft {
3430                    departed: (3..30)
3431                        .map(|back| (RTX_SSRC, seq.wrapping_sub(back)))
3432                        .collect(),
3433                    dropped: vec![(RTX_SSRC, seq.wrapping_sub(31))],
3434                })));
3435            }
3436            responder.handle_read(tagged(now, message)).unwrap();
3437            if step % 400 == 0 {
3438                // The report wait follows the round trip.
3439                responder.round_trip_time =
3440                    Some(Duration::from_millis(u64::from(step % 1_200) / 2 + 1));
3441            }
3442            while responder.poll_write().is_some() {}
3443            while responder.poll_read().is_some() {}
3444
3445            let stream = &responder.streams[&SSRC];
3446            for (seq, repair) in stream.repairs.iter() {
3447                if held_packet(&stream.sent_at, *seq) != Some(repair.packet) {
3448                    assert!(
3449                        stream.repairs.written_over.contains(seq)
3450                            || stream.repairs.stale_in_pacer.contains(seq),
3451                        "step {step}: the repair of {seq} has no packet and nothing notes it"
3452                    );
3453                }
3454            }
3455            if step % 7 == 3 {
3456                // Now and then far ahead, the clock alone ending much.
3457                let later = now + Duration::from_millis(u64::from(step % 11) * 450);
3458                let expected = expired_by_a_full_pass(&responder, later);
3459                let before = responder.streams[&SSRC].repairs.len();
3460                responder.expire_repairs(later);
3461                let repairs = &responder.streams[&SSRC].repairs;
3462                let left: HashMap<u16, Repair> = repairs
3463                    .iter()
3464                    .map(|(seq, repair)| (*seq, *repair))
3465                    .collect();
3466                assert_eq!(expected, left, "step {step}");
3467                assert!(repairs.consistent(), "step {step}");
3468                checked += 1;
3469                removed += before - left.len();
3470            }
3471        }
3472        assert!(
3473            checked > 800 && removed > 100,
3474            "{checked} checks, {removed} ended"
3475        );
3476    }
3477
3478    /// What is remembered of a repair ends with the engine's clock at a timeout, with no
3479    /// request and no report to end it: a retransmission reported received is forgotten four
3480    /// seconds after the report.
3481    #[test]
3482    fn a_timeout_alone_ends_the_memory_of_a_delivered_retransmission() {
3483        let mut responder = responder();
3484        let base = Instant::now();
3485        for sequence_number in 0..10 {
3486            original(&mut responder, base, sequence_number);
3487        }
3488        let at = |milliseconds: u64| base + Duration::from_millis(milliseconds);
3489        responder
3490            .handle_read(tagged(
3491                at(100),
3492                AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerNack {
3493                    sender_ssrc: 1,
3494                    media_ssrc: SSRC,
3495                    nacks: nack_pairs_from_sequence_numbers(&[3]),
3496                })])),
3497            ))
3498            .unwrap();
3499        responder
3500            .handle_read(tagged(
3501                at(200),
3502                AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(
3503                    crate::RetransmissionsReported {
3504                        received: vec![crate::ReportedRetransmission {
3505                            ssrc: RTX_SSRC,
3506                            sequence_number: 3,
3507                            sent: at(100),
3508                        }],
3509                        lost: vec![],
3510                    },
3511                ))),
3512            ))
3513            .unwrap();
3514        let state = |responder: &NackResponderInterceptor| {
3515            responder.streams[&SSRC]
3516                .repairs
3517                .get(3)
3518                .map(|repair| repair.state)
3519        };
3520        assert_eq!(
3521            Some(RepairState::Delivered { reported: at(200) }),
3522            state(&responder)
3523        );
3524        responder.handle_timeout(at(4_199)).unwrap();
3525        assert!(state(&responder).is_some(), "1 ms before the memory ends");
3526        responder.handle_timeout(at(4_200)).unwrap();
3527        assert_eq!(None, state(&responder));
3528    }
3529}