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