rtci_interceptor/flexfec/rfc8627/sender.rs
1//! Send-side RFC 8627 FlexFEC: protects outgoing media with parity repair packets and, when
2//! asked, answers NACKs with FlexFEC retransmissions.
3
4use super::decoder::FLEXFEC_DEFAULT_REPAIR_WINDOW;
5use super::encoder::{FlexFecEncoder, FlexFecProtection};
6use super::params::FlexFecParameters;
7use crate::Interceptor;
8use crate::cc::fec_rate::{FEC_DEFAULT_LATENCY_BUDGET, FecRate, LossPattern};
9use crate::fec_layer::LayerReader;
10use crate::stream_info::StreamInfo;
11use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
12use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
13use sansio::Protocol;
14use shared::TransportContext;
15use shared::error::Error;
16use shared::marshal::MarshalSize;
17use std::collections::{HashMap, VecDeque};
18use std::time::{Duration, Instant};
19
20/// The protection applied when the builder names none: flexible masks, two interleaved repair
21/// packets per five source packets (the draft-03 interceptor's default shape).
22pub const FLEXFEC_DEFAULT_PROTECTION: FlexFecProtection = FlexFecProtection::Mask {
23 media_packets: 5,
24 fec_packets: 2,
25};
26
27/// A protection's source packets per block and repair packets per block.
28fn protection_shape(protection: FlexFecProtection) -> (u32, u32) {
29 match protection {
30 FlexFecProtection::Mask {
31 media_packets,
32 fec_packets,
33 } => (media_packets, fec_packets),
34 FlexFecProtection::Row { l } => (u32::from(l), 1),
35 FlexFecProtection::Column { l, d } => (u32::from(l) * u32::from(d), u32::from(l)),
36 FlexFecProtection::RowAndColumn { l, d } => {
37 (u32::from(l) * u32::from(d), u32::from(l) + u32::from(d))
38 }
39 }
40}
41
42/// The protection of one block: which shape covers which run of the block's packets.
43///
44/// `gathered` source packets were gathered of the `configured` shape's block. A full block of a
45/// flexible mask gets as many repair packets as the loss asks for. A full block of rows and
46/// columns becomes rows or columns when the recent losses were isolated or in bursts (RFC 8627
47/// section 8, [`FecRate::loss_pattern`]); the other fixed shapes stay as configured. A block that
48/// closed short (an enhancement-layer packet ended it) is protected as a mask of its own length,
49/// or, for the fixed shapes, by the complete rows it has.
50fn block_plan(
51 configured: FlexFecProtection,
52 rate: &FecRate,
53 retransmission: bool,
54 gathered: usize,
55) -> Vec<(FlexFecProtection, std::ops::Range<usize>)> {
56 let full = gathered == configured.block_len();
57 if gathered == 0 || gathered > configured.block_len() {
58 return Vec::new();
59 }
60 if let FlexFecProtection::Mask { .. } = configured {
61 let fec_packets = if full {
62 rate.fec_packets_with(retransmission)
63 } else {
64 rate.fec_packets_for(gathered as u32, retransmission)
65 };
66 if fec_packets == 0 {
67 return Vec::new();
68 }
69 return vec![(
70 FlexFecProtection::Mask {
71 media_packets: gathered as u32,
72 fec_packets,
73 },
74 0..gathered,
75 )];
76 }
77 // The fixed shapes are sent or not.
78 if rate.fec_packets_with(retransmission) == 0 {
79 return Vec::new();
80 }
81 let rows = |l: u8| -> Vec<(FlexFecProtection, std::ops::Range<usize>)> {
82 let length = usize::from(l);
83 (0..gathered / length.max(1))
84 .map(|row| {
85 (
86 FlexFecProtection::Row { l },
87 row * length..(row + 1) * length,
88 )
89 })
90 .collect()
91 };
92 match configured {
93 FlexFecProtection::Row { .. } if full => vec![(configured, 0..gathered)],
94 FlexFecProtection::Row { l } => rows(l),
95 FlexFecProtection::Column { l, .. } if !full => rows(l),
96 FlexFecProtection::RowAndColumn { l, .. } if !full => rows(l),
97 FlexFecProtection::RowAndColumn { l, d } if rate.adaptive() => match rate.loss_pattern() {
98 Some(LossPattern::Random) => rows(l),
99 Some(LossPattern::Bursty) => {
100 vec![(FlexFecProtection::Column { l, d }, 0..gathered)]
101 }
102 _ => vec![(configured, 0..gathered)],
103 },
104 _ => vec![(configured, 0..gathered)],
105 }
106}
107
108/// The most recent source packets a probe cluster's repair packets protect.
109const PROBE_SOURCE_PACKETS: usize = 16;
110
111/// The most repair packets one probe cluster is filled with.
112const PROBE_MAX_REPAIR_PACKETS: usize = 64;
113
114/// How often a stream whose probe clusters this encoder fills says so to the NACK responder.
115const PROBE_FILLER_ANNOUNCE_INTERVAL: Duration = Duration::from_secs(1);
116
117/// Source packets a stream keeps to answer NACKs from, when retransmissions are on.
118const RETRANSMISSION_HISTORY: usize = 512;
119
120/// A packet is not retransmitted again within this long of its last retransmission.
121const MIN_RETRANSMIT_INTERVAL: Duration = Duration::from_millis(100);
122
123/// Builder for [`FlexFecSendInterceptor`].
124///
125/// # Example
126///
127/// ```
128/// use rtci_interceptor::{FlexFecProtection, FlexFecSendBuilder, Registry, Slot};
129///
130/// let chain = Registry::new()
131/// .with(
132/// Slot::FecEncoder,
133/// FlexFecSendBuilder::new()
134/// .with_protection(FlexFecProtection::RowAndColumn { l: 4, d: 3 })
135/// .build(),
136/// )
137/// .build();
138/// ```
139pub struct FlexFecSendBuilder {
140 protection: FlexFecProtection,
141 adaptive_rate: bool,
142 repair_window: Duration,
143 retransmissions: bool,
144 initial_sequence_number: Option<u16>,
145 initial_timestamp: Option<u32>,
146 latency_budget: Option<Duration>,
147 base_layer_only: bool,
148 probe_fill: bool,
149 source_rate_first: bool,
150}
151
152impl Default for FlexFecSendBuilder {
153 fn default() -> Self {
154 Self {
155 protection: FLEXFEC_DEFAULT_PROTECTION,
156 adaptive_rate: true,
157 repair_window: FLEXFEC_DEFAULT_REPAIR_WINDOW,
158 retransmissions: false,
159 initial_sequence_number: None,
160 initial_timestamp: None,
161 latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
162 base_layer_only: true,
163 probe_fill: true,
164 source_rate_first: true,
165 }
166 }
167}
168
169impl FlexFecSendBuilder {
170 /// A builder with [`FLEXFEC_DEFAULT_PROTECTION`] and a 10 s repair window.
171 pub fn new() -> Self {
172 Self::default()
173 }
174
175 /// The shape of the protection: flexible masks, rows, columns, or rows and columns.
176 ///
177 /// A shape with no usable block (`l` of 0, a column of fewer than two rows, a mask block of
178 /// more than 110 packets) protects nothing.
179 pub fn with_protection(mut self, protection: FlexFecProtection) -> Self {
180 self.protection = protection;
181 self
182 }
183
184 /// The longest repair window this sender uses. A stream whose negotiated `repair-window`
185 /// (its `a=fmtp` line) is shorter is held to that one.
186 ///
187 /// A block of source packets is protected only when its first packet and its repair
188 /// packets are sent within the window: RFC 8627 section 1.1.8 forbids repair packets whose
189 /// L and D exceed it.
190 pub fn with_repair_window(mut self, repair_window: Duration) -> Self {
191 self.repair_window = repair_window;
192 self
193 }
194
195 /// Answer NACKs for the protected streams with FlexFEC retransmission packets (R=1,
196 /// section 4.2.2.3) on the repair stream. Off by default.
197 ///
198 /// This is FlexFEC's own retransmission, in place of RFC 4588 RTX: a chain that turns it on
199 /// must not also run a NACK responder for the same streams, or each NACK is answered twice.
200 pub fn with_retransmissions(mut self, retransmissions: bool) -> Self {
201 self.retransmissions = retransmissions;
202 self
203 }
204
205 /// The sequence number each repair stream starts at. Unset, it is random (section 4.2.1).
206 pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
207 self.initial_sequence_number = Some(sequence_number);
208 self
209 }
210
211 /// The RTP timestamp each repair stream carries at the instant of its first packet. Unset,
212 /// it is random (RFC 3550 section 5.1). From there it follows the send clock.
213 pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
214 self.initial_timestamp = Some(timestamp);
215 self
216 }
217
218 /// Whether the amount of FEC follows the loss the receiver reports (the default), or
219 /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
220 /// for twice the loss above it, at most half the block (flexible masks; rows and columns are sent or not); the FEC sent is taken out of the
221 /// target the application encodes at.
222 pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
223 self.adaptive_rate = adaptive;
224 self
225 }
226
227 /// The application's latency budget (RFC 8854 section 8): while the round trip measured to
228 /// the receiver is within it, a stream that can be repaired by retransmission (RTX: `nack`
229 /// and an RTX stream negotiated; or [`with_retransmissions`](Self::with_retransmissions) on)
230 /// gets no FEC. [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by
231 /// default; `None` sends FEC by the loss whatever the round trip (proactive FEC).
232 pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
233 self.latency_budget = latency_budget;
234 self
235 }
236
237 /// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
238 /// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
239 /// left out, and ends the block gathered so far, which is protected as it is.
240 pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
241 self.base_layer_only = base_layer_only;
242 self
243 }
244
245 /// Whether bandwidth probe clusters are filled with repair packets (RFC 8854 section 8:
246 /// "when probing bandwidth, i.e., speculatively sending extra data to determine if
247 /// additional link capacity exists, FEC data SHOULD be used as the additional data"; the
248 /// default). When the pacer sends a cluster (its [`ProbeFill`](crate::ProbeFill) says how
249 /// much the media it holds leaves to fill), the encoder sends up to that much in repair
250 /// packets over the newest source packets (at most 16, within the repair window; one repair
251 /// packet each at most) of the stream that sent last, and the NACK responder pads only what
252 /// they leave unfilled. These repair packets are not taken
253 /// out of the target the application encodes at: a cluster is sent above it. Off, the NACK
254 /// responder fills clusters with padding on the RTX stream.
255 pub fn with_probe_fill(mut self, probe_fill: bool) -> Self {
256 self.probe_fill = probe_fill;
257 self
258 }
259
260 /// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8:
261 /// "stronger FEC protection MAY be applied only after the source rate has been reduced";
262 /// the default). Once a congestion controller's target went by, the amount of FEC rises
263 /// only when the source sent in the last second plus the FEC the higher amount adds fit
264 /// within the target, and the target for the application is lowered by the FEC asked for
265 /// so the source makes the room. See [`FecRate::with_source_rate_first`](crate::FecRate::with_source_rate_first).
266 pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
267 self.source_rate_first = source_rate_first;
268 self
269 }
270
271 /// Build the interceptor.
272 pub fn build(self) -> FlexFecSendInterceptor {
273 let (media_packets, fec_packets) = protection_shape(self.protection);
274 FlexFecSendInterceptor {
275 rate: FecRate::new(media_packets, fec_packets, self.adaptive_rate)
276 .with_latency_budget(self.latency_budget)
277 .with_source_rate_first(self.source_rate_first)
278 // Rows and columns are sent whole or not at all.
279 .with_fixed_shape(!matches!(self.protection, FlexFecProtection::Mask { .. })),
280 base_layer_only: self.base_layer_only,
281 probe_fill: self.probe_fill,
282 protection: self.protection,
283 repair_window: self.repair_window,
284 retransmissions: self.retransmissions,
285 initial_sequence_number: self.initial_sequence_number,
286 initial_timestamp: self.initial_timestamp,
287 streams: HashMap::new(),
288 repair_streams: HashMap::new(),
289 wire: None,
290 read_queue: VecDeque::new(),
291 write_queue: VecDeque::new(),
292 }
293 }
294}
295
296/// One repair stream: its encoder and its send clock. Several source streams may share one.
297struct RepairStream {
298 encoder: FlexFecEncoder,
299 clock_rate: u32,
300 initial_timestamp: u32,
301 /// The instant of the first repair packet, which carries `initial_timestamp`.
302 epoch: Option<Instant>,
303 /// How many source streams send their repair packets here.
304 users: usize,
305}
306
307impl RepairStream {
308 /// The repair stream's RTP timestamp at `now`: its transmission time (section 4.2.1), on
309 /// the only clock a sans-I/O engine has, the instant the packet is written with.
310 fn timestamp_at(&mut self, now: Instant) -> u32 {
311 let epoch = *self.epoch.get_or_insert(now);
312 let elapsed = now.saturating_duration_since(epoch);
313 let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
314 self.initial_timestamp.wrapping_add(ticks as u32)
315 }
316}
317
318/// One protected source stream.
319struct ProtectedStream {
320 repair_ssrc: u32,
321 repair_window: Duration,
322 /// Source packets awaiting a full block, consecutive.
323 block: Vec<rtp::Packet>,
324 /// When the first packet of `block` was sent.
325 block_started: Option<Instant>,
326 /// Recent source packets and when they were sent, oldest first, for retransmission.
327 history: VecDeque<(Instant, rtp::Packet)>,
328 /// When each sequence number was last retransmitted.
329 last_retransmit: HashMap<u16, Instant>,
330 /// Whether the stream can be repaired by retransmission: by RTX (`nack` and an RTX stream
331 /// negotiated), or FlexFEC retransmissions are on.
332 retransmission: bool,
333 /// The temporal layer of its packets.
334 layers: LayerReader,
335 /// The newest run of consecutive base-layer source packets and when each was sent, for the
336 /// repair packets of a probe cluster.
337 recent: VecDeque<(Instant, rtp::Packet)>,
338 /// When the NACK responder was last told this encoder fills the stream's probe clusters.
339 announced: Option<Instant>,
340 /// Whether the stream has an RTX stream (`nack` and an RTX stream negotiated), which the
341 /// NACK responder pads the rest of a cluster on. Without one (RFC 8627 section 1.1.7
342 /// answers FlexFEC alone), this encoder fills the whole cluster.
343 rtx: bool,
344}
345
346/// Produces RFC 8627 FlexFEC repair packets (`flexfec`, not `flexfec-03`) for outgoing media.
347///
348/// Binds a local stream that names a FEC SSRC, a FEC payload type and the `flexfec` format
349/// ([`StreamInfo::fec_is_flexfec`]). Its `repair-window` is read from the FEC format's
350/// `a=fmtp` line.
351///
352/// Source packets pass through unaltered (section 4.1); repair packets follow the packet that
353/// completed their block, on the repair SSRC, with the protected SSRC in their CSRC list.
354pub struct FlexFecSendInterceptor {
355 protection: FlexFecProtection,
356 /// The loss-driven amount of FEC.
357 rate: FecRate,
358 /// Only base-layer frames are protected.
359 base_layer_only: bool,
360 /// Probe clusters are filled with repair packets.
361 probe_fill: bool,
362 repair_window: Duration,
363 retransmissions: bool,
364 initial_sequence_number: Option<u16>,
365 initial_timestamp: Option<u32>,
366 /// Keyed by the **source** SSRC being protected.
367 streams: HashMap<u32, ProtectedStream>,
368 /// Keyed by the repair SSRC.
369 repair_streams: HashMap<u32, RepairStream>,
370 /// Where the source packets are read from once [`wire_tap`](Self::wire_tap) was called: as
371 /// they left, below everything that edits them.
372 wire: Option<WireImages>,
373 read_queue: VecDeque<TaggedPacket>,
374 write_queue: VecDeque<TaggedPacket>,
375}
376
377impl FlexFecSendInterceptor {
378 /// Tells the FEC rate whether every protected stream can be repaired by retransmission, so
379 /// that no FEC is reserved out of the target while none will be sent.
380 fn update_retransmission_repairable(&mut self) {
381 let repairable =
382 !self.streams.is_empty() && self.streams.values().all(|stream| stream.retransmission);
383 self.rate.set_retransmission_repairable(repairable);
384 }
385
386 /// The source SSRCs currently being protected.
387 pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
388 self.streams.keys().copied()
389 }
390
391 /// The repair window in force for the source stream `ssrc`.
392 pub fn repair_window(&self, ssrc: u32) -> Option<Duration> {
393 self.streams.get(&ssrc).map(|stream| stream.repair_window)
394 }
395
396 /// Answer one NACK from the retransmission history.
397 fn retransmit(&mut self, now: Instant, media_ssrc: u32, sequence_numbers: Vec<u16>) {
398 let Some(stream) = self.streams.get_mut(&media_ssrc) else {
399 return;
400 };
401 let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) else {
402 return;
403 };
404 stream
405 .last_retransmit
406 .retain(|_, at| now.saturating_duration_since(*at) < MIN_RETRANSMIT_INTERVAL);
407
408 for sequence_number in sequence_numbers {
409 if stream.last_retransmit.contains_key(&sequence_number) {
410 continue;
411 }
412 // Only what is still inside the repair window: the receiver has agreed to accept a
413 // retransmission of any source packet within it (section 1.1.8), and no further.
414 let Some((_, source)) = stream.history.iter().find(|(sent, packet)| {
415 packet.header.sequence_number == sequence_number
416 && now.saturating_duration_since(*sent) <= stream.repair_window
417 }) else {
418 continue;
419 };
420 let timestamp = repair.timestamp_at(now);
421 let Ok(packet) = repair.encoder.retransmit(source, timestamp) else {
422 continue;
423 };
424 stream.last_retransmit.insert(sequence_number, now);
425 self.write_queue.push_back(TaggedPacket {
426 now,
427 transport: TransportContext::default(),
428 message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
429 });
430 }
431 }
432}
433
434impl FlexFecSendInterceptor {
435 /// The tap this encoder reads the source packets from, to register at
436 /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
437 ///
438 /// FEC covers the source packets as they are on the wire (RFC 8627 section 4.1). This
439 /// interceptor generates packets, so it sits above the pacer, where a source packet is not
440 /// final: the TWCC sender below writes the transport-wide sequence number into it, adding
441 /// the header extension when the packet has none. With the tap registered the encoder
442 /// protects the packet that left (and keeps that image for retransmission), and the repair
443 /// packets still enter the chain here, so they are paced, numbered and recorded. Without a
444 /// tap the encoder reads the packets as they pass this slot, which is the wire image only
445 /// when nothing below edits them.
446 pub fn wire_tap(&mut self) -> WireImageTap {
447 let (tap, images) = wire_image_tap();
448 for ssrc in self.streams.keys() {
449 images.watch(*ssrc);
450 }
451 self.wire = Some(images);
452 tap
453 }
454
455 /// Add one source packet to its stream's block and queue the repair packets a full block
456 /// yields.
457 fn protect(&mut self, now: Instant, transport: TransportContext, rtp_packet: &rtp::Packet) {
458 let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc) else {
459 return;
460 };
461
462 if self.retransmissions {
463 if stream.history.len() == RETRANSMISSION_HISTORY {
464 stream.history.pop_front();
465 }
466 stream.history.push_back((now, rtp_packet.clone()));
467 }
468
469 let mut repair_packets = Vec::new();
470 let block_len = self.protection.block_len();
471 // RFC 8854 section 8: with a layered codec only base-layer frames are protected. A
472 // packet of a higher temporal layer is left out; since a block is a run of consecutive
473 // packets it ends the block, which is protected with what it has.
474 let enhancement = self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload);
475 // The newest run of consecutive base-layer packets: an enhancement-layer packet is
476 // passed over, and the next base-layer packet, not consecutive, starts a new run.
477 if self.probe_fill && !enhancement {
478 if stream.recent.back().is_some_and(|(_, last)| {
479 rtp_packet.header.sequence_number != last.header.sequence_number.wrapping_add(1)
480 }) {
481 stream.recent.clear();
482 }
483 if stream.recent.len() == PROBE_SOURCE_PACKETS {
484 stream.recent.pop_front();
485 }
486 stream.recent.push_back((now, rtp_packet.clone()));
487 }
488 if block_len > 0 {
489 let closed = if enhancement {
490 Some(std::mem::take(&mut stream.block))
491 } else {
492 // L, D and the masks describe positions from one base sequence number, so a
493 // block is a run of consecutive packets: a gap starts a new one.
494 if let Some(last) = stream.block.last()
495 && rtp_packet.header.sequence_number
496 != last.header.sequence_number.wrapping_add(1)
497 {
498 stream.block.clear();
499 }
500 if stream.block.is_empty() {
501 stream.block_started = Some(now);
502 }
503 stream.block.push(rtp_packet.clone());
504 (stream.block.len() >= block_len).then(|| std::mem::take(&mut stream.block))
505 };
506
507 if let Some(block) = closed.filter(|block| !block.is_empty()) {
508 // Section 1.1.8: nothing is sent that reaches beyond the repair window. A block
509 // that took longer than the window to fill goes unprotected.
510 let within_window = stream.block_started.is_some_and(|started| {
511 now.saturating_duration_since(started) <= stream.repair_window
512 });
513 if within_window
514 && let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc)
515 {
516 // The loss decides how much (flexible masks carry as many repair packets
517 // as it asks for, the fixed shapes are sent or not) and, for rows and
518 // columns, which.
519 let plan = block_plan(
520 self.protection,
521 &self.rate,
522 stream.retransmission,
523 block.len(),
524 );
525 if !plan.is_empty() {
526 let timestamp = repair.timestamp_at(now);
527 for (protection, run) in plan {
528 repair_packets.extend(repair.encoder.encode_block(
529 protection,
530 &block[run],
531 timestamp,
532 ));
533 }
534 }
535 }
536 }
537 }
538
539 for packet in repair_packets {
540 self.rate.on_repair_sent(now, packet.marshal_size());
541 let fec_bytes = packet.payload.len();
542 self.write_queue.push_back(TaggedPacket {
543 now,
544 transport,
545 message: AttributedPacket::new(Packet::Rtp(packet))
546 .with(crate::FecSent::one(rtp_packet.header.ssrc, fec_bytes)),
547 });
548 }
549 }
550
551 /// Fills a probe cluster with `octets` of repair packets (RFC 8854 section 8): a flexible
552 /// mask over the newest run of source packets of the stream that sent last, as many repair
553 /// packets as the octets ask for (at most one per source packet). The run is what is still
554 /// inside the repair window (section 1.1.8). Not counted in the FEC bit rate taken out of
555 /// the media target: a cluster is sent above the target.
556 ///
557 /// Returns the octets of the repair packets made: fewer than asked for when the run is
558 /// short (a layered stream's newest base-layer frame), and the NACK responder pads the rest
559 /// ([`FecProbeFilled`](crate::cc::probe::FecProbeFilled)) on the stream's RTX stream. A
560 /// stream without one (RFC 8627 section 1.1.7 left FlexFEC alone negotiated) has nothing
561 /// the responder could pad on: the encoder makes further repair packets over the same run
562 /// until the cluster is filled (at most [`PROBE_MAX_REPAIR_PACKETS`]), each another copy
563 /// of the protection, still FEC data protecting the media.
564 ///
565 /// `mark`: the cluster, when no pacer sends it (the request carried no
566 /// [`ProbeFill`](crate::ProbeFill)): the repair packets leave as one burst, marked
567 /// [`ProbePacket`](crate::ProbePacket) here, as the NACK responder marks its padding then.
568 fn fill_probe(
569 &mut self,
570 now: Instant,
571 transport: TransportContext,
572 octets: usize,
573 mark: Option<u32>,
574 ) -> usize {
575 let Some((&ssrc, stream)) = self
576 .streams
577 .iter_mut()
578 .filter(|(_, stream)| !stream.recent.is_empty())
579 .max_by_key(|(_, stream)| stream.recent.back().map(|(at, _)| *at))
580 else {
581 return 0;
582 };
583 let window = stream.repair_window;
584 while stream
585 .recent
586 .front()
587 .is_some_and(|(at, _)| now.saturating_duration_since(*at) > window)
588 {
589 stream.recent.pop_front();
590 }
591 if stream.recent.is_empty() || octets == 0 {
592 return 0;
593 }
594 let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) else {
595 return 0;
596 };
597 let sources: Vec<rtp::Packet> = stream
598 .recent
599 .iter()
600 .map(|(_, packet)| packet.clone())
601 .collect();
602 // A repair packet is about as large as the largest source packet it protects, with the
603 // FlexFEC header (at most 20 octets for these masks) in front.
604 let repair_size = sources
605 .iter()
606 .map(|packet| packet.marshal_size())
607 .max()
608 .unwrap_or(0)
609 + 20;
610 let rtx = stream.rtx;
611 let timestamp = repair.timestamp_at(now);
612 let mut filled = 0;
613 let mut made = 0usize;
614 loop {
615 let wanted = octets.saturating_sub(filled).div_ceil(repair_size.max(1));
616 let fec_packets = wanted
617 .clamp(1, sources.len())
618 .min(PROBE_MAX_REPAIR_PACKETS - made);
619 let packets = repair.encoder.encode_block(
620 FlexFecProtection::Mask {
621 media_packets: sources.len() as u32,
622 fec_packets: fec_packets as u32,
623 },
624 &sources,
625 timestamp,
626 );
627 if packets.is_empty() {
628 break;
629 }
630 for packet in packets {
631 filled += packet.marshal_size();
632 made += 1;
633 let fec_bytes = packet.payload.len();
634 let mut message = AttributedPacket::new(Packet::Rtp(packet))
635 .with(crate::FecSent::one(ssrc, fec_bytes));
636 if let Some(cluster) = mark {
637 message.add(Attribute::Custom(std::sync::Arc::new(crate::ProbePacket {
638 cluster,
639 })));
640 }
641 self.write_queue.push_back(TaggedPacket {
642 now,
643 transport,
644 message,
645 });
646 }
647 // With an RTX stream the responder pads the rest; without, the encoder goes on.
648 if rtx || filled >= octets || made >= PROBE_MAX_REPAIR_PACKETS {
649 break;
650 }
651 }
652 filled
653 }
654
655 /// Protect the source packets that left since the last call.
656 fn protect_wire_images(&mut self) {
657 let Some(images) = self.wire.as_ref().map(WireImages::take) else {
658 return;
659 };
660 for image in images {
661 // A retransmission on the media SSRC (a NACK answered without RTX, RFC 8627
662 // section 1.1.7 leaves none negotiated next to FlexFEC) is a source packet that
663 // already left and was protected then: taken again, its old sequence number would
664 // break the run of consecutive packets every block is (section 4.2.2.2).
665 if image.message.has(&Attribute::Retransmission) {
666 continue;
667 }
668 if let Packet::Rtp(rtp_packet) = &image.message.packet {
669 // `image.now` is the instant the pacer released the packet.
670 self.protect(image.now, image.transport, rtp_packet);
671 }
672 }
673 }
674}
675
676impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFecSendInterceptor {
677 type Rout = TaggedPacket;
678 type Wout = TaggedPacket;
679 type Eout = ();
680 type Error = Error;
681 type Time = Instant;
682
683 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
684 let streams = &self.streams;
685 self.rate
686 .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
687 // A probe cluster (RFC 8854 section 8): what its media leaves to fill (the pacer's
688 // `ProbeFill`; without a pacer, the whole cluster) is filled with repair packets, and
689 // what they cannot fill the NACK responder pads.
690 // An encoder that protects no stream says nothing: another encoder of the chain (ULPFEC
691 // beside it) may be the one filling, and its report is the one the responder waits for.
692 if self.probe_fill
693 && !self.streams.is_empty()
694 && let Some(request) = msg.message.custom::<crate::ProbeRequest>().copied()
695 {
696 let paced = msg
697 .message
698 .custom::<crate::ProbeFill>()
699 .filter(|fill| fill.cluster == request.cluster)
700 .map(|fill| fill.octets.min(request.octets));
701 let fill = paced.unwrap_or(request.octets);
702 let mark = paced.is_none().then_some(request.cluster);
703 self.protect_wire_images();
704 let filled = self.fill_probe(msg.now, msg.transport, fill, mark);
705 // After the repair packets, wire-ward: the NACK responder pads what they left.
706 self.write_queue.push_back(
707 crate::cc::probe::FecProbeFilled {
708 cluster: request.cluster,
709 octets: filled,
710 }
711 .into_packet(msg.now, msg.transport),
712 );
713 }
714 if self.retransmissions
715 && let Packet::Rtcp(rtcp_packets) = &msg.message.packet
716 {
717 let mut requests = Vec::new();
718 for rtcp_packet in rtcp_packets {
719 if let Some(nack) = rtcp_packet
720 .as_any()
721 .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
722 && self.streams.contains_key(&nack.media_ssrc)
723 {
724 let mut sequence_numbers: Vec<u16> = nack
725 .nacks
726 .iter()
727 .flat_map(|pair| pair.packet_list())
728 .collect();
729 sequence_numbers.sort_unstable();
730 sequence_numbers.dedup();
731 requests.push((nack.media_ssrc, sequence_numbers));
732 }
733 }
734 for (media_ssrc, sequence_numbers) in requests {
735 self.retransmit(msg.now, media_ssrc, sequence_numbers);
736 }
737 }
738 self.read_queue.push_back(msg);
739 Ok(())
740 }
741
742 fn poll_read(&mut self) -> Option<Self::Rout> {
743 self.read_queue.pop_front()
744 }
745
746 fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
747 // The source's rate, which stronger FEC waits on (RFC 8627 section 8).
748 let streams = &self.streams;
749 self.rate.on_write(&msg, |ssrc| streams.contains_key(&ssrc));
750 // The NACK responder learns that this encoder fills the stream's probe clusters.
751 if self.probe_fill
752 && let Packet::Rtp(rtp_packet) = &msg.message.packet
753 && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
754 && stream.announced.is_none_or(|at| {
755 msg.now.saturating_duration_since(at) >= PROBE_FILLER_ANNOUNCE_INTERVAL
756 })
757 {
758 stream.announced = Some(msg.now);
759 let ssrc = rtp_packet.header.ssrc;
760 msg.message.add(Attribute::Custom(std::sync::Arc::new(
761 crate::cc::probe::FecProbeFiller { ssrc },
762 )));
763 }
764 if self.wire.is_some() {
765 // The packets are protected as they leave, from the tap: here they only pass.
766 self.protect_wire_images();
767 self.write_queue.push_back(msg);
768 return Ok(());
769 }
770
771 let Packet::Rtp(rtp_packet) = &msg.message.packet else {
772 self.write_queue.push_back(msg);
773 return Ok(());
774 };
775 if msg.message.has(&Attribute::Retransmission) {
776 // Protected when it was first sent (see `protect_wire_images`).
777 self.write_queue.push_back(msg);
778 return Ok(());
779 }
780 let rtp_packet = rtp_packet.clone();
781 let now = msg.now;
782 let transport = msg.transport;
783
784 // The source packet goes out first, as it was handed over; the repair packets protect
785 // what has already left.
786 self.write_queue.push_back(msg);
787 self.protect(now, transport, &rtp_packet);
788 Ok(())
789 }
790
791 fn poll_write(&mut self) -> Option<TaggedPacket> {
792 self.protect_wire_images();
793 self.write_queue.pop_front()
794 }
795
796 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
797 Ok(())
798 }
799
800 fn poll_timeout(&mut self) -> Option<Self::Time> {
801 None
802 }
803}
804
805impl Interceptor for FlexFecSendInterceptor {
806 fn bind_local_stream(&mut self, info: &StreamInfo) {
807 let (Some(repair_ssrc), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
808 else {
809 return;
810 };
811 if !info.fec_is_flexfec() || self.streams.contains_key(&info.ssrc) {
812 return;
813 }
814
815 // The negotiated repair window bounds what may be sent; the builder's can only narrow
816 // it.
817 let negotiated = FlexFecParameters::parse(&info.sdp_fmtp_line_fec).repair_window;
818 let repair_window = negotiated.map_or(self.repair_window, |negotiated| {
819 negotiated.min(self.repair_window)
820 });
821
822 let (initial_sequence_number, initial_timestamp) =
823 (self.initial_sequence_number, self.initial_timestamp);
824 self.repair_streams
825 .entry(repair_ssrc)
826 .or_insert_with(|| RepairStream {
827 encoder: FlexFecEncoder::new(payload_type_fec, repair_ssrc)
828 .with_base_sequence_number(
829 initial_sequence_number.unwrap_or_else(rand::random),
830 ),
831 // The rate of `flexfec` is recommended to match the source's (section 5.1); 90
832 // kHz is the video clock when a stream names none.
833 clock_rate: if info.clock_rate == 0 {
834 90_000
835 } else {
836 info.clock_rate
837 },
838 initial_timestamp: initial_timestamp.unwrap_or_else(rand::random),
839 epoch: None,
840 users: 0,
841 })
842 .users += 1;
843 self.streams.insert(
844 info.ssrc,
845 ProtectedStream {
846 repair_ssrc,
847 repair_window,
848 block: Vec::new(),
849 block_started: None,
850 history: VecDeque::new(),
851 last_retransmit: HashMap::new(),
852 // RTX, this encoder's own retransmissions, or (a stream with `nack` and no RTX:
853 // RFC 8627 section 1.1.7 left FlexFEC alone negotiated) the NACK responder's
854 // FlexFEC retransmissions on the repair stream (`RepairForm::FlexFec`): RFC 8854
855 // section 8's "RTX or Flexible FEC retransmissions", so no FEC within the
856 // latency budget.
857 retransmission: self.retransmissions
858 || crate::nack::stream_supports_rtx_repair(info)
859 || crate::nack::stream_supports_nack(info),
860 layers: LayerReader::for_mime_type(&info.mime_type),
861 recent: VecDeque::new(),
862 announced: None,
863 rtx: crate::nack::stream_supports_rtx_repair(info),
864 },
865 );
866 if let Some(images) = &self.wire {
867 images.watch(info.ssrc);
868 // Without RTX the stream's NACKs are answered with FlexFEC retransmissions on this
869 // repair stream (the NACK responder's, or this encoder's own): they leave with the
870 // wire image the repair packets protect (RFC 8627 section 4.2.2.3).
871 if !crate::nack::stream_supports_rtx_repair(info) {
872 images.retransmit_on(repair_ssrc);
873 }
874 }
875 self.update_retransmission_repairable();
876 }
877
878 fn unbind_local_stream(&mut self, info: &StreamInfo) {
879 if let Some(images) = &self.wire {
880 images.unwatch(info.ssrc);
881 }
882 let Some(stream) = self.streams.remove(&info.ssrc) else {
883 return;
884 };
885 if let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) {
886 repair.users -= 1;
887 if repair.users == 0 {
888 self.repair_streams.remove(&stream.repair_ssrc);
889 if let Some(images) = &self.wire {
890 images.stop_retransmit_on(stream.repair_ssrc);
891 }
892 }
893 }
894 self.update_retransmission_repairable();
895 }
896
897 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
898
899 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
900}