Skip to main content

rtci_interceptor/ulpfec/
receiver.rs

1//! Receive-side ULPFEC: takes RED apart, recovers lost media, keeps FEC away from the application.
2
3use super::decoder::{UlpfecDecoder, UlpfecDecoderStats};
4use super::red::depacketize_red;
5use super::sender::{Carriage, StreamFilter, video_streams};
6use crate::Interceptor;
7use crate::stream_info::StreamInfo;
8use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
9use bytes::Bytes;
10use sansio::Protocol;
11use shared::error::Error;
12use std::collections::{HashMap, VecDeque};
13use std::sync::Arc;
14use std::time::Instant;
15
16/// Marks an RTP packet that carried only FEC in a RED stream.
17///
18/// Such a packet has a sequence number of the media stream. The interceptors application-ward of
19/// the FEC decoder (the NACK generator, the receiver report, the arrival recorders) count
20/// sequence numbers, so the packet is passed on to them, with its payload removed and this
21/// attached as [`Attribute::Custom`], instead of being swallowed: swallowed, it would read as a
22/// lost media packet and be asked for again. It is not media. Whatever sits at the end of the
23/// chain drops it: `rtci`'s peer connection does, and an application driving a chain itself checks
24/// `message.custom::<UlpfecRepair>()`.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct UlpfecRepair;
27
28/// Builder for [`UlpfecReceiveInterceptor`].
29///
30/// # Example
31///
32/// ```
33/// use rtci_interceptor::{Registry, Slot, UlpfecReceiveBuilder};
34///
35/// // `a=rtpmap:116 red/90000`, `a=rtpmap:117 ulpfec/90000`
36/// let chain = Registry::new()
37///     .with(Slot::FecDecoder, UlpfecReceiveBuilder::red(116, 117).build())
38///     .build();
39/// ```
40pub struct UlpfecReceiveBuilder {
41    carriage: Carriage,
42    one_level_only: bool,
43    forward_repair: bool,
44    filter: StreamFilter,
45}
46
47impl UlpfecReceiveBuilder {
48    fn new(carriage: Carriage) -> Self {
49        Self {
50            carriage,
51            one_level_only: false,
52            forward_repair: true,
53            filter: video_streams(),
54        }
55    }
56
57    /// FEC as a redundant encoding (RFC 5109 14.2): the protected streams arrive as RED packets
58    /// of `red_payload_type`, with FEC blocks of `fec_payload_type`.
59    pub fn red(red_payload_type: u8, fec_payload_type: u8) -> Self {
60        Self::new(Carriage::Red {
61            red_payload_type: red_payload_type & 0x7F,
62            fec_payload_type: fec_payload_type & 0x7F,
63        })
64    }
65
66    /// FEC as a stream of its own (RFC 5109 14.1), on the repair SSRC of
67    /// [`StreamInfo::ssrc_fec`]. A stream without a repair SSRC and payload type is not bound.
68    pub fn stream() -> Self {
69        Self::new(Carriage::Stream)
70    }
71
72    /// Refuse FEC with more than one protection level: this endpoint signalled `onelevelonly=1`
73    /// (RFC 5109 13, 14.3: for a receiver the parameter says what it accepts).
74    pub fn with_one_level_only(mut self, one_level_only: bool) -> Self {
75        self.one_level_only = one_level_only;
76        self
77    }
78
79    /// Whether a RED packet that held only FEC is passed on, emptied and marked
80    /// [`UlpfecRepair`], so the interceptors behind this one see its sequence number (the
81    /// default), or swallowed here.
82    pub fn with_repair_forwarding(mut self, forward_repair: bool) -> Self {
83        self.forward_repair = forward_repair;
84        self
85    }
86
87    /// Which bound remote streams are protected. The default is every `video/` stream.
88    pub fn with_stream_filter(
89        mut self,
90        filter: impl Fn(&StreamInfo) -> bool + Send + Sync + 'static,
91    ) -> Self {
92        self.filter = Arc::new(filter);
93        self
94    }
95
96    /// Build the interceptor.
97    pub fn build(self) -> UlpfecReceiveInterceptor {
98        UlpfecReceiveInterceptor {
99            carriage: self.carriage,
100            one_level_only: self.one_level_only,
101            forward_repair: self.forward_repair,
102            filter: self.filter,
103            decoders: HashMap::new(),
104            repair_to_media: HashMap::new(),
105            read_queue: VecDeque::new(),
106            write_queue: VecDeque::new(),
107        }
108    }
109}
110
111/// Recovers media lost from streams protected by ULPFEC (RFC 5109).
112///
113/// # RED carriage
114///
115/// A RED packet of a protected stream is taken apart (RFC 2198): its primary block goes on as
116/// the RTP packet it stands for, with the primary's payload type, which is the *virtual* packet
117/// the FEC protects (RFC 5109 14.2); its FEC blocks go to the decoder. A packet of the stream
118/// that is not RED passes as it is and is still given to the decoder, since a receiver that
119/// accepts RED accepts its encodings bare as well (RFC 2198 5). A bare packet of the FEC payload
120/// type on the media SSRC is dropped: FEC is not sent by itself in a RED stream (RFC 5109 14.2).
121/// So is a RED packet whose block headers do not fit its length.
122///
123/// Recovered packets rejoin the read leg marked [`Attribute::RecoveredByFec`].
124///
125/// # Where it belongs
126///
127/// [`Slot::FecDecoder`](crate::Slot::FecDecoder): wire-ward of the NACK generator, so a packet
128/// that FEC rebuilds is not also asked for.
129pub struct UlpfecReceiveInterceptor {
130    carriage: Carriage,
131    one_level_only: bool,
132    forward_repair: bool,
133    filter: StreamFilter,
134    /// Decoders keyed by the media SSRC they protect.
135    decoders: HashMap<u32, UlpfecDecoder>,
136    /// Separate stream: repair SSRC (and its payload type) to the media SSRC.
137    repair_to_media: HashMap<u32, (u32, u8)>,
138    read_queue: VecDeque<TaggedPacket>,
139    write_queue: VecDeque<TaggedPacket>,
140}
141
142impl UlpfecReceiveInterceptor {
143    /// The media SSRCs currently protected.
144    pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
145        self.decoders.keys().copied()
146    }
147
148    /// The decoder's counters for the media stream `ssrc`.
149    pub fn stats(&self, ssrc: u32) -> Option<UlpfecDecoderStats> {
150        self.decoders.get(&ssrc).map(UlpfecDecoder::stats)
151    }
152
153    fn queue_recovered(
154        &mut self,
155        now: Instant,
156        transport: shared::TransportContext,
157        recovered: Vec<rtp::Packet>,
158    ) {
159        for packet in recovered {
160            // Says how it got here: it was never on the wire in this form, so anything measuring
161            // the network can tell it from a packet that was.
162            let message =
163                AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::RecoveredByFec);
164            self.read_queue.push_back(TaggedPacket {
165                now,
166                transport,
167                message,
168            });
169        }
170    }
171}
172
173impl Protocol<TaggedPacket, TaggedPacket, ()> for UlpfecReceiveInterceptor {
174    type Rout = TaggedPacket;
175    type Wout = TaggedPacket;
176    type Eout = ();
177    type Error = Error;
178    type Time = Instant;
179
180    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
181        let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
182            self.read_queue.push_back(msg);
183            return Ok(());
184        };
185        let ssrc = rtp_packet.header.ssrc;
186        let now = msg.now;
187        let transport = msg.transport;
188
189        // A packet of a separate FEC stream: to the decoder, and no further. It has an SSRC of
190        // its own, so nothing behind this interceptor is waiting for its sequence number.
191        if let Some(&(media_ssrc, payload_type_fec)) = self.repair_to_media.get(&ssrc) {
192            let recovered = match self.decoders.get_mut(&media_ssrc) {
193                Some(decoder) if rtp_packet.header.payload_type == payload_type_fec => {
194                    decoder.push_fec(&rtp_packet.payload).unwrap_or_default()
195                }
196                _ => Vec::new(),
197            };
198            self.queue_recovered(now, transport, recovered);
199            return Ok(());
200        }
201
202        let Some(decoder) = self.decoders.get_mut(&ssrc) else {
203            self.read_queue.push_back(msg);
204            return Ok(());
205        };
206
207        let mut recovered = Vec::new();
208        if let Carriage::Red {
209            red_payload_type,
210            fec_payload_type,
211        } = self.carriage
212        {
213            if rtp_packet.header.payload_type == fec_payload_type {
214                // FEC by itself in a RED stream (RFC 5109 14.2 forbids it).
215                return Ok(());
216            }
217            if rtp_packet.header.payload_type == red_payload_type {
218                let Ok(red) = depacketize_red(&rtp_packet.payload, fec_payload_type) else {
219                    return Ok(());
220                };
221                for fec in &red.fec {
222                    recovered.extend(decoder.push_fec(fec).unwrap_or_default());
223                }
224                match red.primary {
225                    Some((payload_type, data)) => {
226                        // The virtual RTP packet: the RED packet without its block headers and
227                        // redundant data, under the primary's payload type.
228                        rtp_packet.header.payload_type = payload_type;
229                        rtp_packet.payload = data;
230                    }
231                    None => {
232                        if self.forward_repair {
233                            rtp_packet.header.payload_type = fec_payload_type;
234                            rtp_packet.payload = Bytes::new();
235                            msg.message.add(Attribute::Custom(Arc::new(UlpfecRepair)));
236                            self.read_queue.push_back(msg);
237                        }
238                        self.queue_recovered(now, transport, recovered);
239                        return Ok(());
240                    }
241                }
242            }
243        }
244
245        // A media packet: the decoder needs it to rebuild its neighbours, and it carries on.
246        recovered.extend(decoder.push_media(rtp_packet));
247        self.read_queue.push_back(msg);
248        self.queue_recovered(now, transport, recovered);
249        Ok(())
250    }
251
252    fn poll_read(&mut self) -> Option<TaggedPacket> {
253        self.read_queue.pop_front()
254    }
255
256    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
257        self.write_queue.push_back(msg);
258        Ok(())
259    }
260
261    fn poll_write(&mut self) -> Option<Self::Wout> {
262        self.write_queue.pop_front()
263    }
264
265    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
266        Ok(())
267    }
268
269    fn poll_timeout(&mut self) -> Option<Self::Time> {
270        None
271    }
272}
273
274impl Interceptor for UlpfecReceiveInterceptor {
275    fn bind_remote_stream(&mut self, info: &StreamInfo) {
276        if !(self.filter)(info) {
277            return;
278        }
279        // The repair flow the signalling associated with the stream (RFC 5956 section 4.3,
280        // `a=ssrc-group:FEC-FR <media> <repair>` with a `ulpfec` format): FEC as a stream of its
281        // own (RFC 5109 section 14.1), whichever carriage the builder names, since the
282        // multiplexing is "indicated out of band" per stream (section 14). With the stream
283        // carriage a repair flow that names no format is taken as ULPFEC.
284        let separate = match (info.ssrc_fec, info.payload_type_fec) {
285            (Some(ssrc_fec), Some(payload_type_fec))
286                if info.fec_is_ulpfec()
287                    || (self.carriage == Carriage::Stream && info.mime_type_fec.is_empty()) =>
288            {
289                Some((ssrc_fec, payload_type_fec))
290            }
291            _ => None,
292        };
293        if let Some((ssrc_fec, payload_type_fec)) = separate {
294            self.repair_to_media
295                .insert(ssrc_fec, (info.ssrc, payload_type_fec));
296        } else if self.carriage == Carriage::Stream {
297            return;
298        }
299        // RFC 5109 section 13: `onelevelonly=1` on this endpoint's `ulpfec` format of the
300        // section ("what the receiver accepts to receive", section 14.3): FEC with more than
301        // one level is refused.
302        let fec_format = separate
303            .map(|(_, payload_type)| payload_type)
304            .or(match self.carriage {
305                Carriage::Red {
306                    fec_payload_type, ..
307                } => Some(fec_payload_type),
308                Carriage::Stream => None,
309            });
310        let one_level_only = self.one_level_only
311            || fec_format.is_some_and(|payload_type| {
312                info.section_fmtp_lines
313                    .iter()
314                    .any(|(pt, fmtp)| *pt == payload_type && super::one_level_only_from_fmtp(fmtp))
315            });
316        self.decoders.insert(
317            info.ssrc,
318            UlpfecDecoder::new(info.ssrc).with_one_level_only(one_level_only),
319        );
320    }
321
322    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
323        self.decoders.remove(&info.ssrc);
324        self.repair_to_media
325            .retain(|_, (media, _)| *media != info.ssrc);
326    }
327
328    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
329
330    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
331}