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::FecRate;
9use crate::stream_info::StreamInfo;
10use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
11use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
12use sansio::Protocol;
13use shared::TransportContext;
14use shared::error::Error;
15use shared::marshal::MarshalSize;
16use std::collections::{HashMap, VecDeque};
17use std::time::{Duration, Instant};
18
19/// The protection applied when the builder names none: flexible masks, two interleaved repair
20/// packets per five source packets (the draft-03 interceptor's default shape).
21pub const FLEXFEC_DEFAULT_PROTECTION: FlexFecProtection = FlexFecProtection::Mask {
22    media_packets: 5,
23    fec_packets: 2,
24};
25
26/// A protection's source packets per block and repair packets per block.
27fn protection_shape(protection: FlexFecProtection) -> (u32, u32) {
28    match protection {
29        FlexFecProtection::Mask {
30            media_packets,
31            fec_packets,
32        } => (media_packets, fec_packets),
33        FlexFecProtection::Row { l } => (u32::from(l), 1),
34        FlexFecProtection::Column { l, d } => (u32::from(l) * u32::from(d), u32::from(l)),
35        FlexFecProtection::RowAndColumn { l, d } => {
36            (u32::from(l) * u32::from(d), u32::from(l) + u32::from(d))
37        }
38    }
39}
40
41/// Source packets a stream keeps to answer NACKs from, when retransmissions are on.
42const RETRANSMISSION_HISTORY: usize = 512;
43
44/// A packet is not retransmitted again within this long of its last retransmission.
45const MIN_RETRANSMIT_INTERVAL: Duration = Duration::from_millis(100);
46
47/// Builder for [`FlexFecSendInterceptor`].
48///
49/// # Example
50///
51/// ```
52/// use rtci_interceptor::{FlexFecProtection, FlexFecSendBuilder, Registry, Slot};
53///
54/// let chain = Registry::new()
55///     .with(
56///         Slot::FecEncoder,
57///         FlexFecSendBuilder::new()
58///             .with_protection(FlexFecProtection::RowAndColumn { l: 4, d: 3 })
59///             .build(),
60///     )
61///     .build();
62/// ```
63pub struct FlexFecSendBuilder {
64    protection: FlexFecProtection,
65    adaptive_rate: bool,
66    repair_window: Duration,
67    retransmissions: bool,
68    initial_sequence_number: Option<u16>,
69    initial_timestamp: Option<u32>,
70}
71
72impl Default for FlexFecSendBuilder {
73    fn default() -> Self {
74        Self {
75            protection: FLEXFEC_DEFAULT_PROTECTION,
76            adaptive_rate: true,
77            repair_window: FLEXFEC_DEFAULT_REPAIR_WINDOW,
78            retransmissions: false,
79            initial_sequence_number: None,
80            initial_timestamp: None,
81        }
82    }
83}
84
85impl FlexFecSendBuilder {
86    /// A builder with [`FLEXFEC_DEFAULT_PROTECTION`] and a 10 s repair window.
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// The shape of the protection: flexible masks, rows, columns, or rows and columns.
92    ///
93    /// A shape with no usable block (`l` of 0, a column of fewer than two rows, a mask block of
94    /// more than 110 packets) protects nothing.
95    pub fn with_protection(mut self, protection: FlexFecProtection) -> Self {
96        self.protection = protection;
97        self
98    }
99
100    /// The longest repair window this sender uses. A stream whose negotiated `repair-window`
101    /// (its `a=fmtp` line) is shorter is held to that one.
102    ///
103    /// A block of source packets is protected only when its first packet and its repair
104    /// packets are sent within the window: RFC 8627 section 1.1.8 forbids repair packets whose
105    /// L and D exceed it.
106    pub fn with_repair_window(mut self, repair_window: Duration) -> Self {
107        self.repair_window = repair_window;
108        self
109    }
110
111    /// Answer NACKs for the protected streams with FlexFEC retransmission packets (R=1,
112    /// section 4.2.2.3) on the repair stream. Off by default.
113    ///
114    /// This is FlexFEC's own retransmission, in place of RFC 4588 RTX: a chain that turns it on
115    /// must not also run a NACK responder for the same streams, or each NACK is answered twice.
116    pub fn with_retransmissions(mut self, retransmissions: bool) -> Self {
117        self.retransmissions = retransmissions;
118        self
119    }
120
121    /// The sequence number each repair stream starts at. Unset, it is random (section 4.2.1).
122    pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
123        self.initial_sequence_number = Some(sequence_number);
124        self
125    }
126
127    /// The RTP timestamp each repair stream carries at the instant of its first packet. Unset,
128    /// it is random (RFC 3550 section 5.1). From there it follows the send clock.
129    pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
130        self.initial_timestamp = Some(timestamp);
131        self
132    }
133
134    /// Whether the amount of FEC follows the loss the receiver reports (the default), or
135    /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
136    /// 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
137    /// target the application encodes at.
138    pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
139        self.adaptive_rate = adaptive;
140        self
141    }
142
143    /// Build the interceptor.
144    pub fn build(self) -> FlexFecSendInterceptor {
145        let (media_packets, fec_packets) = protection_shape(self.protection);
146        FlexFecSendInterceptor {
147            rate: FecRate::new(media_packets, fec_packets, self.adaptive_rate),
148            protection: self.protection,
149            repair_window: self.repair_window,
150            retransmissions: self.retransmissions,
151            initial_sequence_number: self.initial_sequence_number,
152            initial_timestamp: self.initial_timestamp,
153            streams: HashMap::new(),
154            repair_streams: HashMap::new(),
155            wire: None,
156            read_queue: VecDeque::new(),
157            write_queue: VecDeque::new(),
158        }
159    }
160}
161
162/// One repair stream: its encoder and its send clock. Several source streams may share one.
163struct RepairStream {
164    encoder: FlexFecEncoder,
165    clock_rate: u32,
166    initial_timestamp: u32,
167    /// The instant of the first repair packet, which carries `initial_timestamp`.
168    epoch: Option<Instant>,
169    /// How many source streams send their repair packets here.
170    users: usize,
171}
172
173impl RepairStream {
174    /// The repair stream's RTP timestamp at `now`: its transmission time (section 4.2.1), on
175    /// the only clock a sans-I/O engine has, the instant the packet is written with.
176    fn timestamp_at(&mut self, now: Instant) -> u32 {
177        let epoch = *self.epoch.get_or_insert(now);
178        let elapsed = now.saturating_duration_since(epoch);
179        let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
180        self.initial_timestamp.wrapping_add(ticks as u32)
181    }
182}
183
184/// One protected source stream.
185struct ProtectedStream {
186    repair_ssrc: u32,
187    repair_window: Duration,
188    /// Source packets awaiting a full block, consecutive.
189    block: Vec<rtp::Packet>,
190    /// When the first packet of `block` was sent.
191    block_started: Option<Instant>,
192    /// Recent source packets and when they were sent, oldest first, for retransmission.
193    history: VecDeque<(Instant, rtp::Packet)>,
194    /// When each sequence number was last retransmitted.
195    last_retransmit: HashMap<u16, Instant>,
196}
197
198/// Produces RFC 8627 FlexFEC repair packets (`flexfec`, not `flexfec-03`) for outgoing media.
199///
200/// Binds a local stream that names a FEC SSRC, a FEC payload type and the `flexfec` format
201/// ([`StreamInfo::fec_is_flexfec`]). Its `repair-window` is read from the FEC format's
202/// `a=fmtp` line.
203///
204/// Source packets pass through unaltered (section 4.1); repair packets follow the packet that
205/// completed their block, on the repair SSRC, with the protected SSRC in their CSRC list.
206pub struct FlexFecSendInterceptor {
207    protection: FlexFecProtection,
208    /// The loss-driven amount of FEC.
209    rate: FecRate,
210    repair_window: Duration,
211    retransmissions: bool,
212    initial_sequence_number: Option<u16>,
213    initial_timestamp: Option<u32>,
214    /// Keyed by the **source** SSRC being protected.
215    streams: HashMap<u32, ProtectedStream>,
216    /// Keyed by the repair SSRC.
217    repair_streams: HashMap<u32, RepairStream>,
218    /// Where the source packets are read from once [`wire_tap`](Self::wire_tap) was called: as
219    /// they left, below everything that edits them.
220    wire: Option<WireImages>,
221    read_queue: VecDeque<TaggedPacket>,
222    write_queue: VecDeque<TaggedPacket>,
223}
224
225impl FlexFecSendInterceptor {
226    /// The source SSRCs currently being protected.
227    pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
228        self.streams.keys().copied()
229    }
230
231    /// The repair window in force for the source stream `ssrc`.
232    pub fn repair_window(&self, ssrc: u32) -> Option<Duration> {
233        self.streams.get(&ssrc).map(|stream| stream.repair_window)
234    }
235
236    /// Answer one NACK from the retransmission history.
237    fn retransmit(&mut self, now: Instant, media_ssrc: u32, sequence_numbers: Vec<u16>) {
238        let Some(stream) = self.streams.get_mut(&media_ssrc) else {
239            return;
240        };
241        let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) else {
242            return;
243        };
244        stream
245            .last_retransmit
246            .retain(|_, at| now.saturating_duration_since(*at) < MIN_RETRANSMIT_INTERVAL);
247
248        for sequence_number in sequence_numbers {
249            if stream.last_retransmit.contains_key(&sequence_number) {
250                continue;
251            }
252            // Only what is still inside the repair window: the receiver has agreed to accept a
253            // retransmission of any source packet within it (section 1.1.8), and no further.
254            let Some((_, source)) = stream.history.iter().find(|(sent, packet)| {
255                packet.header.sequence_number == sequence_number
256                    && now.saturating_duration_since(*sent) <= stream.repair_window
257            }) else {
258                continue;
259            };
260            let timestamp = repair.timestamp_at(now);
261            let Ok(packet) = repair.encoder.retransmit(source, timestamp) else {
262                continue;
263            };
264            stream.last_retransmit.insert(sequence_number, now);
265            self.write_queue.push_back(TaggedPacket {
266                now,
267                transport: TransportContext::default(),
268                message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
269            });
270        }
271    }
272}
273
274impl FlexFecSendInterceptor {
275    /// The tap this encoder reads the source packets from, to register at
276    /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
277    ///
278    /// FEC covers the source packets as they are on the wire (RFC 8627 section 4.1). This
279    /// interceptor generates packets, so it sits above the pacer, where a source packet is not
280    /// final: the TWCC sender below writes the transport-wide sequence number into it, adding
281    /// the header extension when the packet has none. With the tap registered the encoder
282    /// protects the packet that left (and keeps that image for retransmission), and the repair
283    /// packets still enter the chain here, so they are paced, numbered and recorded. Without a
284    /// tap the encoder reads the packets as they pass this slot, which is the wire image only
285    /// when nothing below edits them.
286    pub fn wire_tap(&mut self) -> WireImageTap {
287        let (tap, images) = wire_image_tap();
288        for ssrc in self.streams.keys() {
289            images.watch(*ssrc);
290        }
291        self.wire = Some(images);
292        tap
293    }
294
295    /// Add one source packet to its stream's block and queue the repair packets a full block
296    /// yields.
297    fn protect(&mut self, now: Instant, transport: TransportContext, rtp_packet: &rtp::Packet) {
298        let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc) else {
299            return;
300        };
301
302        if self.retransmissions {
303            if stream.history.len() == RETRANSMISSION_HISTORY {
304                stream.history.pop_front();
305            }
306            stream.history.push_back((now, rtp_packet.clone()));
307        }
308
309        let mut repair_packets = Vec::new();
310        let block_len = self.protection.block_len();
311        if block_len > 0 {
312            // L, D and the masks describe positions from one base sequence number, so a block
313            // is a run of consecutive packets: a gap starts a new one.
314            if let Some(last) = stream.block.last()
315                && rtp_packet.header.sequence_number != last.header.sequence_number.wrapping_add(1)
316            {
317                stream.block.clear();
318            }
319            if stream.block.is_empty() {
320                stream.block_started = Some(now);
321            }
322            stream.block.push(rtp_packet.clone());
323
324            if stream.block.len() >= block_len {
325                // Section 1.1.8: nothing is sent that reaches beyond the repair window. A block
326                // that took longer than the window to fill goes unprotected.
327                let within_window = stream.block_started.is_some_and(|started| {
328                    now.saturating_duration_since(started) <= stream.repair_window
329                });
330                if within_window
331                    && let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc)
332                {
333                    // The loss decides how much: flexible masks carry as many repair packets as
334                    // it asks for, the fixed shapes are sent or not.
335                    let protection = match self.protection {
336                        FlexFecProtection::Mask { media_packets, .. } => FlexFecProtection::Mask {
337                            media_packets,
338                            fec_packets: self.rate.fec_packets(),
339                        },
340                        fixed => fixed,
341                    };
342                    if self.rate.protects() {
343                        let timestamp = repair.timestamp_at(now);
344                        repair_packets =
345                            repair
346                                .encoder
347                                .encode_block(protection, &stream.block, timestamp);
348                    }
349                }
350                stream.block.clear();
351            }
352        }
353
354        for packet in repair_packets {
355            self.rate.on_repair_sent(now, packet.marshal_size());
356            self.write_queue.push_back(TaggedPacket {
357                now,
358                transport,
359                message: AttributedPacket::new(Packet::Rtp(packet)),
360            });
361        }
362    }
363
364    /// Protect the source packets that left since the last call.
365    fn protect_wire_images(&mut self) {
366        let Some(images) = self.wire.as_ref().map(WireImages::take) else {
367            return;
368        };
369        for image in images {
370            if let Packet::Rtp(rtp_packet) = &image.message.packet {
371                // `image.now` is the instant the pacer released the packet.
372                self.protect(image.now, image.transport, rtp_packet);
373            }
374        }
375    }
376}
377
378impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFecSendInterceptor {
379    type Rout = TaggedPacket;
380    type Wout = TaggedPacket;
381    type Eout = ();
382    type Error = Error;
383    type Time = Instant;
384
385    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
386        let streams = &self.streams;
387        self.rate
388            .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
389        if self.retransmissions
390            && let Packet::Rtcp(rtcp_packets) = &msg.message.packet
391        {
392            let mut requests = Vec::new();
393            for rtcp_packet in rtcp_packets {
394                if let Some(nack) = rtcp_packet
395                    .as_any()
396                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
397                    && self.streams.contains_key(&nack.media_ssrc)
398                {
399                    let mut sequence_numbers: Vec<u16> = nack
400                        .nacks
401                        .iter()
402                        .flat_map(|pair| pair.packet_list())
403                        .collect();
404                    sequence_numbers.sort_unstable();
405                    sequence_numbers.dedup();
406                    requests.push((nack.media_ssrc, sequence_numbers));
407                }
408            }
409            for (media_ssrc, sequence_numbers) in requests {
410                self.retransmit(msg.now, media_ssrc, sequence_numbers);
411            }
412        }
413        self.read_queue.push_back(msg);
414        Ok(())
415    }
416
417    fn poll_read(&mut self) -> Option<Self::Rout> {
418        self.read_queue.pop_front()
419    }
420
421    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
422        if self.wire.is_some() {
423            // The packets are protected as they leave, from the tap: here they only pass.
424            self.protect_wire_images();
425            self.write_queue.push_back(msg);
426            return Ok(());
427        }
428
429        let Packet::Rtp(rtp_packet) = &msg.message.packet else {
430            self.write_queue.push_back(msg);
431            return Ok(());
432        };
433        let rtp_packet = rtp_packet.clone();
434        let now = msg.now;
435        let transport = msg.transport;
436
437        // The source packet goes out first, as it was handed over; the repair packets protect
438        // what has already left.
439        self.write_queue.push_back(msg);
440        self.protect(now, transport, &rtp_packet);
441        Ok(())
442    }
443
444    fn poll_write(&mut self) -> Option<TaggedPacket> {
445        self.protect_wire_images();
446        self.write_queue.pop_front()
447    }
448
449    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
450        Ok(())
451    }
452
453    fn poll_timeout(&mut self) -> Option<Self::Time> {
454        None
455    }
456}
457
458impl Interceptor for FlexFecSendInterceptor {
459    fn bind_local_stream(&mut self, info: &StreamInfo) {
460        let (Some(repair_ssrc), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
461        else {
462            return;
463        };
464        if !info.fec_is_flexfec() || self.streams.contains_key(&info.ssrc) {
465            return;
466        }
467
468        // The negotiated repair window bounds what may be sent; the builder's can only narrow
469        // it.
470        let negotiated = FlexFecParameters::parse(&info.sdp_fmtp_line_fec).repair_window;
471        let repair_window = negotiated.map_or(self.repair_window, |negotiated| {
472            negotiated.min(self.repair_window)
473        });
474
475        let (initial_sequence_number, initial_timestamp) =
476            (self.initial_sequence_number, self.initial_timestamp);
477        self.repair_streams
478            .entry(repair_ssrc)
479            .or_insert_with(|| RepairStream {
480                encoder: FlexFecEncoder::new(payload_type_fec, repair_ssrc)
481                    .with_base_sequence_number(
482                        initial_sequence_number.unwrap_or_else(rand::random),
483                    ),
484                // The rate of `flexfec` is recommended to match the source's (section 5.1); 90
485                // kHz is the video clock when a stream names none.
486                clock_rate: if info.clock_rate == 0 {
487                    90_000
488                } else {
489                    info.clock_rate
490                },
491                initial_timestamp: initial_timestamp.unwrap_or_else(rand::random),
492                epoch: None,
493                users: 0,
494            })
495            .users += 1;
496        self.streams.insert(
497            info.ssrc,
498            ProtectedStream {
499                repair_ssrc,
500                repair_window,
501                block: Vec::new(),
502                block_started: None,
503                history: VecDeque::new(),
504                last_retransmit: HashMap::new(),
505            },
506        );
507        if let Some(images) = &self.wire {
508            images.watch(info.ssrc);
509        }
510    }
511
512    fn unbind_local_stream(&mut self, info: &StreamInfo) {
513        if let Some(images) = &self.wire {
514            images.unwatch(info.ssrc);
515        }
516        let Some(stream) = self.streams.remove(&info.ssrc) else {
517            return;
518        };
519        if let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) {
520            repair.users -= 1;
521            if repair.users == 0 {
522                self.repair_streams.remove(&stream.repair_ssrc);
523            }
524        }
525    }
526
527    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
528
529    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
530}