Skip to main content

rtci_interceptor/flexfec/draft03/
sender.rs

1//! Send-side FlexFEC draft-03: protects outgoing media with repair packets.
2
3use super::encoder::FlexFec03Encoder;
4use crate::Interceptor;
5use crate::cc::fec_rate::FecRate;
6use crate::cc::probe::{
7    FEC_PROBE_FILLER_ANNOUNCE_INTERVAL, FEC_PROBE_MAX_REPAIR_PACKETS, FEC_PROBE_SOURCE_PACKETS,
8};
9use crate::stream_info::StreamInfo;
10use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
11use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
12use sansio::Protocol;
13use shared::error::Error;
14use shared::marshal::MarshalSize;
15use std::collections::{HashMap, VecDeque};
16use std::time::Instant;
17
18/// Media packets gathered before a repair block is produced.
19pub const DEFAULT_NUM_MEDIA_PACKETS: u32 = 5;
20
21/// Repair packets produced per block.
22pub const DEFAULT_NUM_FEC_PACKETS: u32 = 2;
23
24/// Builder for [`FlexFec03SendInterceptor`].
25///
26/// # Example
27///
28/// ```
29/// use rtci_interceptor::{Slot, FlexFec03SendBuilder, Registry};
30///
31/// let mut fec = FlexFec03SendBuilder::new().with_num_fec_packets(1).build();
32/// // The encoder protects the packets as they leave: see `wire_tap`.
33/// let tap = fec.wire_tap();
34/// let chain = Registry::new()
35///     .with(Slot::FecEncoder, fec)
36///     .with(Slot::FecWireImage, tap)
37///     .build();
38/// ```
39pub struct FlexFec03SendBuilder {
40    num_media_packets: u32,
41    num_fec_packets: u32,
42    adaptive_rate: bool,
43    initial_sequence_number: Option<u16>,
44    initial_timestamp: Option<u32>,
45    latency_budget: Option<std::time::Duration>,
46    base_layer_only: bool,
47    source_rate_first: bool,
48    probe_fill: bool,
49}
50
51impl Default for FlexFec03SendBuilder {
52    fn default() -> Self {
53        Self {
54            num_media_packets: DEFAULT_NUM_MEDIA_PACKETS,
55            num_fec_packets: DEFAULT_NUM_FEC_PACKETS,
56            adaptive_rate: true,
57            initial_sequence_number: None,
58            initial_timestamp: None,
59            latency_budget: Some(crate::FEC_DEFAULT_LATENCY_BUDGET),
60            base_layer_only: true,
61            source_rate_first: true,
62            probe_fill: true,
63        }
64    }
65}
66
67impl FlexFec03SendBuilder {
68    /// Create a builder with the default block shape.
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// How many media packets one repair block protects.
74    ///
75    /// Larger blocks cost less bandwidth per protected packet and recover later, since the block
76    /// is only sent once it is full.
77    pub fn with_num_media_packets(mut self, num_media_packets: u32) -> Self {
78        self.num_media_packets = num_media_packets;
79        self
80    }
81
82    /// How many repair packets each block produces.
83    ///
84    /// This is what the block can survive: *n* repair packets recover up to *n* losses, spread
85    /// across the block by the interleaving.
86    pub fn with_num_fec_packets(mut self, num_fec_packets: u32) -> Self {
87        self.num_fec_packets = num_fec_packets;
88        self
89    }
90
91    /// The sequence number each repair stream starts at.
92    ///
93    /// Unset, every repair stream starts at a random one (draft-03 section 4.2, RFC 3550 section
94    /// 5.1). A test pins it to assert on the numbers.
95    pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
96        self.initial_sequence_number = Some(sequence_number);
97        self
98    }
99
100    /// The RTP timestamp each repair stream carries at the instant of its first packet.
101    ///
102    /// Unset, it is random (RFC 3550 section 5.1). From there the timestamp follows the send
103    /// clock: the `now` each media packet is written with, at the stream's clock rate.
104    pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
105        self.initial_timestamp = Some(timestamp);
106        self
107    }
108
109    /// Whether the amount of FEC follows the loss the receiver reports (the default), or
110    /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
111    /// for twice the loss above it, at most half the block; the FEC sent is taken out of the
112    /// target the application encodes at.
113    pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
114        self.adaptive_rate = adaptive;
115        self
116    }
117
118    /// The application's latency budget (RFC 8854 section 8): while the round trip measured to
119    /// the receiver is within it, a stream that can be repaired by RTX (`nack` and an RTX stream
120    /// negotiated) gets no FEC.
121    /// [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by default; `None`
122    /// sends FEC by the loss whatever the round trip (proactive FEC).
123    pub fn with_latency_budget(mut self, latency_budget: Option<std::time::Duration>) -> Self {
124        self.latency_budget = latency_budget;
125        self
126    }
127
128    /// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
129    /// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
130    /// left out, and ends the block gathered so far, which is protected as it is.
131    pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
132        self.base_layer_only = base_layer_only;
133        self
134    }
135
136    /// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8:
137    /// "stronger FEC protection MAY be applied only after the source rate has been reduced";
138    /// the default). Once a congestion controller's target went by, the amount of FEC rises
139    /// only when the source sent in the last second plus the FEC the higher amount adds fit
140    /// within the target, and the target for the application is lowered by the FEC asked for
141    /// so the source makes the room. See [`FecRate::with_source_rate_first`](crate::FecRate::with_source_rate_first).
142    pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
143        self.source_rate_first = source_rate_first;
144        self
145    }
146
147    /// Whether bandwidth probe clusters are filled with repair packets (RFC 8854 section 8:
148    /// "when probing bandwidth, i.e., speculatively sending extra data to determine if
149    /// additional link capacity exists, FEC data SHOULD be used as the additional data"; the
150    /// default). When a cluster is asked for (the pacer's [`ProbeFill`](crate::ProbeFill) says
151    /// how much the media it holds leaves to fill; without a pacer, the whole cluster), the
152    /// encoder sends up to that much in repair packets over the newest run of consecutive
153    /// base-layer packets that left (at most 16, within the repair window; one repair packet
154    /// each at most) of the stream that sent last, on its repair stream, and the NACK responder
155    /// pads only what they leave unfilled (a stream without RTX: the encoder fills it all).
156    /// These repair packets are not taken out of the target the application encodes at. Off,
157    /// the NACK responder fills clusters with padding on the RTX stream.
158    pub fn with_probe_fill(mut self, probe_fill: bool) -> Self {
159        self.probe_fill = probe_fill;
160        self
161    }
162
163    /// Build the interceptor.
164    pub fn build(self) -> FlexFec03SendInterceptor {
165        let mut interceptor =
166            FlexFec03SendInterceptor::new(self.num_media_packets, self.num_fec_packets);
167        interceptor.rate = FecRate::new(
168            self.num_media_packets,
169            self.num_fec_packets,
170            self.adaptive_rate,
171        )
172        .with_latency_budget(self.latency_budget)
173        .with_source_rate_first(self.source_rate_first);
174        interceptor.base_layer_only = self.base_layer_only;
175        interceptor.probe_fill = self.probe_fill;
176        interceptor.initial_sequence_number = self.initial_sequence_number;
177        interceptor.initial_timestamp = self.initial_timestamp;
178        interceptor
179    }
180}
181
182/// One protected media stream.
183struct ProtectedStream {
184    encoder: FlexFec03Encoder,
185    /// Media packets awaiting a full block.
186    block: Vec<rtp::Packet>,
187    /// When the block's first packet left, and the transport it left on.
188    block_started: Option<(Instant, shared::TransportContext)>,
189    /// The negotiated `repair-window` (draft section 5.1, "the time that spans the source
190    /// packets and the corresponding repair packets"): a block is closed and protected no
191    /// later than this after its first packet left.
192    repair_window: Option<std::time::Duration>,
193    /// The repair stream's send clock: its rate, and the timestamp it carries at `epoch`.
194    clock: RepairClock,
195    /// Whether the stream can be repaired by RTX (`nack` and an RTX stream negotiated).
196    retransmission: bool,
197    /// The temporal layer of its packets.
198    layers: crate::fec_layer::LayerReader,
199    /// The newest run of consecutive base-layer media packets that left and when each did, for
200    /// the repair packets of a probe cluster.
201    recent: VecDeque<(Instant, rtp::Packet)>,
202    /// When the NACK responder was last told this encoder fills the stream's probe clusters.
203    announced: Option<Instant>,
204}
205
206/// The repair stream's RTP clock, driven by the instants packets are written with.
207///
208/// A repair packet's timestamp is its transmission time (draft-03 section 4.2), so it comes from
209/// the send clock and not from the media it protects. The engine is sans-I/O: the only clock is
210/// the `now` each packet carries.
211struct RepairClock {
212    clock_rate: u32,
213    initial_timestamp: u32,
214    /// The instant of the first repair packet, which carries `initial_timestamp`.
215    epoch: Option<Instant>,
216}
217
218impl RepairClock {
219    fn timestamp_at(&mut self, now: Instant) -> u32 {
220        let epoch = *self.epoch.get_or_insert(now);
221        let elapsed = now.saturating_duration_since(epoch);
222        let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
223        // The RTP timestamp is modulo 2^32.
224        self.initial_timestamp.wrapping_add(ticks as u32)
225    }
226}
227
228/// Produces FlexFEC draft-03 repair packets for outgoing media.
229///
230/// Binds only when the stream carries both a FEC SSRC and a FEC payload type: a repair stream
231/// needs its own SSRC to send on and its own payload type to be recognised by, and half an
232/// association is not usable. Those come from the negotiated `a=ssrc-group:FEC-FR`.
233pub struct FlexFec03SendInterceptor {
234    num_media_packets: u32,
235    num_fec_packets: u32,
236    /// The loss-driven amount of FEC.
237    rate: FecRate,
238    /// Only base-layer frames are protected.
239    base_layer_only: bool,
240    /// Probe clusters are filled with repair packets ([`FlexFec03SendBuilder::with_probe_fill`]).
241    probe_fill: bool,
242    /// Keyed by the **media** SSRC being protected.
243    streams: HashMap<u32, ProtectedStream>,
244    /// Pinned by the builder; random per repair stream when unset.
245    initial_sequence_number: Option<u16>,
246    initial_timestamp: Option<u32>,
247    /// Where the media packets are read from once [`wire_tap`](Self::wire_tap) was called: as
248    /// they left, below everything that edits them.
249    wire: Option<WireImages>,
250    /// Repair packets the encoder produced, waiting to join the belt.
251    /// Inbound packets ready for the next interceptor.
252    read_queue: VecDeque<TaggedPacket>,
253    /// Outbound packets ready for the next interceptor: what passed through, plus
254    /// anything this one generated.
255    write_queue: VecDeque<TaggedPacket>,
256}
257
258impl FlexFec03SendInterceptor {
259    fn new(num_media_packets: u32, num_fec_packets: u32) -> Self {
260        Self {
261            read_queue: VecDeque::new(),
262            write_queue: VecDeque::new(),
263            num_media_packets: num_media_packets.max(1),
264            num_fec_packets,
265            rate: FecRate::new(num_media_packets, num_fec_packets, true),
266            base_layer_only: true,
267            probe_fill: true,
268            streams: HashMap::new(),
269            initial_sequence_number: None,
270            initial_timestamp: None,
271            wire: None,
272        }
273    }
274
275    /// The tap this encoder reads the media packets from, to register at
276    /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
277    ///
278    /// FEC covers the source packets as they are on the wire (draft-03 section 4.1). This
279    /// interceptor generates packets, so it sits above the pacer, where a media packet is not
280    /// final: the TWCC sender below writes the transport-wide sequence number into it, adding
281    /// the header extension when the packet has none. Encoding there protects an image the
282    /// receiver never sees, and what it recovers from it is corrupt. With the tap registered the
283    /// encoder protects the packet that left, and the repair packets still enter the chain
284    /// here, so they are paced, numbered and recorded.
285    ///
286    /// Without a tap (this method never called) the encoder reads the packets as they pass this
287    /// slot, which is the wire image only when nothing below edits them: no TWCC sender in the
288    /// chain.
289    pub fn wire_tap(&mut self) -> WireImageTap {
290        let (tap, images) = wire_image_tap();
291        for ssrc in self.streams.keys() {
292            images.watch(*ssrc);
293        }
294        self.wire = Some(images);
295        tap
296    }
297
298    /// Add one media packet to its stream's block and queue the repair packets a full block
299    /// yields.
300    fn protect(
301        &mut self,
302        now: Instant,
303        transport: shared::TransportContext,
304        rtp_packet: &rtp::Packet,
305    ) {
306        let ssrc = rtp_packet.header.ssrc;
307        // A block whose window ended before this packet left is protected first.
308        self.close_expired_block(ssrc, now);
309        let Some(stream) = self.streams.get_mut(&ssrc) else {
310            return;
311        };
312
313        // RFC 8854 section 8: with a layered codec only base-layer frames are protected. A
314        // packet of a higher temporal layer is left out; a block is a run of consecutive
315        // packets, so it ends the block, which is protected with what it has.
316        if self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload) {
317            if !stream.block.is_empty() {
318                self.complete_block(ssrc, now, transport);
319            }
320            return;
321        }
322
323        // The newest run of consecutive base-layer packets, for a probe cluster's repair
324        // packets: the next base-layer packet after an enhancement-layer one starts a new run.
325        if self.probe_fill {
326            if stream.recent.back().is_some_and(|(_, last)| {
327                rtp_packet.header.sequence_number != last.header.sequence_number.wrapping_add(1)
328            }) {
329                stream.recent.clear();
330            }
331            if stream.recent.len() == FEC_PROBE_SOURCE_PACKETS {
332                stream.recent.pop_front();
333            }
334            stream.recent.push_back((now, rtp_packet.clone()));
335        }
336
337        stream.block.push(rtp_packet.clone());
338        stream.block_started.get_or_insert((now, transport));
339        if (stream.block.len() as u32) < self.num_media_packets {
340            return;
341        }
342        self.complete_block(ssrc, now, transport);
343    }
344
345    /// Protects the block of `ssrc` now if its repair window ran out by `now`.
346    fn close_expired_block(&mut self, ssrc: u32, now: Instant) {
347        let Some(stream) = self.streams.get(&ssrc) else {
348            return;
349        };
350        if let (Some(window), Some((started, transport))) =
351            (stream.repair_window, stream.block_started)
352            && !stream.block.is_empty()
353            && now.saturating_duration_since(started) >= window
354        {
355            self.complete_block(ssrc, (started + window).min(now), transport);
356        }
357    }
358
359    /// Encodes the block of `ssrc` gathered so far and queues its repair packets.
360    fn complete_block(&mut self, ssrc: u32, now: Instant, transport: shared::TransportContext) {
361        let Some(stream) = self.streams.get_mut(&ssrc) else {
362            return;
363        };
364        stream.block_started = None;
365        // The repair packets carry the send clock at `now`: the instant the block's last packet
366        // was written with (from the wire tap, the instant the pacer released it).
367        let timestamp = stream.clock.timestamp_at(now);
368        // None while retransmission is preferred (RFC 8854 section 8).
369        self.num_fec_packets = self.rate.fec_packets_with(stream.retransmission);
370        let repair_packets = if self.num_fec_packets == 0 {
371            Vec::new()
372        } else {
373            stream
374                .encoder
375                .encode(&stream.block, self.num_fec_packets, timestamp)
376        };
377        // Cleared either way: a block the encoder refused — a gap, or one longer than the
378        // masks describe — must not be retried packet by packet as more arrive.
379        stream.block.clear();
380
381        for packet in repair_packets {
382            self.rate.on_repair_sent(now, packet.marshal_size());
383            // Queued for `poll_write`, which puts them back on the belt: a repair packet is a real
384            // outgoing RTP packet and still needs every interceptor ahead — a transport-wide sequence
385            // number, the pacer, and a place in the send history congestion control reads.
386            let fec_bytes = packet.payload.len();
387            self.write_queue.push_back(TaggedPacket {
388                now,
389                transport,
390                message: AttributedPacket::new(Packet::Rtp(packet))
391                    .with(crate::FecSent::one(ssrc, fec_bytes)),
392            });
393        }
394    }
395
396    /// Protect the media packets that left since the last call.
397    fn protect_wire_images(&mut self) {
398        let Some(images) = self.wire.as_ref().map(WireImages::take) else {
399            return;
400        };
401        for image in images {
402            if let Packet::Rtp(rtp_packet) = &image.message.packet {
403                // `image.now` is the instant the pacer released the packet.
404                self.protect(image.now, image.transport, rtp_packet);
405            }
406        }
407    }
408
409    /// The media SSRCs currently being protected.
410    pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
411        self.streams.keys().copied()
412    }
413
414    /// Fills a probe cluster with `octets` of repair packets (RFC 8854 section 8) over the
415    /// newest run of base-layer packets of the stream that sent last, as many as the octets ask
416    /// for (at most one per media packet), within the repair window when one was negotiated.
417    /// Not counted in the FEC bit rate taken out of the media target. Returns the octets made;
418    /// the NACK responder pads the rest on the stream's RTX stream, and a stream without one
419    /// is filled whole here (further repair packets over the same run, at most
420    /// [`FEC_PROBE_MAX_REPAIR_PACKETS`]). `mark`: the cluster, when no pacer sends it.
421    fn fill_probe(
422        &mut self,
423        now: Instant,
424        transport: shared::TransportContext,
425        octets: usize,
426        mark: Option<u32>,
427    ) -> usize {
428        let Some((&ssrc, stream)) = self
429            .streams
430            .iter_mut()
431            .filter(|(_, stream)| !stream.recent.is_empty())
432            .max_by_key(|(_, stream)| stream.recent.back().map(|(at, _)| *at))
433        else {
434            return 0;
435        };
436        if let Some(window) = stream.repair_window {
437            while stream
438                .recent
439                .front()
440                .is_some_and(|(at, _)| now.saturating_duration_since(*at) > window)
441            {
442                stream.recent.pop_front();
443            }
444        }
445        if stream.recent.is_empty() || octets == 0 {
446            return 0;
447        }
448        let sources: Vec<rtp::Packet> = stream
449            .recent
450            .iter()
451            .map(|(_, packet)| packet.clone())
452            .collect();
453        // A repair packet is about as large as the largest packet it protects, with the
454        // draft-03 header (at most 24 octets) in front.
455        let repair_size = sources
456            .iter()
457            .map(|packet| packet.marshal_size())
458            .max()
459            .unwrap_or(0)
460            + 24;
461        let rtx = stream.retransmission;
462        let timestamp = stream.clock.timestamp_at(now);
463        let (mut filled, mut made) = (0usize, 0usize);
464        loop {
465            let wanted = octets.saturating_sub(filled).div_ceil(repair_size.max(1));
466            let count = wanted
467                .clamp(1, sources.len())
468                .min(FEC_PROBE_MAX_REPAIR_PACKETS - made);
469            let packets = stream.encoder.encode(&sources, count as u32, timestamp);
470            if packets.is_empty() {
471                break;
472            }
473            for packet in packets {
474                filled += packet.marshal_size();
475                made += 1;
476                let fec_bytes = packet.payload.len();
477                let mut message = AttributedPacket::new(Packet::Rtp(packet))
478                    .with(crate::FecSent::one(ssrc, fec_bytes));
479                if let Some(cluster) = mark {
480                    message.add(Attribute::Custom(std::sync::Arc::new(crate::ProbePacket {
481                        cluster,
482                    })));
483                }
484                self.write_queue.push_back(TaggedPacket {
485                    now,
486                    transport,
487                    message,
488                });
489            }
490            // With an RTX stream the responder pads the rest; without, the encoder goes on.
491            if rtx || filled >= octets || made >= FEC_PROBE_MAX_REPAIR_PACKETS {
492                break;
493            }
494        }
495        filled
496    }
497}
498
499impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFec03SendInterceptor {
500    type Rout = TaggedPacket;
501    type Wout = TaggedPacket;
502    type Eout = ();
503    type Error = Error;
504    type Time = Instant;
505
506    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
507        let streams = &self.streams;
508        self.rate
509            .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
510        // A probe cluster (RFC 8854 section 8): what its media leaves to fill (the pacer's
511        // `ProbeFill`; without a pacer, the whole cluster) is filled with repair packets, and
512        // what they cannot fill the NACK responder pads.
513        if self.probe_fill
514            && !self.streams.is_empty()
515            && let Some(request) = msg.message.custom::<crate::ProbeRequest>().copied()
516        {
517            let paced = msg
518                .message
519                .custom::<crate::ProbeFill>()
520                .filter(|fill| fill.cluster == request.cluster)
521                .map(|fill| fill.octets.min(request.octets));
522            let fill = paced.unwrap_or(request.octets);
523            let mark = paced.is_none().then_some(request.cluster);
524            self.protect_wire_images();
525            let filled = self.fill_probe(msg.now, msg.transport, fill, mark);
526            // After the repair packets, wire-ward: the NACK responder pads what they left.
527            self.write_queue.push_back(
528                crate::cc::probe::FecProbeFilled {
529                    cluster: request.cluster,
530                    octets: filled,
531                }
532                .into_packet(msg.now, msg.transport),
533            );
534        }
535        self.read_queue.push_back(msg);
536        Ok(())
537    }
538
539    fn poll_read(&mut self) -> Option<Self::Rout> {
540        self.read_queue.pop_front()
541    }
542
543    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
544        // The source's rate, which stronger FEC waits on (RFC 8627 section 8).
545        let streams = &self.streams;
546        self.rate.on_write(&msg, |ssrc| streams.contains_key(&ssrc));
547        // The NACK responder learns that this encoder fills the stream's probe clusters.
548        if self.probe_fill
549            && let Packet::Rtp(rtp_packet) = &msg.message.packet
550            && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
551            && stream.announced.is_none_or(|at| {
552                msg.now.saturating_duration_since(at) >= FEC_PROBE_FILLER_ANNOUNCE_INTERVAL
553            })
554        {
555            stream.announced = Some(msg.now);
556            let ssrc = rtp_packet.header.ssrc;
557            msg.message.add(Attribute::Custom(std::sync::Arc::new(
558                crate::cc::probe::FecProbeFiller { ssrc },
559            )));
560        }
561        if self.wire.is_some() {
562            // The packets are protected as they leave, from the tap: here they only pass.
563            self.protect_wire_images();
564            self.write_queue.push_back(msg);
565            return Ok(());
566        }
567
568        let Packet::Rtp(rtp_packet) = &msg.message.packet else {
569            self.write_queue.push_back(msg);
570            return Ok(());
571        };
572        let rtp_packet = rtp_packet.clone();
573        let now = msg.now;
574        let transport = msg.transport;
575
576        // The media packet goes out first; the repair packets protect what has already left.
577        self.write_queue.push_back(msg);
578        self.protect(now, transport, &rtp_packet);
579        Ok(())
580    }
581
582    fn poll_write(&mut self) -> Option<TaggedPacket> {
583        self.protect_wire_images();
584        self.write_queue.pop_front()
585    }
586
587    /// A block whose repair window ends is protected then, with what it has: its repair
588    /// packets must not leave later than the window after its first packet.
589    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
590        let ssrcs: Vec<u32> = self.streams.keys().copied().collect();
591        for ssrc in ssrcs {
592            self.close_expired_block(ssrc, now);
593        }
594        Ok(())
595    }
596
597    fn poll_timeout(&mut self) -> Option<Self::Time> {
598        self.streams
599            .values()
600            .filter(|stream| !stream.block.is_empty())
601            .filter_map(|stream| Some(stream.block_started?.0 + stream.repair_window?))
602            .min()
603    }
604}
605
606impl Interceptor for FlexFec03SendInterceptor {
607    fn bind_local_stream(&mut self, info: &StreamInfo) {
608        // The gate FEC-PRE-01 exists to open. Both halves or neither: an SSRC with no payload
609        // type has nothing to mark its packets with, and a payload type with no SSRC has nowhere
610        // to send them.
611        //
612        // And only for this format: RFC 8627 `flexfec` is another wire format with its own
613        // interceptor.
614        if let (Some(ssrc_fec), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
615            && info.fec_is_flexfec03()
616        {
617            self.streams.insert(
618                info.ssrc,
619                ProtectedStream {
620                    encoder: FlexFec03Encoder::new(payload_type_fec, ssrc_fec)
621                        .with_base_sequence_number(
622                            self.initial_sequence_number.unwrap_or_else(rand::random),
623                        ),
624                    block: Vec::new(),
625                    block_started: None,
626                    repair_window: crate::FlexFecParameters::parse(&info.sdp_fmtp_line_fec)
627                        .repair_window
628                        .filter(|window| !window.is_zero()),
629                    clock: RepairClock {
630                        // The FlexFEC rate is negotiated equal to the media's (section 5.1);
631                        // 90 kHz is the video clock when a stream names none.
632                        clock_rate: if info.clock_rate == 0 {
633                            90_000
634                        } else {
635                            info.clock_rate
636                        },
637                        initial_timestamp: self.initial_timestamp.unwrap_or_else(rand::random),
638                        epoch: None,
639                    },
640                    retransmission: crate::nack::stream_supports_rtx_repair(info),
641                    layers: crate::fec_layer::LayerReader::for_mime_type(&info.mime_type),
642                    recent: VecDeque::new(),
643                    announced: None,
644                },
645            );
646            if let Some(images) = &self.wire {
647                images.watch(info.ssrc);
648            }
649        }
650    }
651
652    fn unbind_local_stream(&mut self, info: &StreamInfo) {
653        // Any partly-filled block goes with it: those packets have already been sent unprotected,
654        // and a repair packet for a stream that has stopped has nothing left to repair.
655        self.streams.remove(&info.ssrc);
656        if let Some(images) = &self.wire {
657            images.unwatch(info.ssrc);
658        }
659    }
660
661    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
662
663    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
664}