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