rtci_interceptor/ulpfec/sender.rs
1//! Send-side ULPFEC: protects outgoing media, in RED or as a stream of its own.
2
3use super::encoder::{ProtectionLevel, RTP_FIXED_HEADER, UlpfecEncoder, wire_image};
4use super::header::LONG_MASK_BITS;
5use super::red;
6use crate::Interceptor;
7use crate::cc::fec_rate::FecRate;
8use crate::stream_info::StreamInfo;
9use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
10use crate::{Attribute, AttributedPacket, FecSent, Packet, TaggedPacket};
11use bytes::Bytes;
12use sansio::Protocol;
13use shared::error::Error;
14use std::collections::{HashMap, VecDeque};
15use std::sync::Arc;
16use std::time::Instant;
17
18use super::encoder::UlpfecStreamPacketizer;
19
20/// Media packets gathered before FEC is produced for them.
21pub const ULPFEC_DEFAULT_NUM_MEDIA_PACKETS: usize = 5;
22
23/// FEC packets produced per block of media.
24pub const ULPFEC_DEFAULT_NUM_FEC_PACKETS: usize = 1;
25
26/// The most FEC packets held back for the end of a frame
27/// ([`UlpfecSendBuilder::with_fec_after_frame`]). A stream that never sets the marker bit, or a
28/// frame of more packets than this many FEC packets protect, gets them where the count is
29/// reached.
30pub const ULPFEC_MAX_HELD_FEC_PACKETS: usize = 128;
31
32/// Where FEC data goes in a RED stream.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum RedPlacement {
35 /// A RED packet of its own, whose only block has the FEC payload type. It takes the next
36 /// sequence number of the media stream. What libwebrtc sends and the only form it reads
37 /// (its receiver drops a RED packet with more than one block): the setting for a browser
38 /// peer. RFC 5109 14.2 does not allow it: "the FEC MUST NOT be sent by itself for this
39 /// stream". Such packets follow the last packet of a frame, never lie inside one
40 /// ([`UlpfecSendBuilder::with_fec_after_frame`]).
41 OwnPacket,
42 /// A redundant block in the next media packet, ahead of its primary block: the carriage of
43 /// RFC 5109 14.2 ("the FEC data ... is sent in the same packets as the protected payload")
44 /// and 10.3, and the default. FEC is never sent by itself and the media stream's sequence
45 /// numbers are untouched. A redundant block holds at most 1023 octets (RFC 2198 section 3),
46 /// so FEC data longer than that (protection of full-size video packets) cannot be carried
47 /// this way and still goes in a packet of its own.
48 #[default]
49 WithNextMedia,
50}
51
52/// Which streams an interceptor protects.
53pub(crate) type StreamFilter = Arc<dyn Fn(&StreamInfo) -> bool + Send + Sync>;
54
55/// The default choice: video streams, the only kind `ulpfec` is negotiated for in WebRTC.
56pub(crate) fn video_streams() -> StreamFilter {
57 Arc::new(|info: &StreamInfo| {
58 info.mime_type
59 .get(..6)
60 .is_some_and(|kind| kind.eq_ignore_ascii_case("video/"))
61 })
62}
63
64/// How the FEC travels.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) enum Carriage {
67 Red {
68 red_payload_type: u8,
69 fec_payload_type: u8,
70 },
71 Stream,
72}
73
74/// Builder for [`UlpfecSendInterceptor`].
75///
76/// # Example
77///
78/// ```
79/// use rtci_interceptor::{Registry, Slot, UlpfecSendBuilder};
80///
81/// // `a=rtpmap:116 red/90000`, `a=rtpmap:117 ulpfec/90000`
82/// let chain = Registry::new()
83/// .with(Slot::FecEncoder, UlpfecSendBuilder::red(116, 117).build())
84/// .build();
85/// ```
86pub struct UlpfecSendBuilder {
87 carriage: Carriage,
88 placement: RedPlacement,
89 num_media_packets: usize,
90 num_fec_packets: usize,
91 adaptive_rate: bool,
92 level_lengths: Vec<u16>,
93 one_level_only: bool,
94 flush_on_marker: bool,
95 fec_after_frame: bool,
96 initial_fec_sequence_number: Option<u16>,
97 filter: StreamFilter,
98 zero_mutable_extensions: bool,
99}
100
101impl UlpfecSendBuilder {
102 fn new(carriage: Carriage) -> Self {
103 Self {
104 carriage,
105 placement: RedPlacement::default(),
106 num_media_packets: ULPFEC_DEFAULT_NUM_MEDIA_PACKETS,
107 num_fec_packets: ULPFEC_DEFAULT_NUM_FEC_PACKETS,
108 adaptive_rate: true,
109 level_lengths: Vec::new(),
110 one_level_only: false,
111 flush_on_marker: false,
112 fec_after_frame: true,
113 initial_fec_sequence_number: None,
114 filter: video_streams(),
115 zero_mutable_extensions: false,
116 }
117 }
118
119 /// Protect each media packet with the values of its transport-wide sequence number,
120 /// abs-send-time and toffset extensions zeroed, as libwebrtc's sender does (`false` by
121 /// default; the `Chrome` profile's `DefaultInterceptorOptions::ulpfec_zero_mutable_extensions`).
122 ///
123 /// libwebrtc computes its FEC before it writes those values (`RtpSenderEgress::SendPacket`
124 /// at a222406d: `AddPacketAndGenerateFec` comes before the `SetExtension<TransmissionOffset>`,
125 /// `<AbsoluteSendTime>` and `<TransportSequenceNumber>` calls, "these modifications of the
126 /// header below are happening after the FEC protection packets are calculated"; the packet
127 /// reserved them as zeros), and its receiver zeroes them in its copy of each media packet
128 /// before recovering (`UlpfecReceiver::ProcessReceivedFec`, `ZeroMutableExtensions`). With
129 /// this on, a packet libwebrtc rebuilds from this engine's FEC is exactly the one its own
130 /// FEC would rebuild: as sent, those values zero. Off (RFC 5109 section 8), the FEC covers
131 /// the packet as it left, and those octets of a packet libwebrtc rebuilds are XOR noise.
132 pub fn with_mutable_extensions_zeroed(mut self, zero: bool) -> Self {
133 self.zero_mutable_extensions = zero;
134 self
135 }
136
137 /// FEC as a redundant encoding (RFC 5109 14.2): every packet of a protected stream leaves as
138 /// a RED packet of `red_payload_type`, and FEC data has `fec_payload_type`. Both come from
139 /// the negotiated `a=rtpmap` lines (`red`, `ulpfec`).
140 pub fn red(red_payload_type: u8, fec_payload_type: u8) -> Self {
141 Self::new(Carriage::Red {
142 red_payload_type: red_payload_type & 0x7F,
143 fec_payload_type: fec_payload_type & 0x7F,
144 })
145 }
146
147 /// FEC as a stream of its own (RFC 5109 14.1), on the repair SSRC and payload type of
148 /// [`StreamInfo::ssrc_fec`] / [`StreamInfo::payload_type_fec`]. A stream without both is not
149 /// protected. See [`UlpfecStreamPacketizer`] for why this is not the media SSRC.
150 pub fn stream() -> Self {
151 Self::new(Carriage::Stream)
152 }
153
154 /// Where FEC data goes in a RED stream. Ignored for a separate stream.
155 pub fn with_red_placement(mut self, placement: RedPlacement) -> Self {
156 self.placement = placement;
157 self
158 }
159
160 /// How many media packets one block of FEC protects, 1 to 48 (the long mask's reach).
161 pub fn with_num_media_packets(mut self, num_media_packets: usize) -> Self {
162 self.num_media_packets = num_media_packets.clamp(1, LONG_MASK_BITS);
163 self
164 }
165
166 /// How many FEC packets each block produces. The block's packets are dealt to them in turn,
167 /// so `n` FEC packets recover a burst of up to `n` losses. Zero sends no FEC.
168 pub fn with_num_fec_packets(mut self, num_fec_packets: usize) -> Self {
169 self.num_fec_packets = num_fec_packets;
170 self
171 }
172
173 /// Protection lengths of the levels, level 0 first, for uneven protection: level 0 covers the
174 /// first `lengths[0]` octets after the fixed RTP header, level 1 the next `lengths[1]`, and
175 /// so on; what lies beyond the last level is not protected.
176 ///
177 /// Empty, the default, is one level as long as the block's longest packet: full protection.
178 pub fn with_level_lengths(mut self, lengths: impl Into<Vec<u16>>) -> Self {
179 self.level_lengths = lengths.into();
180 self
181 }
182
183 /// Use one level only, whatever [`with_level_lengths`](Self::with_level_lengths) says: for a
184 /// stream whose `ulpfec` format carries `onelevelonly=1` (RFC 5109 13). See
185 /// [`one_level_only_from_fmtp`](super::one_level_only_from_fmtp).
186 pub fn with_one_level_only(mut self, one_level_only: bool) -> Self {
187 self.one_level_only = one_level_only;
188 self
189 }
190
191 /// Also close a block at a packet with the marker bit (the last packet of a video frame), so
192 /// FEC never waits for the next frame.
193 pub fn with_flush_on_marker(mut self, flush_on_marker: bool) -> Self {
194 self.flush_on_marker = flush_on_marker;
195 self
196 }
197
198 /// With [`RedPlacement::OwnPacket`]: whether the FEC packets of the blocks that close
199 /// inside a frame wait for the frame's last packet (the one with the marker bit) and take
200 /// the sequence numbers after it (`true`, the default), or each block's FEC packets follow
201 /// the block's last packet wherever in the frame that is (`false`).
202 ///
203 /// A FEC packet of this placement takes a sequence number of the media stream. A receiver
204 /// puts a frame together from consecutive sequence numbers, so a number inside a frame
205 /// that is not media leaves the frame incomplete: libwebrtc's packet buffer finds a frame
206 /// only over packets it holds without a gap, and a received FEC packet closes a gap between
207 /// frames only (`modules/video_coding/packet_buffer.cc:168-174`, `InsertPadding`, and
208 /// `FindFrames`, at a222406d). libwebrtc's sender therefore produces FEC only at a packet
209 /// that completes a frame (`modules/rtp_rtcp/source/ulpfec_generator.cc:134` and
210 /// `:157-159`: `complete_frame = packet.Marker()`, `if (complete_frame && ...)`
211 /// `EncodeFec`), and its FEC packets follow that packet. RFC 5109 and RFC 2198 say nothing
212 /// about where in a stream a FEC packet lies: only the order on the wire changes, each FEC
213 /// packet protects the same media packets either way.
214 ///
215 /// At most [`ULPFEC_MAX_HELD_FEC_PACKETS`] FEC packets wait; they leave when that many
216 /// have gathered, so a stream that never sets the marker bit is still protected. No
217 /// effect on the other placements and carriages, whose FEC takes no sequence number of
218 /// the media stream.
219 pub fn with_fec_after_frame(mut self, fec_after_frame: bool) -> Self {
220 self.fec_after_frame = fec_after_frame;
221 self
222 }
223
224 /// The first sequence number of a separate FEC stream. Random when not set, as an RTP
225 /// stream's is (RFC 3550 5.1); a test pins it.
226 pub fn with_initial_fec_sequence_number(mut self, sequence_number: u16) -> Self {
227 self.initial_fec_sequence_number = Some(sequence_number);
228 self
229 }
230
231 /// Which bound local streams are protected. The default is every `video/` stream.
232 pub fn with_stream_filter(
233 mut self,
234 filter: impl Fn(&StreamInfo) -> bool + Send + Sync + 'static,
235 ) -> Self {
236 self.filter = Arc::new(filter);
237 self
238 }
239
240 /// Whether the amount of FEC follows the loss the receiver reports (the default), or
241 /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
242 /// for twice the loss above it, at most half the block; the FEC sent is taken out of the
243 /// target the application encodes at.
244 pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
245 self.adaptive_rate = adaptive;
246 self
247 }
248
249 /// Build the interceptor.
250 pub fn build(self) -> UlpfecSendInterceptor {
251 let mut level_lengths = self.level_lengths;
252 if self.one_level_only {
253 level_lengths.truncate(1);
254 }
255 UlpfecSendInterceptor {
256 carriage: self.carriage,
257 placement: self.placement,
258 num_media_packets: self.num_media_packets,
259 num_fec_packets: self.num_fec_packets,
260 rate: FecRate::new(
261 self.num_media_packets as u32,
262 self.num_fec_packets as u32,
263 self.adaptive_rate,
264 ),
265 level_lengths,
266 flush_on_marker: self.flush_on_marker,
267 fec_after_frame: self.fec_after_frame,
268 initial_fec_sequence_number: self.initial_fec_sequence_number,
269 filter: self.filter,
270 zero_mutable_extensions: self.zero_mutable_extensions,
271 streams: HashMap::new(),
272 sequence_offsets: HashMap::new(),
273 wire: None,
274 read_queue: VecDeque::new(),
275 write_queue: VecDeque::new(),
276 }
277 }
278}
279
280/// One protected media stream.
281struct ProtectedStream {
282 /// How this stream's FEC travels, with the negotiated payload types
283 /// ([`UlpfecSendInterceptor::negotiated_carriage`]).
284 carriage: Carriage,
285 /// The packets of the block being gathered, as protected: sequence number and wire image.
286 block: Vec<(u16, Bytes)>,
287 /// RED, [`RedPlacement::WithNextMedia`]: FEC payloads waiting for the next media packet.
288 pending: VecDeque<Bytes>,
289 /// FEC payloads of the blocks that closed and have not been sent: with
290 /// [`UlpfecSendBuilder::with_fec_after_frame`], until the frame's last packet.
291 held: VecDeque<Bytes>,
292 /// With a wire tap: the FEC packets of the blocks that closed at this slot since sequence
293 /// numbers were last set aside for FEC.
294 promised: usize,
295 /// Separate stream: the FEC stream's packetizer.
296 packetizer: Option<UlpfecStreamPacketizer>,
297 /// The sequence number of the last packet sent on the media SSRC, media or FEC.
298 last_wire_sequence: u16,
299 /// With a wire tap: media packets that passed this slot and have not been seen leaving
300 /// yet, oldest first.
301 in_flight: VecDeque<InFlight>,
302 /// With a wire tap: media packets that passed this slot since the last block was closed.
303 passing: usize,
304 /// One protection level only for this stream (RFC 5109 section 13: `onelevelonly=1` on
305 /// the negotiated `ulpfec` format, or the builder's setting).
306 one_level_only: bool,
307 /// The ids of the extensions whose values are zeroed in what is protected
308 /// ([`UlpfecSendBuilder::with_mutable_extensions_zeroed`]); empty when off.
309 zeroed_extensions: Vec<u8>,
310}
311
312/// The most media packets remembered between this slot and the wire tap. The pacer between the
313/// two holds at most its queue limit; anything older than this was dropped on the way.
314const MAX_IN_FLIGHT: usize = 4096;
315
316/// A media packet on its way from this slot to the wire.
317struct InFlight {
318 /// Its sequence number on the wire.
319 sequence_number: u16,
320 /// Set on the packet that closes a block: how many FEC packets the block gets, as decided
321 /// when the packet passed this slot.
322 closes: Option<usize>,
323 /// Set on the packet behind which the FEC of the blocks closed so far is sent.
324 sends: Option<BlockEnd>,
325}
326
327/// What was decided about the FEC to send when the media packet it follows passed this slot.
328struct BlockEnd {
329 /// RED with [`RedPlacement::OwnPacket`]: the sequence numbers of the media stream set aside
330 /// for the FEC packets.
331 reserved: Vec<u16>,
332 /// The RTP timestamp of the media packet the FEC follows, which the FEC packets carry.
333 timestamp: u32,
334}
335
336/// With a wire tap: what a media packet that left (or never did) settles, in order.
337enum WireStep {
338 /// A block is complete: its packets as they left, and how many FEC packets it gets.
339 Block(usize, Vec<(u16, Bytes)>),
340 /// The FEC gathered so far is sent.
341 Send(BlockEnd),
342}
343
344/// Produces ULPFEC (RFC 5109) for outgoing media.
345///
346/// # RED carriage
347///
348/// Each media packet of a protected stream is rewritten into a RED packet: the payload gains the
349/// one-octet primary block header naming the media payload type, and the RTP payload type becomes
350/// RED's. FEC is computed over the packets as they would be without RED (the *virtual* packets
351/// of RFC 5109 14.2) and with the sequence numbers they have on the wire.
352///
353/// With [`RedPlacement::OwnPacket`] a FEC packet takes a sequence number of the media stream, so
354/// every later media packet of the stream is sent with its sequence number moved up by the number
355/// of FEC packets sent so far. Those sequence numbers follow the last packet of a frame
356/// ([`UlpfecSendBuilder::with_fec_after_frame`]): the receiver finds no FEC packet between two
357/// packets of a frame. The NACK responder sits wire-ward of this interceptor and buffers
358/// what is on the wire, so a NACK, which names wire sequence numbers, is answered correctly. The
359/// marker bit of the media packet is kept on the RED packet, as browsers do; RFC 2198 has no
360/// field for it otherwise.
361///
362/// # Where it belongs
363///
364/// [`Slot::FecEncoder`](crate::Slot::FecEncoder): application-ward of the pacer and the
365/// transport-wide numbering, so FEC is paced, numbered and recorded as the bytes on the wire it
366/// is.
367pub struct UlpfecSendInterceptor {
368 carriage: Carriage,
369 placement: RedPlacement,
370 num_media_packets: usize,
371 num_fec_packets: usize,
372 /// The loss-driven amount of FEC.
373 rate: FecRate,
374 level_lengths: Vec<u16>,
375 flush_on_marker: bool,
376 /// See [`UlpfecSendBuilder::with_fec_after_frame`].
377 fec_after_frame: bool,
378 initial_fec_sequence_number: Option<u16>,
379 filter: StreamFilter,
380 /// See [`UlpfecSendBuilder::with_mutable_extensions_zeroed`].
381 zero_mutable_extensions: bool,
382 /// Keyed by the media SSRC.
383 streams: HashMap<u32, ProtectedStream>,
384 /// FEC packets inserted so far into each media stream's sequence space. Kept apart from
385 /// `streams` so a stream that is unbound and bound again continues where it was: going back
386 /// would reuse sequence numbers already on the wire.
387 sequence_offsets: HashMap<u32, u16>,
388 /// Where the media packets are read from once [`wire_tap`](Self::wire_tap) was called: as
389 /// they left, below everything that edits them.
390 wire: Option<WireImages>,
391 read_queue: VecDeque<TaggedPacket>,
392 write_queue: VecDeque<TaggedPacket>,
393}
394
395impl UlpfecSendInterceptor {
396 /// How the FEC of `info`'s stream travels: RFC 5109 section 14, "the multiplexing
397 /// configuration ... MUST be indicated out of band", and section 14.2, "An rtpmap attribute
398 /// MUST be used to indicate a dynamic payload type number for the FEC packets". So the
399 /// stream's negotiated formats ([`StreamInfo::section_mime_types`]) decide, not only the
400 /// builder:
401 ///
402 /// - RED: the section's `red` and `ulpfec` formats, the builder's payload types when the
403 /// section has them under those numbers, else the section's own; without a `red` and a
404 /// `ulpfec` format the stream is not protected as RED, and goes as a separate stream when
405 /// the description gives it a ULPFEC repair flow.
406 /// - A separate stream: the repair flow of [`StreamInfo::ssrc_fec`] /
407 /// [`StreamInfo::payload_type_fec`] when its format is `ulpfec`; without one, RED when the
408 /// section negotiated `red` and `ulpfec`.
409 ///
410 /// - A separate RTP session ([`StreamInfo::fec_session`]): a separate stream, whatever
411 /// the builder and the media section's formats say.
412 ///
413 /// `None`: the stream is not protected. A binder that names no formats (an empty
414 /// `section_mime_types`) gets the builder's carriage as it is.
415 fn negotiated_carriage(&self, info: &StreamInfo) -> Option<Carriage> {
416 negotiated_carriage(self.carriage, info)
417 }
418 /// The media SSRCs currently being protected.
419 pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
420 self.streams.keys().copied()
421 }
422
423 /// The FEC payloads for a full block: `fec_packets` of them (no more than the block has
424 /// packets), each protecting every `count`-th packet.
425 fn encode_block(
426 &self,
427 block: &[(u16, Bytes)],
428 one_level_only: bool,
429 fec_packets: usize,
430 ) -> Vec<Bytes> {
431 let count = fec_packets.min(block.len());
432 if count == 0 {
433 return Vec::new();
434 }
435 let images: HashMap<u16, Bytes> = block.iter().cloned().collect();
436 let encoder = UlpfecEncoder::new();
437 let mut out = Vec::with_capacity(count);
438 for index in 0..count {
439 let sequences: Vec<u16> = block
440 .iter()
441 .enumerate()
442 .filter(|(position, _)| position % count == index)
443 .map(|(_, (sequence, _))| *sequence)
444 .collect();
445 let levels: Vec<ProtectionLevel> = if self.level_lengths.is_empty() {
446 let longest = sequences
447 .iter()
448 .map(|sequence| images[sequence].len() - RTP_FIXED_HEADER)
449 .max()
450 .unwrap_or(0);
451 vec![ProtectionLevel::new(longest as u16, sequences)]
452 } else {
453 let levels = if one_level_only {
454 &self.level_lengths[..1]
455 } else {
456 &self.level_lengths[..]
457 };
458 levels
459 .iter()
460 .map(|length| ProtectionLevel::new(*length, sequences.clone()))
461 .collect()
462 };
463 // A block the encoder refuses (a gap in the sequence numbers wider than a mask)
464 // goes unprotected rather than half-described.
465 if let Ok(fec) = encoder.encode_images(&images, &levels) {
466 out.push(fec.marshal());
467 }
468 }
469 out
470 }
471}
472
473impl UlpfecSendInterceptor {
474 /// The tap this encoder reads the media packets from, to register at
475 /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
476 ///
477 /// FEC protects the packets as they are sent (RFC 5109 section 8). This interceptor sits
478 /// above the pacer, where a media packet is not final: the TWCC sender below writes the
479 /// transport-wide sequence number into it, adding the header extension when the packet has
480 /// none, and the receiver XORs what arrived. With the tap registered the work is split in
481 /// two:
482 ///
483 /// - **here**, as a media packet passes: it gets its sequence number on the wire and its
484 /// RED wrapping, and when it closes a block the sequence numbers the block's FEC packets
485 /// will take are set aside (RED carriage with [`RedPlacement::OwnPacket`]), so later
486 /// media is numbered past them;
487 /// - **at the tap**, as the packet leaves: its image goes into the block, and when the
488 /// block's last packet has left the FEC is computed over those images and sent, in the
489 /// sequence numbers set aside for it, on the FEC stream, or with the next media packet.
490 ///
491 /// A FEC packet therefore leaves after the block it protects has left, a few packets
492 /// later than its sequence number says when a pacer holds the media in between. Every
493 /// sequence number of the media stream is still used exactly once.
494 ///
495 /// Without a tap (this method never called) the encoder protects the packets as they pass
496 /// this slot, which is the wire image only when nothing below edits them.
497 pub fn wire_tap(&mut self) -> WireImageTap {
498 let (tap, images) = wire_image_tap();
499 for ssrc in self.streams.keys() {
500 images.watch(*ssrc);
501 }
502 self.wire = Some(images);
503 tap
504 }
505
506 /// With a wire tap: send a protected media packet on its way, numbered and wrapped, and
507 /// note what its block's FEC will need. `msg` already has its wire sequence number.
508 fn pass_to_the_wire(&mut self, mut msg: TaggedPacket) {
509 let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
510 self.write_queue.push_back(msg);
511 return;
512 };
513 let ssrc = rtp_packet.header.ssrc;
514 let Some(stream) = self.streams.get_mut(&ssrc) else {
515 self.write_queue.push_back(msg);
516 return;
517 };
518 let sequence_number = rtp_packet.header.sequence_number;
519 let timestamp = rtp_packet.header.timestamp;
520 let marker = rtp_packet.header.marker;
521 stream.last_wire_sequence = sequence_number;
522
523 // RED: the media packet becomes the primary block, behind any FEC waiting for a ride.
524 if let Carriage::Red {
525 red_payload_type,
526 fec_payload_type,
527 } = stream.carriage
528 {
529 let pending: Vec<Bytes> = stream.pending.drain(..).collect();
530 let redundant: Vec<(u8, u16, &[u8])> = pending
531 .iter()
532 .map(|fec| (fec_payload_type, 0u16, &fec[..]))
533 .collect();
534 if let Ok(payload) = red::write(
535 &redundant,
536 rtp_packet.header.payload_type,
537 &rtp_packet.payload,
538 ) {
539 rtp_packet.payload = payload;
540 rtp_packet.header.payload_type = red_payload_type;
541 if let Some(sent) = fec_riding_along(ssrc, &pending) {
542 msg.message.add(sent);
543 }
544 }
545 }
546
547 stream.passing += 1;
548 let own_packets = matches!(stream.carriage, Carriage::Red { .. })
549 && self.placement == RedPlacement::OwnPacket;
550 let closes = (stream.passing >= self.num_media_packets || (self.flush_on_marker && marker))
551 .then(|| {
552 let fec_packets = self.num_fec_packets.min(stream.passing);
553 stream.passing = 0;
554 fec_packets
555 });
556 stream.promised += closes.unwrap_or(0);
557 // Where the FEC goes: behind the block's last packet, or, for FEC packets that take
558 // sequence numbers of the media stream, behind the frame's last packet.
559 let send_now = if own_packets && self.fec_after_frame {
560 stream.promised > 0 && (marker || stream.promised >= ULPFEC_MAX_HELD_FEC_PACKETS)
561 } else {
562 closes.is_some()
563 };
564 let sends = send_now.then(|| {
565 let fec_packets = std::mem::take(&mut stream.promised);
566 // The FEC packets take the next sequence numbers of the media stream, now, so the
567 // media that follows is numbered past them.
568 let reserved = if own_packets {
569 let offset = self.sequence_offsets.entry(ssrc).or_insert(0);
570 (0..fec_packets)
571 .map(|_| {
572 *offset = offset.wrapping_add(1);
573 stream.last_wire_sequence = stream.last_wire_sequence.wrapping_add(1);
574 stream.last_wire_sequence
575 })
576 .collect()
577 } else {
578 Vec::new()
579 };
580 BlockEnd {
581 reserved,
582 timestamp,
583 }
584 });
585 if stream.in_flight.len() == MAX_IN_FLIGHT {
586 stream.in_flight.pop_front();
587 }
588 stream.in_flight.push_back(InFlight {
589 sequence_number,
590 closes,
591 sends,
592 });
593 self.write_queue.push_back(msg);
594 }
595
596 /// With a wire tap: take the media packets that left since the last call into their blocks,
597 /// and send the FEC of every block whose last packet has left.
598 fn protect_wire_images(&mut self) {
599 let Some(images) = self.wire.as_ref().map(WireImages::take) else {
600 return;
601 };
602 for image in images {
603 let Packet::Rtp(rtp_packet) = &image.message.packet else {
604 continue;
605 };
606 self.on_wire_image(image.now, image.transport, rtp_packet);
607 }
608 }
609
610 /// One packet of a protected stream, as it left.
611 fn on_wire_image(
612 &mut self,
613 now: Instant,
614 transport: shared::TransportContext,
615 rtp_packet: &rtp::Packet,
616 ) {
617 let ssrc = rtp_packet.header.ssrc;
618 let sequence_number = rtp_packet.header.sequence_number;
619 let Some(stream) = self.streams.get_mut(&ssrc) else {
620 return;
621 };
622 // Only the media this interceptor sent on its way: a retransmission, a FEC packet of
623 // its own, or a packet the application built as RED itself is not waited for.
624 let Some(position) = stream
625 .in_flight
626 .iter()
627 .position(|waiting| waiting.sequence_number == sequence_number)
628 else {
629 return;
630 };
631 // Whatever was sent before it and has not been seen never reached the wire (the pacer
632 // refused it, a circuit breaker stopped the flow). A block one of those closed is
633 // closed with what did leave, and the FEC that was to follow one of those is sent.
634 let mut steps = Vec::new();
635 for _ in 0..position {
636 let Some(lost) = stream.in_flight.pop_front() else {
637 break;
638 };
639 if let Some(fec_packets) = lost.closes {
640 steps.push(WireStep::Block(
641 fec_packets,
642 std::mem::take(&mut stream.block),
643 ));
644 }
645 if let Some(end) = lost.sends {
646 steps.push(WireStep::Send(end));
647 }
648 }
649 let Some(arrived) = stream.in_flight.pop_front() else {
650 return;
651 };
652
653 // The packet FEC protects: in RED, the virtual packet of RFC 5109 section 14.2, which is
654 // the packet on the wire without its block headers and redundant data, under the
655 // primary's payload type. That is what the receiver rebuilds from what arrives.
656 let zeroed;
657 let rtp_packet = if stream.zeroed_extensions.is_empty() {
658 rtp_packet
659 } else {
660 zeroed = super::with_extensions_zeroed(rtp_packet, &stream.zeroed_extensions);
661 &zeroed
662 };
663 let protected = match stream.carriage {
664 Carriage::Stream => wire_image(rtp_packet).ok(),
665 Carriage::Red { .. } => {
666 red::parse(&rtp_packet.payload)
667 .ok()
668 .and_then(|(_, primary)| {
669 let mut header = rtp_packet.header.clone();
670 header.payload_type = primary.payload_type;
671 wire_image(&rtp::Packet {
672 header,
673 payload: Bytes::copy_from_slice(primary.data),
674 })
675 .ok()
676 })
677 }
678 };
679 if let Some(protected) = protected {
680 stream.block.push((sequence_number, protected));
681 }
682 if let Some(packetizer) = stream.packetizer.as_mut() {
683 packetizer.on_media(rtp_packet.header.timestamp, now);
684 }
685 if let Some(fec_packets) = arrived.closes {
686 steps.push(WireStep::Block(
687 fec_packets,
688 std::mem::take(&mut stream.block),
689 ));
690 }
691 if let Some(end) = arrived.sends {
692 steps.push(WireStep::Send(end));
693 }
694
695 for step in steps {
696 match step {
697 WireStep::Block(fec_packets, block) => {
698 self.encode_wire_block(now, ssrc, fec_packets, &block);
699 }
700 WireStep::Send(end) => self.send_held_fec(now, transport, ssrc, end),
701 }
702 }
703 }
704
705 /// Compute the FEC of a block whose packets have left; it waits to be sent.
706 fn encode_wire_block(
707 &mut self,
708 now: Instant,
709 ssrc: u32,
710 fec_packets: usize,
711 block: &[(u16, Bytes)],
712 ) {
713 let one_level_only = self
714 .streams
715 .get(&ssrc)
716 .is_some_and(|stream| stream.one_level_only);
717 let fec_payloads = self.encode_block(block, one_level_only, fec_packets);
718 for fec in &fec_payloads {
719 self.rate.on_repair_sent(now, fec.len());
720 }
721 if let Some(stream) = self.streams.get_mut(&ssrc) {
722 stream.held.extend(fec_payloads);
723 }
724 }
725
726 /// Send the FEC of the blocks whose packets have left.
727 fn send_held_fec(
728 &mut self,
729 now: Instant,
730 transport: shared::TransportContext,
731 ssrc: u32,
732 end: BlockEnd,
733 ) {
734 let Some(stream) = self.streams.get_mut(&ssrc) else {
735 return;
736 };
737 let mut fec_payloads = std::mem::take(&mut stream.held);
738 // Each packet with the FEC octets it carries (none: an empty block in a reserved slot).
739 let mut packets = Vec::new();
740 match stream.carriage {
741 Carriage::Stream => {
742 for fec in fec_payloads {
743 if let Some(packetizer) = stream.packetizer.as_mut()
744 && let Ok(parsed) = super::header::UlpfecPacket::parse(&fec)
745 {
746 packets.push((packetizer.packetize(&parsed, now), fec.len()));
747 }
748 }
749 }
750 Carriage::Red {
751 red_payload_type,
752 fec_payload_type,
753 } => {
754 if self.placement == RedPlacement::WithNextMedia {
755 stream.pending.extend(
756 fec_payloads
757 .into_iter()
758 .filter(|fec| fec.len() <= red::MAX_REDUNDANT_BLOCK),
759 );
760 return;
761 }
762 // Every sequence number set aside is used, so the stream has no hole of this
763 // interceptor's making: a slot the blocks gave no FEC for (packets of one never
764 // left, or the encoder refused it) carries an empty FEC block.
765 for sequence_number in end.reserved {
766 let fec = fec_payloads.pop_front().unwrap_or_default();
767 let Ok(payload) = red::write(&[], fec_payload_type, &fec) else {
768 continue;
769 };
770 packets.push((
771 rtp::Packet {
772 header: rtp::header::Header {
773 version: 2,
774 marker: false,
775 payload_type: red_payload_type,
776 sequence_number,
777 timestamp: end.timestamp,
778 ssrc,
779 ..Default::default()
780 },
781 payload,
782 },
783 fec.len(),
784 ));
785 }
786 }
787 }
788 for (packet, fec_bytes) in packets {
789 let mut message = AttributedPacket::new(Packet::Rtp(packet));
790 if fec_bytes > 0 {
791 message.add(FecSent::one(ssrc, fec_bytes));
792 }
793 self.write_queue.push_back(TaggedPacket {
794 now,
795 transport,
796 message,
797 });
798 }
799 }
800}
801
802/// The carriage of `info`'s stream given the builder's (`builder`): see
803/// [`UlpfecSendInterceptor::negotiated_carriage`]. The receive side reads a stream the same way,
804/// so the payload types the section negotiated are the ones it looks for.
805pub(super) fn negotiated_carriage(builder: Carriage, info: &StreamInfo) -> Option<Carriage> {
806 // A FEC session of its own was negotiated for the stream (RFC 5109 section 14.1, an
807 // m= section grouped with the media's): that is where its FEC goes.
808 if info.fec_session.is_some() {
809 return Some(Carriage::Stream);
810 }
811 if info.section_mime_types.is_empty() {
812 return Some(builder);
813 }
814 let formats = |subtype: &str| -> Vec<u8> {
815 info.section_mime_types
816 .iter()
817 .filter(|(_, mime_type)| {
818 mime_type
819 .rsplit_once('/')
820 .is_some_and(|(_, sub)| sub.eq_ignore_ascii_case(subtype))
821 })
822 .map(|(payload_type, _)| *payload_type)
823 .collect()
824 };
825 let red = |wanted: Option<(u8, u8)>| -> Option<Carriage> {
826 let (reds, fecs) = (formats("red"), formats("ulpfec"));
827 let pick = |found: &[u8], wanted: Option<u8>| {
828 wanted
829 .filter(|payload_type| found.contains(payload_type))
830 .or_else(|| found.first().copied())
831 };
832 Some(Carriage::Red {
833 red_payload_type: pick(&reds, wanted.map(|(red, _)| red))?,
834 fec_payload_type: pick(&fecs, wanted.map(|(_, fec)| fec))?,
835 })
836 };
837 let separate = (info.ssrc_fec.is_some()
838 && info
839 .payload_type_fec
840 .is_some_and(|payload_type| formats("ulpfec").contains(&payload_type)))
841 .then_some(Carriage::Stream);
842 match builder {
843 Carriage::Red {
844 red_payload_type,
845 fec_payload_type,
846 } => red(Some((red_payload_type, fec_payload_type))).or(separate),
847 Carriage::Stream => separate.or_else(|| red(None)),
848 }
849}
850
851/// The [`FecSent`] mark for a media packet in RED that FEC blocks ride with, if any do.
852fn fec_riding_along(media_ssrc: u32, blocks: &[Bytes]) -> Option<Attribute> {
853 (!blocks.is_empty()).then(|| {
854 Attribute::Custom(Arc::new(FecSent {
855 media_ssrc,
856 packets: blocks.len() as u32,
857 bytes: blocks.iter().map(|block| block.len() as u64).sum(),
858 }))
859 })
860}
861
862impl Protocol<TaggedPacket, TaggedPacket, ()> for UlpfecSendInterceptor {
863 type Rout = TaggedPacket;
864 type Wout = TaggedPacket;
865 type Eout = ();
866 type Error = Error;
867 type Time = Instant;
868
869 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
870 let streams = &self.streams;
871 self.rate
872 .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
873 self.read_queue.push_back(msg);
874 Ok(())
875 }
876
877 fn poll_read(&mut self) -> Option<Self::Rout> {
878 self.read_queue.pop_front()
879 }
880
881 fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
882 // The amount of FEC for the blocks that close from here on (the loss reported so far).
883 self.num_fec_packets = self.rate.fec_packets() as usize;
884 // FEC for what has left goes ahead of what is passing now.
885 self.protect_wire_images();
886 let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
887 self.write_queue.push_back(msg);
888 return Ok(());
889 };
890 let ssrc = rtp_packet.header.ssrc;
891 if !self.streams.contains_key(&ssrc) {
892 self.write_queue.push_back(msg);
893 return Ok(());
894 }
895 let now = msg.now;
896 let transport = msg.transport;
897
898 // The sequence number this packet has on the wire.
899 if let Some(offset) = self.sequence_offsets.get(&ssrc) {
900 rtp_packet.header.sequence_number =
901 rtp_packet.header.sequence_number.wrapping_add(*offset);
902 }
903
904 // A packet the application already built as RED, or as FEC, is not ours to protect.
905 let foreign = match self.streams[&ssrc].carriage {
906 Carriage::Red {
907 red_payload_type,
908 fec_payload_type,
909 } => {
910 rtp_packet.header.payload_type == red_payload_type
911 || rtp_packet.header.payload_type == fec_payload_type
912 }
913 Carriage::Stream => false,
914 };
915 if foreign {
916 if let Some(stream) = self.streams.get_mut(&ssrc) {
917 stream.last_wire_sequence = rtp_packet.header.sequence_number;
918 }
919 self.write_queue.push_back(msg);
920 return Ok(());
921 }
922 if self.wire.is_some() {
923 self.pass_to_the_wire(msg);
924 return Ok(());
925 }
926
927 // A packet that cannot be protected (it does not serialise) still leaves.
928 let Ok(image) = wire_image(rtp_packet) else {
929 self.write_queue.push_back(msg);
930 return Ok(());
931 };
932
933 let sequence_number = rtp_packet.header.sequence_number;
934 let timestamp = rtp_packet.header.timestamp;
935 let marker = rtp_packet.header.marker;
936
937 let Some(stream) = self.streams.get_mut(&ssrc) else {
938 self.write_queue.push_back(msg);
939 return Ok(());
940 };
941 stream.block.push((sequence_number, image));
942 stream.last_wire_sequence = sequence_number;
943 if let Some(packetizer) = stream.packetizer.as_mut() {
944 packetizer.on_media(timestamp, now);
945 }
946
947 // RED: the media packet becomes the primary block, behind any FEC waiting for a ride.
948 if let Carriage::Red {
949 red_payload_type,
950 fec_payload_type,
951 } = stream.carriage
952 {
953 let pending: Vec<Bytes> = stream.pending.drain(..).collect();
954 let redundant: Vec<(u8, u16, &[u8])> = pending
955 .iter()
956 .map(|fec| (fec_payload_type, 0u16, &fec[..]))
957 .collect();
958 // Pending blocks were checked against the block length limit when they were queued.
959 if let Ok(payload) = red::write(
960 &redundant,
961 rtp_packet.header.payload_type,
962 &rtp_packet.payload,
963 ) {
964 rtp_packet.payload = payload;
965 rtp_packet.header.payload_type = red_payload_type;
966 if let Some(sent) = fec_riding_along(ssrc, &pending) {
967 msg.message.add(sent);
968 }
969 }
970 }
971
972 let block =
973 if stream.block.len() >= self.num_media_packets || (self.flush_on_marker && marker) {
974 std::mem::take(&mut stream.block)
975 } else {
976 Vec::new()
977 };
978 // FEC packets that take sequence numbers of the media stream wait for the frame's
979 // last packet.
980 let after_frame = self.fec_after_frame
981 && self.placement == RedPlacement::OwnPacket
982 && matches!(stream.carriage, Carriage::Red { .. });
983
984 // The media packet goes first; the FEC protects what has already left.
985 self.write_queue.push_back(msg);
986
987 let one_level_only = self
988 .streams
989 .get(&ssrc)
990 .is_some_and(|stream| stream.one_level_only);
991 let fec_payloads = if block.is_empty() {
992 Vec::new()
993 } else {
994 self.encode_block(&block, one_level_only, self.num_fec_packets)
995 };
996 for fec in &fec_payloads {
997 self.rate.on_repair_sent(now, fec.len());
998 }
999 let Some(stream) = self.streams.get_mut(&ssrc) else {
1000 return Ok(());
1001 };
1002 let fec_payloads: Vec<Bytes> = if after_frame {
1003 stream.held.extend(fec_payloads);
1004 if marker || stream.held.len() >= ULPFEC_MAX_HELD_FEC_PACKETS {
1005 stream.held.drain(..).collect()
1006 } else {
1007 Vec::new()
1008 }
1009 } else {
1010 fec_payloads
1011 };
1012 for fec in fec_payloads {
1013 let fec_bytes = fec.len();
1014 let packet = match stream.carriage {
1015 Carriage::Stream => {
1016 let Some(packetizer) = stream.packetizer.as_mut() else {
1017 continue;
1018 };
1019 // Already serialised; parse errors cannot happen for our own output.
1020 let Ok(parsed) = super::header::UlpfecPacket::parse(&fec) else {
1021 continue;
1022 };
1023 packetizer.packetize(&parsed, now)
1024 }
1025 Carriage::Red {
1026 red_payload_type,
1027 fec_payload_type,
1028 } => {
1029 if self.placement == RedPlacement::WithNextMedia
1030 && fec.len() <= red::MAX_REDUNDANT_BLOCK
1031 {
1032 stream.pending.push_back(fec);
1033 continue;
1034 }
1035 let Ok(payload) = red::write(&[], fec_payload_type, &fec) else {
1036 continue;
1037 };
1038 // The next sequence number of the media stream: one past the last packet
1039 // sent on it, media or FEC.
1040 let offset = self.sequence_offsets.entry(ssrc).or_insert(0);
1041 *offset = offset.wrapping_add(1);
1042 stream.last_wire_sequence = stream.last_wire_sequence.wrapping_add(1);
1043 rtp::Packet {
1044 header: rtp::header::Header {
1045 version: 2,
1046 marker: false,
1047 payload_type: red_payload_type,
1048 sequence_number: stream.last_wire_sequence,
1049 timestamp,
1050 ssrc,
1051 ..Default::default()
1052 },
1053 payload,
1054 }
1055 }
1056 };
1057 self.write_queue.push_back(TaggedPacket {
1058 now,
1059 transport,
1060 message: AttributedPacket::new(Packet::Rtp(packet))
1061 .with(FecSent::one(ssrc, fec_bytes)),
1062 });
1063 }
1064 Ok(())
1065 }
1066
1067 fn poll_write(&mut self) -> Option<TaggedPacket> {
1068 self.protect_wire_images();
1069 self.write_queue.pop_front()
1070 }
1071
1072 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
1073 Ok(())
1074 }
1075
1076 fn poll_timeout(&mut self) -> Option<Self::Time> {
1077 None
1078 }
1079}
1080
1081impl Interceptor for UlpfecSendInterceptor {
1082 fn bind_local_stream(&mut self, info: &StreamInfo) {
1083 if !(self.filter)(info) {
1084 return;
1085 }
1086 let Some(carriage) = self.negotiated_carriage(info) else {
1087 return;
1088 };
1089 // RFC 5109 section 13: "If 1 is signaled, only one level of FEC protection SHALL be
1090 // used in the stream": `onelevelonly=1` on the negotiated `ulpfec` format.
1091 // The FEC stream of a separate stream: in an RTP session of its own
1092 // ([`StreamInfo::fec_session`]), else the repair flow of the media's session.
1093 let separate = match info.fec_session {
1094 Some(session) => (Some(session.ssrc), Some(session.payload_type)),
1095 None => (info.ssrc_fec, info.payload_type_fec),
1096 };
1097 let fec_format = match carriage {
1098 Carriage::Red {
1099 fec_payload_type, ..
1100 } => Some(fec_payload_type),
1101 Carriage::Stream => separate.1,
1102 };
1103 let one_level_only = info
1104 .fec_session
1105 .is_some_and(|session| session.one_level_only)
1106 || fec_format.is_some_and(|payload_type| {
1107 info.section_fmtp_lines
1108 .iter()
1109 .any(|(pt, fmtp)| *pt == payload_type && super::one_level_only_from_fmtp(fmtp))
1110 });
1111 let packetizer = match carriage {
1112 Carriage::Red { .. } => None,
1113 Carriage::Stream => {
1114 // Both halves or neither, as for FlexFEC: a repair SSRC with no payload type has
1115 // nothing to mark its packets with, and the reverse has nowhere to send them.
1116 let (Some(ssrc_fec), Some(payload_type_fec)) = separate else {
1117 return;
1118 };
1119 Some(UlpfecStreamPacketizer::new(
1120 payload_type_fec,
1121 ssrc_fec,
1122 info.clock_rate,
1123 self.initial_fec_sequence_number
1124 .unwrap_or_else(rand::random),
1125 ))
1126 }
1127 };
1128 self.streams.insert(
1129 info.ssrc,
1130 ProtectedStream {
1131 carriage,
1132 block: Vec::new(),
1133 pending: VecDeque::new(),
1134 held: VecDeque::new(),
1135 promised: 0,
1136 packetizer,
1137 last_wire_sequence: 0,
1138 in_flight: VecDeque::new(),
1139 passing: 0,
1140 one_level_only,
1141 zeroed_extensions: if self.zero_mutable_extensions {
1142 super::mutable_extension_ids(info)
1143 } else {
1144 vec![]
1145 },
1146 },
1147 );
1148 if let Some(images) = &self.wire {
1149 images.watch(info.ssrc);
1150 }
1151 }
1152
1153 fn unbind_local_stream(&mut self, info: &StreamInfo) {
1154 // A partly filled block goes with it: its packets have left, and FEC for a stream that
1155 // has stopped has nothing left to repair. The sequence offset stays.
1156 self.streams.remove(&info.ssrc);
1157 if let Some(images) = &self.wire {
1158 images.unwatch(info.ssrc);
1159 }
1160 }
1161
1162 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1163
1164 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1165}