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