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::ProbeRequest;
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}
39
40impl Default for NackResponderBuilder {
41 fn default() -> Self {
42 Self {
43 size: 1024,
44 max_packet_age: None,
45 rate_limit: RetransmissionRateLimit::default(),
46 max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
47 }
48 }
49}
50
51/// How the NACK responder holds its retransmissions to the congestion controller's target
52/// (RFC 4588 section 7), read from [`Attribute::TargetBitrateChanged`] as it passes on the read
53/// leg. Until a target has passed, and in a chain without a congestion controller, nothing is
54/// held back.
55///
56/// The rate is counted over the last [`RETRANSMISSION_RATE_WINDOW`]. A NACKed packet that
57/// does not fit now waits, oldest request first, and leaves when the window has room for it
58/// ([`poll_timeout`](sansio::Protocol::poll_timeout) is that instant), for as long as the
59/// receiver keeps asking for it ([`PENDING_REQUEST_LIFETIME`]). Section 7 lets the sender
60/// "selectively retransmit only the packets that it deems important and ignore NACK messages
61/// for other packets in order to limit the bitrate": a packet still asked for is the one
62/// deemed important, one the receiver stopped asking for is dropped.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64#[non_exhaustive]
65pub enum RetransmissionRateLimit {
66 /// RFC 4588 section 7, both halves: "the acceptable packet rate and bitrate include both
67 /// the original and retransmitted data", and "the sender SHOULD NOT send retransmission
68 /// packets without reducing the packet rate and bitrate of the original stream (for
69 /// example, by encoding the data at a lower rate)".
70 ///
71 /// Retransmissions take what the original packets of every local stream leave of the
72 /// target. While retransmissions wait or were sent within the window, the target reported
73 /// for the original media is the congestion controller's less a **retransmission
74 /// reserve**: on the read leg [`Attribute::TargetBitrateChanged`] is lowered by it on its
75 /// way to the application, and [`RetransmissionReserve`] rides down the write leg to the
76 /// congestion controller, whose handle (`GccHandle::target_bitrate_bps`,
77 /// `CongestionControlHandle::target_bitrate`) reports the lowered target and keeps the
78 /// estimate itself readable (`estimate_bps`, `estimate_bitrate`). An encoder that follows
79 /// the target leaves the reserve free, so the repairs have room.
80 ///
81 /// The reserve is what the waiting requests need to leave within about one round trip
82 /// (their octets over the round-trip time the RTCP session measured, at most
83 /// [`RETRANSMISSION_RATE_WINDOW`]), or the retransmission rate of the window when that is
84 /// more, and never more than [`MAX_RETRANSMISSION_RESERVE`] of the target
85 /// ([`NackResponderBuilder::with_max_reserve_fraction`]). It is released as the requests
86 /// are served and the retransmissions leave the window: with nothing waiting and nothing
87 /// retransmitted within the last window it is zero.
88 ///
89 /// **At the congestion controller's floor.** The controller's minimum bit rate is this
90 /// engine's setting, not the RFC's, and the controller announces it with its target
91 /// ([`MinimumTarget`]). The original media is never told less than that minimum (the least
92 /// the application set its media to need). When lowering the original media by the reserve
93 /// would take it under that floor (target − reserve < minimum), it cannot make the room:
94 /// an encoder at its own minimum already fills the floor (in the capacity-cap test, 30
95 /// kbit/s of video and 80 kbit/s of audio against a 100 kbit/s target), and the rule above
96 /// would leave the repairs nothing for as long as the estimate stays near the floor. There
97 /// the retransmissions of packets still asked for take the window's room first: they may
98 /// send up to the target within the window, whatever the original packets took, and the
99 /// original media is told the target less the reserve. Section 7 lets the sender
100 /// "selectively retransmit only the packets that it deems important"; a packet still asked
101 /// for is the one deemed important. An application at its minimum adds its own excess
102 /// over the floor; the retransmissions never go over the target.
103 ///
104 /// What holds the sum on the wire when the application ignores the lowered target: with
105 /// a pacer in the chain (the default interceptor set) the pacer sends at the controller's
106 /// target, retransmissions and media alike; without one (a chain of NACK, TWCC and GCC
107 /// alone) it is this rule: above the floor the retransmissions take only what the
108 /// original packets leave, so the engine never adds to an application's excess; near the
109 /// floor (target under the minimum plus the reserve, at most twice the minimum with the
110 /// default reserve) they take at most the target.
111 #[default]
112 WithinTarget,
113 /// A rate limiter on the retransmissions alone, its maximum the target (the form of
114 /// libwebrtc's `RtpSender` when it is given a `retransmission_rate_limiter`,
115 /// `modules/rtp_rtcp/source/rtp_sender.cc`): the retransmissions stay under the target
116 /// whatever the original packets take, and the target reported for the original media is
117 /// not lowered, so the sum may reach twice the target. A setting in no behaviour profile:
118 /// libwebrtc gives its video senders no such limiter (`call/rtp_video_sender.cc:292-354`
119 /// at a222406d; `rtp_rtcp_interface.h:92` defaults it to null) and lowers the encoder
120 /// target by the protection share instead. Measured in
121 /// `tests/capacity_cap_video_rtc2rtc.rs` against the default: longest freeze 0.84 to
122 /// 1.29 s against 0.83 to 1.24 s, 17 to 27 retransmissions dropped at the capped link
123 /// against 14 to 17.
124 UpToTarget,
125 /// No limit beyond the per-stream budget (one retransmission per original packet sent): the
126 /// fork's behaviour before. Retransmissions are then not congestion controlled.
127 Unlimited,
128}
129
130/// The window [`RetransmissionRateLimit`] measures the rates over (libwebrtc's
131/// `kRetransmitWindowSizeMs`).
132pub const RETRANSMISSION_RATE_WINDOW: Duration = Duration::from_secs(1);
133
134/// The most of the congestion controller's target the retransmission reserve of
135/// [`RetransmissionRateLimit::WithinTarget`] takes, by default: half.
136pub const MAX_RETRANSMISSION_RESERVE: f64 = 0.5;
137
138/// A request that waits for room is dropped when the receiver has not asked for the packet
139/// again within this long, or within two round trips when that is longer: a receiver asks
140/// again every round trip while the packet is missing, so one that stopped asking has the
141/// packet or no longer wants it.
142pub const PENDING_REQUEST_LIFETIME: Duration = Duration::from_secs(1);
143
144/// The shortest round trip the reserve spreads the waiting requests over.
145const MIN_RESERVE_HORIZON: Duration = Duration::from_millis(10);
146
147/// The retransmission reserve of [`RetransmissionRateLimit::WithinTarget`], in bits per
148/// second: the part of the congestion controller's target kept for retransmissions, which the
149/// target reported for the original media leaves out.
150///
151/// The NACK responder sends it down the write leg (on a packet of its own, an empty RTCP
152/// carrier, when it changes), so a congestion controller wire-ward of it reports the lowered
153/// target through its handle. Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
154#[derive(Debug, Clone, Copy, PartialEq)]
155pub struct RetransmissionReserve {
156 /// The reserve, bits per second.
157 pub bits_per_second: f64,
158}
159
160/// Rides with [`Attribute::TargetBitrateChanged`]: the congestion controller's minimum bit
161/// rate, the floor its target never goes under. Where lowering the original media by the
162/// retransmission reserve would take it under this floor the NACK responder lets the
163/// retransmissions take the window's room first ([`RetransmissionRateLimit::WithinTarget`]).
164/// Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
165#[derive(Debug, Clone, Copy, PartialEq)]
166pub struct MinimumTarget {
167 /// The minimum, bits per second.
168 pub bits_per_second: f64,
169}
170
171/// The target for the original media: the controller's `target` less the `reserve`, never
172/// under the controller's `minimum` (the least the application set its media to need; near it
173/// the retransmissions take the room first instead, see [`RetransmissionRateLimit::WithinTarget`]).
174fn media_target(target: f64, reserve: f64, minimum: f64) -> f64 {
175 (target - reserve).max(minimum.min(target)).max(0.0)
176}
177
178/// How much the reported reserve may move before a new one is announced: 5 % of the target,
179/// at least 5 kbit/s, and any change to or from zero.
180fn reserve_moved(announced: f64, reserve: f64, target_bps: f64) -> bool {
181 (announced == 0.0) != (reserve == 0.0)
182 || (reserve - announced).abs() >= (0.05 * target_bps).max(5_000.0)
183}
184
185/// Octets sent within the last [`RETRANSMISSION_RATE_WINDOW`].
186#[derive(Default)]
187struct RateWindow {
188 sent: VecDeque<(Instant, usize)>,
189 octets: usize,
190}
191
192/// The instant at which the entries of `windows` leaving [`RETRANSMISSION_RATE_WINDOW`] have
193/// freed `deficit` octets, oldest first; `None` if all of them together free less.
194fn freed_at(windows: &[&RateWindow], deficit: usize) -> Option<Instant> {
195 let mut cursors = vec![0usize; windows.len()];
196 let mut freed = 0usize;
197 loop {
198 let (index, &(at, octets)) = windows
199 .iter()
200 .zip(&cursors)
201 .enumerate()
202 .filter_map(|(index, (window, &cursor))| window.sent.get(cursor).map(|e| (index, e)))
203 .min_by_key(|(_, (at, _))| *at)?;
204 cursors[index] += 1;
205 freed += octets;
206 if freed >= deficit {
207 return Some(at + RETRANSMISSION_RATE_WINDOW);
208 }
209 }
210}
211
212/// A NACKed packet waiting for room in the rate limit.
213struct PendingRetransmission {
214 ssrc: u32,
215 sequence_number: u16,
216 /// The size its retransmission has on the wire.
217 octets: usize,
218}
219
220impl RateWindow {
221 fn expire(&mut self, now: Instant) {
222 while let Some(&(at, octets)) = self.sent.front() {
223 if now.saturating_duration_since(at) < RETRANSMISSION_RATE_WINDOW {
224 break;
225 }
226 self.sent.pop_front();
227 self.octets -= octets;
228 }
229 }
230
231 fn add(&mut self, now: Instant, octets: usize) {
232 self.sent.push_back((now, octets));
233 self.octets += octets;
234 }
235
236 /// Takes back `octets` added at `at`, if the entry is still in the window.
237 fn forget(&mut self, at: Instant, octets: usize) {
238 if let Some(entry) = self
239 .sent
240 .iter_mut()
241 .rev()
242 .find(|(sent, size)| *sent == at && *size == octets)
243 {
244 entry.1 = 0;
245 self.octets -= octets;
246 }
247 }
248}
249
250impl NackResponderBuilder {
251 /// Create a new builder with default settings.
252 pub fn new() -> Self {
253 Self::default()
254 }
255
256 /// Set the size of the send buffer.
257 ///
258 /// Size must be a power of 2 between 1 and 32768 (inclusive).
259 /// Larger buffers can retransmit older packets but use more memory.
260 pub fn with_size(mut self, size: u16) -> Self {
261 self.size = size;
262 self
263 }
264
265 /// Set how long a sent packet is kept for retransmission: the `rtx-time` of RFC 4588
266 /// 8.1, when one is signalled. A NACK for a packet sent longer ago is not answered.
267 ///
268 /// Default: `None`, a packet is available for as long as the buffer holds it.
269 pub fn with_max_packet_age(mut self, max_packet_age: Option<Duration>) -> Self {
270 self.max_packet_age = max_packet_age;
271 self
272 }
273
274 /// Set how retransmissions are held to the congestion controller's target (RFC 4588
275 /// section 7). Default: [`RetransmissionRateLimit::WithinTarget`], the RFC's form;
276 /// [`RetransmissionRateLimit::UpToTarget`] is the limiter libwebrtc's `RtpSender` has
277 /// when it is given one.
278 pub fn with_rate_limit(mut self, rate_limit: RetransmissionRateLimit) -> Self {
279 self.rate_limit = rate_limit;
280 self
281 }
282
283 /// Set the most of the congestion controller's target the retransmission reserve of
284 /// [`RetransmissionRateLimit::WithinTarget`] takes, from 0 (no reserve: the target is
285 /// never lowered) to 1. Default: [`MAX_RETRANSMISSION_RESERVE`].
286 pub fn with_max_reserve_fraction(mut self, fraction: f64) -> Self {
287 self.max_reserve_fraction = if fraction.is_finite() {
288 fraction.clamp(0.0, 1.0)
289 } else {
290 MAX_RETRANSMISSION_RESERVE
291 };
292 self
293 }
294
295 /// Build the interceptor.
296 pub fn build(self) -> NackResponderInterceptor {
297 let mut interceptor = NackResponderInterceptor::new(self.size);
298 interceptor.max_packet_age = self.max_packet_age;
299 interceptor.rate_limit = self.rate_limit;
300 interceptor.max_reserve_fraction = self.max_reserve_fraction;
301 interceptor
302 }
303}
304
305/// The RID header extension (RFC 8852 3.1).
306const RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id";
307/// The repaired-RID header extension (RFC 8852 3.2), which an RTX packet carries instead.
308const REPAIRED_RTP_STREAM_ID_URI: &str = "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
309
310/// The one-byte or two-byte id `info` negotiated for `uri`.
311fn extension_id(info: &StreamInfo, uri: &str) -> Option<u8> {
312 info.rtp_header_extensions
313 .iter()
314 .find(|extension| extension.uri == uri)
315 .and_then(|extension| u8::try_from(extension.id).ok())
316}
317
318/// Per-stream state for the responder.
319struct LocalStream {
320 /// Buffer of sent packets for retransmission.
321 send_buffer: SendBuffer,
322 /// RTX SSRC for RFC4588 retransmission (if configured).
323 ssrc_rtx: Option<u32>,
324 /// RTX payload type for RFC4588 retransmission (if configured).
325 payload_type_rtx: Option<u8>,
326 /// Sequence number counter for RTX packets.
327 rtx_sequence_number: u16,
328 /// The sequence number of the packet sent last, and when.
329 last_sent: Option<(u16, Instant)>,
330 /// When each sequence number was last retransmitted, so a repeated NACK within
331 /// [`MIN_RETRANSMIT_INTERVAL`] does not resend it again.
332 last_retransmit: HashMap<u16, Instant>,
333 /// The RID extension id, if negotiated.
334 rid_extension_id: Option<u8>,
335 /// The repaired-RID extension id, if negotiated.
336 repaired_rid_extension_id: Option<u8>,
337 /// Retransmissions this stream may still send: one more for each original packet sent, up
338 /// to the send buffer's size, and one less per retransmission. A NACK naming the whole buffer
339 /// may be answered once in full, but repeated NACKs cannot make the stream retransmit faster
340 /// than it sends, so the peer cannot turn its NACKs into a multiple of our send rate.
341 retransmit_budget: usize,
342 /// The budget's ceiling: the send buffer's size.
343 retransmit_budget_max: usize,
344 /// When each buffered packet was sent, by its place in the send buffer (the sequence
345 /// number modulo the buffer size), with the sequence number the entry is for.
346 sent_at: Vec<Option<(u16, Instant)>>,
347}
348
349/// The most octets one probe cluster is filled with.
350const MAX_PROBE_FILL_OCTETS: usize = crate::cc::probe::PROBE_MAX_OCTETS;
351
352/// The most packets one probe cluster is filled with.
353const MAX_PROBE_FILL_PACKETS: usize = 128;
354
355/// The padding octets of one probe packet: the most RFC 3550 section 5.1 padding holds (its
356/// count is one octet).
357pub const PROBE_PADDING_OCTETS: u8 = 255;
358
359/// A sequence number is retransmitted at most once per this interval, however often it is
360/// NACKed. Receivers repeat NACKs while the repair is in flight; without this a peer can make
361/// us resend the same packets as fast as it can send RTCP (an amplifier).
362pub const MIN_RETRANSMIT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(20);
363
364/// How long after its retransmission a packet is not retransmitted again however often it is
365/// asked for: [`MIN_RETRANSMIT_INTERVAL`]. libwebrtc waits a round trip
366/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`, `VerifyRtt`); measured here that loses
367/// repairs: when a retransmission is itself lost, the receiver's next request can fall inside
368/// that round trip and be ignored, and the one after waits for RFC 4585's early-feedback hold
369/// (`tests/vp8_nack_jitter_buffer_rtc2rtc.rs`, seed 4: packet 1272 retransmitted again 1.42 s
370/// after the lost copy, after the 2 s jitter buffer had played past it). A request that
371/// crossed a repair in flight costs one duplicate instead.
372fn resend_interval(round_trip_time: Option<Duration>) -> Duration {
373 let _ = round_trip_time;
374 MIN_RETRANSMIT_INTERVAL
375}
376
377/// How long a retransmission is taken to wait in the pacer at most: longer than the pacer's
378/// queue time bound (2 s by default), past which the pacer drops it and says so.
379const IN_PACER_LIFETIME: Duration = Duration::from_secs(4);
380
381/// Most retransmissions queued and not yet taken by `poll_write`. Past it further NACKed
382/// packets are not queued until the queue drains.
383pub const MAX_QUEUED_RETRANSMISSIONS: usize = 1024;
384
385/// The most retransmission SSRCs whose next sequence number is remembered after their stream
386/// was unbound.
387const MAX_REMEMBERED_RTX_SSRCS: usize = 1024;
388
389/// Interceptor that responds to NACK requests by retransmitting packets.
390///
391/// This interceptor buffers outgoing RTP packets on local streams and
392/// retransmits them when RTCP TransportLayerNack packets are received.
393pub struct NackResponderInterceptor {
394 /// Configuration
395 size: u16,
396
397 /// How long a sent packet stays available for retransmission (`rtx-time`).
398 max_packet_age: Option<Duration>,
399 /// The `rtx-time` this endpoint announced, by retransmission payload type
400 /// ([`NackControl::LocalRtxTime`](super::NackControl::LocalRtxTime)): it replaces
401 /// `max_packet_age` for the streams repaired under that payload type.
402 local_rtx_times: HashMap<u8, Duration>,
403
404 /// Send buffers per local stream SSRC
405 streams: HashMap<u32, LocalStream>,
406
407 /// The next sequence number of each retransmission SSRC this interceptor has sent on,
408 /// kept when its stream is unbound: a stream bound again with the same RTX SSRC (a
409 /// renegotiation re-binding it) carries on from here. Starting over would repeat sequence
410 /// numbers on a live SSRC, which SRTP refuses to protect twice (the packet index is the
411 /// SSRC's rollover counter and sequence number).
412 rtx_sequence_numbers: HashMap<u32, u16>,
413
414 /// Queue for retransmitted packets
415 write_queue: VecDeque<TaggedPacket>,
416 /// Retransmissions in `write_queue` not yet taken by `poll_write`.
417 retransmissions_queued: usize,
418 /// Inbound packets ready for the next interceptor.
419 read_queue: VecDeque<TaggedPacket>,
420 /// The RTP session (transport) of each SSRC, from the peer connection's
421 /// [`RtpSessionAssignment`](crate::RtpSessionAssignment)s; empty while there is one.
422 sessions: HashMap<u32, usize>,
423
424 /// See [`NackResponderBuilder::with_rate_limit`].
425 rate_limit: RetransmissionRateLimit,
426 /// The congestion controller's latest target, bits per second.
427 target_bps: Option<f64>,
428 /// The controller's minimum ([`MinimumTarget`]), bits per second.
429 minimum_bps: Option<f64>,
430 /// The original packets of the local streams, and the retransmissions, sent lately.
431 originals: RateWindow,
432 retransmitted: RateWindow,
433 /// See [`NackResponderBuilder::with_max_reserve_fraction`].
434 max_reserve_fraction: f64,
435 /// The round trip the RTCP session measured last.
436 round_trip_time: Option<Duration>,
437 /// NACKed packets waiting for room, oldest request first.
438 pending: VecDeque<PendingRetransmission>,
439 /// When each waiting packet was last asked for.
440 pending_asked: HashMap<(u32, u16), Instant>,
441 /// The octets of `pending`.
442 pending_octets: usize,
443 /// The reserve last announced, bits per second.
444 announced_reserve: f64,
445 /// When the next waiting retransmission can leave, worked out since the last change:
446 /// `None` when it has to be worked out again.
447 release_at: Option<Option<Instant>>,
448 /// Retransmissions made and still waiting in the pacer, by (media SSRC, sequence number),
449 /// with when they were made: a NACK for one is not answered again
450 /// ([`RetransmissionsLeft`](crate::RetransmissionsLeft)).
451 in_pacer: HashMap<(u32, u16), Instant>,
452 /// Whether a pacer wire-ward reports its retransmissions' departures (it has once).
453 pacer_reports: bool,
454 /// Whether the pacer tells the source to pause ([`PacerPause`](crate::PacerPause)): the
455 /// target the application reads is zero.
456 paused: bool,
457}
458
459impl NackResponderInterceptor {
460 fn new(size: u16) -> Self {
461 Self {
462 read_queue: VecDeque::new(),
463 size,
464 max_packet_age: None,
465 local_rtx_times: HashMap::new(),
466 streams: HashMap::new(),
467 rtx_sequence_numbers: HashMap::new(),
468 write_queue: VecDeque::new(),
469 retransmissions_queued: 0,
470 sessions: HashMap::new(),
471 rate_limit: RetransmissionRateLimit::default(),
472 target_bps: None,
473 minimum_bps: None,
474 originals: RateWindow::default(),
475 retransmitted: RateWindow::default(),
476 max_reserve_fraction: MAX_RETRANSMISSION_RESERVE,
477 round_trip_time: None,
478 pending: VecDeque::new(),
479 pending_asked: HashMap::new(),
480 pending_octets: 0,
481 announced_reserve: 0.0,
482 release_at: None,
483 in_pacer: HashMap::new(),
484 pacer_reports: false,
485 paused: false,
486 }
487 }
488
489 /// Octets at `bits_per_second` over the window.
490 fn window_octets(bits_per_second: f64) -> usize {
491 (bits_per_second / 8.0 * RETRANSMISSION_RATE_WINDOW.as_secs_f64()) as usize
492 }
493
494 /// The octets retransmissions may still take within the window, `None` for no limit.
495 fn retransmission_allowance(&mut self, now: Instant) -> Option<usize> {
496 let target_bps = self.target_bps?;
497 self.originals.expire(now);
498 self.retransmitted.expire(now);
499 let target = Self::window_octets(target_bps);
500 let limit = match self.rate_limit {
501 RetransmissionRateLimit::WithinTarget => {
502 if self.at_floor() {
503 // Near the floor the retransmissions take the window's room first.
504 target
505 } else {
506 // What the originals leave, or the reserve the original media has already
507 // been lowered by, whichever is more.
508 target
509 .saturating_sub(self.originals.octets)
510 .max(Self::window_octets(self.announced_reserve))
511 }
512 }
513 RetransmissionRateLimit::UpToTarget => target,
514 RetransmissionRateLimit::Unlimited => return None,
515 };
516 Some(limit.saturating_sub(self.retransmitted.octets))
517 }
518
519 /// Whether lowering the original media by the reserve would take it under the
520 /// controller's minimum (see [`RetransmissionRateLimit::WithinTarget`]).
521 fn at_floor(&self) -> bool {
522 self.rate_limit == RetransmissionRateLimit::WithinTarget
523 && self.announced_reserve > 0.0
524 && match (self.target_bps, self.minimum_bps) {
525 (Some(target), Some(minimum)) => target - self.announced_reserve < minimum,
526 _ => false,
527 }
528 }
529
530 /// The retransmission reserve at `now`, bits per second (see
531 /// [`RetransmissionRateLimit::WithinTarget`]); zero under the other rules.
532 fn reserve(&mut self, now: Instant) -> f64 {
533 let Some(target_bps) = self.target_bps else {
534 return 0.0;
535 };
536 if self.rate_limit != RetransmissionRateLimit::WithinTarget {
537 return 0.0;
538 }
539 self.retransmitted.expire(now);
540 if self.pending.is_empty() && self.retransmitted.octets == 0 {
541 return 0.0;
542 }
543 let horizon = self
544 .round_trip_time
545 .unwrap_or(RETRANSMISSION_RATE_WINDOW)
546 .clamp(MIN_RESERVE_HORIZON, RETRANSMISSION_RATE_WINDOW);
547 let needed = self.pending_octets as f64 * 8.0 / horizon.as_secs_f64();
548 let in_use =
549 self.retransmitted.octets as f64 * 8.0 / RETRANSMISSION_RATE_WINDOW.as_secs_f64();
550 needed
551 .max(in_use)
552 .min(self.max_reserve_fraction * target_bps)
553 }
554
555 /// How long a waiting request stays without being asked for again.
556 fn pending_lifetime(&self) -> Duration {
557 self.round_trip_time
558 .map_or(PENDING_REQUEST_LIFETIME, |rtt| {
559 (rtt * 2).max(PENDING_REQUEST_LIFETIME)
560 })
561 }
562
563 /// Drops the waiting requests nobody asked for again within their lifetime.
564 fn expire_pending(&mut self, now: Instant) {
565 let lifetime = self.pending_lifetime();
566 let before = self.pending.len();
567 let asked = &mut self.pending_asked;
568 let octets = &mut self.pending_octets;
569 self.pending.retain(|entry| {
570 let key = (entry.ssrc, entry.sequence_number);
571 let fresh = asked
572 .get(&key)
573 .is_some_and(|at| now.saturating_duration_since(*at) <= lifetime);
574 if !fresh {
575 asked.remove(&key);
576 *octets -= entry.octets;
577 }
578 fresh
579 });
580 if self.pending.len() != before {
581 self.release_at = None;
582 }
583 }
584
585 /// The wire size of the retransmission of `packet` on `stream`.
586 fn retransmission_size(stream: &LocalStream, packet: &rtp::Packet) -> usize {
587 packet.marshal_size()
588 + if stream.ssrc_rtx.is_some() && stream.payload_type_rtx.is_some() {
589 2
590 } else {
591 0
592 }
593 }
594
595 /// Whether `seq` of `stream` may be retransmitted at `now` (it is still held, not older
596 /// than the `rtx-time`), and its retransmission's size.
597 fn retransmittable(&self, stream: &LocalStream, seq: u16, now: Instant) -> Option<usize> {
598 let original_packet = stream.send_buffer.get(seq)?;
599 // RFC 4588 8.1 (`rtx-time`): a packet is kept for retransmission that long. What
600 // the session description announced for the stream's retransmission format is
601 // the value; without one, the configured age.
602 if let Some(max_packet_age) = stream
603 .payload_type_rtx
604 .and_then(|payload_type_rtx| self.local_rtx_times.get(&payload_type_rtx))
605 .copied()
606 .or(self.max_packet_age)
607 && let Some((_, sent)) = stream.sent_at[usize::from(seq) % stream.sent_at.len()]
608 .filter(|(sequence_number, _)| *sequence_number == seq)
609 && now.saturating_duration_since(sent) > max_packet_age
610 {
611 return None;
612 }
613 Some(Self::retransmission_size(stream, original_packet))
614 }
615
616 /// Sends the waiting retransmissions the rate limit has room for, oldest request first.
617 fn release(&mut self, now: Instant) {
618 let mut allowance = self.retransmission_allowance(now);
619 let resend_interval = resend_interval(self.round_trip_time);
620 while let Some(entry) = self.pending.front() {
621 if self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
622 break;
623 }
624 let (ssrc, seq) = (entry.ssrc, entry.sequence_number);
625 let current = self.streams.get(&ssrc).and_then(|stream| {
626 let recently = stream
627 .last_retransmit
628 .get(&seq)
629 .is_some_and(|at| now.saturating_duration_since(*at) < resend_interval)
630 || self.in_pacer.contains_key(&(ssrc, seq));
631 if recently {
632 None
633 } else {
634 self.retransmittable(stream, seq, now)
635 .map(|size| (size, stream.retransmit_budget))
636 }
637 });
638 let Some((size, budget)) = current else {
639 // Gone from the buffer, too old, its stream unbound, or just sent.
640 self.pop_pending();
641 continue;
642 };
643 if budget == 0 {
644 // Waits for the next original packet, which adds to the budget.
645 break;
646 }
647 if let Some(left) = allowance.as_mut() {
648 if size > *left {
649 break;
650 }
651 *left -= size;
652 }
653 self.pop_pending();
654 self.retransmit(now, ssrc, seq, size);
655 }
656 }
657
658 fn pop_pending(&mut self) {
659 if let Some(entry) = self.pending.pop_front() {
660 self.pending_asked
661 .remove(&(entry.ssrc, entry.sequence_number));
662 self.pending_octets -= entry.octets;
663 self.release_at = None;
664 }
665 }
666
667 /// Queues the retransmission of `seq` of the stream `ssrc`.
668 fn retransmit(&mut self, now: Instant, ssrc: u32, seq: u16, size: usize) {
669 let Some(stream) = self.streams.get_mut(&ssrc) else {
670 return;
671 };
672 let Some(original_packet) = stream.send_buffer.get(seq) else {
673 return;
674 };
675 stream.last_retransmit.insert(seq, now);
676 if self.pacer_reports {
677 self.in_pacer.insert((ssrc, seq), now);
678 }
679 stream.retransmit_budget -= 1;
680 self.retransmissions_queued += 1;
681
682 let packet =
683 if let (Some(ssrc_rtx), Some(pt_rtx)) = (stream.ssrc_rtx, stream.payload_type_rtx) {
684 rtx_packet(
685 &mut stream.rtx_sequence_number,
686 (stream.rid_extension_id, stream.repaired_rid_extension_id),
687 original_packet,
688 ssrc_rtx,
689 pt_rtx,
690 )
691 } else {
692 // No RTX: retransmit original packet as-is
693 original_packet.clone()
694 };
695 self.retransmitted.add(now, size);
696 self.release_at = None;
697
698 // Tagged so a send history downstream counts it as new bytes on the wire rather
699 // than as the original transmission. A bandwidth estimator that cannot tell the two
700 // apart under-counts exactly when the path is lossy — it sees fewer bytes than are
701 // really being sent, infers headroom, and raises the target during loss.
702 self.write_queue.push_back(TaggedPacket {
703 now,
704 transport: TransportContext::default(),
705 message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
706 });
707 }
708
709 /// When the oldest waiting retransmission fits the rate limit: the instant enough of the
710 /// window's packets have left it. `None` with nothing waiting, without a target to wait
711 /// for, or while the stream's budget waits for an original packet (the write of that
712 /// packet tries again).
713 pub fn next_release(&mut self) -> Option<Instant> {
714 if let Some(at) = self.release_at {
715 return at;
716 }
717 let at = self.work_out_release();
718 self.release_at = Some(at);
719 at
720 }
721
722 fn work_out_release(&self) -> Option<Instant> {
723 let target_bps = self.target_bps?;
724 // With nothing waiting, the reserve falls to zero when the last retransmission leaves
725 // the window.
726 let Some(entry) = self.pending.front() else {
727 return (self.announced_reserve > 0.0)
728 .then(|| self.retransmitted.sent.back())
729 .flatten()
730 .map(|(at, _)| *at + RETRANSMISSION_RATE_WINDOW);
731 };
732 // The lifetime of the oldest request ends: due then, to drop it.
733 let lifetime = self.pending_lifetime();
734 let stale = self
735 .pending
736 .iter()
737 .filter_map(|entry| self.pending_asked.get(&(entry.ssrc, entry.sequence_number)))
738 .min()
739 .map(|asked| *asked + lifetime + Duration::from_micros(1));
740 if self
741 .streams
742 .get(&entry.ssrc)
743 .is_none_or(|stream| stream.retransmit_budget == 0)
744 {
745 return stale;
746 }
747 let size = entry.octets;
748 let target = Self::window_octets(target_bps);
749 let (originals, retransmitted) = (self.originals.octets, self.retransmitted.octets);
750 let fits = match self.rate_limit {
751 RetransmissionRateLimit::WithinTarget if !self.at_floor() => {
752 let by_share = freed_at(
753 &[&self.originals, &self.retransmitted],
754 (originals + retransmitted + size)
755 .saturating_sub(target)
756 .max(1),
757 )
758 .filter(|_| size <= target);
759 // The reserve frees as the retransmissions leave the window.
760 let reserve = Self::window_octets(self.announced_reserve);
761 let by_reserve = freed_at(
762 &[&self.retransmitted],
763 (retransmitted + size).saturating_sub(reserve).max(1),
764 )
765 .filter(|_| size <= reserve);
766 by_share.into_iter().chain(by_reserve).min()
767 }
768 // Near the floor the room is the retransmissions' first: only they leaving the
769 // window frees it.
770 RetransmissionRateLimit::WithinTarget | RetransmissionRateLimit::UpToTarget => {
771 freed_at(
772 &[&self.retransmitted],
773 (retransmitted + size).saturating_sub(target).max(1),
774 )
775 .filter(|_| size <= target)
776 }
777 RetransmissionRateLimit::Unlimited => None,
778 };
779 fits.into_iter().chain(stale).min()
780 }
781
782 /// Announces a reserve that moved: down the write leg for the congestion controller, and
783 /// up the read leg as the lowered target for the application.
784 /// The carrier that tells the application its target when only the reserve moved: the
785 /// controller's target less the reserve, or, while the pacer has the source paused, zero
786 /// with the controller's target riding along as the pacer's own announcement of a pause
787 /// has it ([`PacerPause`](crate::PacerPause)). Without it a reader of the carrier takes
788 /// the zero for the congestion controller's estimate (`availableOutgoingBitrate` read
789 /// nothing until the next target from the pacer).
790 fn target_carrier(&self, now: Instant, target_bps: f64, reserve: f64) -> TaggedPacket {
791 let mut message = AttributedPacket::new(Packet::Rtcp(vec![]));
792 if self.paused {
793 message.add(Attribute::TargetBitrateChanged {
794 bits_per_second: 0.0,
795 });
796 message.add(Attribute::Custom(std::sync::Arc::new(crate::PacerPause {
797 target_bits_per_second: target_bps,
798 })));
799 } else {
800 message.add(Attribute::TargetBitrateChanged {
801 bits_per_second: media_target(target_bps, reserve, self.minimum_bps.unwrap_or(0.0)),
802 });
803 }
804 TaggedPacket {
805 now,
806 transport: TransportContext::default(),
807 message,
808 }
809 }
810
811 fn announce_reserve(&mut self, now: Instant, carrier: bool) {
812 let Some(target_bps) = self.target_bps else {
813 return;
814 };
815 let reserve = self.reserve(now);
816 if !reserve_moved(self.announced_reserve, reserve, target_bps) {
817 return;
818 }
819 self.announced_reserve = reserve;
820 self.release_at = None;
821 self.write_queue.push_back(TaggedPacket {
822 now,
823 transport: TransportContext::default(),
824 message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
825 std::sync::Arc::new(RetransmissionReserve {
826 bits_per_second: reserve,
827 }),
828 )),
829 });
830 if carrier {
831 let carrier = self.target_carrier(now, target_bps, reserve);
832 self.read_queue.push_back(carrier);
833 }
834 if self.at_floor() {
835 // Near the floor the window's room is the retransmissions': use it now.
836 self.release(now);
837 }
838 }
839
840 /// Fills a probe cluster ([`ProbeRequest`]) with padding-only packets on the RTX stream of
841 /// the media stream that sent most recently.
842 ///
843 /// A probe needs a burst of packets at a multiple of the target rate, and an application
844 /// that follows the target does not have one waiting. Each packet is an RTP packet of the
845 /// RTX stream with no payload and [`PROBE_PADDING_OCTETS`] of padding (RFC 3550 section
846 /// 5.1): an RTX packet too short to hold the original sequence number of RFC 4588 section
847 /// 4 carries no media, and every receiver drops it after its transport-wide sequence
848 /// number has been recorded (this crate's endpoint, libwebrtc's `RtxReceiveStream`). A
849 /// retransmission of a packet already delivered would be a duplicate the receiving
850 /// application may play twice. The header is the newest packet's, with its extensions
851 /// (MID, the repaired RID in place of the RID), so the packet is demultiplexed as that
852 /// stream's repair flow. Without RTX negotiated nothing is added: padding under the media
853 /// SSRC would take sequence numbers the application owns. Not charged to the NACK budget:
854 /// it answers no NACK.
855 ///
856 /// With several RTP sessions (transports) a cluster is the session's that asked for it
857 /// (the request carries its [`RtpSession`](crate::RtpSession)): it is filled on a stream of
858 /// that session only, so the probe travels the path whose capacity it measures (RFC 8836
859 /// section 2: each path its own capacity).
860 fn fill_probe(&mut self, now: Instant, request: &ProbeRequest, session: Option<usize>) {
861 let sessions = &self.sessions;
862 let Some(stream) = self
863 .streams
864 .iter_mut()
865 .filter(|(ssrc, _)| match session {
866 Some(session) if !sessions.is_empty() => sessions.get(ssrc) == Some(&session),
867 _ => true,
868 })
869 .map(|(_, stream)| stream)
870 .filter(|stream| stream.ssrc_rtx.is_some() && stream.payload_type_rtx.is_some())
871 .filter(|stream| stream.last_sent.is_some())
872 .max_by_key(|stream| stream.last_sent.map(|(_, at)| at))
873 else {
874 return;
875 };
876 let (Some(ssrc_rtx), Some(pt_rtx), Some((newest, _))) =
877 (stream.ssrc_rtx, stream.payload_type_rtx, stream.last_sent)
878 else {
879 return;
880 };
881
882 // The newest packet still held gives the header.
883 let Some(template) = stream.send_buffer.get(newest).cloned() else {
884 return;
885 };
886
887 let wanted = request.octets.min(MAX_PROBE_FILL_OCTETS);
888 let mut filled = 0usize;
889 for _ in 0..MAX_PROBE_FILL_PACKETS {
890 if filled >= wanted || self.retransmissions_queued >= MAX_QUEUED_RETRANSMISSIONS {
891 break;
892 }
893 let packet = padding_packet(
894 &mut stream.rtx_sequence_number,
895 (stream.rid_extension_id, stream.repaired_rid_extension_id),
896 &template,
897 ssrc_rtx,
898 pt_rtx,
899 );
900 filled += packet.marshal_size();
901 self.retransmissions_queued += 1;
902 self.write_queue.push_back(TaggedPacket {
903 now,
904 transport: TransportContext::default(),
905 message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
906 });
907 }
908 }
909
910 /// Forgets the packets the pacer discarded ([`PacerDiscard`](crate::PacerDiscard)): out of
911 /// the retransmission buffer, so a NACK for one is answered by nothing (RFC 4588 section 7:
912 /// the sender "MAY selectively retransmit only the packets that it deems important"; a frame
913 /// the pacer gave up is not), out of the requests waiting, and out of the original packets
914 /// counted against the target, since they never used the link.
915 fn forget_discarded(&mut self, discard: &crate::PacerDiscard) {
916 if let Some(stream) = self.streams.get_mut(&discard.ssrc) {
917 for &seq in &discard.sequence_numbers {
918 let Some(packet) = stream.send_buffer.remove(seq) else {
919 continue;
920 };
921 let slot = usize::from(seq) % stream.sent_at.len();
922 if let Some((sequence_number, at)) = stream.sent_at[slot]
923 && sequence_number == seq
924 {
925 self.originals.forget(at, packet.marshal_size());
926 stream.sent_at[slot] = None;
927 }
928 }
929 }
930 let before = self.pending.len();
931 let asked = &mut self.pending_asked;
932 let octets = &mut self.pending_octets;
933 self.pending.retain(|entry| {
934 let discarded = entry.ssrc == discard.ssrc
935 && discard.sequence_numbers.contains(&entry.sequence_number);
936 if discarded {
937 asked.remove(&(entry.ssrc, entry.sequence_number));
938 *octets -= entry.octets;
939 }
940 !discarded
941 });
942 if self.pending.len() != before {
943 self.release_at = None;
944 }
945 }
946
947 /// The pacer's report of retransmissions that left it or were dropped
948 /// ([`RetransmissionsLeft`](crate::RetransmissionsLeft)): no longer on their way. One that
949 /// left counts its resend interval from now, the instant it went toward the wire, not from
950 /// when it was made (libwebrtc's `RtpPacketHistory` sets the send time when the pacer sends
951 /// it); one that was dropped may be asked for again.
952 fn retransmissions_left(&mut self, now: Instant, notice: &crate::RetransmissionsLeft) {
953 self.pacer_reports = true;
954 let media_ssrc = |streams: &HashMap<u32, LocalStream>, ssrc: u32| {
955 if streams.contains_key(&ssrc) {
956 Some(ssrc)
957 } else {
958 streams
959 .iter()
960 .find(|(_, stream)| stream.ssrc_rtx == Some(ssrc))
961 .map(|(media, _)| *media)
962 }
963 };
964 for &(ssrc, seq) in ¬ice.departed {
965 let Some(media) = media_ssrc(&self.streams, ssrc) else {
966 continue;
967 };
968 if self.in_pacer.remove(&(media, seq)).is_some()
969 && let Some(stream) = self.streams.get_mut(&media)
970 {
971 stream.last_retransmit.insert(seq, now);
972 }
973 }
974 for &(ssrc, seq) in ¬ice.dropped {
975 if let Some(media) = media_ssrc(&self.streams, ssrc) {
976 self.in_pacer.remove(&(media, seq));
977 }
978 }
979 // A pacer drops what waited its queue time bound and says so; anything older than
980 // that is no longer there.
981 self.in_pacer
982 .retain(|_, made| now.saturating_duration_since(*made) < IN_PACER_LIFETIME);
983 self.release_at = None;
984 }
985
986 /// Handle a NACK request by queuing retransmissions.
987 fn handle_nack(
988 &mut self,
989 now: Instant,
990 nack: &rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack,
991 ) {
992 // Collect sequence numbers to retransmit
993 let mut seqs_to_retransmit = Vec::new();
994
995 for nack_pair in &nack.nacks {
996 // Check the base packet ID
997 seqs_to_retransmit.push(nack_pair.packet_id);
998
999 // Check each bit in lost_packets bitmap
1000 for i in 0..16 {
1001 if nack_pair.lost_packets & (1 << i) != 0 {
1002 let seq = nack_pair.packet_id.wrapping_add(i + 1);
1003 seqs_to_retransmit.push(seq);
1004 }
1005 }
1006 }
1007
1008 let ssrc = nack.media_ssrc;
1009 let resend_interval = resend_interval(self.round_trip_time);
1010 let Some(stream) = self.streams.get_mut(&ssrc) else {
1011 return;
1012 };
1013
1014 // A NACK may name the same packet in several pairs; resend each once.
1015 seqs_to_retransmit.sort_unstable();
1016 seqs_to_retransmit.dedup();
1017 // Forget suppression entries old enough not to matter.
1018 stream
1019 .last_retransmit
1020 .retain(|_, at| now.saturating_duration_since(*at) < resend_interval);
1021
1022 // Every packet asked for joins the requests waiting, oldest request first (one asked
1023 // for again keeps its place and is asked for afresh), and leaves as the rate limit has
1024 // room (RFC 4588 section 7): what does not fit now leaves when the window has room.
1025 for seq in seqs_to_retransmit {
1026 let Some(stream) = self.streams.get(&ssrc) else {
1027 return;
1028 };
1029 if stream.last_retransmit.contains_key(&seq) || self.in_pacer.contains_key(&(ssrc, seq))
1030 {
1031 continue;
1032 }
1033 let Some(octets) = self.retransmittable(stream, seq, now) else {
1034 continue;
1035 };
1036 let budget = stream.retransmit_budget;
1037 match self.pending_asked.get_mut(&(ssrc, seq)) {
1038 Some(asked) => *asked = now,
1039 None => {
1040 // The budget (one retransmission per original sent) refuses it: not
1041 // kept, the receiver asks again. Only the rate limit makes a request wait.
1042 if budget == 0 || self.pending.len() >= MAX_QUEUED_RETRANSMISSIONS {
1043 break;
1044 }
1045 self.pending_asked.insert((ssrc, seq), now);
1046 // A stream's oldest packet first, whenever it was asked for: a receiver
1047 // that plays in order waits for its oldest gap, and a packet asked for
1048 // again (its repair was lost) would otherwise wait behind every newer one.
1049 let at = self
1050 .pending
1051 .iter()
1052 .position(|waiting| {
1053 waiting.ssrc == ssrc
1054 && waiting.sequence_number.wrapping_sub(seq) < 0x8000
1055 })
1056 .unwrap_or(self.pending.len());
1057 self.pending.insert(
1058 at,
1059 PendingRetransmission {
1060 ssrc,
1061 sequence_number: seq,
1062 octets,
1063 },
1064 );
1065 self.pending_octets += octets;
1066 }
1067 }
1068 }
1069 self.release_at = None;
1070 self.expire_pending(now);
1071 // The original media is lowered by the reserve before any of these is sent (RFC 4588
1072 // section 7: "the sender SHOULD NOT send retransmission packets without reducing the
1073 // packet rate and bitrate of the original stream"); the retransmissions may then use it.
1074 self.announce_reserve(now, false);
1075 self.release(now);
1076 }
1077}
1078
1079/// The RTX packet (RFC 4588 section 4) that carries `original` again: the RTX SSRC and
1080/// payload type, the next sequence number of the RTX stream, and the original sequence number
1081/// ahead of the payload.
1082fn rtx_packet(
1083 rtx_sequence_number: &mut u16,
1084 rid_extension_ids: (Option<u8>, Option<u8>),
1085 original_packet: &rtp::Packet,
1086 ssrc_rtx: u32,
1087 pt_rtx: u8,
1088) -> rtp::Packet {
1089 let (rid_extension_id, repaired_rid_extension_id) = rid_extension_ids;
1090 let original_seq = original_packet.header.sequence_number;
1091 let mut rtx_payload = Vec::with_capacity(2 + original_packet.payload.len());
1092 rtx_payload.extend_from_slice(&original_seq.to_be_bytes());
1093 rtx_payload.extend_from_slice(&original_packet.payload);
1094
1095 let rtx_seq = *rtx_sequence_number;
1096 *rtx_sequence_number = rtx_sequence_number.wrapping_add(1);
1097
1098 // RFC 4588 4: the RTX packet carries the original's header "as is" apart from the SSRC,
1099 // payload type and sequence number, so its CSRCs and header extensions (audio level,
1100 // abs-send-time, mid, ...) go with it. Building a fresh header used to drop them. Version
1101 // is set explicitly: a buffered packet built with a defaulted header is version 0, which
1102 // receivers discard on arrival. Padding is not carried: the RTX payload is the original
1103 // payload alone.
1104 let mut header = original_packet.header.clone();
1105 header.version = 2;
1106 header.ssrc = ssrc_rtx;
1107 header.payload_type = pt_rtx;
1108 header.sequence_number = rtx_seq;
1109 header.padding = false;
1110 header.padding_size = 0;
1111 // RFC 8852 3.2: a repair packet names the stream it repairs with the repaired-RID, not
1112 // the RID, so a receiver never takes the RTX SSRC for a simulcast layer of its own.
1113 if let Some(rid_id) = rid_extension_id
1114 && let Some(rid) = header.get_extension(rid_id)
1115 {
1116 let _ = header.del_extension(rid_id);
1117 if let Some(repaired_id) = repaired_rid_extension_id {
1118 let _ = header.set_extension(repaired_id, rid);
1119 }
1120 }
1121
1122 rtp::Packet {
1123 header,
1124 payload: rtx_payload.into(),
1125 }
1126}
1127
1128/// A padding-only packet of the RTX stream (a bandwidth probe): `template`'s header on the RTX
1129/// SSRC and payload type with the next RTX sequence number, no payload, and
1130/// [`PROBE_PADDING_OCTETS`] of padding.
1131fn padding_packet(
1132 rtx_sequence_number: &mut u16,
1133 rid_extension_ids: (Option<u8>, Option<u8>),
1134 template: &rtp::Packet,
1135 ssrc_rtx: u32,
1136 pt_rtx: u8,
1137) -> rtp::Packet {
1138 let mut packet = rtx_packet(
1139 rtx_sequence_number,
1140 rid_extension_ids,
1141 template,
1142 ssrc_rtx,
1143 pt_rtx,
1144 );
1145 packet.payload = bytes::Bytes::new();
1146 packet.header.marker = false;
1147 packet.header.padding = true;
1148 packet.header.padding_size = PROBE_PADDING_OCTETS;
1149 packet
1150}
1151
1152impl Protocol<TaggedPacket, TaggedPacket, ()> for NackResponderInterceptor {
1153 type Rout = TaggedPacket;
1154 type Wout = TaggedPacket;
1155 type Eout = ();
1156 type Error = Error;
1157 type Time = Instant;
1158
1159 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1160 let now = msg.now;
1161 let announced_before = self.announced_reserve;
1162 // The congestion controller's target, which the retransmissions are held to.
1163 let carries_target = if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
1164 msg.message.get(&Attribute::TargetBitrateChanged {
1165 bits_per_second: 0.0,
1166 }) {
1167 if bits_per_second.is_finite() && *bits_per_second >= 0.0 {
1168 self.target_bps = Some(*bits_per_second);
1169 self.minimum_bps = msg
1170 .message
1171 .custom::<MinimumTarget>()
1172 .map(|minimum| minimum.bits_per_second)
1173 .filter(|minimum| minimum.is_finite());
1174 self.release_at = None;
1175 }
1176 true
1177 } else {
1178 false
1179 };
1180
1181 // The round trip the RTCP session measured: the reserve's horizon.
1182 if let Some(crate::RtcpSessionEvent::RoundTripTime { rtt, .. }) =
1183 msg.message.custom::<crate::RtcpSessionEvent>()
1184 {
1185 self.round_trip_time = Some(*rtt);
1186 self.release_at = None;
1187 }
1188
1189 // While the pacer tells the source to pause, the target on the packet is zero and the
1190 // congestion controller's rides with it: the rate the retransmissions are held to.
1191 if carries_target {
1192 let pause = msg.message.custom::<crate::PacerPause>().copied();
1193 self.paused = pause.is_some();
1194 if let Some(pause) = pause
1195 && pause.target_bits_per_second.is_finite()
1196 && pause.target_bits_per_second >= 0.0
1197 {
1198 self.target_bps = Some(pause.target_bits_per_second);
1199 }
1200 }
1201
1202 // Retransmissions that left the pacer (or were dropped there).
1203 if let Some(notice) = msg.message.custom::<crate::RetransmissionsLeft>() {
1204 let notice = notice.clone();
1205 self.retransmissions_left(now, ¬ice);
1206 }
1207
1208 // Packets the pacer (wire-ward of here) discarded: never resent.
1209 if let Some(discard) = msg.message.custom::<crate::PacerDiscard>() {
1210 let discard = discard.clone();
1211 self.forget_discarded(&discard);
1212 }
1213
1214 // A probe cluster the congestion controller asks for: fill it.
1215 if let Some(request) = msg.message.custom::<ProbeRequest>().copied() {
1216 let session = crate::RtpSession::of(&msg.message);
1217 self.fill_probe(now, &request, session);
1218 }
1219
1220 // Process NACK packets
1221 if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
1222 for rtcp_packet in rtcp_packets {
1223 if let Some(nack) = rtcp_packet
1224 .as_any()
1225 .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
1226 {
1227 self.handle_nack(now, nack);
1228 }
1229 }
1230 }
1231 if carries_target {
1232 // A new target may leave room for what waits.
1233 self.release(now);
1234 }
1235
1236 // The application's target is the controller's less the reserve (RFC 4588 section
1237 // 7): lowered on the packet that carries it, or announced on a carrier of its own when
1238 // only the reserve moved.
1239 if !carries_target
1240 && self.announced_reserve != announced_before
1241 && let Some(target_bps) = self.target_bps
1242 {
1243 // Moved while the NACK was read: the application hears of it here.
1244 let carrier = self.target_carrier(now, target_bps, self.announced_reserve);
1245 self.read_queue.push_back(carrier);
1246 }
1247 self.announce_reserve(now, !carries_target);
1248 if carries_target && self.announced_reserve > 0.0 {
1249 let (reserve, minimum) = (self.announced_reserve, self.minimum_bps.unwrap_or(0.0));
1250 for attribute in &mut msg.message.attributes {
1251 if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
1252 *bits_per_second = media_target(*bits_per_second, reserve, minimum);
1253 }
1254 }
1255 }
1256
1257 self.read_queue.push_back(msg);
1258
1259 Ok(())
1260 }
1261
1262 fn poll_read(&mut self) -> Option<Self::Rout> {
1263 self.read_queue.pop_front()
1264 }
1265
1266 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1267 if let Some(assignment) = msg.message.custom::<crate::RtpSessionAssignment>() {
1268 for ssrc in &assignment.ssrcs {
1269 self.sessions.insert(*ssrc, assignment.session);
1270 }
1271 }
1272 if let Some(super::NackControl::LocalRtxTime {
1273 payload_type_rtx,
1274 rtx_time,
1275 }) = msg.message.custom::<super::NackControl>()
1276 {
1277 match rtx_time {
1278 Some(rtx_time) => self.local_rtx_times.insert(*payload_type_rtx, *rtx_time),
1279 None => self.local_rtx_times.remove(payload_type_rtx),
1280 };
1281 }
1282 // Every original packet counts against the target (RFC 4588 section 7), whether or
1283 // not its stream is repaired.
1284 if let Packet::Rtp(ref rtp_packet) = msg.message.packet
1285 && !msg.message.has(&Attribute::Retransmission)
1286 {
1287 self.originals.expire(msg.now);
1288 self.originals.add(msg.now, rtp_packet.marshal_size());
1289 }
1290 // Buffer outgoing RTP packets
1291 if let Packet::Rtp(ref rtp_packet) = msg.message.packet
1292 && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
1293 {
1294 stream.send_buffer.add(rtp_packet.clone());
1295 stream.last_sent = Some((rtp_packet.header.sequence_number, msg.now));
1296 let slot = usize::from(rtp_packet.header.sequence_number) % stream.sent_at.len();
1297 stream.sent_at[slot] = Some((rtp_packet.header.sequence_number, msg.now));
1298 stream.retransmit_budget =
1299 (stream.retransmit_budget + 1).min(stream.retransmit_budget_max);
1300 }
1301 if matches!(msg.message.packet, Packet::Rtp(_)) {
1302 self.release_at = None;
1303 if !self.pending.is_empty() {
1304 // The budget may have room again.
1305 self.release(msg.now);
1306 }
1307 if !self.pending.is_empty() || self.announced_reserve > 0.0 {
1308 self.announce_reserve(msg.now, true);
1309 }
1310 }
1311
1312 self.write_queue.push_back(msg);
1313
1314 Ok(())
1315 }
1316
1317 fn poll_write(&mut self) -> Option<TaggedPacket> {
1318 // First drain retransmitted packets
1319 let packet = self.write_queue.pop_front()?;
1320 if packet.message.has(&Attribute::Retransmission) {
1321 self.retransmissions_queued = self.retransmissions_queued.saturating_sub(1);
1322 }
1323 Some(packet)
1324 }
1325
1326 fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
1327 if !self.pending.is_empty() || self.announced_reserve > 0.0 {
1328 // Worked out afresh: a deadline that passed without a change must not be handed
1329 // back again (a driver would spin on it).
1330 self.release_at = None;
1331 self.expire_pending(now);
1332 self.release(now);
1333 self.announce_reserve(now, true);
1334 }
1335 Ok(())
1336 }
1337
1338 /// Due at once while packets wait in the write queue. A retransmission or a probe cluster's
1339 /// padding is made on the read leg (a NACK, a [`ProbeRequest`]), which a driver reaches
1340 /// after its `poll_write` (`poll_write`, `poll_event`, `poll_read`, then `poll_timeout`
1341 /// and sleep, as the crate's event loop has it): without a deadline the packets would wait
1342 /// for whatever wakes the driver next, a timer or an incoming datagram, which can be a
1343 /// long time on a connection with little traffic. The deadline is the instant they were
1344 /// made, so the driver's `handle_timeout` and the `poll_write` after it take them out at
1345 /// once; it is gone when the queue is drained.
1346 ///
1347 /// A retransmission the rate limit holds back is not in the write queue: its deadline is
1348 /// the instant the limit next has room for it ([`Self::next_release`]), never earlier (a
1349 /// driver woken at once would spin), and the same for a waiting request running out and
1350 /// the reserve falling back to zero.
1351 fn poll_timeout(&mut self) -> Option<Self::Time> {
1352 let queued = self.write_queue.front().map(|packet| packet.now);
1353 queued.into_iter().chain(self.next_release()).min()
1354 }
1355}
1356
1357impl Interceptor for NackResponderInterceptor {
1358 fn bind_local_stream(&mut self, info: &StreamInfo) {
1359 if stream_supports_nack(info)
1360 && let Some(send_buffer) = SendBuffer::new(self.size)
1361 {
1362 // RFC 4588 4: the initial sequence number of the retransmission stream is random
1363 // (RFC 3550 5.1), and the stream is the RTX SSRC's, not the binding's: a stream
1364 // bound again continues where the SSRC left off.
1365 let rtx_sequence_number = info
1366 .ssrc_rtx
1367 .and_then(|ssrc_rtx| self.rtx_sequence_numbers.get(&ssrc_rtx).copied())
1368 .unwrap_or_else(rand::random::<u16>);
1369 self.streams.insert(
1370 info.ssrc,
1371 LocalStream {
1372 send_buffer,
1373 ssrc_rtx: info.ssrc_rtx,
1374 payload_type_rtx: info.payload_type_rtx,
1375 rtx_sequence_number,
1376 last_sent: None,
1377 last_retransmit: HashMap::new(),
1378 rid_extension_id: extension_id(info, RTP_STREAM_ID_URI),
1379 repaired_rid_extension_id: extension_id(info, REPAIRED_RTP_STREAM_ID_URI),
1380 retransmit_budget: usize::from(self.size),
1381 retransmit_budget_max: usize::from(self.size),
1382 sent_at: vec![None; usize::from(self.size).max(1)],
1383 },
1384 );
1385 }
1386 }
1387
1388 fn unbind_local_stream(&mut self, info: &StreamInfo) {
1389 if let Some(stream) = self.streams.remove(&info.ssrc)
1390 && let Some(ssrc_rtx) = stream.ssrc_rtx
1391 {
1392 if self.rtx_sequence_numbers.len() >= MAX_REMEMBERED_RTX_SSRCS
1393 && !self.rtx_sequence_numbers.contains_key(&ssrc_rtx)
1394 {
1395 self.rtx_sequence_numbers.clear();
1396 }
1397 self.rtx_sequence_numbers
1398 .insert(ssrc_rtx, stream.rtx_sequence_number);
1399 }
1400 }
1401
1402 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1403
1404 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1405}