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, negotiated_carriage, 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. Whoever counts the stream's
19/// sequence numbers must see that number as received: the interceptors application-ward of the
20/// FEC decoder (the NACK generator, the receiver report, the arrival recorders), and the
21/// receiver that puts frames together, for which a number that never arrives is a missing
22/// media packet (a frame with one inside it is never complete; one between two frames is
23/// waited for). So the packet is passed on, with its payload removed and this attached as
24/// [`Attribute::Custom`], instead of being swallowed. It is not media: it goes on as a packet
25/// **without a payload**, under the payload type of the stream's media (the primary block of
26/// the last media packet; the FEC payload type before any media arrived), with the FEC
27/// packet's sequence number, timestamp and no marker. That is what a padding packet of
28/// libwebrtc's looks like, and what libwebrtc's own receiver makes of a FEC packet
29/// (`video/rtp_video_stream_receiver2.cc:1603-1612` at a222406d, "Notify video_receiver about
30/// received FEC packets to avoid NACKing these packets": `NotifyReceiverOfEmptyPacket`, which
31/// is `PacketBuffer::InsertPadding` and the NACK module's `OnReceivedPacket`, `:1622-1637`).
32/// `rtci`'s peer connection delivers it to the application so; an application driving a chain
33/// itself can tell it by `message.custom::<UlpfecRepair>()`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct UlpfecRepair;
36
37/// Marks an RTP packet as a FEC packet that arrived in a FEC session of its own (RFC 5109
38/// section 14.1), for a binder that learns which stream a FEC session protects only as its
39/// packets arrive. Carried as [`Attribute::Custom`].
40///
41/// Whoever drives the chain attaches it to each RTP packet read on a FEC session's transport,
42/// beside mapping the packet's SSRC ([`FecSessionSsrcMap`](crate::FecSessionSsrcMap)). The
43/// receive interceptor gives such a packet to the decoder of
44/// [`media_ssrc`](Self::media_ssrc), if it keeps one (a bound stream that passed the filter,
45/// [`UlpfecReceiveBuilder::sessions`] or the RED carriage), and passes it no further. It does
46/// the same for a stream bound with [`StreamInfo::fec_session`], which needs no mark.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct FecSessionPacket {
49 /// The SSRC of the media stream the FEC session's stream protects: the SSRC the packet
50 /// had on the FEC session's transport (RFC 5109 section 7.2).
51 pub media_ssrc: u32,
52 /// The payload type of `ulpfec` in the FEC session's m= section. A packet of the session
53 /// with another payload type is not FEC and is discarded (RFC 3550 section 5.1: a
54 /// receiver "MUST ignore packets with payload types that it does not understand").
55 pub payload_type: u8,
56 /// This endpoint signalled `onelevelonly=1` for the session (RFC 5109 section 13): FEC
57 /// with more than one level is refused.
58 pub one_level_only: bool,
59}
60
61/// What the ULPFEC decoder of one protected stream has received and done so far.
62///
63/// The receive interceptor passes it application-ward as [`Attribute::Custom`] on an empty
64/// RTCP packet (a carrier, which the chain's terminus lets through) whenever it changed, so
65/// whoever drives the chain can report it: `rtci`'s peer connection puts it in the stream's
66/// webrtc-stats `fecPacketsReceived`, `fecBytesReceived` and `fecPacketsDiscarded`. The counts
67/// are totals since the stream was bound, so a carrier that is lost loses nothing.
68///
69/// FEC on a repair SSRC or in a FEC session of its own arrives as packets of its own, which
70/// the one who reads them off the wire can count; FEC blocks in RED packets of the media
71/// stream (RFC 5109 section 14.2) are known only here, and are counted in
72/// [`fec_packets_in_red`](Self::fec_packets_in_red).
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct UlpfecReceiveStats {
76 /// The protected media stream.
77 pub media_ssrc: u32,
78 /// FEC blocks that arrived in RED packets of the stream, whatever became of them.
79 pub fec_packets_in_red: u64,
80 /// Their octets: the FEC header, the level headers and the protected data (the block,
81 /// not the RED packet around it).
82 pub fec_bytes_in_red: u64,
83 /// The decoder's counters: what it took, rebuilt and discarded, from every carriage.
84 pub decoder: UlpfecDecoderStats,
85}
86
87/// Builder for [`UlpfecReceiveInterceptor`].
88///
89/// # Example
90///
91/// ```
92/// use rtci_interceptor::{Registry, Slot, UlpfecReceiveBuilder};
93///
94/// // `a=rtpmap:116 red/90000`, `a=rtpmap:117 ulpfec/90000`
95/// let chain = Registry::new()
96/// .with(Slot::FecDecoder, UlpfecReceiveBuilder::red(116, 117).build())
97/// .build();
98/// ```
99pub struct UlpfecReceiveBuilder {
100 carriage: Carriage,
101 one_level_only: bool,
102 forward_repair: bool,
103 decode_every_stream: bool,
104 filter: StreamFilter,
105 zero_mutable_extensions: bool,
106}
107
108impl UlpfecReceiveBuilder {
109 fn new(carriage: Carriage) -> Self {
110 Self {
111 carriage,
112 one_level_only: false,
113 forward_repair: true,
114 decode_every_stream: false,
115 filter: video_streams(),
116 zero_mutable_extensions: false,
117 }
118 }
119
120 /// FEC in RTP sessions of their own (RFC 5109 section 14.1), told packet by packet
121 /// ([`FecSessionPacket`]): every bound stream that passes the filter has a decoder from
122 /// the start, fed with its media, so that the FEC of a session whose protected stream is
123 /// only known once packets arrive finds it. A stream bound with a repair flow of the
124 /// media's own session ([`StreamInfo::ssrc_fec`]) is read as [`stream`](Self::stream)
125 /// reads it.
126 pub fn sessions() -> Self {
127 let mut builder = Self::new(Carriage::Stream);
128 builder.decode_every_stream = true;
129 builder
130 }
131
132 /// FEC as a redundant encoding (RFC 5109 14.2): the protected streams arrive as RED packets
133 /// of `red_payload_type`, with FEC blocks of `fec_payload_type`.
134 pub fn red(red_payload_type: u8, fec_payload_type: u8) -> Self {
135 Self::new(Carriage::Red {
136 red_payload_type: red_payload_type & 0x7F,
137 fec_payload_type: fec_payload_type & 0x7F,
138 })
139 }
140
141 /// FEC as a stream of its own (RFC 5109 14.1), on the repair SSRC of
142 /// [`StreamInfo::ssrc_fec`]. A stream without a repair SSRC and payload type is not bound.
143 pub fn stream() -> Self {
144 Self::new(Carriage::Stream)
145 }
146
147 /// Refuse FEC with more than one protection level: this endpoint signalled `onelevelonly=1`
148 /// (RFC 5109 13, 14.3: for a receiver the parameter says what it accepts).
149 pub fn with_one_level_only(mut self, one_level_only: bool) -> Self {
150 self.one_level_only = one_level_only;
151 self
152 }
153
154 /// Whether a RED packet that held only FEC is passed on, emptied and marked
155 /// [`UlpfecRepair`], so the interceptors behind this one and the receiver that puts frames
156 /// together see its sequence number (the default), or swallowed here: its sequence number
157 /// is then a missing packet to them.
158 pub fn with_repair_forwarding(mut self, forward_repair: bool) -> Self {
159 self.forward_repair = forward_repair;
160 self
161 }
162
163 /// Which bound remote streams are protected. The default is every `video/` stream.
164 pub fn with_stream_filter(
165 mut self,
166 filter: impl Fn(&StreamInfo) -> bool + Send + Sync + 'static,
167 ) -> Self {
168 self.filter = Arc::new(filter);
169 self
170 }
171
172 /// Recover with the values of the transport-wide sequence number, abs-send-time and toffset
173 /// extensions zeroed in this receiver's copy of each media packet, as libwebrtc's receiver
174 /// does (`UlpfecReceiver::ProcessReceivedFec`, `RtpPacket::ZeroMutableExtensions` at
175 /// a222406d): its sender protects them as zeros, since it writes them after its FEC was
176 /// computed (see `UlpfecSendBuilder::with_mutable_extensions_zeroed`). A packet rebuilt
177 /// from such FEC then has every octet as sent and those values zero, instead of XOR noise
178 /// there. `false` by default (RFC 5109 section 8: the FEC covers the packet as sent).
179 pub fn with_mutable_extensions_zeroed(mut self, zero: bool) -> Self {
180 self.zero_mutable_extensions = zero;
181 self
182 }
183
184 /// Build the interceptor.
185 pub fn build(self) -> UlpfecReceiveInterceptor {
186 UlpfecReceiveInterceptor {
187 carriage: self.carriage,
188 one_level_only: self.one_level_only,
189 forward_repair: self.forward_repair,
190 decode_every_stream: self.decode_every_stream,
191 filter: self.filter,
192 zero_mutable_extensions: self.zero_mutable_extensions,
193 zeroed_extensions: HashMap::new(),
194 decoders: HashMap::new(),
195 carriages: HashMap::new(),
196 in_red: HashMap::new(),
197 reported: HashMap::new(),
198 repair_to_media: HashMap::new(),
199 media_transport: HashMap::new(),
200 media_payload_type: HashMap::new(),
201 read_queue: VecDeque::new(),
202 write_queue: VecDeque::new(),
203 }
204 }
205}
206
207/// Recovers media lost from streams protected by ULPFEC (RFC 5109).
208///
209/// # RED carriage
210///
211/// A RED packet of a protected stream is taken apart (RFC 2198): its primary block goes on as
212/// the RTP packet it stands for, with the primary's payload type, which is the *virtual* packet
213/// the FEC protects (RFC 5109 14.2); its FEC blocks go to the decoder. A packet of the stream
214/// that is not RED passes as it is and is still given to the decoder, since a receiver that
215/// accepts RED accepts its encodings bare as well (RFC 2198 5). A bare packet of the FEC payload
216/// type on the media SSRC is dropped: FEC is not sent by itself in a RED stream (RFC 5109 14.2).
217/// So is a RED packet whose block headers do not fit its length.
218///
219/// Recovered packets rejoin the read leg marked [`Attribute::RecoveredByFec`].
220///
221/// # Where it belongs
222///
223/// [`Slot::FecDecoder`](crate::Slot::FecDecoder): wire-ward of the NACK generator, so a packet
224/// that FEC rebuilds is not also asked for.
225pub struct UlpfecReceiveInterceptor {
226 carriage: Carriage,
227 one_level_only: bool,
228 forward_repair: bool,
229 decode_every_stream: bool,
230 filter: StreamFilter,
231 /// See [`UlpfecReceiveBuilder::with_mutable_extensions_zeroed`].
232 zero_mutable_extensions: bool,
233 /// With it: the ids of each protected stream's extensions zeroed in the decoder's copies.
234 zeroed_extensions: HashMap<u32, Vec<u8>>,
235 /// Decoders keyed by the media SSRC they protect.
236 decoders: HashMap<u32, UlpfecDecoder>,
237 /// How each protected stream's FEC travels, with the payload types its section
238 /// negotiated (the builder's when the section lists none, or lists them under those
239 /// numbers).
240 carriages: HashMap<u32, Carriage>,
241 /// FEC blocks (and their octets) read from each protected stream's RED packets.
242 in_red: HashMap<u32, (u64, u64)>,
243 /// What was last passed on about each protected stream ([`UlpfecReceiveStats`]).
244 reported: HashMap<u32, UlpfecReceiveStats>,
245 /// Separate stream: repair SSRC (and its payload type) to the media SSRC.
246 repair_to_media: HashMap<u32, (u32, u8)>,
247 /// Where each protected stream's media last arrived from. A packet rebuilt from a FEC
248 /// packet is media of that stream, and the FEC may have come over another transport (a
249 /// FEC session of its own, RFC 5109 section 14.1).
250 media_transport: HashMap<u32, shared::TransportContext>,
251 /// The payload type of each protected stream's last media packet, which a FEC-only packet
252 /// of the stream goes on under, emptied ([`UlpfecRepair`]).
253 media_payload_type: HashMap<u32, u8>,
254 read_queue: VecDeque<TaggedPacket>,
255 write_queue: VecDeque<TaggedPacket>,
256}
257
258impl UlpfecReceiveInterceptor {
259 /// The media SSRCs currently protected.
260 pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
261 self.decoders.keys().copied()
262 }
263
264 /// The decoder's counters for the media stream `ssrc`.
265 pub fn stats(&self, ssrc: u32) -> Option<UlpfecDecoderStats> {
266 self.decoders.get(&ssrc).map(UlpfecDecoder::stats)
267 }
268
269 /// What this interceptor has received and done for the media stream `ssrc`.
270 pub fn receive_stats(&self, ssrc: u32) -> Option<UlpfecReceiveStats> {
271 let decoder = self.decoders.get(&ssrc)?;
272 let (fec_packets_in_red, fec_bytes_in_red) =
273 self.in_red.get(&ssrc).copied().unwrap_or_default();
274 Some(UlpfecReceiveStats {
275 media_ssrc: ssrc,
276 fec_packets_in_red,
277 fec_bytes_in_red,
278 decoder: decoder.stats(),
279 })
280 }
281
282 /// Pass [`UlpfecReceiveStats`] of `media_ssrc` application-ward if it changed.
283 fn report(&mut self, now: Instant, transport: shared::TransportContext, media_ssrc: u32) {
284 let Some(stats) = self.receive_stats(media_ssrc) else {
285 return;
286 };
287 if self.reported.get(&media_ssrc) == Some(&stats) {
288 return;
289 }
290 self.reported.insert(media_ssrc, stats);
291 self.read_queue.push_back(TaggedPacket {
292 now,
293 transport,
294 message: AttributedPacket::new(Packet::Rtcp(Vec::new()))
295 .with(Attribute::Custom(Arc::new(stats))),
296 });
297 }
298
299 fn queue_recovered(
300 &mut self,
301 now: Instant,
302 transport: shared::TransportContext,
303 recovered: Vec<rtp::Packet>,
304 ) {
305 for packet in recovered {
306 // Says how it got here: it was never on the wire in this form, so anything measuring
307 // the network can tell it from a packet that was.
308 let message =
309 AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::RecoveredByFec);
310 self.read_queue.push_back(TaggedPacket {
311 now,
312 transport,
313 message,
314 });
315 }
316 }
317}
318
319impl Protocol<TaggedPacket, TaggedPacket, ()> for UlpfecReceiveInterceptor {
320 type Rout = TaggedPacket;
321 type Wout = TaggedPacket;
322 type Eout = ();
323 type Error = Error;
324 type Time = Instant;
325
326 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
327 let of_fec_session = msg.message.custom::<FecSessionPacket>().copied();
328 let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
329 self.read_queue.push_back(msg);
330 return Ok(());
331 };
332 let ssrc = rtp_packet.header.ssrc;
333 let now = msg.now;
334 let transport = msg.transport;
335
336 // A packet that arrived in a FEC session of its own, marked by whoever read it there:
337 // to the decoder of the stream it protects, and no further. A session's packet with
338 // another payload type, or for a stream this interceptor keeps no decoder for, ends
339 // here too: it is not media of any stream.
340 if let Some(session) = of_fec_session {
341 let recovered = match self.decoders.get_mut(&session.media_ssrc) {
342 Some(decoder) if rtp_packet.header.payload_type == session.payload_type => {
343 match super::header::UlpfecPacket::parse(&rtp_packet.payload) {
344 Ok(fec) if session.one_level_only && fec.levels.len() > 1 => Vec::new(),
345 _ => decoder.push_fec(&rtp_packet.payload).unwrap_or_default(),
346 }
347 }
348 _ => Vec::new(),
349 };
350 let transport = self
351 .media_transport
352 .get(&session.media_ssrc)
353 .copied()
354 .unwrap_or(transport);
355 self.queue_recovered(now, transport, recovered);
356 self.report(now, transport, session.media_ssrc);
357 return Ok(());
358 }
359
360 // A packet of a separate FEC stream: to the decoder, and no further. It has an SSRC of
361 // its own, so nothing behind this interceptor is waiting for its sequence number.
362 if let Some(&(media_ssrc, payload_type_fec)) = self.repair_to_media.get(&ssrc) {
363 let recovered = match self.decoders.get_mut(&media_ssrc) {
364 Some(decoder) if rtp_packet.header.payload_type == payload_type_fec => {
365 decoder.push_fec(&rtp_packet.payload).unwrap_or_default()
366 }
367 _ => Vec::new(),
368 };
369 let transport = self
370 .media_transport
371 .get(&media_ssrc)
372 .copied()
373 .unwrap_or(transport);
374 self.queue_recovered(now, transport, recovered);
375 self.report(now, transport, media_ssrc);
376 return Ok(());
377 }
378
379 let Some(decoder) = self.decoders.get_mut(&ssrc) else {
380 self.read_queue.push_back(msg);
381 return Ok(());
382 };
383
384 let mut recovered = Vec::new();
385 if let Carriage::Red {
386 red_payload_type,
387 fec_payload_type,
388 } = self.carriages.get(&ssrc).copied().unwrap_or(self.carriage)
389 {
390 if rtp_packet.header.payload_type == fec_payload_type {
391 // FEC by itself in a RED stream (RFC 5109 14.2 forbids it).
392 return Ok(());
393 }
394 if rtp_packet.header.payload_type == red_payload_type {
395 let Ok(red) = depacketize_red(&rtp_packet.payload, fec_payload_type) else {
396 return Ok(());
397 };
398 let in_red = self.in_red.entry(ssrc).or_default();
399 for fec in &red.fec {
400 in_red.0 += 1;
401 in_red.1 += fec.len() as u64;
402 recovered.extend(decoder.push_fec(fec).unwrap_or_default());
403 }
404 match red.primary {
405 Some((payload_type, data)) => {
406 // The virtual RTP packet: the RED packet without its block headers and
407 // redundant data, under the primary's payload type.
408 rtp_packet.header.payload_type = payload_type;
409 rtp_packet.payload = data;
410 }
411 None => {
412 if self.forward_repair {
413 // Present, and no media: no payload, under the media's payload
414 // type, as padding in the stream would be.
415 rtp_packet.header.payload_type = self
416 .media_payload_type
417 .get(&ssrc)
418 .copied()
419 .unwrap_or(fec_payload_type);
420 rtp_packet.payload = Bytes::new();
421 msg.message.add(Attribute::Custom(Arc::new(UlpfecRepair)));
422 self.read_queue.push_back(msg);
423 }
424 self.queue_recovered(now, transport, recovered);
425 self.report(now, transport, ssrc);
426 return Ok(());
427 }
428 }
429 }
430 }
431
432 // A media packet: the decoder needs it to rebuild its neighbours, and it carries on.
433 match self.zeroed_extensions.get(&ssrc) {
434 Some(ids) => {
435 recovered
436 .extend(decoder.push_media(&super::with_extensions_zeroed(rtp_packet, ids)));
437 }
438 None => recovered.extend(decoder.push_media(rtp_packet)),
439 }
440 self.media_transport.insert(ssrc, transport);
441 self.media_payload_type
442 .insert(ssrc, rtp_packet.header.payload_type);
443 self.read_queue.push_back(msg);
444 self.queue_recovered(now, transport, recovered);
445 self.report(now, transport, ssrc);
446 Ok(())
447 }
448
449 fn poll_read(&mut self) -> Option<TaggedPacket> {
450 self.read_queue.pop_front()
451 }
452
453 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
454 self.write_queue.push_back(msg);
455 Ok(())
456 }
457
458 fn poll_write(&mut self) -> Option<Self::Wout> {
459 self.write_queue.pop_front()
460 }
461
462 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
463 Ok(())
464 }
465
466 fn poll_timeout(&mut self) -> Option<Self::Time> {
467 None
468 }
469}
470
471impl Interceptor for UlpfecReceiveInterceptor {
472 fn bind_remote_stream(&mut self, info: &StreamInfo) {
473 if !(self.filter)(info) {
474 return;
475 }
476 // The repair flow the signalling associated with the stream (RFC 5956 section 4.3,
477 // `a=ssrc-group:FEC-FR <media> <repair>` with a `ulpfec` format): FEC as a stream of its
478 // own (RFC 5109 section 14.1), whichever carriage the builder names, since the
479 // multiplexing is "indicated out of band" per stream (section 14). With the stream
480 // carriage a repair flow that names no format is taken as ULPFEC.
481 //
482 // A FEC session of its own ([`StreamInfo::fec_session`], an m= section grouped with
483 // the media's): its stream, under the SSRC it has in this chain.
484 let separate = match (info.fec_session, info.ssrc_fec, info.payload_type_fec) {
485 (Some(session), _, _) => Some((session.ssrc, session.payload_type)),
486 (None, Some(ssrc_fec), Some(payload_type_fec))
487 if info.fec_is_ulpfec()
488 || (self.carriage == Carriage::Stream && info.mime_type_fec.is_empty()) =>
489 {
490 Some((ssrc_fec, payload_type_fec))
491 }
492 _ => None,
493 };
494 if self.zero_mutable_extensions {
495 self.zeroed_extensions
496 .insert(info.ssrc, super::mutable_extension_ids(info));
497 }
498 if let Some((ssrc_fec, payload_type_fec)) = separate {
499 self.repair_to_media
500 .insert(ssrc_fec, (info.ssrc, payload_type_fec));
501 } else if self.carriage == Carriage::Stream && !self.decode_every_stream {
502 return;
503 }
504 // RFC 5109 section 13: `onelevelonly=1` on this endpoint's `ulpfec` format of the
505 // section ("what the receiver accepts to receive", section 14.3): FEC with more than
506 // one level is refused.
507 // RFC 5109 section 14.2: the RED and FEC payload types are the section's, as the
508 // sender reads them (an answer keeps the offerer's numbers).
509 let carriage = negotiated_carriage(self.carriage, info).unwrap_or(self.carriage);
510 let fec_format = separate
511 .map(|(_, payload_type)| payload_type)
512 .or(match carriage {
513 Carriage::Red {
514 fec_payload_type, ..
515 } => Some(fec_payload_type),
516 Carriage::Stream => None,
517 });
518 let one_level_only = self.one_level_only
519 || info
520 .fec_session
521 .is_some_and(|session| session.one_level_only)
522 || fec_format.is_some_and(|payload_type| {
523 info.section_fmtp_lines
524 .iter()
525 .any(|(pt, fmtp)| *pt == payload_type && super::one_level_only_from_fmtp(fmtp))
526 });
527 self.decoders.insert(
528 info.ssrc,
529 UlpfecDecoder::new(info.ssrc).with_one_level_only(one_level_only),
530 );
531 self.carriages.insert(info.ssrc, carriage);
532 }
533
534 fn unbind_remote_stream(&mut self, info: &StreamInfo) {
535 self.decoders.remove(&info.ssrc);
536 self.carriages.remove(&info.ssrc);
537 self.in_red.remove(&info.ssrc);
538 self.reported.remove(&info.ssrc);
539 self.media_transport.remove(&info.ssrc);
540 self.media_payload_type.remove(&info.ssrc);
541 self.zeroed_extensions.remove(&info.ssrc);
542 self.repair_to_media
543 .retain(|_, (media, _)| *media != info.ssrc);
544 }
545
546 fn bind_local_stream(&mut self, _info: &StreamInfo) {}
547
548 fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
549}