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::cc::probe::{
9 FEC_PROBE_FILLER_ANNOUNCE_INTERVAL, FEC_PROBE_MAX_REPAIR_PACKETS, FEC_PROBE_SOURCE_PACKETS,
10};
11use crate::stream_info::StreamInfo;
12use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
13use crate::{Attribute, AttributedPacket, FecSent, Packet, TaggedPacket};
14use bytes::Bytes;
15use sansio::Protocol;
16use shared::error::Error;
17use shared::marshal::MarshalSize;
18use std::collections::{HashMap, VecDeque};
19use std::sync::Arc;
20use std::time::Instant;
21
22use super::encoder::UlpfecStreamPacketizer;
23
24/// Media packets gathered before FEC is produced for them.
25pub const ULPFEC_DEFAULT_NUM_MEDIA_PACKETS: usize = 5;
26
27/// FEC packets produced per block of media.
28pub const ULPFEC_DEFAULT_NUM_FEC_PACKETS: usize = 1;
29
30/// The most FEC packets held back for the end of a frame
31/// ([`UlpfecSendBuilder::with_fec_after_frame`]). A stream that never sets the marker bit, or a
32/// frame of more packets than this many FEC packets protect, gets them where the count is
33/// reached.
34pub const ULPFEC_MAX_HELD_FEC_PACKETS: usize = 128;
35
36/// Where FEC data goes in a RED stream.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum RedPlacement {
39 /// A RED packet of its own, whose only block has the FEC payload type. It takes the next
40 /// sequence number of the media stream. What libwebrtc sends and the only form it reads
41 /// (its receiver drops a RED packet with more than one block): the setting for a browser
42 /// peer. RFC 5109 14.2 does not allow it: "the FEC MUST NOT be sent by itself for this
43 /// stream". Such packets follow the last packet of a frame, never lie inside one
44 /// ([`UlpfecSendBuilder::with_fec_after_frame`]).
45 OwnPacket,
46 /// A redundant block in the next media packet, ahead of its primary block: the carriage of
47 /// RFC 5109 14.2 ("the FEC data ... is sent in the same packets as the protected payload")
48 /// and 10.3, and the default. FEC is never sent by itself and the media stream's sequence
49 /// numbers are untouched. A redundant block holds at most 1023 octets (RFC 2198 section 3),
50 /// so FEC data longer than that (protection of full-size video packets) cannot be carried
51 /// this way and still goes in a packet of its own.
52 #[default]
53 WithNextMedia,
54}
55
56/// Which streams an interceptor protects.
57pub(crate) type StreamFilter = Arc<dyn Fn(&StreamInfo) -> bool + Send + Sync>;
58
59/// The default choice: video streams, the only kind `ulpfec` is negotiated for in WebRTC.
60pub(crate) fn video_streams() -> StreamFilter {
61 Arc::new(|info: &StreamInfo| {
62 info.mime_type
63 .get(..6)
64 .is_some_and(|kind| kind.eq_ignore_ascii_case("video/"))
65 })
66}
67
68/// How the FEC travels.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub(crate) enum Carriage {
71 Red {
72 red_payload_type: u8,
73 fec_payload_type: u8,
74 },
75 Stream,
76}
77
78/// Builder for [`UlpfecSendInterceptor`].
79///
80/// # Example
81///
82/// ```
83/// use rtci_interceptor::{Registry, Slot, UlpfecSendBuilder};
84///
85/// // `a=rtpmap:116 red/90000`, `a=rtpmap:117 ulpfec/90000`
86/// let chain = Registry::new()
87/// .with(Slot::FecEncoder, UlpfecSendBuilder::red(116, 117).build())
88/// .build();
89/// ```
90pub struct UlpfecSendBuilder {
91 carriage: Carriage,
92 placement: RedPlacement,
93 num_media_packets: usize,
94 num_fec_packets: usize,
95 adaptive_rate: bool,
96 level_lengths: Vec<u16>,
97 one_level_only: bool,
98 flush_on_marker: bool,
99 fec_after_frame: bool,
100 initial_fec_sequence_number: Option<u16>,
101 filter: StreamFilter,
102 zero_mutable_extensions: bool,
103 latency_budget: Option<std::time::Duration>,
104 base_layer_only: bool,
105 source_rate_first: bool,
106 probe_fill: bool,
107}
108
109impl UlpfecSendBuilder {
110 fn new(carriage: Carriage) -> Self {
111 Self {
112 carriage,
113 placement: RedPlacement::default(),
114 num_media_packets: ULPFEC_DEFAULT_NUM_MEDIA_PACKETS,
115 num_fec_packets: ULPFEC_DEFAULT_NUM_FEC_PACKETS,
116 adaptive_rate: true,
117 level_lengths: Vec::new(),
118 one_level_only: false,
119 flush_on_marker: false,
120 fec_after_frame: true,
121 initial_fec_sequence_number: None,
122 filter: video_streams(),
123 zero_mutable_extensions: false,
124 latency_budget: Some(crate::FEC_DEFAULT_LATENCY_BUDGET),
125 base_layer_only: true,
126 source_rate_first: true,
127 probe_fill: true,
128 }
129 }
130
131 /// Whether bandwidth probe clusters are filled with FEC (RFC 8854 section 8: "when probing
132 /// bandwidth, i.e., speculatively sending extra data to determine if additional link
133 /// capacity exists, FEC data SHOULD be used as the additional data"; the default). When a
134 /// cluster is asked for (the pacer's [`ProbeFill`](crate::ProbeFill) says how much the
135 /// media it holds leaves to fill; without a pacer, the whole cluster), the encoder sends up
136 /// to that much in FEC packets over the newest media packets that left (at most 16, within
137 /// one mask; at most one FEC packet each) of the stream that sent last, and the NACK
138 /// responder pads only what they leave unfilled. These FEC packets are not taken out of the
139 /// target the application encodes at: a cluster is sent above it.
140 ///
141 /// Where the FEC can go: on a separate FEC stream of the media's RTP session
142 /// ([`Self::stream`], the stream's repair flow) always; never in a FEC session of its own
143 /// ([`StreamInfo::fec_session`]: another transport, whose path a cluster of the media's
144 /// session does not measure); in RED with
145 /// [`RedPlacement::OwnPacket`] as RED packets of their own that take the media stream's next
146 /// sequence numbers, so only between frames (the last packet written had the marker bit)
147 /// and when every media packet written has left (none of their FEC is still to take a
148 /// number); in RED with [`RedPlacement::WithNextMedia`] never (RFC 5109 section 14.2: "the
149 /// FEC MUST NOT be sent by itself for this stream", and a probe has no media to ride with).
150 /// Where it cannot, the cluster is padded as before. Off, the NACK responder pads every
151 /// cluster on the RTX stream, as libwebrtc does (the `Chrome` profile's
152 /// `DefaultInterceptorOptions::fec_probe_fill`).
153 pub fn with_probe_fill(mut self, probe_fill: bool) -> Self {
154 self.probe_fill = probe_fill;
155 self
156 }
157
158 /// The application's latency budget (RFC 8854 section 8): while the round trip measured to
159 /// the receiver is within it, a stream that can be repaired by RTX (`nack` and an RTX stream
160 /// negotiated) gets no FEC.
161 /// [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by default; `None`
162 /// sends FEC by the loss whatever the round trip (proactive FEC).
163 pub fn with_latency_budget(mut self, latency_budget: Option<std::time::Duration>) -> Self {
164 self.latency_budget = latency_budget;
165 self
166 }
167
168 /// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
169 /// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
170 /// left out of the blocks (it still goes in RED where the stream is carried in RED).
171 pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
172 self.base_layer_only = base_layer_only;
173 self
174 }
175
176 /// Protect each media packet with the values of its transport-wide sequence number,
177 /// abs-send-time and toffset extensions zeroed, as libwebrtc's sender does (`false` by
178 /// default; the `Chrome` profile's `DefaultInterceptorOptions::ulpfec_zero_mutable_extensions`).
179 ///
180 /// libwebrtc computes its FEC before it writes those values (`RtpSenderEgress::SendPacket`
181 /// at a222406d: `AddPacketAndGenerateFec` comes before the `SetExtension<TransmissionOffset>`,
182 /// `<AbsoluteSendTime>` and `<TransportSequenceNumber>` calls, "these modifications of the
183 /// header below are happening after the FEC protection packets are calculated"; the packet
184 /// reserved them as zeros), and its receiver zeroes them in its copy of each media packet
185 /// before recovering (`UlpfecReceiver::ProcessReceivedFec`, `ZeroMutableExtensions`). With
186 /// this on, a packet libwebrtc rebuilds from this engine's FEC is exactly the one its own
187 /// FEC would rebuild: as sent, those values zero. Off (RFC 5109 section 8), the FEC covers
188 /// the packet as it left, and those octets of a packet libwebrtc rebuilds are XOR noise.
189 pub fn with_mutable_extensions_zeroed(mut self, zero: bool) -> Self {
190 self.zero_mutable_extensions = zero;
191 self
192 }
193
194 /// FEC as a redundant encoding (RFC 5109 14.2): every packet of a protected stream leaves as
195 /// a RED packet of `red_payload_type`, and FEC data has `fec_payload_type`. Both come from
196 /// the negotiated `a=rtpmap` lines (`red`, `ulpfec`).
197 pub fn red(red_payload_type: u8, fec_payload_type: u8) -> Self {
198 Self::new(Carriage::Red {
199 red_payload_type: red_payload_type & 0x7F,
200 fec_payload_type: fec_payload_type & 0x7F,
201 })
202 }
203
204 /// FEC as a stream of its own (RFC 5109 14.1), on the repair SSRC and payload type of
205 /// [`StreamInfo::ssrc_fec`] / [`StreamInfo::payload_type_fec`]. A stream without both is not
206 /// protected. See [`UlpfecStreamPacketizer`] for why this is not the media SSRC.
207 pub fn stream() -> Self {
208 Self::new(Carriage::Stream)
209 }
210
211 /// Where FEC data goes in a RED stream. Ignored for a separate stream.
212 pub fn with_red_placement(mut self, placement: RedPlacement) -> Self {
213 self.placement = placement;
214 self
215 }
216
217 /// How many media packets one block of FEC protects, 1 to 48 (the long mask's reach).
218 pub fn with_num_media_packets(mut self, num_media_packets: usize) -> Self {
219 self.num_media_packets = num_media_packets.clamp(1, LONG_MASK_BITS);
220 self
221 }
222
223 /// How many FEC packets each block produces. The block's packets are dealt to them in turn,
224 /// so `n` FEC packets recover a burst of up to `n` losses. Zero sends no FEC.
225 pub fn with_num_fec_packets(mut self, num_fec_packets: usize) -> Self {
226 self.num_fec_packets = num_fec_packets;
227 self
228 }
229
230 /// Protection lengths of the levels, level 0 first, for uneven protection: level 0 covers the
231 /// first `lengths[0]` octets after the fixed RTP header, level 1 the next `lengths[1]`, and
232 /// so on; what lies beyond the last level is not protected.
233 ///
234 /// Empty, the default, is one level as long as the block's longest packet: full protection.
235 pub fn with_level_lengths(mut self, lengths: impl Into<Vec<u16>>) -> Self {
236 self.level_lengths = lengths.into();
237 self
238 }
239
240 /// Use one level only, whatever [`with_level_lengths`](Self::with_level_lengths) says: for a
241 /// stream whose `ulpfec` format carries `onelevelonly=1` (RFC 5109 13). See
242 /// [`one_level_only_from_fmtp`](super::one_level_only_from_fmtp).
243 pub fn with_one_level_only(mut self, one_level_only: bool) -> Self {
244 self.one_level_only = one_level_only;
245 self
246 }
247
248 /// Also close a block at a packet with the marker bit (the last packet of a video frame), so
249 /// FEC never waits for the next frame.
250 pub fn with_flush_on_marker(mut self, flush_on_marker: bool) -> Self {
251 self.flush_on_marker = flush_on_marker;
252 self
253 }
254
255 /// With [`RedPlacement::OwnPacket`]: whether the FEC packets of the blocks that close
256 /// inside a frame wait for the frame's last packet (the one with the marker bit) and take
257 /// the sequence numbers after it (`true`, the default), or each block's FEC packets follow
258 /// the block's last packet wherever in the frame that is (`false`).
259 ///
260 /// A FEC packet of this placement takes a sequence number of the media stream. A receiver
261 /// puts a frame together from consecutive sequence numbers, so a number inside a frame
262 /// that is not media leaves the frame incomplete: libwebrtc's packet buffer finds a frame
263 /// only over packets it holds without a gap, and a received FEC packet closes a gap between
264 /// frames only (`modules/video_coding/packet_buffer.cc:168-174`, `InsertPadding`, and
265 /// `FindFrames`, at a222406d). libwebrtc's sender therefore produces FEC only at a packet
266 /// that completes a frame (`modules/rtp_rtcp/source/ulpfec_generator.cc:134` and
267 /// `:157-159`: `complete_frame = packet.Marker()`, `if (complete_frame && ...)`
268 /// `EncodeFec`), and its FEC packets follow that packet. RFC 5109 and RFC 2198 say nothing
269 /// about where in a stream a FEC packet lies: only the order on the wire changes, each FEC
270 /// packet protects the same media packets either way.
271 ///
272 /// At most [`ULPFEC_MAX_HELD_FEC_PACKETS`] FEC packets wait; they leave when that many
273 /// have gathered, so a stream that never sets the marker bit is still protected. No
274 /// effect on the other placements and carriages, whose FEC takes no sequence number of
275 /// the media stream.
276 pub fn with_fec_after_frame(mut self, fec_after_frame: bool) -> Self {
277 self.fec_after_frame = fec_after_frame;
278 self
279 }
280
281 /// The first sequence number of a separate FEC stream. Random when not set, as an RTP
282 /// stream's is (RFC 3550 5.1); a test pins it.
283 pub fn with_initial_fec_sequence_number(mut self, sequence_number: u16) -> Self {
284 self.initial_fec_sequence_number = Some(sequence_number);
285 self
286 }
287
288 /// Which bound local streams are protected. The default is every `video/` stream.
289 pub fn with_stream_filter(
290 mut self,
291 filter: impl Fn(&StreamInfo) -> bool + Send + Sync + 'static,
292 ) -> Self {
293 self.filter = Arc::new(filter);
294 self
295 }
296
297 /// Whether the amount of FEC follows the loss the receiver reports (the default), or
298 /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
299 /// for twice the loss above it, at most half the block; the FEC sent is taken out of the
300 /// target the application encodes at.
301 pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
302 self.adaptive_rate = adaptive;
303 self
304 }
305
306 /// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8:
307 /// "stronger FEC protection MAY be applied only after the source rate has been reduced";
308 /// the default). Once a congestion controller's target went by, the amount of FEC rises
309 /// only when the source sent in the last second plus the FEC the higher amount adds fit
310 /// within the target, and the target for the application is lowered by the FEC asked for
311 /// so the source makes the room. See [`FecRate::with_source_rate_first`](crate::FecRate::with_source_rate_first).
312 pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
313 self.source_rate_first = source_rate_first;
314 self
315 }
316
317 /// Build the interceptor.
318 pub fn build(self) -> UlpfecSendInterceptor {
319 let mut level_lengths = self.level_lengths;
320 if self.one_level_only {
321 level_lengths.truncate(1);
322 }
323 UlpfecSendInterceptor {
324 carriage: self.carriage,
325 placement: self.placement,
326 num_media_packets: self.num_media_packets,
327 num_fec_packets: self.num_fec_packets,
328 rate: FecRate::new(
329 self.num_media_packets as u32,
330 self.num_fec_packets as u32,
331 self.adaptive_rate,
332 )
333 .with_latency_budget(self.latency_budget)
334 .with_source_rate_first(self.source_rate_first),
335 base_layer_only: self.base_layer_only,
336 probe_fill: self.probe_fill,
337 level_lengths,
338 flush_on_marker: self.flush_on_marker,
339 fec_after_frame: self.fec_after_frame,
340 initial_fec_sequence_number: self.initial_fec_sequence_number,
341 filter: self.filter,
342 zero_mutable_extensions: self.zero_mutable_extensions,
343 streams: HashMap::new(),
344 sequence_offsets: HashMap::new(),
345 wire: None,
346 read_queue: VecDeque::new(),
347 write_queue: VecDeque::new(),
348 }
349 }
350}
351
352/// One protected media stream.
353struct ProtectedStream {
354 /// How this stream's FEC travels, with the negotiated payload types
355 /// ([`UlpfecSendInterceptor::negotiated_carriage`]).
356 carriage: Carriage,
357 /// The packets of the block being gathered, as protected: sequence number and wire image.
358 block: Vec<(u16, Bytes)>,
359 /// RED, [`RedPlacement::WithNextMedia`]: FEC payloads waiting for the next media packet.
360 pending: VecDeque<Bytes>,
361 /// FEC payloads of the blocks that closed and have not been sent: with
362 /// [`UlpfecSendBuilder::with_fec_after_frame`], until the frame's last packet.
363 held: VecDeque<Bytes>,
364 /// With a wire tap: the FEC packets of the blocks that closed at this slot since sequence
365 /// numbers were last set aside for FEC.
366 promised: usize,
367 /// Separate stream: the FEC stream's packetizer.
368 packetizer: Option<UlpfecStreamPacketizer>,
369 /// The sequence number of the last packet sent on the media SSRC, media or FEC.
370 last_wire_sequence: u16,
371 /// With a wire tap: media packets that passed this slot and have not been seen leaving
372 /// yet, oldest first.
373 in_flight: VecDeque<InFlight>,
374 /// With a wire tap: media packets that passed this slot since the last block was closed.
375 passing: usize,
376 /// One protection level only for this stream (RFC 5109 section 13: `onelevelonly=1` on
377 /// the negotiated `ulpfec` format, or the builder's setting).
378 one_level_only: bool,
379 /// The ids of the extensions whose values are zeroed in what is protected
380 /// ([`UlpfecSendBuilder::with_mutable_extensions_zeroed`]); empty when off.
381 zeroed_extensions: Vec<u8>,
382 /// Whether the stream can be repaired by RTX (`nack` and an RTX stream negotiated).
383 retransmission: bool,
384 /// The temporal layer of its packets.
385 layers: crate::fec_layer::LayerReader,
386 /// The newest base-layer media packets that left, as protected (sequence number on the
387 /// wire, image), within one mask's reach: what the FEC of a probe cluster protects.
388 recent: VecDeque<(u16, Bytes)>,
389 /// When the newest of `recent` left.
390 recent_at: Option<Instant>,
391 /// Whether the last media packet written ended a frame (the marker bit): FEC that takes
392 /// sequence numbers of the media stream may go now.
393 between_frames: bool,
394 /// The RTP timestamp of the last media packet written, which a FEC packet in RED carries.
395 last_timestamp: u32,
396 /// When the NACK responder was last told this encoder fills the stream's probe clusters.
397 announced: Option<Instant>,
398 /// Its FEC goes in a FEC session of its own ([`StreamInfo::fec_session`]): another
399 /// transport, which a cluster of the media's session does not measure.
400 own_session: bool,
401}
402
403/// The most media packets remembered between this slot and the wire tap. The pacer between the
404/// two holds at most its queue limit; anything older than this was dropped on the way.
405const MAX_IN_FLIGHT: usize = 4096;
406
407/// A media packet on its way from this slot to the wire.
408struct InFlight {
409 /// Its sequence number on the wire.
410 sequence_number: u16,
411 /// Set on the packet that closes a block: how many FEC packets the block gets, as decided
412 /// when the packet passed this slot.
413 closes: Option<usize>,
414 /// Set on the packet behind which the FEC of the blocks closed so far is sent.
415 sends: Option<BlockEnd>,
416 /// A packet of a temporal layer above the base, left out of the blocks.
417 enhancement: bool,
418}
419
420/// What was decided about the FEC to send when the media packet it follows passed this slot.
421struct BlockEnd {
422 /// RED with [`RedPlacement::OwnPacket`]: the sequence numbers of the media stream set aside
423 /// for the FEC packets.
424 reserved: Vec<u16>,
425 /// The RTP timestamp of the media packet the FEC follows, which the FEC packets carry.
426 timestamp: u32,
427}
428
429/// With a wire tap: what a media packet that left (or never did) settles, in order.
430enum WireStep {
431 /// A block is complete: its packets as they left, and how many FEC packets it gets.
432 Block(usize, Vec<(u16, Bytes)>),
433 /// The FEC gathered so far is sent.
434 Send(BlockEnd),
435}
436
437/// Produces ULPFEC (RFC 5109) for outgoing media.
438///
439/// # RED carriage
440///
441/// Each media packet of a protected stream is rewritten into a RED packet: the payload gains the
442/// one-octet primary block header naming the media payload type, and the RTP payload type becomes
443/// RED's. FEC is computed over the packets as they would be without RED (the *virtual* packets
444/// of RFC 5109 14.2) and with the sequence numbers they have on the wire.
445///
446/// With [`RedPlacement::OwnPacket`] a FEC packet takes a sequence number of the media stream, so
447/// every later media packet of the stream is sent with its sequence number moved up by the number
448/// of FEC packets sent so far. Those sequence numbers follow the last packet of a frame
449/// ([`UlpfecSendBuilder::with_fec_after_frame`]): the receiver finds no FEC packet between two
450/// packets of a frame. The NACK responder sits wire-ward of this interceptor and buffers
451/// what is on the wire, so a NACK, which names wire sequence numbers, is answered correctly. The
452/// marker bit of the media packet is kept on the RED packet, as browsers do; RFC 2198 has no
453/// field for it otherwise.
454///
455/// # Where it belongs
456///
457/// [`Slot::FecEncoder`](crate::Slot::FecEncoder): application-ward of the pacer and the
458/// transport-wide numbering, so FEC is paced, numbered and recorded as the bytes on the wire it
459/// is.
460pub struct UlpfecSendInterceptor {
461 carriage: Carriage,
462 placement: RedPlacement,
463 num_media_packets: usize,
464 num_fec_packets: usize,
465 /// The loss-driven amount of FEC.
466 rate: FecRate,
467 /// Only base-layer frames are protected.
468 base_layer_only: bool,
469 /// Probe clusters are filled with FEC ([`UlpfecSendBuilder::with_probe_fill`]).
470 probe_fill: bool,
471 level_lengths: Vec<u16>,
472 flush_on_marker: bool,
473 /// See [`UlpfecSendBuilder::with_fec_after_frame`].
474 fec_after_frame: bool,
475 initial_fec_sequence_number: Option<u16>,
476 filter: StreamFilter,
477 /// See [`UlpfecSendBuilder::with_mutable_extensions_zeroed`].
478 zero_mutable_extensions: bool,
479 /// Keyed by the media SSRC.
480 streams: HashMap<u32, ProtectedStream>,
481 /// FEC packets inserted so far into each media stream's sequence space. Kept apart from
482 /// `streams` so a stream that is unbound and bound again continues where it was: going back
483 /// would reuse sequence numbers already on the wire.
484 sequence_offsets: HashMap<u32, u16>,
485 /// Where the media packets are read from once [`wire_tap`](Self::wire_tap) was called: as
486 /// they left, below everything that edits them.
487 wire: Option<WireImages>,
488 read_queue: VecDeque<TaggedPacket>,
489 write_queue: VecDeque<TaggedPacket>,
490}
491
492impl UlpfecSendInterceptor {
493 /// How the FEC of `info`'s stream travels: RFC 5109 section 14, "the multiplexing
494 /// configuration ... MUST be indicated out of band", and section 14.2, "An rtpmap attribute
495 /// MUST be used to indicate a dynamic payload type number for the FEC packets". So the
496 /// stream's negotiated formats ([`StreamInfo::section_mime_types`]) decide, not only the
497 /// builder:
498 ///
499 /// - RED: the section's `red` and `ulpfec` formats, the builder's payload types when the
500 /// section has them under those numbers, else the section's own; without a `red` and a
501 /// `ulpfec` format the stream is not protected as RED, and goes as a separate stream when
502 /// the description gives it a ULPFEC repair flow.
503 /// - A separate stream: the repair flow of [`StreamInfo::ssrc_fec`] /
504 /// [`StreamInfo::payload_type_fec`] when its format is `ulpfec`; without one, RED when the
505 /// section negotiated `red` and `ulpfec`.
506 ///
507 /// - A separate RTP session ([`StreamInfo::fec_session`]): a separate stream, whatever
508 /// the builder and the media section's formats say.
509 ///
510 /// `None`: the stream is not protected. A binder that names no formats (an empty
511 /// `section_mime_types`) gets the builder's carriage as it is.
512 fn negotiated_carriage(&self, info: &StreamInfo) -> Option<Carriage> {
513 negotiated_carriage(self.carriage, info)
514 }
515 /// The media SSRCs currently being protected.
516 pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
517 self.streams.keys().copied()
518 }
519
520 /// The FEC payloads for a full block: `fec_packets` of them (no more than the block has
521 /// packets), each protecting every `count`-th packet.
522 fn encode_block(
523 &self,
524 block: &[(u16, Bytes)],
525 one_level_only: bool,
526 fec_packets: usize,
527 ) -> Vec<Bytes> {
528 let count = fec_packets.min(block.len());
529 if count == 0 {
530 return Vec::new();
531 }
532 let images: HashMap<u16, Bytes> = block.iter().cloned().collect();
533 let encoder = UlpfecEncoder::new();
534 let mut out = Vec::with_capacity(count);
535 for index in 0..count {
536 let sequences: Vec<u16> = block
537 .iter()
538 .enumerate()
539 .filter(|(position, _)| position % count == index)
540 .map(|(_, (sequence, _))| *sequence)
541 .collect();
542 let levels: Vec<ProtectionLevel> = if self.level_lengths.is_empty() {
543 let longest = sequences
544 .iter()
545 .map(|sequence| images[sequence].len() - RTP_FIXED_HEADER)
546 .max()
547 .unwrap_or(0);
548 vec![ProtectionLevel::new(longest as u16, sequences)]
549 } else {
550 let levels = if one_level_only {
551 &self.level_lengths[..1]
552 } else {
553 &self.level_lengths[..]
554 };
555 levels
556 .iter()
557 .map(|length| ProtectionLevel::new(*length, sequences.clone()))
558 .collect()
559 };
560 // A block the encoder refuses (a gap in the sequence numbers wider than a mask)
561 // goes unprotected rather than half-described.
562 if let Ok(fec) = encoder.encode_images(&images, &levels) {
563 out.push(fec.marshal());
564 }
565 }
566 out
567 }
568}
569
570impl UlpfecSendInterceptor {
571 /// The tap this encoder reads the media packets from, to register at
572 /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
573 ///
574 /// FEC protects the packets as they are sent (RFC 5109 section 8). This interceptor sits
575 /// above the pacer, where a media packet is not final: the TWCC sender below writes the
576 /// transport-wide sequence number into it, adding the header extension when the packet has
577 /// none, and the receiver XORs what arrived. With the tap registered the work is split in
578 /// two:
579 ///
580 /// - **here**, as a media packet passes: it gets its sequence number on the wire and its
581 /// RED wrapping, and when it closes a block the sequence numbers the block's FEC packets
582 /// will take are set aside (RED carriage with [`RedPlacement::OwnPacket`]), so later
583 /// media is numbered past them;
584 /// - **at the tap**, as the packet leaves: its image goes into the block, and when the
585 /// block's last packet has left the FEC is computed over those images and sent, in the
586 /// sequence numbers set aside for it, on the FEC stream, or with the next media packet.
587 ///
588 /// A FEC packet therefore leaves after the block it protects has left, a few packets
589 /// later than its sequence number says when a pacer holds the media in between. Every
590 /// sequence number of the media stream is still used exactly once.
591 ///
592 /// Without a tap (this method never called) the encoder protects the packets as they pass
593 /// this slot, which is the wire image only when nothing below edits them.
594 pub fn wire_tap(&mut self) -> WireImageTap {
595 let (tap, images) = wire_image_tap();
596 for ssrc in self.streams.keys() {
597 images.watch(*ssrc);
598 }
599 self.wire = Some(images);
600 tap
601 }
602
603 /// With a wire tap: send a protected media packet on its way, numbered and wrapped, and
604 /// note what its block's FEC will need. `msg` already has its wire sequence number.
605 fn pass_to_the_wire(&mut self, mut msg: TaggedPacket) {
606 let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
607 self.write_queue.push_back(msg);
608 return;
609 };
610 let ssrc = rtp_packet.header.ssrc;
611 let Some(stream) = self.streams.get_mut(&ssrc) else {
612 self.write_queue.push_back(msg);
613 return;
614 };
615 let sequence_number = rtp_packet.header.sequence_number;
616 let timestamp = rtp_packet.header.timestamp;
617 let marker = rtp_packet.header.marker;
618 stream.last_wire_sequence = sequence_number;
619 stream.between_frames = marker;
620 stream.last_timestamp = timestamp;
621 // RFC 8854 section 8: a packet of a temporal layer above the base is not protected.
622 let enhancement = self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload);
623
624 // RED: the media packet becomes the primary block, behind any FEC waiting for a ride.
625 if let Carriage::Red {
626 red_payload_type,
627 fec_payload_type,
628 } = stream.carriage
629 {
630 let pending: Vec<Bytes> = stream.pending.drain(..).collect();
631 let redundant: Vec<(u8, u16, &[u8])> = pending
632 .iter()
633 .map(|fec| (fec_payload_type, 0u16, &fec[..]))
634 .collect();
635 if let Ok(payload) = red::write(
636 &redundant,
637 rtp_packet.header.payload_type,
638 &rtp_packet.payload,
639 ) {
640 rtp_packet.payload = payload;
641 rtp_packet.header.payload_type = red_payload_type;
642 if let Some(sent) = fec_riding_along(ssrc, &pending) {
643 msg.message.add(sent);
644 }
645 }
646 }
647
648 if !enhancement {
649 stream.passing += 1;
650 }
651 let own_packets = matches!(stream.carriage, Carriage::Red { .. })
652 && self.placement == RedPlacement::OwnPacket;
653 let closes = (stream.passing >= self.num_media_packets || (self.flush_on_marker && marker))
654 .then(|| {
655 let fec_packets = self.num_fec_packets.min(stream.passing);
656 stream.passing = 0;
657 fec_packets
658 });
659 stream.promised += closes.unwrap_or(0);
660 // Where the FEC goes: behind the block's last packet, or, for FEC packets that take
661 // sequence numbers of the media stream, behind the frame's last packet.
662 let send_now = if own_packets && self.fec_after_frame {
663 stream.promised > 0 && (marker || stream.promised >= ULPFEC_MAX_HELD_FEC_PACKETS)
664 } else {
665 closes.is_some()
666 };
667 let sends = send_now.then(|| {
668 let fec_packets = std::mem::take(&mut stream.promised);
669 // The FEC packets take the next sequence numbers of the media stream, now, so the
670 // media that follows is numbered past them.
671 let reserved = if own_packets {
672 let offset = self.sequence_offsets.entry(ssrc).or_insert(0);
673 (0..fec_packets)
674 .map(|_| {
675 *offset = offset.wrapping_add(1);
676 stream.last_wire_sequence = stream.last_wire_sequence.wrapping_add(1);
677 stream.last_wire_sequence
678 })
679 .collect()
680 } else {
681 Vec::new()
682 };
683 BlockEnd {
684 reserved,
685 timestamp,
686 }
687 });
688 if stream.in_flight.len() == MAX_IN_FLIGHT {
689 stream.in_flight.pop_front();
690 }
691 stream.in_flight.push_back(InFlight {
692 sequence_number,
693 closes,
694 sends,
695 enhancement,
696 });
697 self.write_queue.push_back(msg);
698 }
699
700 /// With a wire tap: take the media packets that left since the last call into their blocks,
701 /// and send the FEC of every block whose last packet has left.
702 fn protect_wire_images(&mut self) {
703 let Some(images) = self.wire.as_ref().map(WireImages::take) else {
704 return;
705 };
706 for image in images {
707 let Packet::Rtp(rtp_packet) = &image.message.packet else {
708 continue;
709 };
710 self.on_wire_image(image.now, image.transport, rtp_packet);
711 }
712 }
713
714 /// One packet of a protected stream, as it left.
715 fn on_wire_image(
716 &mut self,
717 now: Instant,
718 transport: shared::TransportContext,
719 rtp_packet: &rtp::Packet,
720 ) {
721 let ssrc = rtp_packet.header.ssrc;
722 let sequence_number = rtp_packet.header.sequence_number;
723 let Some(stream) = self.streams.get_mut(&ssrc) else {
724 return;
725 };
726 // Only the media this interceptor sent on its way: a retransmission, a FEC packet of
727 // its own, or a packet the application built as RED itself is not waited for.
728 let Some(position) = stream
729 .in_flight
730 .iter()
731 .position(|waiting| waiting.sequence_number == sequence_number)
732 else {
733 return;
734 };
735 // Whatever was sent before it and has not been seen never reached the wire (the pacer
736 // refused it, a circuit breaker stopped the flow). A block one of those closed is
737 // closed with what did leave, and the FEC that was to follow one of those is sent.
738 let mut steps = Vec::new();
739 for _ in 0..position {
740 let Some(lost) = stream.in_flight.pop_front() else {
741 break;
742 };
743 if let Some(fec_packets) = lost.closes {
744 steps.push(WireStep::Block(
745 fec_packets,
746 std::mem::take(&mut stream.block),
747 ));
748 }
749 if let Some(end) = lost.sends {
750 steps.push(WireStep::Send(end));
751 }
752 }
753 let Some(arrived) = stream.in_flight.pop_front() else {
754 return;
755 };
756
757 // The packet FEC protects: in RED, the virtual packet of RFC 5109 section 14.2, which is
758 // the packet on the wire without its block headers and redundant data, under the
759 // primary's payload type. That is what the receiver rebuilds from what arrives.
760 let zeroed;
761 let rtp_packet = if stream.zeroed_extensions.is_empty() {
762 rtp_packet
763 } else {
764 zeroed = super::with_extensions_zeroed(rtp_packet, &stream.zeroed_extensions);
765 &zeroed
766 };
767 let protected = match stream.carriage {
768 Carriage::Stream => wire_image(rtp_packet).ok(),
769 Carriage::Red { .. } => {
770 red::parse(&rtp_packet.payload)
771 .ok()
772 .and_then(|(_, primary)| {
773 let mut header = rtp_packet.header.clone();
774 header.payload_type = primary.payload_type;
775 wire_image(&rtp::Packet {
776 header,
777 payload: Bytes::copy_from_slice(primary.data),
778 })
779 .ok()
780 })
781 }
782 };
783 if let Some(protected) = protected
784 && !arrived.enhancement
785 {
786 if self.probe_fill {
787 remember_for_probes(stream, now, sequence_number, protected.clone());
788 }
789 stream.block.push((sequence_number, protected));
790 }
791 if let Some(packetizer) = stream.packetizer.as_mut() {
792 packetizer.on_media(rtp_packet.header.timestamp, now);
793 }
794 if let Some(fec_packets) = arrived.closes {
795 steps.push(WireStep::Block(
796 fec_packets,
797 std::mem::take(&mut stream.block),
798 ));
799 }
800 if let Some(end) = arrived.sends {
801 steps.push(WireStep::Send(end));
802 }
803
804 for step in steps {
805 match step {
806 WireStep::Block(fec_packets, block) => {
807 self.encode_wire_block(now, ssrc, fec_packets, &block);
808 }
809 WireStep::Send(end) => self.send_held_fec(now, transport, ssrc, end),
810 }
811 }
812 }
813
814 /// Compute the FEC of a block whose packets have left; it waits to be sent.
815 fn encode_wire_block(
816 &mut self,
817 now: Instant,
818 ssrc: u32,
819 fec_packets: usize,
820 block: &[(u16, Bytes)],
821 ) {
822 let one_level_only = self
823 .streams
824 .get(&ssrc)
825 .is_some_and(|stream| stream.one_level_only);
826 let fec_payloads = self.encode_block(block, one_level_only, fec_packets);
827 for fec in &fec_payloads {
828 self.rate.on_repair_sent(now, fec.len());
829 }
830 if let Some(stream) = self.streams.get_mut(&ssrc) {
831 stream.held.extend(fec_payloads);
832 }
833 }
834
835 /// Send the FEC of the blocks whose packets have left.
836 fn send_held_fec(
837 &mut self,
838 now: Instant,
839 transport: shared::TransportContext,
840 ssrc: u32,
841 end: BlockEnd,
842 ) {
843 let Some(stream) = self.streams.get_mut(&ssrc) else {
844 return;
845 };
846 let mut fec_payloads = std::mem::take(&mut stream.held);
847 // Each packet with the FEC octets it carries (none: an empty block in a reserved slot).
848 let mut packets = Vec::new();
849 match stream.carriage {
850 Carriage::Stream => {
851 for fec in fec_payloads {
852 if let Some(packetizer) = stream.packetizer.as_mut()
853 && let Ok(parsed) = super::header::UlpfecPacket::parse(&fec)
854 {
855 packets.push((packetizer.packetize(&parsed, now), fec.len()));
856 }
857 }
858 }
859 Carriage::Red {
860 red_payload_type,
861 fec_payload_type,
862 } => {
863 if self.placement == RedPlacement::WithNextMedia {
864 stream.pending.extend(
865 fec_payloads
866 .into_iter()
867 .filter(|fec| fec.len() <= red::MAX_REDUNDANT_BLOCK),
868 );
869 return;
870 }
871 // Every sequence number set aside is used, so the stream has no hole of this
872 // interceptor's making: a slot the blocks gave no FEC for (packets of one never
873 // left, or the encoder refused it) carries an empty FEC block.
874 for sequence_number in end.reserved {
875 let fec = fec_payloads.pop_front().unwrap_or_default();
876 let Ok(payload) = red::write(&[], fec_payload_type, &fec) else {
877 continue;
878 };
879 packets.push((
880 rtp::Packet {
881 header: rtp::header::Header {
882 version: 2,
883 marker: false,
884 payload_type: red_payload_type,
885 sequence_number,
886 timestamp: end.timestamp,
887 ssrc,
888 ..Default::default()
889 },
890 payload,
891 },
892 fec.len(),
893 ));
894 }
895 }
896 }
897 for (packet, fec_bytes) in packets {
898 let mut message = AttributedPacket::new(Packet::Rtp(packet));
899 if fec_bytes > 0 {
900 message.add(FecSent::one(ssrc, fec_bytes));
901 }
902 self.write_queue.push_back(TaggedPacket {
903 now,
904 transport,
905 message,
906 });
907 }
908 }
909}
910
911/// Remembers a base-layer media packet that left (`sequence_number`, its protected `image`) for
912/// the FEC of a probe cluster: the newest [`FEC_PROBE_SOURCE_PACKETS`] within one long mask.
913fn remember_for_probes(
914 stream: &mut ProtectedStream,
915 now: Instant,
916 sequence_number: u16,
917 image: Bytes,
918) {
919 while let Some((first, _)) = stream.recent.front() {
920 if stream.recent.len() >= FEC_PROBE_SOURCE_PACKETS
921 || usize::from(sequence_number.wrapping_sub(*first)) >= LONG_MASK_BITS
922 {
923 stream.recent.pop_front();
924 } else {
925 break;
926 }
927 }
928 stream.recent.push_back((sequence_number, image));
929 stream.recent_at = Some(now);
930}
931
932impl UlpfecSendInterceptor {
933 /// Whether the FEC of `stream` can fill a probe cluster: on a separate FEC stream of the
934 /// media's RTP session, or in RED packets of its own; not as a redundant block of the next
935 /// media packet (RFC 5109 section 14.2: "the FEC MUST NOT be sent by itself for this
936 /// stream"), and not in a FEC session of its own (RFC 5109 section 14.1,
937 /// [`StreamInfo::fec_session`]): that session has its own transport, and a cluster measures
938 /// the path of the session that asked for it (RFC 8836 section 2).
939 fn fills_probes(placement: RedPlacement, stream: &ProtectedStream) -> bool {
940 match stream.carriage {
941 Carriage::Stream => !stream.own_session,
942 Carriage::Red { .. } => placement == RedPlacement::OwnPacket,
943 }
944 }
945
946 /// Whether some protected stream's probe clusters can be filled with this encoder's FEC.
947 fn fills_any_probe(&self) -> bool {
948 self.streams
949 .values()
950 .any(|stream| Self::fills_probes(self.placement, stream))
951 }
952
953 /// Marks `msg`, a media packet of a stream whose clusters this encoder fills, with
954 /// [`FecProbeFiller`](crate::cc::probe::FecProbeFiller) for the NACK responder: on the
955 /// stream's first packet, then once a second.
956 fn announce_probe_filler(&mut self, msg: &mut TaggedPacket) {
957 let Packet::Rtp(rtp_packet) = &msg.message.packet else {
958 return;
959 };
960 let ssrc = rtp_packet.header.ssrc;
961 let placement = self.placement;
962 let Some(stream) = self.streams.get_mut(&ssrc) else {
963 return;
964 };
965 if !Self::fills_probes(placement, stream)
966 || stream.announced.is_some_and(|at| {
967 msg.now.saturating_duration_since(at) < FEC_PROBE_FILLER_ANNOUNCE_INTERVAL
968 })
969 {
970 return;
971 }
972 stream.announced = Some(msg.now);
973 msg.message.add(Attribute::Custom(Arc::new(
974 crate::cc::probe::FecProbeFiller { ssrc },
975 )));
976 }
977
978 /// Fills a probe cluster with `octets` of FEC (RFC 8854 section 8): FEC packets over the
979 /// newest base-layer media packets that left of the stream that sent last, as many as the
980 /// octets ask for (at most one per media packet). Not counted in the FEC bit rate taken out
981 /// of the media target: a cluster is sent above the target.
982 ///
983 /// Returns the octets of the FEC packets made: none where the carriage cannot send FEC by
984 /// itself now (see [`UlpfecSendBuilder::with_probe_fill`]), fewer than asked for when the
985 /// packets held are few; the NACK responder pads the rest on the stream's RTX stream. A
986 /// stream without RTX has nothing the responder could pad on: the encoder makes further
987 /// FEC packets over the same packets until the cluster is filled (at most
988 /// [`FEC_PROBE_MAX_REPAIR_PACKETS`]).
989 ///
990 /// `mark`: the cluster, when no pacer sends it: the FEC packets leave as one burst, marked
991 /// [`ProbePacket`](crate::ProbePacket) here.
992 fn fill_probe(
993 &mut self,
994 now: Instant,
995 transport: shared::TransportContext,
996 octets: usize,
997 mark: Option<u32>,
998 ) -> usize {
999 if octets == 0 {
1000 return 0;
1001 }
1002 let Some((ssrc, sources, one_level_only, rtx)) = self
1003 .streams
1004 .iter()
1005 .filter(|(_, stream)| {
1006 Self::fills_probes(self.placement, stream) && !stream.recent.is_empty()
1007 })
1008 .max_by_key(|(_, stream)| stream.recent_at)
1009 .filter(|(_, stream)| match stream.carriage {
1010 Carriage::Stream => true,
1011 // FEC packets that take the media stream's next sequence numbers: between
1012 // frames, and with no media written still on its way (its FEC would take
1013 // numbers before these).
1014 Carriage::Red { .. } => {
1015 stream.between_frames
1016 && stream.in_flight.is_empty()
1017 && stream.held.is_empty()
1018 && stream.promised == 0
1019 }
1020 })
1021 .map(|(ssrc, stream)| {
1022 (
1023 *ssrc,
1024 stream.recent.iter().cloned().collect::<Vec<_>>(),
1025 stream.one_level_only,
1026 stream.retransmission,
1027 )
1028 })
1029 else {
1030 return 0;
1031 };
1032 // A FEC packet is about as large as the largest packet it protects, with the ULPFEC
1033 // headers (at most 18 octets) and the RED header in front.
1034 let fec_size = sources
1035 .iter()
1036 .map(|(_, image)| image.len())
1037 .max()
1038 .unwrap_or(0)
1039 + 19;
1040 let mut payloads = Vec::new();
1041 let mut planned = 0usize;
1042 loop {
1043 let wanted = octets.saturating_sub(planned).div_ceil(fec_size.max(1));
1044 let count = wanted
1045 .clamp(1, sources.len())
1046 .min(FEC_PROBE_MAX_REPAIR_PACKETS - payloads.len());
1047 let round = self.encode_block(&sources, one_level_only, count);
1048 if round.is_empty() {
1049 break;
1050 }
1051 planned += round.len() * fec_size;
1052 payloads.extend(round);
1053 // With an RTX stream the responder pads the rest; without, the encoder goes on.
1054 if rtx || planned >= octets || payloads.len() >= FEC_PROBE_MAX_REPAIR_PACKETS {
1055 break;
1056 }
1057 }
1058 let Some(stream) = self.streams.get_mut(&ssrc) else {
1059 return 0;
1060 };
1061 let mut filled = 0;
1062 for fec in payloads {
1063 let fec_bytes = fec.len();
1064 let packet = match stream.carriage {
1065 Carriage::Stream => {
1066 let (Some(packetizer), Ok(parsed)) = (
1067 stream.packetizer.as_mut(),
1068 super::header::UlpfecPacket::parse(&fec),
1069 ) else {
1070 continue;
1071 };
1072 packetizer.packetize(&parsed, now)
1073 }
1074 Carriage::Red {
1075 red_payload_type,
1076 fec_payload_type,
1077 } => {
1078 let Ok(payload) = red::write(&[], fec_payload_type, &fec) else {
1079 continue;
1080 };
1081 let offset = self.sequence_offsets.entry(ssrc).or_insert(0);
1082 *offset = offset.wrapping_add(1);
1083 stream.last_wire_sequence = stream.last_wire_sequence.wrapping_add(1);
1084 rtp::Packet {
1085 header: rtp::header::Header {
1086 version: 2,
1087 marker: false,
1088 payload_type: red_payload_type,
1089 sequence_number: stream.last_wire_sequence,
1090 timestamp: stream.last_timestamp,
1091 ssrc,
1092 ..Default::default()
1093 },
1094 payload,
1095 }
1096 }
1097 };
1098 filled += packet.marshal_size();
1099 let mut message =
1100 AttributedPacket::new(Packet::Rtp(packet)).with(FecSent::one(ssrc, fec_bytes));
1101 if let Some(cluster) = mark {
1102 message.add(Attribute::Custom(Arc::new(crate::ProbePacket { cluster })));
1103 }
1104 self.write_queue.push_back(TaggedPacket {
1105 now,
1106 transport,
1107 message,
1108 });
1109 }
1110 filled
1111 }
1112}
1113
1114/// The carriage of `info`'s stream given the builder's (`builder`): see
1115/// [`UlpfecSendInterceptor::negotiated_carriage`]. The receive side reads a stream the same way,
1116/// so the payload types the section negotiated are the ones it looks for.
1117pub(super) fn negotiated_carriage(builder: Carriage, info: &StreamInfo) -> Option<Carriage> {
1118 // A FEC session of its own was negotiated for the stream (RFC 5109 section 14.1, an
1119 // m= section grouped with the media's): that is where its FEC goes.
1120 if info.fec_session.is_some() {
1121 return Some(Carriage::Stream);
1122 }
1123 if info.section_mime_types.is_empty() {
1124 return Some(builder);
1125 }
1126 let formats = |subtype: &str| -> Vec<u8> {
1127 info.section_mime_types
1128 .iter()
1129 .filter(|(_, mime_type)| {
1130 mime_type
1131 .rsplit_once('/')
1132 .is_some_and(|(_, sub)| sub.eq_ignore_ascii_case(subtype))
1133 })
1134 .map(|(payload_type, _)| *payload_type)
1135 .collect()
1136 };
1137 let red = |wanted: Option<(u8, u8)>| -> Option<Carriage> {
1138 let (reds, fecs) = (formats("red"), formats("ulpfec"));
1139 let pick = |found: &[u8], wanted: Option<u8>| {
1140 wanted
1141 .filter(|payload_type| found.contains(payload_type))
1142 .or_else(|| found.first().copied())
1143 };
1144 Some(Carriage::Red {
1145 red_payload_type: pick(&reds, wanted.map(|(red, _)| red))?,
1146 fec_payload_type: pick(&fecs, wanted.map(|(_, fec)| fec))?,
1147 })
1148 };
1149 let separate = (info.ssrc_fec.is_some()
1150 && info
1151 .payload_type_fec
1152 .is_some_and(|payload_type| formats("ulpfec").contains(&payload_type)))
1153 .then_some(Carriage::Stream);
1154 match builder {
1155 Carriage::Red {
1156 red_payload_type,
1157 fec_payload_type,
1158 } => red(Some((red_payload_type, fec_payload_type))).or(separate),
1159 Carriage::Stream => separate.or_else(|| red(None)),
1160 }
1161}
1162
1163/// The [`FecSent`] mark for a media packet in RED that FEC blocks ride with, if any do.
1164fn fec_riding_along(media_ssrc: u32, blocks: &[Bytes]) -> Option<Attribute> {
1165 (!blocks.is_empty()).then(|| {
1166 Attribute::Custom(Arc::new(FecSent {
1167 media_ssrc,
1168 packets: blocks.len() as u32,
1169 bytes: blocks.iter().map(|block| block.len() as u64).sum(),
1170 }))
1171 })
1172}
1173
1174impl Protocol<TaggedPacket, TaggedPacket, ()> for UlpfecSendInterceptor {
1175 type Rout = TaggedPacket;
1176 type Wout = TaggedPacket;
1177 type Eout = ();
1178 type Error = Error;
1179 type Time = Instant;
1180
1181 fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1182 let streams = &self.streams;
1183 self.rate
1184 .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
1185 // A probe cluster (RFC 8854 section 8): what its media leaves to fill (the pacer's
1186 // `ProbeFill`; without a pacer, the whole cluster) is filled with FEC where this
1187 // stream's carriage lets FEC go alone, and what it cannot fill the NACK responder pads.
1188 if self.probe_fill
1189 && self.fills_any_probe()
1190 && let Some(request) = msg.message.custom::<crate::ProbeRequest>().copied()
1191 {
1192 let paced = msg
1193 .message
1194 .custom::<crate::ProbeFill>()
1195 .filter(|fill| fill.cluster == request.cluster)
1196 .map(|fill| fill.octets.min(request.octets));
1197 let fill = paced.unwrap_or(request.octets);
1198 let mark = paced.is_none().then_some(request.cluster);
1199 self.protect_wire_images();
1200 let filled = self.fill_probe(msg.now, msg.transport, fill, mark);
1201 // After the FEC packets, wire-ward: the NACK responder pads what they left.
1202 self.write_queue.push_back(
1203 crate::cc::probe::FecProbeFilled {
1204 cluster: request.cluster,
1205 octets: filled,
1206 }
1207 .into_packet(msg.now, msg.transport),
1208 );
1209 }
1210 self.read_queue.push_back(msg);
1211 Ok(())
1212 }
1213
1214 fn poll_read(&mut self) -> Option<Self::Rout> {
1215 self.read_queue.pop_front()
1216 }
1217
1218 fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1219 // The source's rate, which stronger FEC waits on (RFC 8627 section 8).
1220 let streams = &self.streams;
1221 self.rate.on_write(&msg, |ssrc| streams.contains_key(&ssrc));
1222 // The NACK responder learns that this encoder fills the stream's probe clusters.
1223 if self.probe_fill {
1224 self.announce_probe_filler(&mut msg);
1225 }
1226 // FEC for what has left goes ahead of what is passing now.
1227 self.protect_wire_images();
1228 let Packet::Rtp(rtp_packet) = &mut msg.message.packet else {
1229 self.write_queue.push_back(msg);
1230 return Ok(());
1231 };
1232 let ssrc = rtp_packet.header.ssrc;
1233 let Some(retransmission) = self.streams.get(&ssrc).map(|stream| stream.retransmission)
1234 else {
1235 self.write_queue.push_back(msg);
1236 return Ok(());
1237 };
1238 // The amount of FEC for the blocks of this stream that close from here on (the loss
1239 // reported so far; none while retransmission is preferred, RFC 8854 section 8).
1240 self.num_fec_packets = self.rate.fec_packets_with(retransmission) as usize;
1241 let now = msg.now;
1242 let transport = msg.transport;
1243
1244 // The sequence number this packet has on the wire.
1245 if let Some(offset) = self.sequence_offsets.get(&ssrc) {
1246 rtp_packet.header.sequence_number =
1247 rtp_packet.header.sequence_number.wrapping_add(*offset);
1248 }
1249
1250 // A packet the application already built as RED, or as FEC, is not ours to protect.
1251 let foreign = match self.streams[&ssrc].carriage {
1252 Carriage::Red {
1253 red_payload_type,
1254 fec_payload_type,
1255 } => {
1256 rtp_packet.header.payload_type == red_payload_type
1257 || rtp_packet.header.payload_type == fec_payload_type
1258 }
1259 Carriage::Stream => false,
1260 };
1261 if foreign {
1262 if let Some(stream) = self.streams.get_mut(&ssrc) {
1263 stream.last_wire_sequence = rtp_packet.header.sequence_number;
1264 }
1265 self.write_queue.push_back(msg);
1266 return Ok(());
1267 }
1268 if self.wire.is_some() {
1269 self.pass_to_the_wire(msg);
1270 return Ok(());
1271 }
1272
1273 // A packet that cannot be protected (it does not serialise) still leaves.
1274 let Ok(image) = wire_image(rtp_packet) else {
1275 self.write_queue.push_back(msg);
1276 return Ok(());
1277 };
1278
1279 let sequence_number = rtp_packet.header.sequence_number;
1280 let timestamp = rtp_packet.header.timestamp;
1281 let marker = rtp_packet.header.marker;
1282
1283 let Some(stream) = self.streams.get_mut(&ssrc) else {
1284 self.write_queue.push_back(msg);
1285 return Ok(());
1286 };
1287 // RFC 8854 section 8: a packet of a temporal layer above the base is not protected.
1288 if !(self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload)) {
1289 if self.probe_fill {
1290 remember_for_probes(stream, now, sequence_number, image.clone());
1291 }
1292 stream.block.push((sequence_number, image));
1293 }
1294 stream.last_wire_sequence = sequence_number;
1295 stream.between_frames = marker;
1296 stream.last_timestamp = timestamp;
1297 if let Some(packetizer) = stream.packetizer.as_mut() {
1298 packetizer.on_media(timestamp, now);
1299 }
1300
1301 // RED: the media packet becomes the primary block, behind any FEC waiting for a ride.
1302 if let Carriage::Red {
1303 red_payload_type,
1304 fec_payload_type,
1305 } = stream.carriage
1306 {
1307 let pending: Vec<Bytes> = stream.pending.drain(..).collect();
1308 let redundant: Vec<(u8, u16, &[u8])> = pending
1309 .iter()
1310 .map(|fec| (fec_payload_type, 0u16, &fec[..]))
1311 .collect();
1312 // Pending blocks were checked against the block length limit when they were queued.
1313 if let Ok(payload) = red::write(
1314 &redundant,
1315 rtp_packet.header.payload_type,
1316 &rtp_packet.payload,
1317 ) {
1318 rtp_packet.payload = payload;
1319 rtp_packet.header.payload_type = red_payload_type;
1320 if let Some(sent) = fec_riding_along(ssrc, &pending) {
1321 msg.message.add(sent);
1322 }
1323 }
1324 }
1325
1326 let block =
1327 if stream.block.len() >= self.num_media_packets || (self.flush_on_marker && marker) {
1328 std::mem::take(&mut stream.block)
1329 } else {
1330 Vec::new()
1331 };
1332 // FEC packets that take sequence numbers of the media stream wait for the frame's
1333 // last packet.
1334 let after_frame = self.fec_after_frame
1335 && self.placement == RedPlacement::OwnPacket
1336 && matches!(stream.carriage, Carriage::Red { .. });
1337
1338 // The media packet goes first; the FEC protects what has already left.
1339 self.write_queue.push_back(msg);
1340
1341 let one_level_only = self
1342 .streams
1343 .get(&ssrc)
1344 .is_some_and(|stream| stream.one_level_only);
1345 let fec_payloads = if block.is_empty() {
1346 Vec::new()
1347 } else {
1348 self.encode_block(&block, one_level_only, self.num_fec_packets)
1349 };
1350 for fec in &fec_payloads {
1351 self.rate.on_repair_sent(now, fec.len());
1352 }
1353 let Some(stream) = self.streams.get_mut(&ssrc) else {
1354 return Ok(());
1355 };
1356 let fec_payloads: Vec<Bytes> = if after_frame {
1357 stream.held.extend(fec_payloads);
1358 if marker || stream.held.len() >= ULPFEC_MAX_HELD_FEC_PACKETS {
1359 stream.held.drain(..).collect()
1360 } else {
1361 Vec::new()
1362 }
1363 } else {
1364 fec_payloads
1365 };
1366 for fec in fec_payloads {
1367 let fec_bytes = fec.len();
1368 let packet = match stream.carriage {
1369 Carriage::Stream => {
1370 let Some(packetizer) = stream.packetizer.as_mut() else {
1371 continue;
1372 };
1373 // Already serialised; parse errors cannot happen for our own output.
1374 let Ok(parsed) = super::header::UlpfecPacket::parse(&fec) else {
1375 continue;
1376 };
1377 packetizer.packetize(&parsed, now)
1378 }
1379 Carriage::Red {
1380 red_payload_type,
1381 fec_payload_type,
1382 } => {
1383 if self.placement == RedPlacement::WithNextMedia
1384 && fec.len() <= red::MAX_REDUNDANT_BLOCK
1385 {
1386 stream.pending.push_back(fec);
1387 continue;
1388 }
1389 let Ok(payload) = red::write(&[], fec_payload_type, &fec) else {
1390 continue;
1391 };
1392 // The next sequence number of the media stream: one past the last packet
1393 // sent on it, media or FEC.
1394 let offset = self.sequence_offsets.entry(ssrc).or_insert(0);
1395 *offset = offset.wrapping_add(1);
1396 stream.last_wire_sequence = stream.last_wire_sequence.wrapping_add(1);
1397 rtp::Packet {
1398 header: rtp::header::Header {
1399 version: 2,
1400 marker: false,
1401 payload_type: red_payload_type,
1402 sequence_number: stream.last_wire_sequence,
1403 timestamp,
1404 ssrc,
1405 ..Default::default()
1406 },
1407 payload,
1408 }
1409 }
1410 };
1411 self.write_queue.push_back(TaggedPacket {
1412 now,
1413 transport,
1414 message: AttributedPacket::new(Packet::Rtp(packet))
1415 .with(FecSent::one(ssrc, fec_bytes)),
1416 });
1417 }
1418 Ok(())
1419 }
1420
1421 fn poll_write(&mut self) -> Option<TaggedPacket> {
1422 self.protect_wire_images();
1423 self.write_queue.pop_front()
1424 }
1425
1426 fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
1427 Ok(())
1428 }
1429
1430 fn poll_timeout(&mut self) -> Option<Self::Time> {
1431 None
1432 }
1433}
1434
1435impl Interceptor for UlpfecSendInterceptor {
1436 fn bind_local_stream(&mut self, info: &StreamInfo) {
1437 if !(self.filter)(info) {
1438 return;
1439 }
1440 let Some(carriage) = self.negotiated_carriage(info) else {
1441 return;
1442 };
1443 // RFC 5109 section 13: "If 1 is signaled, only one level of FEC protection SHALL be
1444 // used in the stream": `onelevelonly=1` on the negotiated `ulpfec` format.
1445 // The FEC stream of a separate stream: in an RTP session of its own
1446 // ([`StreamInfo::fec_session`]), else the repair flow of the media's session.
1447 let separate = match info.fec_session {
1448 Some(session) => (Some(session.ssrc), Some(session.payload_type)),
1449 None => (info.ssrc_fec, info.payload_type_fec),
1450 };
1451 let fec_format = match carriage {
1452 Carriage::Red {
1453 fec_payload_type, ..
1454 } => Some(fec_payload_type),
1455 Carriage::Stream => separate.1,
1456 };
1457 let one_level_only = info
1458 .fec_session
1459 .is_some_and(|session| session.one_level_only)
1460 || fec_format.is_some_and(|payload_type| {
1461 info.section_fmtp_lines
1462 .iter()
1463 .any(|(pt, fmtp)| *pt == payload_type && super::one_level_only_from_fmtp(fmtp))
1464 });
1465 let packetizer = match carriage {
1466 Carriage::Red { .. } => None,
1467 Carriage::Stream => {
1468 // Both halves or neither, as for FlexFEC: a repair SSRC with no payload type has
1469 // nothing to mark its packets with, and the reverse has nowhere to send them.
1470 let (Some(ssrc_fec), Some(payload_type_fec)) = separate else {
1471 return;
1472 };
1473 Some(UlpfecStreamPacketizer::new(
1474 payload_type_fec,
1475 ssrc_fec,
1476 info.clock_rate,
1477 self.initial_fec_sequence_number
1478 .unwrap_or_else(rand::random),
1479 ))
1480 }
1481 };
1482 self.streams.insert(
1483 info.ssrc,
1484 ProtectedStream {
1485 carriage,
1486 block: Vec::new(),
1487 pending: VecDeque::new(),
1488 held: VecDeque::new(),
1489 promised: 0,
1490 packetizer,
1491 last_wire_sequence: 0,
1492 in_flight: VecDeque::new(),
1493 passing: 0,
1494 one_level_only,
1495 zeroed_extensions: if self.zero_mutable_extensions {
1496 super::mutable_extension_ids(info)
1497 } else {
1498 vec![]
1499 },
1500 retransmission: crate::nack::stream_supports_rtx_repair(info),
1501 layers: crate::fec_layer::LayerReader::for_mime_type(&info.mime_type),
1502 recent: VecDeque::new(),
1503 recent_at: None,
1504 between_frames: true,
1505 last_timestamp: 0,
1506 announced: None,
1507 own_session: info.fec_session.is_some(),
1508 },
1509 );
1510 if let Some(images) = &self.wire {
1511 images.watch(info.ssrc);
1512 }
1513 }
1514
1515 fn unbind_local_stream(&mut self, info: &StreamInfo) {
1516 // A partly filled block goes with it: its packets have left, and FEC for a stream that
1517 // has stopped has nothing left to repair. The sequence offset stays.
1518 self.streams.remove(&info.ssrc);
1519 if let Some(images) = &self.wire {
1520 images.unwatch(info.ssrc);
1521 }
1522 }
1523
1524 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1525
1526 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1527}