rtci-interceptor 0.4.1

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Send-side RFC 8627 FlexFEC: protects outgoing media with parity repair packets and, when
//! asked, answers NACKs with FlexFEC retransmissions.

use super::decoder::FLEXFEC_DEFAULT_REPAIR_WINDOW;
use super::encoder::{FlexFecEncoder, FlexFecProtection};
use super::params::FlexFecParameters;
use crate::Interceptor;
use crate::cc::fec_rate::{FEC_DEFAULT_LATENCY_BUDGET, FecRate, LossPattern};
use crate::fec_layer::LayerReader;
use crate::stream_info::StreamInfo;
use crate::wire_image::{WireImageTap, WireImages, wire_image_tap};
use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
use sansio::Protocol;
use shared::TransportContext;
use shared::error::Error;
use shared::marshal::MarshalSize;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

/// The protection applied when the builder names none: flexible masks, two interleaved repair
/// packets per five source packets (the draft-03 interceptor's default shape).
pub const FLEXFEC_DEFAULT_PROTECTION: FlexFecProtection = FlexFecProtection::Mask {
    media_packets: 5,
    fec_packets: 2,
};

/// A protection's source packets per block and repair packets per block.
fn protection_shape(protection: FlexFecProtection) -> (u32, u32) {
    match protection {
        FlexFecProtection::Mask {
            media_packets,
            fec_packets,
        } => (media_packets, fec_packets),
        FlexFecProtection::Row { l } => (u32::from(l), 1),
        FlexFecProtection::Column { l, d } => (u32::from(l) * u32::from(d), u32::from(l)),
        FlexFecProtection::RowAndColumn { l, d } => {
            (u32::from(l) * u32::from(d), u32::from(l) + u32::from(d))
        }
    }
}

/// The protection of one block: which shape covers which run of the block's packets.
///
/// `gathered` source packets were gathered of the `configured` shape's block. A full block of a
/// flexible mask gets as many repair packets as the loss asks for. A full block of rows and
/// columns becomes rows or columns when the recent losses were isolated or in bursts (RFC 8627
/// section 8, [`FecRate::loss_pattern`]); the other fixed shapes stay as configured. A block that
/// closed short (an enhancement-layer packet ended it) is protected as a mask of its own length,
/// or, for the fixed shapes, by the complete rows it has.
fn block_plan(
    configured: FlexFecProtection,
    rate: &FecRate,
    retransmission: bool,
    gathered: usize,
) -> Vec<(FlexFecProtection, std::ops::Range<usize>)> {
    let full = gathered == configured.block_len();
    if gathered == 0 || gathered > configured.block_len() {
        return Vec::new();
    }
    if let FlexFecProtection::Mask { .. } = configured {
        let fec_packets = if full {
            rate.fec_packets_with(retransmission)
        } else {
            rate.fec_packets_for(gathered as u32, retransmission)
        };
        if fec_packets == 0 {
            return Vec::new();
        }
        return vec![(
            FlexFecProtection::Mask {
                media_packets: gathered as u32,
                fec_packets,
            },
            0..gathered,
        )];
    }
    // The fixed shapes are sent or not.
    if rate.fec_packets_with(retransmission) == 0 {
        return Vec::new();
    }
    let rows = |l: u8| -> Vec<(FlexFecProtection, std::ops::Range<usize>)> {
        let length = usize::from(l);
        (0..gathered / length.max(1))
            .map(|row| {
                (
                    FlexFecProtection::Row { l },
                    row * length..(row + 1) * length,
                )
            })
            .collect()
    };
    match configured {
        FlexFecProtection::Row { .. } if full => vec![(configured, 0..gathered)],
        FlexFecProtection::Row { l } => rows(l),
        FlexFecProtection::Column { l, .. } if !full => rows(l),
        FlexFecProtection::RowAndColumn { l, .. } if !full => rows(l),
        FlexFecProtection::RowAndColumn { l, d } if rate.adaptive() => match rate.loss_pattern() {
            Some(LossPattern::Random) => rows(l),
            Some(LossPattern::Bursty) => {
                vec![(FlexFecProtection::Column { l, d }, 0..gathered)]
            }
            _ => vec![(configured, 0..gathered)],
        },
        _ => vec![(configured, 0..gathered)],
    }
}

/// The most recent source packets a probe cluster's repair packets protect.
const PROBE_SOURCE_PACKETS: usize = 16;

