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