rtci-interceptor 0.5.0

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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
//! A loss-driven FEC rate, shared by the FEC senders (FlexFEC draft-03, RFC 8627 FlexFEC,
//! ULPFEC), and the FEC overhead taken out of the target the application encodes at.
//!
//! * draft-ietf-payload-flexible-fec-scheme-03 section 8: repair flows "SHOULD" not be sent
//!   when they would not help recover anything, and the amount of FEC is adjusted to the loss
//!   observed; RFC 8627 section 8 likewise ("SHOULD [...] adjust the amount [...] of FEC from
//!   the observed loss rate"); RFC 5109 section 12: users of the format "MUST" monitor packet
//!   loss, and FEC "MUST NOT substantially increase the total bandwidth (media and FEC) as
//!   network loss increases".
//! * The loss is the protected stream's, as its receiver reports it (RFC 3550 6.4.1 fraction
//!   lost, which counts what the path lost, not what FEC rebuilt), smoothed over reports.
//! * The repair packets per block follow it: enough for twice the measured loss
//!   (`ceil(2 * loss * media packets)`), none under [`MIN_LOSS`], at most [`FecRate::max`]
//!   (half the block by default). Before any report the configured amount is sent.
//! * The FEC sent is taken out of the congestion controller's target on its way to the
//!   application ([`FecRate::media_target`]): the bit rate of the repair packets of the last
//!   second is subtracted, so media and FEC together stay at the target however the loss
//!   moves (RFC 5109 section 12), and the controller, which counts the repair packets on the
//!   wire, is not overrun.
//! * RFC 8854 section 8: "WebRTC implementations SHOULD prefer using RTX or Flexible FEC
//!   retransmissions instead of FEC when the connection RTT is within the application's latency
//!   budget, and otherwise SHOULD only transmit the amount of FEC needed to protect against the
//!   observed packet loss [...] unless the application indicates it is willing to pay a quality
//!   penalty to proactively avoid losses". The round trip is the one the RTCP session measured
//!   for a protected stream ([`RtcpSessionEvent::RoundTripTime`](crate::RtcpSessionEvent));
//!   while it is within the latency budget ([`FEC_DEFAULT_LATENCY_BUDGET`] unless the sender's
//!   builder names another) a stream that can be repaired by retransmission (RTX: `nack` and an
//!   RTX stream negotiated; or FlexFEC retransmissions on) gets no FEC
//!   ([`FecRate::fec_packets_with`]). No budget ([`FecRate::with_latency_budget`] `None`) is the
//!   application paying for proactive FEC: the amount then follows the loss whatever the round
//!   trip, as does a fixed amount (`adaptive` false).
//! * RFC 8627 section 8: "It is RECOMMENDED that the amount and type (row, column, or both) of
//!   FEC protection is adjusted dynamically based on the packet loss rate and burst loss length
//!   observed". The runs of lost packets are read from the per-packet congestion control
//!   feedback (transport-wide feedback, and RFC 8888 reports of the protected streams):
//!   [`FecRate::loss_pattern`] says whether the recent losses were isolated, in bursts, or both
//!   (section 1.1.3: rows recover random losses, columns bursts; section 1.1.4: both for mixed
//!   patterns).
//! * RFC 8627 section 8: "the applications MUST NOT arbitrarily increase the amount of FEC
//!   protection since doing so may lead to a congestion collapse. If desired, stronger FEC
//!   protection MAY be applied only after the source rate has been reduced." Once a congestion
//!   controller's target has gone by ([`Attribute::TargetBitrateChanged`]), more FEC than is
//!   sent now waits until the source's rate leaves room for it under that target: the source
//!   packets handed to the sender in the last second ([`FecRate::on_media_sent`]) plus the FEC
//!   the stronger amount would add (its share of the protected packets) within the target (5%
//!   tolerance for an encoder's aim). Meanwhile the target on its way to the application is
//!   lowered by the FEC asked for, not only by the FEC sent, so the application makes the room;
//!   when it passes no target, the lowered one rides up on the next inbound packet. Less FEC is
//!   never held. Without a target (no congestion controller in the chain) the amount follows
//!   the loss as before; [`FecRate::with_source_rate_first`] `false` turns the rule off.

use crate::rtpfb::acknowledgement::Acknowledgement;
use crate::{Attribute, Packet, TaggedPacket};
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

/// Smoothed loss under which no repair packet is sent: it would not help recover anything.
pub const MIN_LOSS: f64 = 0.005;
/// Weight of a new report in the smoothed loss.
const LOSS_WEIGHT: f64 = 0.3;
/// The window the FEC bit rate is measured over.
const RATE_WINDOW: Duration = Duration::from_secs(1);

/// The latency budget a FEC sender assumes when its builder names none: the round trip within
/// which a retransmission is preferred to FEC (RFC 8854 section 8). ITU-T G.114 (05/2003)
/// takes a one-way delay of up to 150 ms as acceptable to most interactive applications; a
/// retransmission delays the packet it repairs by about one round trip.
pub const FEC_DEFAULT_LATENCY_BUDGET: Duration = Duration::from_millis(150);

/// How far above the congestion controller's target the source and the stronger FEC may be
/// measured and still count as within it (RFC 8627 section 8; an encoder aims at its target and
/// lands about it).
const SOURCE_RATE_TOLERANCE: f64 = 0.05;
/// How far (of the target) the target for the application must fall before it is told again
/// while stronger FEC waits.
const ANNOUNCE_STEP: f64 = 0.01;

/// How many of the most recent runs of lost packets [`FecRate::loss_pattern`] reads.
const LOSS_RUN_WINDOW: usize = 32;
/// Runs of lost packets needed before a pattern is named.
const MIN_LOSS_RUNS: usize = 4;

/// What the recent losses of the path looked like (RFC 8627 sections 1.1.3, 1.1.4 and 8).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LossPattern {
    /// Isolated losses (fewer than a quarter of the runs of lost packets are longer than one):
    /// row (non-interleaved) protection recovers them.
    Random,
    /// Losses in bursts (more than three quarters of the runs are longer than one): column
    /// (interleaved) protection recovers a burst no longer than a row.
    Bursty,
    /// Both: rows and columns.
    Mixed,
}