/// How often a stream whose probe clusters this encoder fills says so to the NACK responder.
const PROBE_FILLER_ANNOUNCE_INTERVAL: Duration = Duration::from_secs(1);

/// Source packets a stream keeps to answer NACKs from, when retransmissions are on.
const RETRANSMISSION_HISTORY: usize = 512;

/// A packet is not retransmitted again within this long of its last retransmission.
const MIN_RETRANSMIT_INTERVAL: Duration = Duration::from_millis(100);

/// Builder for [`FlexFecSendInterceptor`].
///
/// # Example
///
/// ```
/// use rtci_interceptor::{FlexFecProtection, FlexFecSendBuilder, Registry, Slot};
///
/// let chain = Registry::new()
///     .with(
///         Slot::FecEncoder,
///         FlexFecSendBuilder::new()
///             .with_protection(FlexFecProtection::RowAndColumn { l: 4, d: 3 })
///             .build(),
///     )
///     .build();
/// ```
pub struct FlexFecSendBuilder {
    protection: FlexFecProtection,
    adaptive_rate: bool,
    repair_window: Duration,
    retransmissions: bool,
    initial_sequence_number: Option<u16>,
    initial_timestamp: Option<u32>,
    latency_budget: Option<Duration>,
    base_layer_only: bool,
    probe_fill: bool,
}

impl Default for FlexFecSendBuilder {
    fn default() -> Self {
        Self {
            protection: FLEXFEC_DEFAULT_PROTECTION,
            adaptive_rate: true,
            repair_window: FLEXFEC_DEFAULT_REPAIR_WINDOW,
            retransmissions: false,
            initial_sequence_number: None,
            initial_timestamp: None,
            latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
            base_layer_only: true,
            probe_fill: true,
        }
    }
}

impl FlexFecSendBuilder {
    /// A builder with [`FLEXFEC_DEFAULT_PROTECTION`] and a 10 s repair window.
    pub fn new() -> Self {
        Self::default()
    }

    /// The shape of the protection: flexible masks, rows, columns, or rows and columns.
    ///
    /// A shape with no usable block (`l` of 0, a column of fewer than two rows, a mask block of
    /// more than 110 packets) protects nothing.
    pub fn with_protection(mut self, protection: FlexFecProtection) -> Self {
        self.protection = protection;
        self
    }

    /// The longest repair window this sender uses. A stream whose negotiated `repair-window`
    /// (its `a=fmtp` line) is shorter is held to that one.
    ///
    /// A block of source packets is protected only when its first packet and its repair
    /// packets are sent within the window: RFC 8627 section 1.1.8 forbids repair packets whose
    /// L and D exceed it.
    pub fn with_repair_window(mut self, repair_window: Duration) -> Self {
        self.repair_window = repair_window;
        self
    }

    /// Answer NACKs for the protected streams with FlexFEC retransmission packets (R=1,
    /// section 4.2.2.3) on the repair stream. Off by default.
    ///
    /// This is FlexFEC's own retransmission, in place of RFC 4588 RTX: a chain that turns it on
    /// must not also run a NACK responder for the same streams, or each NACK is answered twice.
    pub fn with_retransmissions(mut self, retransmissions: bool) -> Self {
        self.retransmissions = retransmissions;
        self
    }

    /// The sequence number each repair stream starts at. Unset, it is random (section 4.2.1).
    pub fn with_initial_sequence_number(mut self, sequence_number: u16) -> Self {
        self.initial_sequence_number = Some(sequence_number);
        self
    }

    /// The RTP timestamp each repair stream carries at the instant of its first packet. Unset,
    /// it is random (RFC 3550 section 5.1). From there it follows the send clock.
    pub fn with_initial_timestamp(mut self, timestamp: u32) -> Self {
        self.initial_timestamp = Some(timestamp);
        self
    }

    /// Whether the amount of FEC follows the loss the receiver reports (the default), or
    /// stays as configured. See [`FecRate`](crate::FecRate): no repair under 0.5% loss, enough
    /// for twice the loss above it, at most half the block (flexible masks; rows and columns are sent or not); the FEC sent is taken out of the
    /// target the application encodes at.
    pub fn with_adaptive_rate(mut self, adaptive: bool) -> Self {
        self.adaptive_rate = adaptive;
        self
    }

