Skip to main content

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