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