    /// The application's latency budget (RFC 8854 section 8): while the round trip measured to
    /// the receiver is within it, a stream that can be repaired by retransmission (RTX: `nack`
    /// and an RTX stream negotiated; or [`with_retransmissions`](Self::with_retransmissions) on)
    /// gets no FEC. [`FEC_DEFAULT_LATENCY_BUDGET`](crate::FEC_DEFAULT_LATENCY_BUDGET) by
    /// default; `None` sends FEC by the loss whatever the round trip (proactive FEC).
    pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
        self.latency_budget = latency_budget;
        self
    }

    /// Whether only base-layer frames of a layered codec are protected (RFC 8854 section 8;
    /// the default): a packet of a temporal layer above the base (VP8, VP9, H.265, AV1) is
    /// left out, and ends the block gathered so far, which is protected as it is.
    pub fn with_base_layer_only(mut self, base_layer_only: bool) -> Self {
        self.base_layer_only = base_layer_only;
        self
    }

    /// Whether bandwidth probe clusters are filled with repair packets (RFC 8854 section 8:
    /// "when probing bandwidth, i.e., speculatively sending extra data to determine if
    /// additional link capacity exists, FEC data SHOULD be used as the additional data"; the
    /// default). When the pacer sends a cluster (its [`ProbeFill`](crate::ProbeFill) says how
    /// much the media it holds leaves to fill), the encoder sends up to that much in repair
    /// packets over the newest source packets (at most 16, within the repair window; one repair
    /// packet each at most) of the stream that sent last, and the NACK responder pads only what
    /// they leave unfilled. These repair packets are not taken
    /// out of the target the application encodes at: a cluster is sent above it. Off, the NACK
    /// responder fills clusters with padding on the RTX stream.
    pub fn with_probe_fill(mut self, probe_fill: bool) -> Self {
        self.probe_fill = probe_fill;
        self
    }

    /// Build the interceptor.
    pub fn build(self) -> FlexFecSendInterceptor {
        let (media_packets, fec_packets) = protection_shape(self.protection);
        FlexFecSendInterceptor {
            rate: FecRate::new(media_packets, fec_packets, self.adaptive_rate)
                .with_latency_budget(self.latency_budget),
            base_layer_only: self.base_layer_only,
            probe_fill: self.probe_fill,
            protection: self.protection,
            repair_window: self.repair_window,
            retransmissions: self.retransmissions,
            initial_sequence_number: self.initial_sequence_number,
            initial_timestamp: self.initial_timestamp,
            streams: HashMap::new(),
            repair_streams: HashMap::new(),
            wire: None,
            read_queue: VecDeque::new(),
            write_queue: VecDeque::new(),
        }
    }
}

/// One repair stream: its encoder and its send clock. Several source streams may share one.
struct RepairStream {
    encoder: FlexFecEncoder,
    clock_rate: u32,
    initial_timestamp: u32,
    /// The instant of the first repair packet, which carries `initial_timestamp`.
    epoch: Option<Instant>,
    /// How many source streams send their repair packets here.
    users: usize,
}

impl RepairStream {
    /// The repair stream's RTP timestamp at `now`: its transmission time (section 4.2.1), on
    /// the only clock a sans-I/O engine has, the instant the packet is written with.
    fn timestamp_at(&mut self, now: Instant) -> u32 {
        let epoch = *self.epoch.get_or_insert(now);
        let elapsed = now.saturating_duration_since(epoch);
        let ticks = elapsed.as_nanos() * u128::from(self.clock_rate) / 1_000_000_000;
        self.initial_timestamp.wrapping_add(ticks as u32)
    }
}

/// One protected source stream.
struct ProtectedStream {
    repair_ssrc: u32,
    repair_window: Duration,
    /// Source packets awaiting a full block, consecutive.
    block: Vec<rtp::Packet>,
    /// When the first packet of `block` was sent.
    block_started: Option<Instant>,
    /// Recent source packets and when they were sent, oldest first, for retransmission.
    history: VecDeque<(Instant, rtp::Packet)>,
    /// When each sequence number was last retransmitted.
    last_retransmit: HashMap<u16, Instant>,
    /// Whether the stream can be repaired by retransmission: by RTX (`nack` and an RTX stream
    /// negotiated), or FlexFEC retransmissions are on.
    retransmission: bool,
    /// The temporal layer of its packets.
    layers: LayerReader,
    /// The newest run of consecutive base-layer source packets and when each was sent, for the
    /// repair packets of a probe cluster.
    recent: VecDeque<(Instant, rtp::Packet)>,
    /// When the NACK responder was last told this encoder fills the stream's probe clusters.
    announced: Option<Instant>,
}