/// Runs of consecutive lost packets, read from per-packet feedback, each sequence number space
/// (transport-wide, or one stream's RTP sequence numbers) on its own.
#[derive(Debug, Clone, Default)]
struct LossRuns {
    /// By space (`None`: transport-wide): the newest sequence number read and the length of the
    /// run of lost packets it ends, if it was lost.
    spaces: HashMap<Option<u32>, (u16, u32)>,
    /// The lengths of the most recent runs that ended, oldest first.
    runs: VecDeque<u32>,
}

impl LossRuns {
    fn close(&mut self, run: u32) {
        if run == 0 {
            return;
        }
        if self.runs.len() == LOSS_RUN_WINDOW {
            self.runs.pop_front();
        }
        self.runs.push_back(run);
    }

    fn on_acknowledgements(&mut self, space: Option<u32>, acknowledgements: &[Acknowledgement]) {
        for acknowledgement in acknowledgements {
            let sequence_number = acknowledgement.sequence_number;
            let open = match self.spaces.get(&space).copied() {
                Some((newest, open)) => {
                    let step = sequence_number.wrapping_sub(newest);
                    // Reported before (feedback ranges may overlap), or older.
                    if step == 0 || step >= 0x8000 {
                        continue;
                    }
                    // Packets no feedback reported: the run cannot be known to go on.
                    if step > 1 {
                        self.close(open);
                        0
                    } else {
                        open
                    }
                }
                None => 0,
            };
            let open = if acknowledgement.arrived {
                self.close(open);
                0
            } else {
                open + 1
            };
            self.spaces.insert(space, (sequence_number, open));
        }
    }

    fn pattern(&self) -> Option<LossPattern> {
        if self.runs.len() < MIN_LOSS_RUNS {
            return None;
        }
        let bursts = self.runs.iter().filter(|run| **run > 1).count();
        Some(if bursts * 4 < self.runs.len() {
            LossPattern::Random
        } else if bursts * 4 > self.runs.len() * 3 {
            LossPattern::Bursty
        } else {
            LossPattern::Mixed
        })
    }
}

/// The loss-driven amount of FEC for one sender. See the module documentation.
#[derive(Debug, Clone)]
pub struct FecRate {
    media_packets: u32,
    configured: u32,
    max: u32,
    adaptive: bool,
    loss: Option<f64>,
    /// Repair packets sent in the last [`RATE_WINDOW`]: when and how many octets.
    sent: VecDeque<(Instant, usize)>,
    /// The round trip within which retransmission is preferred to FEC; `None`: FEC whatever
    /// the round trip.
    latency_budget: Option<Duration>,
    /// The newest round trip measured to the receiver of a protected stream.
    round_trip_time: Option<Duration>,
    /// The runs of lost packets the feedback reported.
    loss_runs: LossRuns,
    /// Stronger FEC only after the source rate has been reduced (RFC 8627 section 8).
    source_rate_first: bool,
    /// The protection is a fixed shape (RFC 8627 rows / columns), sent whole or not at all: its
    /// cost is the configured amount whenever any is sent.
    fixed_shape: bool,
    /// Source packets handed to the sender in the last [`RATE_WINDOW`]: when, how many octets,
    /// and whether their stream is protected.
    media: VecDeque<(Instant, usize, bool)>,
    /// The octets of `media`, all and protected.
    media_octets: usize,
    protected_octets: usize,
    /// The newest congestion controller's target that went by, before the FEC was taken out.
    target: Option<f64>,
    /// The FEC (repair packets per source packet) in force since the rule applies: more waits
    /// for room under `target`. `None` until a target went by.
    granted: Option<f64>,
    /// The target the application was last told on this sender's way.
    announced: Option<f64>,
    /// Every protected stream can be repaired by retransmission (RTX, or FlexFEC's own: the
    /// encoder says so, [`FecRate::set_retransmission_repairable`]): while
    /// [`retransmission_preferred`](Self::retransmission_preferred) no FEC will be sent, so
    /// none is asked for, held or reserved.
    retransmission_repairable: bool,
}

