Skip to main content

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