/// Produces RFC 8627 FlexFEC repair packets (`flexfec`, not `flexfec-03`) for outgoing media.
///
/// Binds a local stream that names a FEC SSRC, a FEC payload type and the `flexfec` format
/// ([`StreamInfo::fec_is_flexfec`]). Its `repair-window` is read from the FEC format's
/// `a=fmtp` line.
///
/// Source packets pass through unaltered (section 4.1); repair packets follow the packet that
/// completed their block, on the repair SSRC, with the protected SSRC in their CSRC list.
pub struct FlexFecSendInterceptor {
    protection: FlexFecProtection,
    /// The loss-driven amount of FEC.
    rate: FecRate,
    /// Only base-layer frames are protected.
    base_layer_only: bool,
    /// Probe clusters are filled with repair packets.
    probe_fill: bool,
    repair_window: Duration,
    retransmissions: bool,
    initial_sequence_number: Option<u16>,
    initial_timestamp: Option<u32>,
    /// Keyed by the **source** SSRC being protected.
    streams: HashMap<u32, ProtectedStream>,
    /// Keyed by the repair SSRC.
    repair_streams: HashMap<u32, RepairStream>,
    /// Where the source packets are read from once [`wire_tap`](Self::wire_tap) was called: as
    /// they left, below everything that edits them.
    wire: Option<WireImages>,
    read_queue: VecDeque<TaggedPacket>,
    write_queue: VecDeque<TaggedPacket>,
}

impl FlexFecSendInterceptor {
    /// The source SSRCs currently being protected.
    pub fn protected_streams(&self) -> impl Iterator<Item = u32> + '_ {
        self.streams.keys().copied()
    }

    /// The repair window in force for the source stream `ssrc`.
    pub fn repair_window(&self, ssrc: u32) -> Option<Duration> {
        self.streams.get(&ssrc).map(|stream| stream.repair_window)
    }

    /// Answer one NACK from the retransmission history.
    fn retransmit(&mut self, now: Instant, media_ssrc: u32, sequence_numbers: Vec<u16>) {
        let Some(stream) = self.streams.get_mut(&media_ssrc) else {
            return;
        };
        let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) else {
            return;
        };
        stream
            .last_retransmit
            .retain(|_, at| now.saturating_duration_since(*at) < MIN_RETRANSMIT_INTERVAL);

        for sequence_number in sequence_numbers {
            if stream.last_retransmit.contains_key(&sequence_number) {
                continue;
            }
            // Only what is still inside the repair window: the receiver has agreed to accept a
            // retransmission of any source packet within it (section 1.1.8), and no further.
            let Some((_, source)) = stream.history.iter().find(|(sent, packet)| {
                packet.header.sequence_number == sequence_number
                    && now.saturating_duration_since(*sent) <= stream.repair_window
            }) else {
                continue;
            };
            let timestamp = repair.timestamp_at(now);
            let Ok(packet) = repair.encoder.retransmit(source, timestamp) else {
                continue;
            };
            stream.last_retransmit.insert(sequence_number, now);
            self.write_queue.push_back(TaggedPacket {
                now,
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtp(packet)).with(Attribute::Retransmission),
            });
        }
    }
}

impl FlexFecSendInterceptor {
    /// The tap this encoder reads the source packets from, to register at
    /// [`Slot::FecWireImage`](crate::Slot::FecWireImage).
    ///
    /// FEC covers the source packets as they are on the wire (RFC 8627 section 4.1). This
    /// interceptor generates packets, so it sits above the pacer, where a source packet is not
    /// final: the TWCC sender below writes the transport-wide sequence number into it, adding
    /// the header extension when the packet has none. With the tap registered the encoder
    /// protects the packet that left (and keeps that image for retransmission), and the repair
    /// packets still enter the chain here, so they are paced, numbered and recorded. Without a
    /// tap the encoder reads the packets as they pass this slot, which is the wire image only
    /// when nothing below edits them.
    pub fn wire_tap(&mut self) -> WireImageTap {
        let (tap, images) = wire_image_tap();
        for ssrc in self.streams.keys() {
            images.watch(*ssrc);
        }
        self.wire = Some(images);
        tap
    }