impl FecRate {
    /// `fec_packets` repair packets per `media_packets` source packets until the loss is known;
    /// `adaptive` false keeps that amount whatever the loss.
    pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
        let media_packets = media_packets.max(1);
        Self {
            media_packets,
            configured: fec_packets,
            max: media_packets.div_ceil(2).max(fec_packets),
            adaptive,
            loss: None,
            sent: VecDeque::new(),
            latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
            round_trip_time: None,
            loss_runs: LossRuns::default(),
            source_rate_first: true,
            fixed_shape: false,
            media: VecDeque::new(),
            media_octets: 0,
            protected_octets: 0,
            target: None,
            granted: None,
            announced: None,
            retransmission_repairable: false,
        }
    }

    /// The encoder's word that every stream it protects can be repaired by retransmission (RTX,
    /// or FlexFEC retransmissions where RFC 8627 section 1.1.7 left FlexFEC alone), or not.
    /// While it does and [`retransmission_preferred`](Self::retransmission_preferred) holds, the
    /// encoder sends no FEC (RFC 8854 section 8), so nothing is asked for, held or taken out of
    /// the target for FEC that will not be sent.
    pub(crate) fn set_retransmission_repairable(&mut self, repairable: bool) {
        self.retransmission_repairable = repairable;
    }

    /// Whether FEC can be sent now: not while every protected stream is left to retransmission
    /// within the latency budget.
    fn fec_expected(&self) -> bool {
        !(self.retransmission_repairable && self.left_to_retransmission())
    }

    /// Whether a stream that can be repaired by retransmission gets no FEC now: while
    /// [`retransmission_preferred`](Self::retransmission_preferred), and, when the amount follows
    /// the loss within a latency budget, before any receiver report told the loss (RFC 8854
    /// section 8: retransmission is preferred within the budget, "and otherwise ... only the
    /// amount of FEC needed to protect against the observed packet loss": none is observed yet,
    /// and nothing says the round trip is beyond the budget). A stream without retransmission
    /// has nothing else, and keeps the configured amount until the loss is known.
    fn left_to_retransmission(&self) -> bool {
        self.retransmission_preferred()
            || (self.adaptive && self.latency_budget.is_some() && self.loss.is_none())
    }

    /// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8;
    /// the default): once a congestion controller's target went by, the amount of FEC rises
    /// only when the source sent in the last second plus the FEC the higher amount adds fit
    /// within that target, and the target for the application is lowered by the FEC asked for
    /// so the source makes the room. `false`: the amount follows the loss at once, and only
    /// the FEC sent is taken out of the target.
    pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
        self.source_rate_first = source_rate_first;
        self
    }

    /// Whether stronger FEC waits until the source rate has been reduced.
    pub fn source_rate_first(&self) -> bool {
        self.source_rate_first
    }

    /// The protection is a fixed shape (sent whole or not at all), whose cost is the configured
    /// amount whenever any is sent.
    pub(crate) fn with_fixed_shape(mut self, fixed_shape: bool) -> Self {
        self.fixed_shape = fixed_shape;
        self
    }

    /// A source packet of `size` octets was handed to the sender at `now`; `protected`: its
    /// stream is one this sender protects. Retransmissions and repair packets are not source
    /// packets.
    pub fn on_media_sent(&mut self, now: Instant, size: usize, protected: bool) {
        self.media.push_back((now, size, protected));
        self.media_octets += size;
        if protected {
            self.protected_octets += size;
        }
        self.admit(now);
    }

    /// Reads what an outbound packet tells the rate: an RTP packet that is no retransmission is
    /// a source packet ([`on_media_sent`](Self::on_media_sent)).
    pub(crate) fn on_write(&mut self, msg: &TaggedPacket, protected: impl Fn(u32) -> bool) {
        if let Packet::Rtp(rtp_packet) = &msg.message.packet
            && !msg.message.has(&Attribute::Retransmission)
        {
            let size = shared::marshal::MarshalSize::marshal_size(rtp_packet);
            self.on_media_sent(msg.now, size, protected(rtp_packet.header.ssrc));
        }
    }

    fn expire_media(&mut self, now: Instant) {
        while let Some(&(at, size, protected)) = self.media.front() {
            if now.saturating_duration_since(at) <= RATE_WINDOW {
                break;
            }
            self.media.pop_front();
            self.media_octets -= size;
            if protected {
                self.protected_octets -= size;
            }
        }
    }

    /// The bit rate of the source packets handed to the sender in the last second at `now`.
    pub fn media_bitrate(&mut self, now: Instant) -> f64 {
        self.expire_media(now);
        self.media_octets as f64 * 8.0 / RATE_WINDOW.as_secs_f64()
    }

    /// [`media_bitrate`](Self::media_bitrate) of the protected streams.
    fn protected_bitrate(&mut self, now: Instant) -> f64 {
        self.expire_media(now);
        self.protected_octets as f64 * 8.0 / RATE_WINDOW.as_secs_f64()
    }

    /// Whether the rule of RFC 8627 section 8 applies now: the amount follows the loss, the rule
    /// is on, and a congestion controller's target went by.
    fn gated(&self) -> bool {
        self.adaptive && self.source_rate_first && self.target.is_some() && self.fec_expected()
    }

    /// Repair packets per source packet the loss asks for (the configured shape's whole amount
    /// for a fixed shape).
    fn wanted_overhead(&self) -> f64 {
        let wanted = self.wanted_packets();
        if wanted == 0 {
            0.0
        } else if self.fixed_shape {
            f64::from(self.configured) / f64::from(self.media_packets)
        } else {
            f64::from(wanted) / f64::from(self.media_packets)
        }
    }

    /// Raises the FEC in force towards what the loss asks for as far as the source leaves room
    /// under the target, or lowers it to that at once.
    fn admit(&mut self, now: Instant) {
        if !self.gated() {
            return;
        }
        let wanted = self.wanted_overhead();
        let granted = *self.granted.get_or_insert(wanted);
        if wanted <= granted {
            self.granted = Some(wanted);
            return;
        }
        let Some(target) = self.target else {
            return;
        };
        let media = self.media_bitrate(now);
        let protected = self.protected_bitrate(now);
        let room = target * (1.0 + SOURCE_RATE_TOLERANCE) - media;
        let fits = if protected > 0.0 {
            room / protected
        } else if room >= 0.0 {
            wanted
        } else {
            0.0
        };
        let admitted = if self.fixed_shape {
            if fits >= wanted { wanted } else { granted }
        } else {
            // Whole repair packets per block.
            let block = f64::from(self.media_packets);
            (fits.min(wanted) * block + 1e-9).floor() / block
        };
        if admitted > granted {
            self.granted = Some(admitted);
        }
    }

    /// `wanted` repair packets for a block of `media_packets`, held to the FEC in force while
    /// the rule applies.
    fn held(&self, wanted: u32, media_packets: u32) -> u32 {
        let Some(granted) = self.granted.filter(|_| self.gated()) else {
            return wanted;
        };
        if self.fixed_shape {
            let whole = f64::from(self.configured) / f64::from(self.media_packets);
            return if granted + 1e-9 >= whole { wanted } else { 0 };
        }
        wanted.min((granted * f64::from(media_packets) - 1e-9).ceil().max(0.0) as u32)
    }

    /// The FEC to take out of the target on its way to the application at `now`: the FEC sent
    /// in the last second, or, while the rule is on, the FEC the loss asks for if that is more.
    ///
    /// The FEC asked for is that of a protected source at most the target: after a collapse of
    /// the target the source rate of the last second is no measure of the FEC to come, and the
    /// application must not be told to stop for it. None is asked for FEC that will not be sent
    /// ([`FecRate::set_retransmission_repairable`]).
    fn reserve(&mut self, now: Instant) -> f64 {
        let sent = self.fec_bitrate(now);
        if !(self.adaptive && self.source_rate_first) || !self.fec_expected() {
            return sent;
        }
        let protected = self.protected_bitrate(now);
        let source = self
            .target
            .map_or(protected, |target| protected.min(target));
        let asked = self.wanted_overhead() * source;
        sent.max(asked)
    }

    /// The round trip within which a stream that can be repaired by retransmission gets no FEC
    /// (RFC 8854 section 8); [`FEC_DEFAULT_LATENCY_BUDGET`] by default. `None` is the
    /// application paying for proactive FEC: the amount follows the loss whatever the round
    /// trip.
    pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
        self.latency_budget = latency_budget;
        self
    }

    /// The latency budget in force.
    pub fn latency_budget(&self) -> Option<Duration> {
        self.latency_budget
    }

    /// The newest round trip measured to the receiver of a protected stream.
    pub fn round_trip_time(&self) -> Option<Duration> {
        self.round_trip_time
    }

    /// A round trip measured to the receiver of a protected stream.
    pub fn on_round_trip_time(&mut self, round_trip_time: Duration) {
        self.round_trip_time = Some(round_trip_time);
    }

    /// Whether retransmission is to repair a stream that can be retransmitted, rather than FEC:
    /// the amount follows the loss, a latency budget is set, and the round trip measured is
    /// within it.
    pub fn retransmission_preferred(&self) -> bool {
        self.adaptive
            && matches!(
                (self.round_trip_time, self.latency_budget),
                (Some(round_trip_time), Some(budget)) if round_trip_time <= budget
            )
    }

    /// Repair packets for the next block of a stream; `retransmission`: whether the stream can
    /// be repaired by retransmission. None while [`retransmission_preferred`](Self::retransmission_preferred)
    /// or, for an amount that follows the loss within a latency budget, before any report told
    /// the loss; otherwise [`fec_packets`](Self::fec_packets).
    pub fn fec_packets_with(&self, retransmission: bool) -> u32 {
        if retransmission && self.left_to_retransmission() {
            0
        } else {
            self.fec_packets()
        }
    }

    /// Repair packets for a block of `media_packets` source packets that closed short (or is
    /// shorter than the configured block), as [`fec_packets_with`](Self::fec_packets_with)
    /// decides for a full one, and never more than the block has packets.
    pub fn fec_packets_for(&self, media_packets: u32, retransmission: bool) -> u32 {
        let media_packets = media_packets.max(1);
        if retransmission && self.left_to_retransmission() {
            return 0;
        }
        let wanted = match self.loss {
            Some(loss) if self.adaptive => {
                if loss < MIN_LOSS {
                    0
                } else {
                    ((2.0 * loss * f64::from(media_packets)).ceil() as u32)
                        .max(1)
                        .min(self.max)
                        .min(media_packets)
                }
            }
            _ => self.configured.min(media_packets),
        };
        self.held(wanted, media_packets)
    }

    /// Per-packet feedback for one sequence number space: `ssrc` names the stream an RFC 8888
    /// report is about, `None` is transport-wide feedback. Feeds [`loss_pattern`](Self::loss_pattern).
    pub fn on_acknowledgements(&mut self, ssrc: Option<u32>, acknowledgements: &[Acknowledgement]) {
        self.loss_runs.on_acknowledgements(ssrc, acknowledgements);
    }

    /// Whether the recent losses were isolated, in bursts, or both (the last 32 runs of lost
    /// packets; `None` before four runs were seen).
    pub fn loss_pattern(&self) -> Option<LossPattern> {
        self.loss_runs.pattern()
    }

    /// The most repair packets per block, whatever the loss.
    pub fn with_max(mut self, max: u32) -> Self {
        self.max = max;
        self
    }

    /// The most repair packets per block.
    pub fn max(&self) -> u32 {
        self.max
    }

    /// Whether the amount follows the loss (`false`: the configured amount whatever happens).
    pub fn adaptive(&self) -> bool {
        self.adaptive
    }

    /// The smoothed loss fraction, once a report gave one.
    pub fn loss(&self) -> Option<f64> {
        self.loss
    }

    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for a protected stream.
    pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
        let sample = f64::from(fraction_lost) / 256.0;
        self.loss = Some(match self.loss {
            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
            None => sample,
        });
    }

    /// Repair packets for the next block: what the loss asks for, held, while the rule of RFC
    /// 8627 section 8 applies, to the amount in force until the source leaves room for more.
    pub fn fec_packets(&self) -> u32 {
        self.held(self.wanted_packets(), self.media_packets)
    }

    /// Repair packets per block the loss asks for.
    fn wanted_packets(&self) -> u32 {
        match self.loss {
            Some(loss) if self.adaptive => {
                if loss < MIN_LOSS {
                    0
                } else {
                    // At least one, unless the bound allows none (`clamp` would panic on it).
                    ((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
                        .max(1)
                        .min(self.max)
                }
            }
            _ => self.configured,
        }
    }

    /// Whether any repair is to be sent now (for protection shapes whose amount is fixed:
    /// sent or not).
    pub fn protects(&self) -> bool {
        self.fec_packets() > 0
    }

    /// A repair packet of `size` octets left at `now`.
    pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
        self.sent.push_back((now, size));
        self.expire(now);
    }

    fn expire(&mut self, now: Instant) {
        while self
            .sent
            .front()
            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
        {
            self.sent.pop_front();
        }
    }

    /// The bit rate of the repair packets of the last second at `now`.
    pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
        self.expire(now);
        self.sent
            .iter()
            .map(|(_, size)| *size as f64 * 8.0)
            .sum::<f64>()
            / RATE_WINDOW.as_secs_f64()
    }

    /// The target the application encodes at, out of the congestion controller's `target`:
    /// what is left after the FEC (the FEC sent in the last second, or, while stronger FEC
    /// waits for the source to give up rate, the FEC asked for if that is more).
    pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
        (target - self.reserve(now)).max(0.0)
    }

    /// Reads what an inbound packet tells the FEC rate, and takes the FEC out of a target it
    /// carries: the receiver reports of `protected` streams feed the loss, the round trip the
    /// RTCP session measured to one of them the latency rule, per-packet feedback (transport-wide,
    /// and RFC 8888 reports on `protected` streams) the loss pattern, and an
    /// [`Attribute::TargetBitrateChanged`] on the packet is lowered by the FEC bit rate.
    pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
        if let Some(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }) =
            msg.message.custom::<crate::RtcpSessionEvent>()
            && protected(*ssrc)
        {
            self.round_trip_time = Some(*rtt);
        }
        if let Packet::Rtcp(packets) = &msg.message.packet {
            for packet in packets {
                let any = packet.as_any();
                if let Some(feedback) = any
                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc>(
                ) {
                    let acknowledgements = crate::rtpfb::convert::convert_twcc(feedback);
                    self.loss_runs.on_acknowledgements(None, &acknowledgements);
                    continue;
                }
                if let Some(feedback) = any
                    .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>(
                ) {
                    let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
                    for (ssrc, acknowledgements) in per_stream {
                        if protected(ssrc) {
                            self.loss_runs
                                .on_acknowledgements(Some(ssrc), &acknowledgements);
                        }
                    }
                    continue;
                }
                let reports = if let Some(rr) =
                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
                {
                    &rr.reports
                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
                    &sr.reports
                } else {
                    continue;
                };
                for report in reports {
                    if protected(report.ssrc) {
                        self.on_fraction_lost(report.fraction_lost);
                    }
                }
            }
        }
        let now = msg.now;
        // The congestion controller's target, before the FEC is taken out of it.
        for attribute in &msg.message.attributes {
            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute
                && bits_per_second.is_finite()
                && *bits_per_second >= 0.0
            {
                self.target = Some(*bits_per_second);
            }
        }
        self.admit(now);
        let reserve = self.reserve(now);
        let mut carried = false;
        for attribute in &mut msg.message.attributes {
            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
                carried = true;
                if reserve > 0.0 {
                    *bits_per_second = (*bits_per_second - reserve).max(0.0);
                }
                self.announced = Some(*bits_per_second);
            }
        }
        // RFC 8627 section 8: while stronger FEC waits for the source to give up rate, the
        // application is asked for the room even when no new target goes by.
        if !carried
            && self.gated()
            && let Some(target) = self.target.filter(|target| *target > 0.0)
            && self.wanted_overhead() > self.granted.unwrap_or(0.0) + 1e-9
        {
            let lowered = (target - reserve).max(0.0);
            if self
                .announced
                .is_none_or(|announced| lowered < announced - ANNOUNCE_STEP * target)
            {
                msg.message.add(Attribute::TargetBitrateChanged {
                    bits_per_second: lowered,
                });
                self.announced = Some(lowered);
            }
        } else if !carried && let (Some(target), Some(announced)) = (self.target, self.announced) {
            // A reservation that went (the loss fell, the FEC stopped, retransmission took
            // over) gives the room back: the controller's target need not move for the
            // application to hear of it, so the raised target rides up the same way.
            // A reservation gone to nothing gives the whole target back however small it was:
            // the step that keeps small moves quiet must not keep the application under the
            // controller's target for good while that target stands still.
            let raised = (target - reserve).max(0.0);
            if raised > announced + ANNOUNCE_STEP * target || (reserve == 0.0 && raised > announced)
            {
                msg.message.add(Attribute::TargetBitrateChanged {
                    bits_per_second: raised,
                });
                self.announced = Some(raised);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn before_any_report_the_configured_amount_is_sent() {
        assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
        assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
    }

    #[test]
    fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(0);
        assert_eq!(
            rate.fec_packets(),
            0,
            "repair that helps nothing is not sent"
        );
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(5); // 2%
        assert_eq!(rate.fec_packets(), 1);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(13); // 5%
        assert_eq!(rate.fec_packets(), 2);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51); // 20%
        assert_eq!(rate.fec_packets(), 4);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(200); // 78%
        assert_eq!(rate.fec_packets(), 5, "at most half the block");
    }

    #[test]
    fn the_loss_is_smoothed_over_reports() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51);
        rate.on_fraction_lost(0);
        let loss = rate.loss().unwrap();
        assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
        assert_eq!(rate.fec_packets(), 3);
    }

    #[test]
    fn a_fixed_rate_ignores_the_loss() {
        let mut rate = FecRate::new(10, 1, false);
        rate.on_fraction_lost(0);
        assert_eq!(rate.fec_packets(), 1);
        rate.on_fraction_lost(128);
        assert_eq!(rate.fec_packets(), 1);
    }

    fn carrier(now: Instant, target: Option<f64>, fraction_lost: Option<u8>) -> TaggedPacket {
        let mut packets: Vec<Box<dyn rtcp::Packet>> = Vec::new();
        if let Some(fraction_lost) = fraction_lost {
            packets.push(Box::new(rtcp::receiver_report::ReceiverReport {
                ssrc: 0x7777,
                reports: vec![rtcp::reception_report::ReceptionReport {
                    ssrc: 1000,
                    fraction_lost,
                    ..Default::default()
                }],
                ..Default::default()
            }));
        }
        let mut message = crate::AttributedPacket::new(Packet::Rtcp(packets));
        if let Some(bits_per_second) = target {
            message.add(Attribute::TargetBitrateChanged { bits_per_second });
        }
        TaggedPacket {
            now,
            transport: shared::TransportContext::default(),
            message,
        }
    }

    fn target_of(msg: &TaggedPacket) -> Option<f64> {
        msg.message
            .attributes
            .iter()
            .find_map(|attribute| match attribute {
                Attribute::TargetBitrateChanged { bits_per_second } => Some(*bits_per_second),
                _ => None,
            })
    }

    /// `count` source packets of 1000 octets of the protected stream, `interval_ms` apart from
    /// `from`; returns the instant of the last.
    fn source(rate: &mut FecRate, from: Instant, count: u64, interval_ms: u64) -> Instant {
        let mut at = from;
        for n in 0..count {
            at = from + Duration::from_millis(n * interval_ms);
            rate.on_media_sent(at, 1000, true);
        }
        at
    }

    /// RFC 8627 section 8: "stronger FEC protection MAY be applied only after the source rate
    /// has been reduced". A source at the 800 kbit/s target: the 20% loss asks for four repair
    /// packets per ten and gets the one in force; the application is told the target less the
    /// FEC asked for; once the source sent half as much for a second, the four go. Less FEC is
    /// never held.
    #[test]
    fn stronger_fec_waits_for_room_under_the_target_and_less_is_never_held() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(10, 1, true);
        let mut msg = carrier(t0, Some(800_000.0), None);
        rate.on_read(&mut msg, |_| true);
        assert_eq!(target_of(&msg), Some(800_000.0));
        let at = source(&mut rate, t0, 100, 10);
        assert!((rate.media_bitrate(at) - 800_000.0).abs() < 1e-6);
        rate.on_fraction_lost(51);
        assert_eq!(rate.loss_pattern(), None);
        assert_eq!(
            rate.fec_packets(),
            1,
            "the amount in force, not the four the loss asks for"
        );
        let at = source(&mut rate, at + Duration::from_millis(10), 1, 10);
        assert_eq!(rate.fec_packets(), 1, "the source has not slowed");
        let told = rate.media_target(at, 800_000.0);
        assert!(
            (told - 480_000.0).abs() < 10_000.0,
            "the application is asked for the room: {told}"
        );
        // A second at half the rate.
        let at = source(&mut rate, at + Duration::from_millis(20), 50, 20);
        assert!(rate.media_bitrate(at) <= 410_000.0);
        assert_eq!(rate.fec_packets(), 4, "the source gave the rate up");
        rate.on_fraction_lost(0);
        assert_eq!(rate.fec_packets(), 3, "less FEC at once");
    }

    /// Rows and columns are sent whole or not at all: they start only when the source leaves
    /// room for the whole shape (seven repair packets per twelve).
    #[test]
    fn a_fixed_shape_waits_for_room_for_the_whole_shape() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(12, 7, true).with_fixed_shape(true);
        rate.on_read(&mut carrier(t0, Some(800_000.0), Some(0)), |_| true);
        let at = source(&mut rate, t0, 100, 10);
        assert_eq!(rate.fec_packets(), 0, "no loss, no repair");
        rate.on_fraction_lost(51);
        assert_eq!(rate.fec_packets(), 0, "no room for 7/12 more");
        // A second at about 570 kbit/s: room for the two repair packets the loss asks for,
        // not for the seven of the shape.
        let at = source(&mut rate, at + Duration::from_millis(14), 72, 14);
        let media = rate.media_bitrate(at);
        assert!(media > 560_000.0 && media < 580_000.0, "{media}");
        assert_eq!(rate.fec_packets(), 0, "no room for the whole shape");
        let at = source(&mut rate, at + Duration::from_millis(20), 50, 20);
        assert!(rate.media_bitrate(at) <= 410_000.0);
        assert!(rate.fec_packets() > 0, "room for the shape");
    }

    /// While stronger FEC waits and no target goes by, the lowered target rides up on an inbound
    /// packet, once until it falls further.
    #[test]
    fn a_held_increase_asks_the_application_for_room() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(10, 1, true);
        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
        let at = source(&mut rate, t0, 100, 10);
        let mut report = carrier(at, None, Some(51));
        rate.on_read(&mut report, |_| true);
        assert_eq!(rate.fec_packets(), 1, "held at the amount in force");
        let told = target_of(&report).expect("the room is asked for");
        assert!((told - 480_000.0).abs() < 10_000.0, "{told}");
        let mut again = carrier(at + Duration::from_millis(5), None, None);
        rate.on_read(&mut again, |_| true);
        assert_eq!(target_of(&again), None, "told once");
    }

    /// RFC 8854 section 8: a stream that retransmission repairs gets no FEC within the latency
    /// budget, so none is reserved either. Every protected stream repairable by retransmission,
    /// a 20 ms round trip, 20 % loss: the 800 kbit/s target reaches the application whole and
    /// no FEC is asked for (the same loss without the encoder's word reserves 320 kbit/s).
    #[test]
    fn no_fec_is_reserved_while_retransmission_repairs_every_protected_stream() {
        let t0 = Instant::now();
        for repairable in [true, false] {
            let mut rate = FecRate::new(10, 1, true);
            rate.set_retransmission_repairable(repairable);
            rate.on_round_trip_time(Duration::from_millis(20));
            rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
            let at = source(&mut rate, t0, 100, 10);
            rate.on_fraction_lost(51);
            let told = rate.media_target(at, 800_000.0);
            if repairable {
                assert_eq!(told, 800_000.0, "nothing reserved");
                assert_eq!(rate.fec_packets_with(true), 0, "no FEC sent");
            } else {
                assert!((told - 480_000.0).abs() < 10_000.0, "reserved: {told}");
            }
        }
    }

    /// After a collapse of the target, the FEC asked for is that of a source at the target, not
    /// at the rate of the second before: a source at 2.4 Mbit/s whose target falls to 300 kbit/s
    /// at 20 % loss is told 300 kbit/s less four tenths of it (180 kbit/s), not to stop.
    #[test]
    fn the_fec_asked_for_is_that_of_a_source_at_the_target() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(10, 1, true);
        rate.on_read(&mut carrier(t0, Some(2_400_000.0), None), |_| true);
        // 2.4 Mbit/s: 300 packets of 1000 octets in a second.
        let mut at = t0;
        for n in 0..300u64 {
            at = t0 + Duration::from_micros(n * 3_333);
            rate.on_media_sent(at, 1000, true);
        }
        rate.on_fraction_lost(51);
        let mut collapse = carrier(at, Some(300_000.0), None);
        rate.on_read(&mut collapse, |_| true);
        let told = target_of(&collapse).expect("the target");
        assert!((told - 180_000.0).abs() < 5_000.0, "{told}");
    }

    /// A reservation that goes gives its room back without waiting for the controller's target
    /// to move: once retransmission takes the stream over (a round trip within the budget) the
    /// next inbound packet carries the whole target again.
    #[test]
    fn a_released_reservation_gives_the_room_back() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(10, 1, true);
        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
        let at = source(&mut rate, t0, 100, 10);
        let mut report = carrier(at, None, Some(51));
        rate.on_read(&mut report, |_| true);
        let lowered = target_of(&report).expect("the room is asked for");
        assert!(lowered < 600_000.0, "{lowered}");
        rate.set_retransmission_repairable(true);
        rate.on_round_trip_time(Duration::from_millis(20));
        let mut later = carrier(at + Duration::from_millis(5), None, None);
        rate.on_read(&mut later, |_| true);
        assert_eq!(target_of(&later), Some(800_000.0), "the room given back");
    }

    /// RFC 8854 section 8 before the first receiver report: nothing is observed, so a stream
    /// that retransmission can repair gets no FEC and none is reserved (the default chain's
    /// open link sent two repair packets before the first report, and the application's target
    /// was the start rate less them); a stream without retransmission, or an application that
    /// named no latency budget, keeps the configured amount; once the loss is reported it
    /// decides, the round trip still unknown.
    #[test]
    fn before_any_report_a_stream_retransmission_repairs_gets_no_fec() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(5, 2, true);
        rate.set_retransmission_repairable(true);
        assert_eq!(rate.fec_packets_with(true), 0);
        assert_eq!(rate.fec_packets_for(3, true), 0);
        assert_eq!(rate.fec_packets_with(false), 2, "no retransmission: FEC");
        let mut start = carrier(t0, Some(300_000.0), None);
        rate.on_read(&mut start, |_| true);
        let at = source(&mut rate, t0, 50, 10);
        assert_eq!(
            rate.media_target(at, 300_000.0),
            300_000.0,
            "nothing reserved"
        );
        rate.on_fraction_lost(51);
        assert_eq!(rate.fec_packets_with(true), 2, "the loss reported decides");
        let proactive = FecRate::new(5, 2, true).with_latency_budget(None);
        assert_eq!(
            proactive.fec_packets_with(true),
            2,
            "no budget: proactive FEC"
        );
    }

    /// A reservation that fell to nothing gives the whole target back however small it was: a
    /// repair packet of 2472 octets took 19.8 kbit/s off a 2.5 Mbit/s target that then stood
    /// still (the open link's maximum), under the step a re-announcement waits for (1 % of the
    /// target), and the application stayed under the maximum for the rest of the call.
    #[test]
    fn a_reservation_gone_to_nothing_gives_the_whole_target_back() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(5, 2, true);
        rate.on_repair_sent(t0, 2472);
        let mut at_max = carrier(t0, Some(2_500_000.0), None);
        rate.on_read(&mut at_max, |_| true);
        assert_eq!(target_of(&at_max), Some(2_500_000.0 - 19_776.0));
        let mut later = carrier(t0 + Duration::from_millis(1_500), None, None);
        rate.on_read(&mut later, |_| true);
        assert_eq!(
            target_of(&later),
            Some(2_500_000.0),
            "the whole target again"
        );
    }

    /// Without a congestion controller's target, or with the rule off, the amount follows the
    /// loss at once (and only the FEC sent comes out of the target).
    #[test]
    fn without_a_target_or_with_the_rule_off_the_amount_follows_the_loss_at_once() {
        let t0 = Instant::now();
        let mut rate = FecRate::new(10, 1, true);
        let at = source(&mut rate, t0, 100, 10);
        rate.on_fraction_lost(51);
        assert_eq!(rate.fec_packets(), 4);
        let mut rate = FecRate::new(10, 1, true).with_source_rate_first(false);
        assert!(!rate.source_rate_first());
        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
        source(&mut rate, t0, 100, 10);
        rate.on_fraction_lost(51);
        assert_eq!(rate.fec_packets(), 4);
        assert_eq!(rate.media_target(at, 800_000.0), 800_000.0);
    }

    #[test]
    fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
        let mut rate = FecRate::new(10, 1, true);
        let now = Instant::now();
        for n in 0..10u64 {
            rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
        }
        let at = now + Duration::from_millis(950);
        assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
        assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
        // A second later the repair has aged out.
        assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
    }

    /// RFC 8854 section 8: retransmission is preferred to FEC while the round trip is within
    /// the latency budget, for a stream that can be retransmitted; otherwise the amount
    /// follows the loss.
    #[test]
    fn within_the_latency_budget_a_stream_with_rtx_gets_no_fec() {
        let mut rate = FecRate::new(10, 1, true);
        assert_eq!(rate.latency_budget(), Some(FEC_DEFAULT_LATENCY_BUDGET));
        rate.on_fraction_lost(51); // 20%
        assert_eq!(rate.fec_packets(), 4, "precondition: the loss asks for FEC");
        assert_eq!(rate.fec_packets_with(true), 4, "no round trip measured yet");
        rate.on_round_trip_time(Duration::from_millis(80));
        assert!(rate.retransmission_preferred());
        assert_eq!(
            rate.fec_packets_with(true),
            0,
            "RTX repairs within the budget"
        );
        assert_eq!(rate.fec_packets_for(3, true), 0);
        assert_eq!(
            rate.fec_packets_with(false),
            4,
            "a stream without RTX keeps its FEC"
        );
        rate.on_round_trip_time(FEC_DEFAULT_LATENCY_BUDGET + Duration::from_millis(1));
        assert_eq!(
            rate.fec_packets_with(true),
            4,
            "beyond the budget FEC follows the loss"
        );
        // No budget: the application pays for proactive FEC.
        let mut rate = FecRate::new(10, 1, true).with_latency_budget(None);
        rate.on_fraction_lost(51);
        rate.on_round_trip_time(Duration::from_millis(1));
        assert_eq!(rate.fec_packets_with(true), 4);
        // A fixed amount was asked for explicitly.
        let mut rate = FecRate::new(10, 2, false);
        rate.on_round_trip_time(Duration::from_millis(1));
        assert_eq!(rate.fec_packets_with(true), 2);
    }

    /// A block that closed short gets its share of the repair, never more packets than it has.
    #[test]
    fn a_short_block_gets_its_share_of_the_repair() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51); // 20%: 4 for 10 packets
        assert_eq!(rate.fec_packets_for(10, false), 4);
        assert_eq!(rate.fec_packets_for(3, false), 2);
        assert_eq!(rate.fec_packets_for(1, false), 1);
        let rate = FecRate::new(10, 3, false);
        assert_eq!(rate.fec_packets_for(2, false), 2);
    }

    fn session_round_trip(ssrc: u32, rtt: Duration) -> TaggedPacket {
        TaggedPacket {
            now: Instant::now(),
            transport: shared::TransportContext::default(),
            message: crate::AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
                std::sync::Arc::new(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }),
            )),
        }
    }

    /// The round trip the RTCP session measured to the receiver of a protected stream is the
    /// one the latency rule reads; another stream's is not.
    #[test]
    fn the_round_trip_the_rtcp_session_measured_to_a_protected_stream_is_read() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_read(
            &mut session_round_trip(7, Duration::from_millis(40)),
            |ssrc| ssrc == 9,
        );
        assert_eq!(rate.round_trip_time(), None, "not a protected stream");
        rate.on_read(
            &mut session_round_trip(9, Duration::from_millis(40)),
            |ssrc| ssrc == 9,
        );
        assert_eq!(rate.round_trip_time(), Some(Duration::from_millis(40)));
    }

    fn acks(statuses: &[(u16, bool)]) -> Vec<Acknowledgement> {
        statuses
            .iter()
            .map(|&(sequence_number, arrived)| {
                if arrived {
                    Acknowledgement::received(
                        sequence_number,
                        None,
                        rtcp::transport_feedbacks::cc_feedback_report::Ecn::NotEct,
                    )
                } else {
                    Acknowledgement::lost(sequence_number)
                }
            })
            .collect()
    }

    /// A run of `lost` packets lost then one received, from `first`.
    fn run(first: u16, lost: u16) -> Vec<(u16, bool)> {
        (0..lost)
            .map(|offset| (first.wrapping_add(offset), false))
            .chain(std::iter::once((first.wrapping_add(lost), true)))
            .collect()
    }

    /// RFC 8627 sections 1.1.3, 1.1.4 and 8: isolated losses, bursts, and both, read from the
    /// runs of lost packets.
    #[test]
    fn isolated_losses_bursts_and_both_are_told_apart() {
        let pattern = |runs: &[u16]| {
            let mut rate = FecRate::new(12, 7, true);
            let mut at = 1000u16;
            for lost in runs {
                rate.on_acknowledgements(None, &acks(&run(at, *lost)));
                at = at.wrapping_add(lost + 1);
            }
            rate.loss_pattern()
        };
        assert_eq!(pattern(&[1, 1, 1]), None, "too few runs to tell");
        assert_eq!(pattern(&[1; 8]), Some(LossPattern::Random));
        assert_eq!(
            pattern(&[1, 1, 1, 1, 1, 1, 1, 2]),
            Some(LossPattern::Random)
        );
        assert_eq!(pattern(&[3; 8]), Some(LossPattern::Bursty));
        assert_eq!(pattern(&[1, 4, 1, 4, 1, 4, 1, 4]), Some(LossPattern::Mixed));
        // The window is the last 32 runs: bursts long ago are forgotten.
        let mut runs = vec![3u16; 32];
        runs.extend([1u16; 32]);
        assert_eq!(pattern(&runs), Some(LossPattern::Random));
    }

    /// A packet reported twice (overlapping feedback) is read once, a run cut by packets no
    /// report covered is not taken as going on, and the streams of RFC 8888 reports are runs
    /// of their own.
    #[test]
    fn feedback_is_read_once_per_packet_and_per_sequence_space() {
        let mut rate = FecRate::new(12, 7, true);
        // Four bursts of two, each report repeating the packets of the one before.
        let mut previous: Vec<(u16, bool)> = Vec::new();
        for first in [10u16, 13, 16, 19] {
            let mut report = previous.clone();
            report.extend(run(first, 2));
            rate.on_acknowledgements(None, &acks(&report));
            previous = run(first, 2);
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
        // Isolated losses on two streams, interleaved: neither joins the other's runs.
        let mut rate = FecRate::new(12, 7, true);
        for first in [100u16, 102, 104, 106] {
            rate.on_acknowledgements(Some(1), &acks(&run(first, 1)));
            rate.on_acknowledgements(Some(2), &acks(&run(first, 1)));
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
        // Lost packets on either side of a stretch no report covered are two runs.
        let mut rate = FecRate::new(12, 7, true);
        for first in [200u16, 300, 400, 500] {
            rate.on_acknowledgements(None, &acks(&[(first, false)]));
            rate.on_acknowledgements(None, &acks(&[(first + 50, false), (first + 51, true)]));
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
    }

    /// Transport-wide feedback read through `on_read` feeds the pattern; an RFC 8888 report
    /// only for a protected stream.
    #[test]
    fn per_packet_feedback_on_the_read_path_feeds_the_loss_pattern() {
        use rtcp::transport_feedbacks::transport_layer_cc::{
            PacketStatusChunk, RecvDelta, RunLengthChunk, SymbolTypeTcc, TransportLayerCc,
        };
        let chunk = |symbol, run_length| {
            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
                packet_status_symbol: symbol,
                run_length,
                ..Default::default()
            })
        };
        let mut rate = FecRate::new(12, 7, true);
        let mut base = 500u16;
        for _ in 0..4 {
            // Three lost, then two received.
            let feedback = TransportLayerCc {
                base_sequence_number: base,
                packet_status_count: 5,
                packet_chunks: vec![
                    chunk(SymbolTypeTcc::PacketNotReceived, 3),
                    chunk(SymbolTypeTcc::PacketReceivedSmallDelta, 2),
                ],
                recv_deltas: vec![
                    RecvDelta {
                        delta: 1000,
                        ..Default::default()
                    };
                    2
                ],
                ..Default::default()
            };
            let mut msg = TaggedPacket {
                now: Instant::now(),
                transport: shared::TransportContext::default(),
                message: crate::AttributedPacket::new(Packet::Rtcp(vec![Box::new(feedback)])),
            };
            rate.on_read(&mut msg, |_| true);
            base = base.wrapping_add(5);
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
    }

    /// A fixed corpus of arbitrary report and send sequences: the repair per block stays
    /// within zero and the bound, the media target never goes negative or above the target it
    /// is cut from, and the FEC bit rate never goes negative.
    #[test]
    fn arbitrary_reports_keep_the_rate_within_its_bounds() {
        let mut state = 0x0FEC_0001u32;
        let mut next = move || {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            state >> 8
        };
        for _ in 0..300 {
            let media = 1 + next() % 48;
            let configured = next() % 8;
            let mut rate = FecRate::new(media, configured, next() % 4 != 0);
            if next() % 3 == 0 {
                rate = rate.with_max(next() % 30);
            }
            let mut at = Instant::now();
            for _ in 0..300 {
                at += Duration::from_millis(u64::from(next() % 200));
                match next() % 3 {
                    0 => rate.on_fraction_lost(next() as u8),
                    1 => rate.on_repair_sent(at, (next() % 1500) as usize),
                    _ => {
                        let k = rate.fec_packets();
                        assert!(k <= rate.max().max(configured), "{k} over the bound");
                        let target = f64::from(next() % 5_000_000);
                        let media_target = rate.media_target(at, target);
                        assert!((0.0..=target).contains(&media_target));
                        assert!(rate.fec_bitrate(at) >= 0.0);
                    }
                }
            }
        }
    }
}