Skip to main content

rtci_interceptor/flexfec/rfc8627/
receiver.rs

1//! Receive-side RFC 8627 FlexFEC: recovers lost media and keeps repair packets from the
2//! application.
3
4use super::decoder::{
5    FLEXFEC_DEFAULT_REPAIR_WINDOW, FlexFecDecoder, FlexFecDecoderConfig, FlexFecDecoderStats,
6};
7use super::params::FlexFecParameters;
8use crate::Interceptor;
9use crate::stream_info::StreamInfo;
10use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
11use sansio::Protocol;
12use shared::error::Error;
13use std::collections::{HashMap, VecDeque};
14use std::time::{Duration, Instant};
15
16/// The longest repair window a receiver built without
17/// [`with_max_repair_window`](FlexFecReceiveBuilder::with_max_repair_window) supports: 10 s.
18pub const FLEXFEC_MAX_REPAIR_WINDOW: Duration = FLEXFEC_DEFAULT_REPAIR_WINDOW;
19
20/// Builder for [`FlexFecReceiveInterceptor`].
21///
22/// # Example
23///
24/// ```
25/// use rtci_interceptor::{FlexFecReceiveBuilder, Registry, Slot};
26///
27/// let chain = Registry::new()
28///     .with(Slot::FecDecoder, FlexFecReceiveBuilder::new().build())
29///     .build();
30/// ```
31pub struct FlexFecReceiveBuilder {
32    max_repair_window: Duration,
33    in_band_payload_type: Option<u8>,
34}
35
36impl Default for FlexFecReceiveBuilder {
37    fn default() -> Self {
38        Self {
39            max_repair_window: FLEXFEC_MAX_REPAIR_WINDOW,
40            in_band_payload_type: None,
41        }
42    }
43}
44
45impl FlexFecReceiveBuilder {
46    /// A builder supporting repair windows up to [`FLEXFEC_MAX_REPAIR_WINDOW`].
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// The longest repair window this receiver buffers for.
52    ///
53    /// A stream whose negotiated `repair-window` is longer is not protected: the receiver
54    /// "must support any valid FLEX FEC configuration within the repair window" it agreed to
55    /// (RFC 8627 section 5.2.1), and it cannot for a window it does not buffer. (Refusing the
56    /// payload type in the answer is the application's part: see the media engine.)
57    pub fn with_max_repair_window(mut self, max_repair_window: Duration) -> Self {
58        self.max_repair_window = max_repair_window;
59        self
60    }
61
62    /// In-band SSRC mapping (RFC 8627 section 7.1.1): there is no `a=ssrc-group:FEC-FR`, a
63    /// packet with `payload_type` on an SSRC that is not a bound media stream is a repair
64    /// packet, and its CSRC list says which streams it protects. Every bound remote stream is
65    /// then a source stream.
66    pub fn with_in_band_ssrc_mapping(mut self, payload_type: u8) -> Self {
67        self.in_band_payload_type = Some(payload_type);
68        self
69    }
70
71    /// Build the interceptor.
72    pub fn build(self) -> FlexFecReceiveInterceptor {
73        FlexFecReceiveInterceptor {
74            max_repair_window: self.max_repair_window,
75            in_band_payload_type: self.in_band_payload_type,
76            decoder: None,
77            repair_streams: HashMap::new(),
78            source_streams: HashMap::new(),
79            read_queue: VecDeque::new(),
80            write_queue: VecDeque::new(),
81        }
82    }
83}
84
85/// Recovers media lost from streams protected by RFC 8627 FlexFEC (`flexfec`, not
86/// `flexfec-03`).
87///
88/// Binds a remote stream that names a FEC SSRC, a FEC payload type and the `flexfec` format
89/// ([`StreamInfo::fec_is_flexfec`]). One decoder serves every stream, so a repair packet may
90/// protect several of them (its CSRC list), and one repair stream may serve several sources.
91///
92/// Repair packets are consumed; recovered packets continue up the chain tagged
93/// [`Attribute::RecoveredByFec`], a retransmitted one (R=1) tagged
94/// [`Attribute::Retransmission`].
95pub struct FlexFecReceiveInterceptor {
96    max_repair_window: Duration,
97    in_band_payload_type: Option<u8>,
98    /// Built at the first binding; buffers for the longest repair window bound so far.
99    decoder: Option<FlexFecDecoder>,
100    /// Repair SSRC to its payload type and how many source streams named it.
101    repair_streams: HashMap<u32, (u8, usize)>,
102    /// Source SSRC to the repair SSRC it was bound with, if any.
103    source_streams: HashMap<u32, Option<u32>>,
104    read_queue: VecDeque<TaggedPacket>,
105    write_queue: VecDeque<TaggedPacket>,
106}
107
108impl FlexFecReceiveInterceptor {
109    /// The source SSRCs currently protected.
110    pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
111        self.source_streams.keys().copied()
112    }
113
114    /// The decoder's counters; zeros before any stream is bound.
115    pub fn stats(&self) -> FlexFecDecoderStats {
116        self.decoder
117            .as_ref()
118            .map(FlexFecDecoder::stats)
119            .unwrap_or_default()
120    }
121
122    fn decoder_for(&mut self, repair_window: Duration) -> &mut FlexFecDecoder {
123        let config = FlexFecDecoderConfig::for_repair_window(repair_window);
124        let decoder = self
125            .decoder
126            .get_or_insert_with(|| FlexFecDecoder::new(config));
127        // One decoder serves every stream, so it buffers for the longest window among them.
128        decoder.widen(config);
129        decoder
130    }
131
132    /// Whether a packet on `ssrc` with `payload_type` belongs to a repair stream.
133    fn is_repair(&self, ssrc: u32, payload_type: u8) -> bool {
134        match self.repair_streams.get(&ssrc) {
135            // The association says which SSRC; the payload type says it is FlexFEC and not
136            // something else on that SSRC.
137            Some((repair_payload_type, _)) => *repair_payload_type == payload_type,
138            None => {
139                self.in_band_payload_type == Some(payload_type)
140                    && !self.source_streams.contains_key(&ssrc)
141            }
142        }
143    }
144
145    fn queue_available(&mut self, msg: &TaggedPacket, available: Vec<rtp::Packet>, how: Attribute) {
146        for packet in available {
147            let mut message = AttributedPacket::new(Packet::Rtp(packet));
148            // Says how it got here: it was never on the wire in this form, so anything
149            // measuring the network (arrival times, loss) can tell it from a packet that was.
150            message.add(how.clone());
151            self.read_queue.push_back(TaggedPacket {
152                now: msg.now,
153                transport: msg.transport,
154                message,
155            });
156        }
157    }
158}
159
160impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFecReceiveInterceptor {
161    type Rout = TaggedPacket;
162    type Wout = TaggedPacket;
163    type Eout = ();
164    type Error = Error;
165    type Time = Instant;
166
167    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
168        let Packet::Rtp(rtp_packet) = &msg.message.packet else {
169            self.read_queue.push_back(msg);
170            return Ok(());
171        };
172        let ssrc = rtp_packet.header.ssrc;
173
174        if self.is_repair(ssrc, rtp_packet.header.payload_type) {
175            // A repair packet: the decoder takes it and it goes no further. It is not media.
176            let Some(decoder) = self.decoder.as_mut() else {
177                return Ok(());
178            };
179            let before = decoder.stats().retransmitted;
180            let mut available = decoder.push_repair(msg.now, rtp_packet);
181            // A retransmission delivers its packet first; anything after it was rebuilt from
182            // parity that packet completed.
183            let retransmitted = if decoder.stats().retransmitted > before {
184                vec![available.remove(0)]
185            } else {
186                Vec::new()
187            };
188            self.queue_available(&msg, retransmitted, Attribute::Retransmission);
189            self.queue_available(&msg, available, Attribute::RecoveredByFec);
190            return Ok(());
191        }
192
193        // A source packet: the decoder needs it to recover its neighbours, and it carries on
194        // as it arrived. What it made recoverable follows it.
195        let recovered = match self.decoder.as_mut() {
196            Some(decoder) if decoder.protects(ssrc) => decoder.push_source(msg.now, rtp_packet),
197            _ => Vec::new(),
198        };
199        let (now, transport) = (msg.now, msg.transport);
200        self.read_queue.push_back(msg);
201        for packet in recovered {
202            let mut message = AttributedPacket::new(Packet::Rtp(packet));
203            message.add(Attribute::RecoveredByFec);
204            self.read_queue.push_back(TaggedPacket {
205                now,
206                transport,
207                message,
208            });
209        }
210        Ok(())
211    }
212
213    fn poll_read(&mut self) -> Option<TaggedPacket> {
214        self.read_queue.pop_front()
215    }
216
217    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
218        self.write_queue.push_back(msg);
219        Ok(())
220    }
221
222    fn poll_write(&mut self) -> Option<Self::Wout> {
223        self.write_queue.pop_front()
224    }
225
226    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
227        Ok(())
228    }
229
230    fn poll_timeout(&mut self) -> Option<Self::Time> {
231        None
232    }
233}
234
235impl Interceptor for FlexFecReceiveInterceptor {
236    fn bind_remote_stream(&mut self, info: &StreamInfo) {
237        if self.source_streams.contains_key(&info.ssrc) {
238            return;
239        }
240
241        if let (Some(repair_ssrc), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
242            && info.fec_is_flexfec()
243        {
244            let repair_window = FlexFecParameters::parse(&info.sdp_fmtp_line_fec)
245                .repair_window
246                .unwrap_or(FLEXFEC_DEFAULT_REPAIR_WINDOW);
247            // A window longer than this receiver buffers for cannot be honoured: the stream
248            // goes unprotected instead of being half supported.
249            if repair_window > self.max_repair_window {
250                return;
251            }
252            self.decoder_for(repair_window).add_source_stream(info.ssrc);
253            self.repair_streams
254                .entry(repair_ssrc)
255                .or_insert((payload_type_fec, 0))
256                .1 += 1;
257            self.source_streams.insert(info.ssrc, Some(repair_ssrc));
258            return;
259        }
260
261        // In-band mapping: every media stream may be named by a repair packet's CSRC list. A
262        // repair flow bound in its own right (its own SSRC as the stream) is not a source.
263        if self.in_band_payload_type.is_some()
264            && self.in_band_payload_type != Some(info.payload_type)
265            && !self.repair_streams.contains_key(&info.ssrc)
266        {
267            let max_repair_window = self.max_repair_window;
268            self.decoder_for(max_repair_window)
269                .add_source_stream(info.ssrc);
270            self.source_streams.insert(info.ssrc, None);
271        }
272    }
273
274    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
275        let Some(repair_ssrc) = self.source_streams.remove(&info.ssrc) else {
276            return;
277        };
278        if let Some(decoder) = self.decoder.as_mut() {
279            decoder.remove_source_stream(info.ssrc);
280        }
281        if let Some(repair_ssrc) = repair_ssrc
282            && let Some((_, users)) = self.repair_streams.get_mut(&repair_ssrc)
283        {
284            *users -= 1;
285            if *users == 0 {
286                self.repair_streams.remove(&repair_ssrc);
287            }
288        }
289    }
290
291    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
292
293    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
294}