    /// Add one source packet to its stream's block and queue the repair packets a full block
    /// yields.
    fn protect(&mut self, now: Instant, transport: TransportContext, rtp_packet: &rtp::Packet) {
        let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc) else {
            return;
        };

        if self.retransmissions {
            if stream.history.len() == RETRANSMISSION_HISTORY {
                stream.history.pop_front();
            }
            stream.history.push_back((now, rtp_packet.clone()));
        }

        let mut repair_packets = Vec::new();
        let block_len = self.protection.block_len();
        // RFC 8854 section 8: with a layered codec only base-layer frames are protected. A
        // packet of a higher temporal layer is left out; since a block is a run of consecutive
        // packets it ends the block, which is protected with what it has.
        let enhancement = self.base_layer_only && stream.layers.is_enhancement(&rtp_packet.payload);
        // The newest run of consecutive base-layer packets: an enhancement-layer packet is
        // passed over, and the next base-layer packet, not consecutive, starts a new run.
        if self.probe_fill && !enhancement {
            if stream.recent.back().is_some_and(|(_, last)| {
                rtp_packet.header.sequence_number != last.header.sequence_number.wrapping_add(1)
            }) {
                stream.recent.clear();
            }
            if stream.recent.len() == PROBE_SOURCE_PACKETS {
                stream.recent.pop_front();
            }
            stream.recent.push_back((now, rtp_packet.clone()));
        }
        if block_len > 0 {
            let closed = if enhancement {
                Some(std::mem::take(&mut stream.block))
            } else {
                // L, D and the masks describe positions from one base sequence number, so a
                // block is a run of consecutive packets: a gap starts a new one.
                if let Some(last) = stream.block.last()
                    && rtp_packet.header.sequence_number
                        != last.header.sequence_number.wrapping_add(1)
                {
                    stream.block.clear();
                }
                if stream.block.is_empty() {
                    stream.block_started = Some(now);
                }
                stream.block.push(rtp_packet.clone());
                (stream.block.len() >= block_len).then(|| std::mem::take(&mut stream.block))
            };

            if let Some(block) = closed.filter(|block| !block.is_empty()) {
                // Section 1.1.8: nothing is sent that reaches beyond the repair window. A block
                // that took longer than the window to fill goes unprotected.
                let within_window = stream.block_started.is_some_and(|started| {
                    now.saturating_duration_since(started) <= stream.repair_window
                });
                if within_window
                    && let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc)
                {
                    // The loss decides how much (flexible masks carry as many repair packets
                    // as it asks for, the fixed shapes are sent or not) and, for rows and
                    // columns, which.
                    let plan = block_plan(
                        self.protection,
                        &self.rate,
                        stream.retransmission,
                        block.len(),
                    );
                    if !plan.is_empty() {
                        let timestamp = repair.timestamp_at(now);
                        for (protection, run) in plan {
                            repair_packets.extend(repair.encoder.encode_block(
                                protection,
                                &block[run],
                                timestamp,
                            ));
                        }
                    }
                }
            }
        }

        for packet in repair_packets {
            self.rate.on_repair_sent(now, packet.marshal_size());
            let fec_bytes = packet.payload.len();
            self.write_queue.push_back(TaggedPacket {
                now,
                transport,
                message: AttributedPacket::new(Packet::Rtp(packet))
                    .with(crate::FecSent::one(rtp_packet.header.ssrc, fec_bytes)),
            });
        }
    }

    /// Fills a probe cluster with `octets` of repair packets (RFC 8854 section 8): a flexible
    /// mask over the newest run of source packets of the stream that sent last, as many repair
    /// packets as the octets ask for (at most one per source packet). The run is what is still
    /// inside the repair window (section 1.1.8). Not counted in the FEC bit rate taken out of
    /// the media target: a cluster is sent above the target.
    ///
    /// Returns the octets of the repair packets made: fewer than asked for when the run is
    /// short (a layered stream's newest base-layer frame), and the NACK responder pads the rest
    /// ([`FecProbeFilled`](crate::cc::probe::FecProbeFilled)).
    fn fill_probe(&mut self, now: Instant, transport: TransportContext, octets: usize) -> usize {
        let Some((&ssrc, stream)) = self
            .streams
            .iter_mut()
            .filter(|(_, stream)| !stream.recent.is_empty())
            .max_by_key(|(_, stream)| stream.recent.back().map(|(at, _)| *at))
        else {
            return 0;
        };
        let window = stream.repair_window;
        while stream
            .recent
            .front()
            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > window)
        {
            stream.recent.pop_front();
        }
        if stream.recent.is_empty() || octets == 0 {
            return 0;
        }
        let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) else {
            return 0;
        };
        let sources: Vec<rtp::Packet> = stream
            .recent
            .iter()
            .map(|(_, packet)| packet.clone())
            .collect();
        // A repair packet is about as large as the largest source packet it protects, with the
        // FlexFEC header (at most 20 octets for these masks) in front.
        let repair_size = sources
            .iter()
            .map(|packet| packet.marshal_size())
            .max()
            .unwrap_or(0)
            + 20;
        let fec_packets = octets.div_ceil(repair_size.max(1)).clamp(1, sources.len());
        let timestamp = repair.timestamp_at(now);
        let packets = repair.encoder.encode_block(
            FlexFecProtection::Mask {
                media_packets: sources.len() as u32,
                fec_packets: fec_packets as u32,
            },
            &sources,
            timestamp,
        );
        let mut filled = 0;
        for packet in packets {
            filled += packet.marshal_size();
            let fec_bytes = packet.payload.len();
            self.write_queue.push_back(TaggedPacket {
                now,
                transport,
                message: AttributedPacket::new(Packet::Rtp(packet))
                    .with(crate::FecSent::one(ssrc, fec_bytes)),
            });
        }
        filled
    }

    /// Protect the source packets that left since the last call.
    fn protect_wire_images(&mut self) {
        let Some(images) = self.wire.as_ref().map(WireImages::take) else {
            return;
        };
        for image in images {
            // A retransmission on the media SSRC (a NACK answered without RTX, RFC 8627
            // section 1.1.7 leaves none negotiated next to FlexFEC) is a source packet that
            // already left and was protected then: taken again, its old sequence number would
            // break the run of consecutive packets every block is (section 4.2.2.2).
            if image.message.has(&Attribute::Retransmission) {
                continue;
            }
            if let Packet::Rtp(rtp_packet) = &image.message.packet {
                // `image.now` is the instant the pacer released the packet.
                self.protect(image.now, image.transport, rtp_packet);
            }
        }
    }
}

impl Protocol<TaggedPacket, TaggedPacket, ()> for FlexFecSendInterceptor {
    type Rout = TaggedPacket;
    type Wout = TaggedPacket;
    type Eout = ();
    type Error = Error;
    type Time = Instant;

    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
        let streams = &self.streams;
        self.rate
            .on_read(&mut msg, |ssrc| streams.contains_key(&ssrc));
        // A probe cluster the pacer sends (RFC 8854 section 8): what its media leaves to fill
        // is filled with repair packets, and what they cannot fill the NACK responder pads.
        // Without a pacer (no `ProbeFill`) the NACK responder pads the cluster as before.
        if self.probe_fill
            && let Some(request) = msg.message.custom::<crate::ProbeRequest>().copied()
            && let Some(fill) = msg
                .message
                .custom::<crate::ProbeFill>()
                .filter(|fill| fill.cluster == request.cluster)
                .map(|fill| fill.octets.min(request.octets))
        {
            self.protect_wire_images();
            let filled = self.fill_probe(msg.now, msg.transport, fill);
            // After the repair packets, wire-ward: the NACK responder pads what they left.
            self.write_queue.push_back(
                crate::cc::probe::FecProbeFilled {
                    cluster: request.cluster,
                    octets: filled,
                }
                .into_packet(msg.now, msg.transport),
            );
        }
        if self.retransmissions
            && let Packet::Rtcp(rtcp_packets) = &msg.message.packet
        {
            let mut requests = Vec::new();
            for rtcp_packet in rtcp_packets {
                if let Some(nack) = rtcp_packet
                    .as_any()
                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_nack::TransportLayerNack>()
                    && self.streams.contains_key(&nack.media_ssrc)
                {
                    let mut sequence_numbers: Vec<u16> = nack
                        .nacks
                        .iter()
                        .flat_map(|pair| pair.packet_list())
                        .collect();
                    sequence_numbers.sort_unstable();
                    sequence_numbers.dedup();
                    requests.push((nack.media_ssrc, sequence_numbers));
                }
            }
            for (media_ssrc, sequence_numbers) in requests {
                self.retransmit(msg.now, media_ssrc, sequence_numbers);
            }
        }
        self.read_queue.push_back(msg);
        Ok(())
    }

    fn poll_read(&mut self) -> Option<Self::Rout> {
        self.read_queue.pop_front()
    }

    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
        // The NACK responder learns that this encoder fills the stream's probe clusters.
        if self.probe_fill
            && let Packet::Rtp(rtp_packet) = &msg.message.packet
            && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
            && stream.announced.is_none_or(|at| {
                msg.now.saturating_duration_since(at) >= PROBE_FILLER_ANNOUNCE_INTERVAL
            })
        {
            stream.announced = Some(msg.now);
            let ssrc = rtp_packet.header.ssrc;
            msg.message.add(Attribute::Custom(std::sync::Arc::new(
                crate::cc::probe::FecProbeFiller { ssrc },
            )));
        }
        if self.wire.is_some() {
            // The packets are protected as they leave, from the tap: here they only pass.
            self.protect_wire_images();
            self.write_queue.push_back(msg);
            return Ok(());
        }

        let Packet::Rtp(rtp_packet) = &msg.message.packet else {
            self.write_queue.push_back(msg);
            return Ok(());
        };
        if msg.message.has(&Attribute::Retransmission) {
            // Protected when it was first sent (see `protect_wire_images`).
            self.write_queue.push_back(msg);
            return Ok(());
        }
        let rtp_packet = rtp_packet.clone();
        let now = msg.now;
        let transport = msg.transport;

        // The source packet goes out first, as it was handed over; the repair packets protect
        // what has already left.
        self.write_queue.push_back(msg);
        self.protect(now, transport, &rtp_packet);
        Ok(())
    }

    fn poll_write(&mut self) -> Option<TaggedPacket> {
        self.protect_wire_images();
        self.write_queue.pop_front()
    }

    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
        Ok(())
    }

    fn poll_timeout(&mut self) -> Option<Self::Time> {
        None
    }
}

impl Interceptor for FlexFecSendInterceptor {
    fn bind_local_stream(&mut self, info: &StreamInfo) {
        let (Some(repair_ssrc), Some(payload_type_fec)) = (info.ssrc_fec, info.payload_type_fec)
        else {
            return;
        };
        if !info.fec_is_flexfec() || self.streams.contains_key(&info.ssrc) {
            return;
        }

        // The negotiated repair window bounds what may be sent; the builder's can only narrow
        // it.
        let negotiated = FlexFecParameters::parse(&info.sdp_fmtp_line_fec).repair_window;
        let repair_window = negotiated.map_or(self.repair_window, |negotiated| {
            negotiated.min(self.repair_window)
        });

        let (initial_sequence_number, initial_timestamp) =
            (self.initial_sequence_number, self.initial_timestamp);
        self.repair_streams
            .entry(repair_ssrc)
            .or_insert_with(|| RepairStream {
                encoder: FlexFecEncoder::new(payload_type_fec, repair_ssrc)
                    .with_base_sequence_number(
                        initial_sequence_number.unwrap_or_else(rand::random),
                    ),
                // The rate of `flexfec` is recommended to match the source's (section 5.1); 90
                // kHz is the video clock when a stream names none.
                clock_rate: if info.clock_rate == 0 {
                    90_000
                } else {
                    info.clock_rate
                },
                initial_timestamp: initial_timestamp.unwrap_or_else(rand::random),
                epoch: None,
                users: 0,
            })
            .users += 1;
        self.streams.insert(
            info.ssrc,
            ProtectedStream {
                repair_ssrc,
                repair_window,
                block: Vec::new(),
                block_started: None,
                history: VecDeque::new(),
                last_retransmit: HashMap::new(),
                retransmission: self.retransmissions
                    || crate::nack::stream_supports_rtx_repair(info),
                layers: LayerReader::for_mime_type(&info.mime_type),
                recent: VecDeque::new(),
                announced: None,
            },
        );
        if let Some(images) = &self.wire {
            images.watch(info.ssrc);
        }
    }

    fn unbind_local_stream(&mut self, info: &StreamInfo) {
        if let Some(images) = &self.wire {
            images.unwatch(info.ssrc);
        }
        let Some(stream) = self.streams.remove(&info.ssrc) else {
            return;
        };
        if let Some(repair) = self.repair_streams.get_mut(&stream.repair_ssrc) {
            repair.users -= 1;
            if repair.users == 0 {
                self.repair_streams.remove(&stream.repair_ssrc);
            }
        }
    }

    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}

    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
}