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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
//! Redundant audio data, RED (RFC 2198), for the audio streams whose m= section negotiated a
//! RED format (`a=rtpmap:<pt> red/48000/2`, `a=fmtp:<pt> 111/111`).
//!
//! RFC 8854 section 4.2 has a WebRTC endpoint support RED for audio; Chromium and WebKit
//! offer it with Opus as both the primary and the redundant encoding (the fmtp lists the Opus
//! payload type twice), the form RFC 2198 section 3 allows ("a copy of the primary MAY be
//! used as the redundancy").
//!
//! - **Send, when.** Negotiating RED does not by itself make the sender use it
//!   ([`AudioRedundancy`], [`RedAudioBuilder::with_audio_redundancy`]). By default a local
//!   stream is sent in RED only when its remote description lists the RED format ahead of the
//!   stream's primary encoding: RFC 3264 sections 5.1 and 6.1 have the formats of an m= line
//!   "listed in order of preference", and the sender "SHOULD use the format with the highest
//!   preference"; RFC 2198 section 5 reads a section that leads with `red` as "the sender will
//!   send redundancy by default, but also may send" the others. libwebrtc decides the same way
//!   (`WebRtcVoiceSendChannel::SetSendCodecs`: "RED codec needs to be negotiated before the
//!   actual codec they reference"), and Chromium and WebKit list RED after Opus, in their
//!   offers and their answers alike, so neither they nor this engine send it between each
//!   other by default. RFC 8854 section 4.1 recommends Opus's own in-band FEC over RED for
//!   Opus, and section 8 has FEC sent only for the loss observed or when the application asks:
//!   [`AudioRedundancy::Always`] is that request.
//! - **Send, when the loss asks for it.** With [`RedAudioBuilder::with_redundancy_on_loss`]
//!   (off by default), a stream that negotiated RED and is not otherwise sent in it (under
//!   [`AudioRedundancy::WhenPreferred`]) goes in RED while the loss its receiver reports is
//!   0.5% or more ([`RED_AUDIO_LOSS_ON`], smoothed over reports as `FecRate` smooths it), and
//!   back to the primary once it falls under half that: RFC 8854 section 5, "FEC should only
//!   be activated if network conditions warrant it", and section 7, "Use of these formats
//!   when sending ... is RECOMMENDED", within section 8's limits: not while the loss is
//!   congestion loss (the congestion controller's estimate fell in the last
//!   [`RED_AUDIO_CONGESTION_HOLD`]: "if the loss is caused by network congestion, the
//!   additional bandwidth used by the redundant data may actually make the situation worse"),
//!   and only while the target leaves room for the redundancy above the controller's floor and
//!   the audio ("the total amount of data must remain within any bandwidth limits indicated by
//!   congestion control"). What RED adds is taken out of the target the application encodes
//!   at.
//! - **Send, how.** A packet of a local stream sent in RED, whose payload type is the primary
//!   of the negotiated RED format, leaves as a RED packet: the RED payload type in the header,
//!   the copies of the last [`RedAudioBuilder::with_redundancy`] primaries (one by default, as
//!   Chromium sends) before the new primary, the header otherwise the primary's (RFC 2198
//!   section 3). A primary too large to be wrapped, or of another payload type (comfort noise,
//!   DTMF), leaves as it is: the receiver negotiated it too. A packet written with a
//!   [`RedundantEncoding`] (another, lower-bitrate encoding of its audio, RFC 8854 section 4.1:
//!   "redundant encoding with reduced-bitrate Opus encodings") is carried as that encoding in
//!   the packets after it instead of a copy.
//! - **Receive.** A RED packet of a remote stream is taken apart into the packets of its
//!   blocks (RFC 2198 section 4): the primary with the RED packet's sequence number, marker
//!   and CSRCs, and the earlier primaries a lost packet carried, recovered from the redundant
//!   blocks with the sequence numbers they had (one packet per block, as the encoder above and
//!   Chromium send them), no marker ("the marker bit ... is lost") and the RED packet's CSRCs.
//!   Nothing is delivered twice (`RedDecoder`). What arrives after this interceptor (the NACK
//!   generator, the jitter buffer, the application) sees the primary encoding only. Received
//!   RED is taken apart whatever the [`AudioRedundancy`] setting: the setting is about what
//!   this side sends, and RFC 8854 section 7 has an endpoint "receive and make use of" the FEC
//!   formats it indicated.
//!
//! # Where it belongs
//!
//! [`Slot::Redundancy`](crate::Slot::Redundancy) (10_450). On the write leg it is
//! application-ward of the NACK responder (4_000) and the FEC encoder (5_000): what is
//! buffered for retransmission and protected is the RED packet on the wire. On the read leg it
//! is application-ward of the receiver report (10_000) and the FEC decoder (10_300), which
//! count and repair the RED packets that arrived, and wire-ward of the NACK generator
//! (10_600), which then does not ask for a packet RED recovered.

use crate::stream_info::StreamInfo;
use crate::{Interceptor, Packet, TaggedPacket};
use bytes::Bytes;
use rtp::codec::red::{RedDecoder, RedEncoder, RedPacket, parse_red_fmtp};
use sansio::Protocol;
use shared::error::Error;
use std::collections::{HashMap, VecDeque};
use std::time::Instant;

/// How many earlier primaries a RED packet carries by default: one, as Chromium sends Opus
/// RED.
pub const RED_AUDIO_DEFAULT_REDUNDANCY: usize = 1;

/// The largest RED payload the sender builds by default: redundant blocks that would make
/// the payload larger are left out (an Opus packet is far smaller), so that a RED packet
/// stays within the path MTU the application sized the primary for, with the header, its
/// extensions and the SRTP tag.
pub const RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;

/// The smoothed loss at which a stream sent in RED on loss
/// ([`RedAudioBuilder::with_redundancy_on_loss`]) goes in RED: the loss under which the FEC
/// senders send no repair ([`FEC_MIN_LOSS`](crate::FEC_MIN_LOSS)). It goes back to the primary
/// under half of it.
pub const RED_AUDIO_LOSS_ON: f64 = crate::cc::fec_rate::MIN_LOSS;

/// Weight of a new receiver report in the smoothed loss (as `FecRate` smooths it).
const LOSS_WEIGHT: f64 = 0.3;

/// Another encoding of a packet's audio, for the RED packets after it to carry instead of a
/// copy of the packet (RFC 8854 section 4.1: when multi-packet protection is needed,
/// "redundant encoding with reduced-bitrate Opus encodings SHOULD be used"; RFC 2198 section 3:
/// "the redundant encoding shall use significantly less bandwidth"). The engine does not
/// encode audio: the application's encoder makes it, at the primary's payload type and
/// timestamp, and puts it on the packet it writes as [`Attribute::Custom`](crate::Attribute::Custom).
/// One larger than the primary is not used (RFC 2198: it "MUST NOT be higher bandwidth than
/// the primary"); a stream not sent in RED ignores it.
///
/// ```
/// use bytes::Bytes;
/// use rtci_interceptor::{Attribute, AttributedPacket, Packet, RedundantEncoding};
/// use std::sync::Arc;
///
/// # let primary = rtp::Packet::default();
/// let low_bitrate = Bytes::from_static(&[0x08, 0x01, 0x02]);
/// let message = AttributedPacket::new(Packet::Rtp(primary))
///     .with(Attribute::Custom(Arc::new(RedundantEncoding::new(low_bitrate))));
/// # let _ = message;
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RedundantEncoding {
    /// The payload of the other encoding.
    pub payload: Bytes,
}

impl RedundantEncoding {
    /// `payload` as the redundant encoding of the packet it rides on.
    pub fn new(payload: Bytes) -> Self {
        Self { payload }
    }
}

/// When a local audio stream whose section negotiated RED (RFC 2198) is sent in RED. Received
/// RED is taken apart in every case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AudioRedundancy {
    /// In RED when the remote description lists the RED format ahead of the stream's primary
    /// encoding, the remote side's preference (RFC 3264 sections 5.1 and 6.1; libwebrtc's
    /// rule too). Chromium and WebKit list it after Opus, so a call with them carries plain
    /// Opus. The default.
    #[default]
    WhenPreferred,
    /// In RED whenever RED is negotiated, whatever its place on the m= line: the application's
    /// request for redundancy (RFC 8854 section 8). Each packet then carries a copy of the
    /// one before, about doubling the audio bitrate.
    Always,
    /// Never in RED, even when the remote side prefers it (RFC 3264's "SHOULD" set aside).
    Never,
}

/// Builder for [`RedAudioInterceptor`].
#[derive(Debug, Clone)]
pub struct RedAudioBuilder {
    redundancy: usize,
    max_payload_size: usize,
    audio_redundancy: AudioRedundancy,
    redundancy_on_loss: bool,
}

impl Default for RedAudioBuilder {
    fn default() -> Self {
        Self {
            redundancy: RED_AUDIO_DEFAULT_REDUNDANCY,
            max_payload_size: RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE,
            audio_redundancy: AudioRedundancy::default(),
            redundancy_on_loss: false,
        }
    }
}

impl RedAudioBuilder {
    /// One earlier primary per packet, payloads of at most
    /// [`RED_AUDIO_DEFAULT_MAX_PAYLOAD_SIZE`] octets, sent in RED when the remote side prefers
    /// it ([`AudioRedundancy::WhenPreferred`]).
    pub fn new() -> Self {
        Self::default()
    }

    /// When a local stream that negotiated RED is sent in RED; see [`AudioRedundancy`].
    pub fn with_audio_redundancy(mut self, audio_redundancy: AudioRedundancy) -> Self {
        self.audio_redundancy = audio_redundancy;
        self
    }

    /// How many earlier primaries each RED packet carries (0 sends RED packets with the
    /// primary alone).
    pub fn with_redundancy(mut self, redundancy: usize) -> Self {
        self.redundancy = redundancy;
        self
    }

    /// The largest RED payload built; redundant blocks that would exceed it are left out.
    pub fn with_max_payload_size(mut self, max_payload_size: usize) -> Self {
        self.max_payload_size = max_payload_size;
        self
    }

    /// Under [`AudioRedundancy::WhenPreferred`], also send a stream that negotiated RED, and
    /// whose remote side did not prefer it, in RED while the loss its receiver reports is at
    /// least [`RED_AUDIO_LOSS_ON`] (smoothed), back to the primary under half of it (RFC 8854
    /// sections 5, 7 and 8). Off by default: see the module documentation.
    pub fn with_redundancy_on_loss(mut self, redundancy_on_loss: bool) -> Self {
        self.redundancy_on_loss = redundancy_on_loss;
        self
    }

    /// The interceptor.
    pub fn build(self) -> RedAudioInterceptor {
        RedAudioInterceptor {
            config: self,
            senders: HashMap::new(),
            redundancy_sent: VecDeque::new(),
            primaries_sent: VecDeque::new(),
            estimate: None,
            target: None,
            minimum: 0.0,
            estimate_fell: None,
            receivers: HashMap::new(),
            read_queue: VecDeque::new(),
            write_queue: VecDeque::new(),
        }
    }
}

struct SendStream {
    red_payload_type: u8,
    primary_payload_type: u8,
    encoder: RedEncoder,
    /// The sequence number of the last primary wrapped.
    last_sequence_number: Option<u16>,
    /// Sent in RED only while `lossy` ([`RedAudioBuilder::with_redundancy_on_loss`]).
    on_loss: bool,
    /// The loss the receiver reports, smoothed.
    loss: Option<f64>,
    /// Whether the loss asks for RED: on at [`RED_AUDIO_LOSS_ON`], off under half of it.
    lossy: bool,
}

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

    /// Whether the packets written now go in RED, `room` the congestion state's answer for the
    /// loss rule ([`RedAudioInterceptor::room_for_redundancy`]).
    fn sends_red(&self, room: bool) -> bool {
        !self.on_loss || (self.lossy && room)
    }
}

struct ReceiveStream {
    red_payload_type: u8,
    decoder: RedDecoder,
    /// The ids of the stream's audio level extensions (RFC 6464 `ssrc-audio-level`, RFC 6465
    /// `csrc-audio-level`): what a packet rebuilt from a redundant block takes from the RED
    /// packet that carried it, as an approximation (RFC 8854 section 4.1).
    level_extensions: Vec<u8>,
}

/// The ids `info` negotiated the audio level extensions under.
fn level_extension_ids(info: &StreamInfo) -> Vec<u8> {
    info.rtp_header_extensions
        .iter()
        .filter(|extension| {
            extension.uri == rtp::extension::AUDIO_LEVEL_URI
                || extension.uri == rtp::extension::CSRC_AUDIO_LEVEL_URI
        })
        .filter_map(|extension| u8::try_from(extension.id).ok())
        .collect()
}

/// How long after a fall of the congestion controller's estimate RED is not turned on by loss
/// (RFC 8854 section 8: redundancy against congestion loss "may actually make the situation
/// worse"): the loss of a path whose estimate is falling is congestion loss.
pub const RED_AUDIO_CONGESTION_HOLD: std::time::Duration = std::time::Duration::from_secs(5);
/// A fall of the estimate by more than this share counts as a decrease.
const ESTIMATE_DECREASE: f64 = 0.05;

/// How long the redundancy sent is measured over, for what is taken out of the target.
const REDUNDANCY_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(1);
/// The shortest span the redundancy rate is computed over (the first packets after RED went on).
const REDUNDANCY_RATE_MIN_SPAN: std::time::Duration = std::time::Duration::from_millis(200);

/// RFC 2198 audio redundancy for the streams that negotiated it; see the module
/// documentation.
pub struct RedAudioInterceptor {
    config: RedAudioBuilder,
    senders: HashMap<u32, SendStream>,
    /// The octets RED added to the packets sent (the redundant blocks and the RED headers),
    /// and when, over the last [`REDUNDANCY_RATE_WINDOW`]: RFC 8854 section 8, "the total
    /// amount of data must remain within any bandwidth limits indicated by congestion
    /// control", so their rate is taken out of the congestion controller's target on its way
    /// to the application (as the FEC encoders take out theirs, `FecRate`).
    redundancy_sent: VecDeque<(Instant, usize)>,
    /// The primaries of the streams sent in RED on loss, and when: (octets on the wire, payload
    /// octets), over the last [`REDUNDANCY_RATE_WINDOW`]: the audio rate, and what a copy of it
    /// would add.
    primaries_sent: VecDeque<(Instant, usize, usize)>,
    /// The congestion controller's last estimate (`SendEstimate`), its last target for the
    /// application as it reaches this interceptor, and its floor (`MinimumTarget`).
    estimate: Option<f64>,
    target: Option<f64>,
    minimum: f64,
    /// When the estimate last fell by more than [`ESTIMATE_DECREASE`].
    estimate_fell: Option<Instant>,
    receivers: HashMap<u32, ReceiveStream>,
    read_queue: VecDeque<TaggedPacket>,
    write_queue: VecDeque<TaggedPacket>,
}

impl Default for RedAudioInterceptor {
    fn default() -> Self {
        RedAudioBuilder::new().build()
    }
}

/// The RED format of an audio stream's m= section and its primary encoding: a format named
/// `red` (RFC 2198 section 5) whose fmtp lists only `primary`, the stream's payload type, as
/// the primary and every redundant encoding (the copy-of-the-primary form this interceptor
/// sends and Chromium and WebKit offer). `None` for a video stream or a section without one.
fn negotiated_red(info: &StreamInfo, primary: u8) -> Option<u8> {
    if !info.mime_type.to_ascii_lowercase().starts_with("audio/") {
        return None;
    }
    info.section_mime_types
        .iter()
        .filter(|(_, mime_type)| mime_type.to_ascii_lowercase().ends_with("/red"))
        .find_map(|(payload_type, _)| {
            let fmtp = info
                .section_fmtp_lines
                .iter()
                .find(|(pt, _)| pt == payload_type)
                .map(|(_, fmtp)| fmtp.trim())?;
            let encodings = parse_red_fmtp(fmtp).ok()?;
            encodings
                .iter()
                .all(|pt| *pt == primary)
                .then_some(*payload_type)
        })
}

/// Whether the stream's section lists the RED format `red` ahead of the stream's own payload
/// type: the remote side prefers redundancy (RFC 3264 sections 5.1 and 6.1). The section's
/// formats are in the order of the m= line of the description whose numbering the stream
/// uses, the remote one for a local stream.
fn red_is_preferred(info: &StreamInfo, red: u8) -> bool {
    let position = |payload_type: u8| {
        info.section_mime_types
            .iter()
            .position(|(pt, _)| *pt == payload_type)
    };
    matches!(
        (position(red), position(info.payload_type)),
        (Some(red), Some(primary)) if red < primary
    )
}

impl RedAudioInterceptor {
    /// Reads what the congestion controller says on its way to the application: its estimate
    /// (and whether it fell), its target and its floor.
    fn observe_congestion(&mut self, msg: &TaggedPacket) {
        if let Some(estimate) = msg.message.custom::<crate::SendEstimate>() {
            let estimate = estimate.bits_per_second;
            if self
                .estimate
                .is_some_and(|previous| estimate < previous * (1.0 - ESTIMATE_DECREASE))
            {
                self.estimate_fell = Some(msg.now);
            }
            self.estimate = Some(estimate);
        }
        if let Some(minimum) = msg.message.custom::<crate::MinimumTarget>() {
            self.minimum = minimum.bits_per_second;
        }
        for attribute in &msg.message.attributes {
            if let crate::Attribute::TargetBitrateChanged { bits_per_second } = attribute {
                // A controller that announces no estimate (`GccInterceptor`): its target's
                // fall is the estimate's.
                if self.estimate.is_none()
                    && self.target.is_some_and(|previous| {
                        *bits_per_second < previous * (1.0 - ESTIMATE_DECREASE)
                    })
                {
                    self.estimate_fell = Some(msg.now);
                }
                self.target = Some(*bits_per_second);
            }
        }
    }

    /// RFC 8854 sections 7 and 8, the loss rule within the congestion limits: whether a stream
    /// that negotiated RED may be sent in it on reported loss. Not while the loss is congestion
    /// loss (the estimate fell less than [`RED_AUDIO_CONGESTION_HOLD`] ago: "if the loss is
    /// caused by network congestion, the additional bandwidth used by the redundant data may
    /// actually make the situation worse"), and only while the target leaves room for it above
    /// the floor and the audio ("the total amount of data must remain within any bandwidth
    /// limits indicated by congestion control"): target - floor - audio >= redundancy, the
    /// redundancy that sent, or a copy of the primaries. With no congestion controller in the
    /// chain (no target seen), the loss alone decides.
    fn room_for_redundancy(&mut self, now: Instant) -> bool {
        let Some(target) = self.target else {
            return true;
        };
        if self
            .estimate_fell
            .is_some_and(|fell| now.saturating_duration_since(fell) < RED_AUDIO_CONGESTION_HOLD)
        {
            return false;
        }
        while self
            .primaries_sent
            .front()
            .is_some_and(|(at, _, _)| now.saturating_duration_since(*at) > REDUNDANCY_RATE_WINDOW)
        {
            self.primaries_sent.pop_front();
        }
        let span = self
            .primaries_sent
            .front()
            .map_or(REDUNDANCY_RATE_MIN_SPAN, |(first, _, _)| {
                now.saturating_duration_since(*first)
                    .max(REDUNDANCY_RATE_MIN_SPAN)
            })
            .as_secs_f64();
        let (wire, payload, packets) = self
            .primaries_sent
            .iter()
            .fold((0usize, 0usize, 0usize), |(w, p, n), (_, wire, payload)| {
                (w + wire, p + payload, n + 1)
            });
        let audio = wire as f64 * 8.0 / span;
        // A copy of each primary per level of redundancy, with its 4-octet block header.
        let copy = (payload + 4 * packets) as f64 * 8.0 / span * self.config.redundancy as f64;
        let redundancy = self.redundancy_bits_per_second(now).max(copy);
        target - self.minimum - audio >= redundancy
    }

    /// The bit rate of what RED added to the packets sent, over the last
    /// [`REDUNDANCY_RATE_WINDOW`] (at least [`REDUNDANCY_RATE_MIN_SPAN`] of it).
    fn redundancy_bits_per_second(&mut self, now: Instant) -> f64 {
        while self
            .redundancy_sent
            .front()
            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > REDUNDANCY_RATE_WINDOW)
        {
            self.redundancy_sent.pop_front();
        }
        let Some((first, _)) = self.redundancy_sent.front() else {
            return 0.0;
        };
        let span = now
            .saturating_duration_since(*first)
            .max(REDUNDANCY_RATE_MIN_SPAN)
            .as_secs_f64();
        let octets: usize = self.redundancy_sent.iter().map(|(_, octets)| octets).sum();
        octets as f64 * 8.0 / span
    }

    /// A target on its way to the application (`TargetBitrateChanged`) is lowered by the rate
    /// of the redundancy sent, to half of it at most (RFC 8854 section 8).
    fn lower_target(&mut self, msg: &mut TaggedPacket) {
        if !msg
            .message
            .attributes
            .iter()
            .any(|attribute| matches!(attribute, crate::Attribute::TargetBitrateChanged { .. }))
        {
            return;
        }
        let redundancy = self.redundancy_bits_per_second(msg.now);
        if redundancy <= 0.0 {
            return;
        }
        for attribute in &mut msg.message.attributes {
            if let crate::Attribute::TargetBitrateChanged { bits_per_second } = attribute {
                *bits_per_second = (*bits_per_second - redundancy).max(*bits_per_second / 2.0);
            }
        }
    }

    /// The RED payload type a local stream may be sent with, and whether only while the loss
    /// asks for it ([`RedAudioBuilder::with_redundancy_on_loss`]); `None` to send it as it is.
    fn red_mode(&self, info: &StreamInfo) -> Option<(u8, bool)> {
        if let Some(red) = self.red_to_send(info) {
            return Some((red, false));
        }
        if self.config.redundancy_on_loss
            && self.config.audio_redundancy == AudioRedundancy::WhenPreferred
        {
            return negotiated_red(info, info.payload_type).map(|red| (red, true));
        }
        None
    }

    /// The RED payload type a local stream is sent with under the builder's
    /// [`AudioRedundancy`], or `None` to send it as it is.
    fn red_to_send(&self, info: &StreamInfo) -> Option<u8> {
        let red = negotiated_red(info, info.payload_type)?;
        match self.config.audio_redundancy {
            AudioRedundancy::Always => Some(red),
            AudioRedundancy::WhenPreferred => red_is_preferred(info, red).then_some(red),
            AudioRedundancy::Never => None,
        }
    }

    /// The RTP packets of the blocks of the RED packet `packet` (RFC 2198 section 4), each
    /// not yet delivered, the recovered ones first.
    fn take_apart(stream: &mut ReceiveStream, packet: &rtp::Packet) -> Vec<rtp::Packet> {
        // The timestamps of the redundant blocks in header order, oldest first: block `i` of
        // `n` was the primary of the packet `n - i` before this one.
        let redundant: Vec<u32> = match RedPacket::parse(&packet.payload) {
            Ok(red) => red
                .redundant()
                .iter()
                .map(|block| block.timestamp(packet.header.timestamp))
                .collect(),
            Err(_) => return vec![],
        };
        let Ok(blocks) = stream.decoder.decode_rtp(packet) else {
            return vec![];
        };
        blocks
            .into_iter()
            .map(|recovered| {
                let mut header = packet.header.clone();
                header.payload_type = recovered.block.payload_type;
                header.timestamp = recovered.block.timestamp;
                header.marker = recovered.marker;
                header.csrc = recovered.csrc;
                if !recovered.block.primary {
                    let back = redundant
                        .iter()
                        .position(|ts| *ts == recovered.block.timestamp)
                        .map_or(1, |i| redundant.len() - i);
                    header.sequence_number = header.sequence_number.wrapping_sub(back as u16);
                    // The extensions and padding were the RED packet's. RFC 8854 section 4.1:
                    // the header parts RED cannot recover, "RTP header extensions like those
                    // specified in [RFC6464] and [RFC6465]", are approximated "using an
                    // approach similar to those described in [RFC2198], Section 4": as RFC
                    // 2198 applies the RED packet's CSRCs to the rebuilt data, the rebuilt
                    // packet takes the RED packet's audio levels (one packet later in time,
                    // the nearest measure there is). Every other extension is left out.
                    let levels: Vec<(u8, bytes::Bytes)> = stream
                        .level_extensions
                        .iter()
                        .filter_map(|id| packet.header.get_extension(*id).map(|v| (*id, v)))
                        .collect();
                    header.extension = false;
                    header.extensions.clear();
                    header.extension_profile = 0;
                    header.extensions_padding = 0;
                    for (id, value) in levels {
                        // The RED packet carried it in this form, so it fits.
                        let _ = header.set_extension(id, value);
                    }
                }
                header.padding = false;
                rtp::Packet {
                    header,
                    payload: recovered.block.data,
                }
            })
            .collect()
    }
}

impl Protocol<TaggedPacket, TaggedPacket, ()> for RedAudioInterceptor {
    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> {
        // The congestion state the loss rule reads (before this interceptor lowers the target).
        self.observe_congestion(&msg);
        // RFC 8854 section 8: what RED adds is taken out of the target the application
        // encodes at, so media and redundancy together stay within the estimate.
        self.lower_target(&mut msg);
        // The receiver reports of the streams sent in RED on loss.
        if let Packet::Rtcp(packets) = &msg.message.packet
            && self.senders.values().any(|stream| stream.on_loss)
        {
            for packet in packets {
                let any = packet.as_any();
                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 let Some(stream) = self.senders.get_mut(&report.ssrc)
                        && stream.on_loss
                    {
                        stream.on_fraction_lost(report.fraction_lost);
                    }
                }
            }
        }
        let red = match &msg.message.packet {
            Packet::Rtp(packet) => self
                .receivers
                .get(&packet.header.ssrc)
                .is_some_and(|stream| packet.header.payload_type == stream.red_payload_type),
            Packet::Rtcp(_) => false,
        };
        if !red {
            self.read_queue.push_back(msg);
            return Ok(());
        }
        let Packet::Rtp(packet) = &msg.message.packet else {
            return Ok(());
        };
        let Some(stream) = self.receivers.get_mut(&packet.header.ssrc) else {
            return Ok(());
        };
        // A malformed RED payload, or one whose every block was delivered: nothing goes on.
        for media in Self::take_apart(stream, packet) {
            self.read_queue.push_back(TaggedPacket {
                now: msg.now,
                transport: msg.transport,
                message: crate::AttributedPacket {
                    attributes: msg.message.attributes.clone(),
                    packet: Packet::Rtp(media),
                },
            });
        }
        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> {
        let redundant = msg
            .message
            .custom::<RedundantEncoding>()
            .map(|redundant| redundant.payload.clone());
        if let Packet::Rtp(packet) = &mut msg.message.packet
            && !packet.payload.is_empty()
            && let Some(stream) = self.senders.get_mut(&packet.header.ssrc)
            && packet.header.payload_type == stream.primary_payload_type
        {
            // The receiver numbers a recovered block one packet back per block (RFC 2198
            // section 4 leaves the sequence number of redundant data to it): a copy goes only
            // into the packet right after the one it was the primary of.
            if stream
                .last_sequence_number
                .is_some_and(|last| last.wrapping_add(1) != packet.header.sequence_number)
            {
                stream.encoder.reset();
            }
            stream.last_sequence_number = Some(packet.header.sequence_number);
            let on_loss = stream.on_loss;
            let size = (
                shared::marshal::MarshalSize::marshal_size(&*packet),
                packet.payload.len(),
            );
            let room = !on_loss || self.room_for_redundancy(msg.now);
            if on_loss {
                self.primaries_sent.push_back((msg.now, size.0, size.1));
            }
            let Some(stream) = self.senders.get_mut(&packet.header.ssrc) else {
                self.write_queue.push_back(msg);
                return Ok(());
            };
            if stream.sends_red(room) {
                // A primary that does not fit a RED payload goes as it is.
                let red = match redundant {
                    Some(redundant) => stream.encoder.encode_rtp_with_redundant(
                        stream.red_payload_type,
                        packet,
                        redundant,
                    ),
                    None => stream.encoder.encode_rtp(stream.red_payload_type, packet),
                };
                if let Ok(red) = red {
                    let added = red.payload.len().saturating_sub(packet.payload.len());
                    *packet = red;
                    if added > 0 {
                        self.redundancy_sent.push_back((msg.now, added));
                    }
                }
            } else {
                // Not in RED while the loss does not ask for it: the first RED packet after
                // carries no copy of a packet that left as the primary.
                stream.encoder.reset();
            }
        }
        self.write_queue.push_back(msg);
        Ok(())
    }

    fn poll_write(&mut self) -> Option<Self::Wout> {
        self.write_queue.pop_front()
    }

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

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

impl Interceptor for RedAudioInterceptor {
    fn bind_local_stream(&mut self, info: &StreamInfo) {
        match self.red_mode(info) {
            Some((red_payload_type, on_loss)) => {
                let stream = self.senders.entry(info.ssrc).or_insert(SendStream {
                    red_payload_type,
                    primary_payload_type: info.payload_type,
                    encoder: RedEncoder::new(self.config.redundancy, self.config.max_payload_size),
                    last_sequence_number: None,
                    on_loss,
                    loss: None,
                    lossy: false,
                });
                stream.on_loss = on_loss;
                if (stream.red_payload_type, stream.primary_payload_type)
                    != (red_payload_type, info.payload_type)
                {
                    stream.red_payload_type = red_payload_type;
                    stream.primary_payload_type = info.payload_type;
                    stream.encoder.reset();
                }
            }
            None => {
                self.senders.remove(&info.ssrc);
            }
        }
    }

    fn unbind_local_stream(&mut self, info: &StreamInfo) {
        self.senders.remove(&info.ssrc);
    }

    fn bind_remote_stream(&mut self, info: &StreamInfo) {
        match negotiated_red(info, info.payload_type) {
            Some(red_payload_type) => {
                let stream = self.receivers.entry(info.ssrc).or_insert(ReceiveStream {
                    red_payload_type,
                    decoder: RedDecoder::default(),
                    level_extensions: vec![],
                });
                stream.red_payload_type = red_payload_type;
                stream.level_extensions = level_extension_ids(info);
            }
            None => {
                self.receivers.remove(&info.ssrc);
            }
        }
    }

    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
        self.receivers.remove(&info.ssrc);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AttributedPacket, TaggedPacket};
    use bytes::Bytes;
    use shared::TransportContext;

    const OPUS: u8 = 111;
    const RED: u8 = 63;

    /// A stream whose section lists Opus, then RED (Chromium's and WebKit's order).
    fn info(ssrc: u32, red_fmtp: &str) -> StreamInfo {
        StreamInfo {
            ssrc,
            payload_type: OPUS,
            mime_type: "audio/opus".to_owned(),
            clock_rate: 48_000,
            channels: 2,
            section_mime_types: vec![
                (OPUS, "audio/opus".to_owned()),
                (RED, "audio/red".to_owned()),
            ],
            section_fmtp_lines: vec![
                (OPUS, "minptime=10;useinbandfec=1".to_owned()),
                (RED, red_fmtp.to_owned()),
            ],
            ..Default::default()
        }
    }

    /// [`info`] with RED listed ahead of Opus: the remote side prefers redundancy.
    fn info_red_first(ssrc: u32, red_fmtp: &str) -> StreamInfo {
        let mut info = info(ssrc, red_fmtp);
        info.section_mime_types.reverse();
        info.section_fmtp_lines.reverse();
        info
    }

    /// The payload type the first packet of a fresh stream leaves `sender` with.
    fn sent_payload_type(sender: &mut RedAudioInterceptor, ssrc: u32) -> u8 {
        sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
        rtp(sender.poll_write().unwrap()).header.payload_type
    }

    fn opus(ssrc: u32, sequence_number: u16, payload: &'static [u8]) -> TaggedPacket {
        TaggedPacket {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
                header: rtp::header::Header {
                    version: 2,
                    ssrc,
                    payload_type: OPUS,
                    sequence_number,
                    timestamp: u32::from(sequence_number) * 960,
                    marker: sequence_number == 1,
                    ..Default::default()
                },
                payload: Bytes::from_static(payload),
            })),
        }
    }

    fn rtp(msg: TaggedPacket) -> rtp::Packet {
        match msg.message.packet {
            Packet::Rtp(packet) => packet,
            Packet::Rtcp(_) => panic!("RTP expected"),
        }
    }

    /// RFC 2198 sections 3 and 4 through one sender and one receiver: the sender, whose remote
    /// side lists RED first, wraps each Opus packet with a copy of the one before; the receiver
    /// gives back each primary, and, for the packet lost on the way, the copy the next packet
    /// carried, with its sequence number and timestamp and no marker.
    #[test]
    fn red_packets_carry_the_previous_primary_and_recover_a_loss() {
        let mut sender = RedAudioBuilder::new().build();
        let mut receiver = RedAudioBuilder::new().build();
        sender.bind_local_stream(&info_red_first(1, "111/111"));
        receiver.bind_remote_stream(&info(1, "111/111"));

        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
        let mut wire = vec![];
        for (i, payload) in payloads.iter().enumerate() {
            sender.handle_write(opus(1, i as u16 + 1, payload)).unwrap();
            let red = rtp(sender.poll_write().unwrap());
            assert_eq!(red.header.payload_type, RED);
            assert_eq!(red.header.sequence_number, i as u16 + 1);
            let blocks = RedPacket::parse(&red.payload).unwrap();
            assert_eq!(blocks.primary().data.as_ref(), *payload);
            assert_eq!(blocks.redundant().len(), usize::from(i > 0));
            wire.push(red);
        }
        // The third packet is lost.
        let mut delivered = vec![];
        for (i, red) in wire.into_iter().enumerate() {
            if i == 2 {
                continue;
            }
            receiver
                .handle_read(TaggedPacket {
                    now: Instant::now(),
                    transport: TransportContext::default(),
                    message: AttributedPacket::new(Packet::Rtp(red)),
                })
                .unwrap();
            while let Some(out) = receiver.poll_read() {
                delivered.push(rtp(out));
            }
        }
        let got: Vec<(u16, u32, u8, bool, &[u8])> = delivered
            .iter()
            .map(|p| {
                (
                    p.header.sequence_number,
                    p.header.timestamp,
                    p.header.payload_type,
                    p.header.marker,
                    p.payload.as_ref(),
                )
            })
            .collect();
        assert_eq!(
            got,
            vec![
                (1, 960, OPUS, true, b"one".as_ref()),
                (2, 1920, OPUS, false, b"two".as_ref()),
                (3, 2880, OPUS, false, b"three".as_ref()),
                (4, 3840, OPUS, false, b"four".as_ref()),
            ]
        );
    }

    /// Sends `payloads` through `sender`, each RED packet given header extensions by `extend`,
    /// loses the packets at `lost` (indices) and returns what `receiver` delivered.
    fn through(
        sender: &mut RedAudioInterceptor,
        receiver: &mut RedAudioInterceptor,
        payloads: &[&'static [u8]],
        lost: &[usize],
        extend: impl Fn(usize, &mut rtp::header::Header),
    ) -> Vec<rtp::Packet> {
        let mut delivered = vec![];
        for (i, payload) in payloads.iter().enumerate() {
            // `extend` writes the primary's header (its CSRCs and extensions): what the RED
            // packet carries of it is the sender's doing.
            let mut primary = opus(1, i as u16 + 1, payload);
            if let Packet::Rtp(packet) = &mut primary.message.packet {
                extend(i, &mut packet.header);
            }
            sender.handle_write(primary).unwrap();
            let red = rtp(sender.poll_write().unwrap());
            if lost.contains(&i) {
                continue;
            }
            receiver
                .handle_read(TaggedPacket {
                    now: Instant::now(),
                    transport: TransportContext::default(),
                    message: AttributedPacket::new(Packet::Rtp(red)),
                })
                .unwrap();
            while let Some(out) = receiver.poll_read() {
                delivered.push(rtp(out));
            }
        }
        delivered
    }

    /// RFC 8854 section 4.1: "the recommended mechanisms do not allow recovery of parts of the
    /// RTP header that may be important in certain audio applications, e.g., CSRCs and RTP
    /// header extensions like those specified in [RFC6464] and [RFC6465]. Implementations
    /// SHOULD account for this and attempt to approximate this information, using an approach
    /// similar to those described in [RFC2198], Section 4". A packet rebuilt from a redundant
    /// block takes the audio levels of the RED packet that carried it (as RFC 2198 section 4
    /// applies that packet's CSRCs), and no other extension of it. RFC 6464 section 3: with
    /// redundancy the level describes the primary encoding: each primary is written with its
    /// own level, and the RED packet the sender makes of it carries that level.
    #[test]
    fn a_rebuilt_packet_takes_the_audio_levels_of_the_red_packet_that_carried_it() {
        const LEVEL: u8 = 1;
        const CSRC_LEVELS: u8 = 2;
        const OTHER: u8 = 3;
        let mut sender = RedAudioBuilder::new().build();
        let mut receiver = RedAudioBuilder::new().build();
        sender.bind_local_stream(&info_red_first(1, "111/111"));
        let mut remote = info(1, "111/111");
        for (uri, id) in [
            (rtp::extension::AUDIO_LEVEL_URI, LEVEL),
            (rtp::extension::CSRC_AUDIO_LEVEL_URI, CSRC_LEVELS),
            (
                "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
                OTHER,
            ),
        ] {
            remote
                .rtp_header_extensions
                .push(crate::RTPHeaderExtension {
                    uri: uri.to_owned(),
                    id: u16::from(id),
                });
        }
        receiver.bind_remote_stream(&remote);

        let payloads: [&'static [u8]; 4] = [b"one", b"two", b"three", b"four"];
        let delivered = through(&mut sender, &mut receiver, &payloads, &[2], |i, header| {
            header.csrc = vec![77];
            let level = 0x80 | (10 + i as u8);
            header
                .set_extension(LEVEL, Bytes::from(vec![level]))
                .unwrap();
            header
                .set_extension(CSRC_LEVELS, Bytes::from(vec![20 + i as u8]))
                .unwrap();
            header
                .set_extension(OTHER, Bytes::from(vec![1, 2, 3]))
                .unwrap();
        });
        let rebuilt = delivered
            .iter()
            .find(|p| p.header.sequence_number == 3)
            .expect("the lost packet is rebuilt");
        assert_eq!(rebuilt.payload.as_ref(), b"three");
        assert_eq!(
            rebuilt.header.get_extension(LEVEL).as_deref(),
            Some([0x80 | 13].as_ref()),
            "the audio level of the packet that carried it"
        );
        assert_eq!(
            rebuilt.header.get_extension(CSRC_LEVELS).as_deref(),
            Some([23].as_ref())
        );
        assert_eq!(rebuilt.header.csrc, vec![77]);
        assert_eq!(rebuilt.header.get_extension(OTHER), None, "nothing else");
        // The primaries keep their own extensions.
        let primary = delivered
            .iter()
            .find(|p| p.header.sequence_number == 4)
            .unwrap();
        assert_eq!(
            primary.header.get_extension(LEVEL).as_deref(),
            Some([0x80 | 13].as_ref())
        );
        assert!(primary.header.get_extension(OTHER).is_some());
    }

    /// RFC 8854 section 4.1: "if multi-packet protection is needed, the aforementioned
    /// redundant encoding ... SHOULD be used instead". With two redundant blocks per packet
    /// (`with_redundancy(2)`) two consecutive losses are both rebuilt from the packet after
    /// them; with one, only the second of them.
    #[test]
    fn two_redundant_blocks_rebuild_two_consecutive_losses() {
        let payloads: [&'static [u8]; 5] = [b"one", b"two", b"three", b"four", b"five"];
        for (redundancy, rebuilt) in [(2usize, vec![2u16, 3]), (1, vec![3])] {
            let mut sender = RedAudioBuilder::new().with_redundancy(redundancy).build();
            let mut receiver = RedAudioBuilder::new().build();
            sender.bind_local_stream(&info_red_first(1, "111/111/111"));
            receiver.bind_remote_stream(&info(1, "111/111/111"));
            let delivered = through(&mut sender, &mut receiver, &payloads, &[1, 2], |_, _| {});
            let got: Vec<u16> = delivered
                .iter()
                .map(|p| p.header.sequence_number)
                .filter(|seq| [2, 3].contains(seq))
                .collect();
            assert_eq!(got, rebuilt, "redundancy {redundancy}");
            for packet in &delivered {
                assert_eq!(
                    packet.payload.as_ref(),
                    payloads[usize::from(packet.header.sequence_number) - 1]
                );
            }
        }
    }

    /// A receiver report on `ssrc` with `fraction_lost` (in 1/256).
    fn report(fraction_lost: u8, ssrc: u32) -> TaggedPacket {
        TaggedPacket {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
                rtcp::receiver_report::ReceiverReport {
                    ssrc: 0x7777,
                    reports: vec![rtcp::reception_report::ReceptionReport {
                        ssrc,
                        fraction_lost,
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            )])),
        }
    }

    /// RFC 8854 sections 7 and 8: the loss rule acts within the congestion limits. A stream that
    /// negotiated RED, its receiver reporting loss, 150-octet Opus every 20 ms (about 65 kbit/s
    /// with the header; a copy adds about 62): with a target of 1 Mbit/s above a 100 kbit/s floor
    /// it goes in RED; once the estimate falls (1 Mbit/s to 230 kbit/s: the loss is congestion
    /// loss) it goes as Opus for `RED_AUDIO_CONGESTION_HOLD`; after that, with a target of 200
    /// kbit/s that leaves no room above the floor and the audio for a copy, still Opus; with the
    /// estimate and the target back at 1 Mbit/s, RED again.
    #[test]
    fn red_on_loss_waits_for_room_and_stays_off_for_congestion_loss() {
        use std::time::Duration;
        let epoch = Instant::now();
        let mut sender = RedAudioBuilder::new().with_redundancy_on_loss(true).build();
        sender.bind_local_stream(&info(1, "111/111"));
        sender.handle_read(report(64, 1)).unwrap();
        while sender.poll_read().is_some() {}
        let mut seq = 0u16;
        let mut at = Duration::ZERO;
        // Writes a second of packets from `at` on; returns the payload type of the last.
        let mut second = |sender: &mut RedAudioInterceptor| {
            let mut last = 0;
            for _ in 0..50 {
                seq += 1;
                let mut packet = opus(1, seq, &[0x5a; 150]);
                packet.now = epoch + at;
                sender.handle_write(packet).unwrap();
                last = rtp(sender.poll_write().unwrap()).header.payload_type;
                at += Duration::from_millis(20);
            }
            (last, epoch + at)
        };
        let told = |sender: &mut RedAudioInterceptor, now: Instant, estimate: f64, target: f64| {
            let carrier = TaggedPacket {
                now,
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtcp(vec![]))
                    .with(crate::Attribute::TargetBitrateChanged {
                        bits_per_second: target,
                    })
                    .with(crate::Attribute::Custom(std::sync::Arc::new(
                        crate::SendEstimate {
                            bits_per_second: estimate,
                        },
                    )))
                    .with(crate::Attribute::Custom(std::sync::Arc::new(
                        crate::MinimumTarget {
                            bits_per_second: 100_000.0,
                        },
                    ))),
            };
            sender.handle_read(carrier).unwrap();
            while sender.poll_read().is_some() {}
        };
        told(&mut sender, epoch, 1_000_000.0, 1_000_000.0);
        let (last, now) = second(&mut sender);
        assert_eq!(last, RED, "room, and the estimate steady: RED");
        told(&mut sender, now, 230_000.0, 230_000.0);
        let (last, _) = second(&mut sender);
        assert_eq!(last, OPUS, "the estimate fell: congestion loss, no RED");
        let mut now = epoch;
        for _ in 0..5 {
            now = second(&mut sender).1;
        }
        assert!(now > epoch + Duration::from_secs(1) + RED_AUDIO_CONGESTION_HOLD);
        told(&mut sender, now, 230_000.0, 200_000.0);
        let (last, now) = second(&mut sender);
        assert_eq!(last, OPUS, "no room above the floor and the audio: no RED");
        told(&mut sender, now, 1_000_000.0, 1_000_000.0);
        let (last, _) = second(&mut sender);
        assert_eq!(last, RED, "room again: RED");
    }

    /// RFC 8854 section 8: "the total amount of data must remain within any bandwidth limits
    /// indicated by congestion control". A stream sent in RED on loss: one second of 20 ms
    /// packets of 150 octets each carry a copy of the one before (155 octets more, about 62
    /// kbit/s), and the congestion controller's target of 300 kbit/s reaches the application
    /// lowered by that rate, so the media it encodes and the redundancy fit the estimate
    /// together. Without the loss nothing is added and the target passes as it came.
    #[test]
    fn the_redundancy_sent_is_taken_out_of_the_target() {
        let epoch = Instant::now();
        let target_after = |loss: u8| {
            let mut sender = RedAudioBuilder::new().with_redundancy_on_loss(true).build();
            sender.bind_local_stream(&info(1, "111/111"));
            sender.handle_read(report(loss, 1)).unwrap();
            while sender.poll_read().is_some() {}
            let mut red = 0;
            for n in 0..50u16 {
                let mut packet = opus(1, n + 1, &[0x5a; 150]);
                packet.now = epoch + std::time::Duration::from_millis(20 * u64::from(n));
                sender.handle_write(packet).unwrap();
                red += usize::from(rtp(sender.poll_write().unwrap()).header.payload_type == RED);
            }
            let carrier = TaggedPacket {
                now: epoch + std::time::Duration::from_millis(1000),
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtcp(vec![])).with(
                    crate::Attribute::TargetBitrateChanged {
                        bits_per_second: 300_000.0,
                    },
                ),
            };
            sender.handle_read(carrier).unwrap();
            let out = sender.poll_read().unwrap();
            let target = out.message.attributes.iter().find_map(|a| match a {
                crate::Attribute::TargetBitrateChanged { bits_per_second } => {
                    Some(*bits_per_second)
                }
                _ => None,
            });
            (red, target.unwrap())
        };
        let (red, target) = target_after(64);
        assert_eq!(red, 50, "the precondition: the loss turned RED on");
        assert!(
            (230_000.0..=245_000.0).contains(&target),
            "300 kbit/s less about 62 kbit/s of redundancy: {target}"
        );
        assert_eq!(
            target_after(0),
            (0, 300_000.0),
            "no loss, no RED: the target as it came"
        );
    }

    /// RFC 8854 section 5 ("FEC should only be activated if network conditions warrant it")
    /// and section 7 ("Use of these formats when sending ... is RECOMMENDED"): with
    /// `with_redundancy_on_loss`, a stream whose remote side lists RED after Opus goes as Opus
    /// until its receiver reports loss of 0.5% or more (smoothed), then in RED, and back to
    /// Opus once the smoothed loss is under half of that. Another stream's report changes
    /// nothing; without the setting the loss changes nothing.
    #[test]
    fn with_redundancy_on_loss_red_follows_the_reported_loss() {
        let mut sender = RedAudioBuilder::new().with_redundancy_on_loss(true).build();
        sender.bind_local_stream(&info(1, "111/111"));
        let mut seq = 0u16;
        let mut send = |sender: &mut RedAudioInterceptor| {
            seq += 1;
            sender.handle_write(opus(1, seq, b"opus")).unwrap();
            rtp(sender.poll_write().unwrap())
        };
        let read = |sender: &mut RedAudioInterceptor, msg: TaggedPacket| {
            sender.handle_read(msg).unwrap();
            while sender.poll_read().is_some() {}
        };
        assert_eq!(
            send(&mut sender).header.payload_type,
            OPUS,
            "no loss reported"
        );
        read(&mut sender, report(0, 1));
        assert_eq!(send(&mut sender).header.payload_type, OPUS, "no loss");
        read(&mut sender, report(64, 2));
        assert_eq!(
            send(&mut sender).header.payload_type,
            OPUS,
            "another stream's loss"
        );
        read(&mut sender, report(3, 1)); // 0.3 x 1.2%: 0.35%
        assert_eq!(send(&mut sender).header.payload_type, OPUS, "under 0.5%");
        read(&mut sender, report(13, 1)); // 5%: smoothed 1.7%
        let red = send(&mut sender);
        assert_eq!(red.header.payload_type, RED, "the loss turned RED on");
        assert!(
            RedPacket::parse(&red.payload)
                .unwrap()
                .redundant()
                .is_empty(),
            "no copy of a packet that left as Opus"
        );
        let red = send(&mut sender);
        assert_eq!(red.header.payload_type, RED);
        assert_eq!(RedPacket::parse(&red.payload).unwrap().redundant().len(), 1);
        // Reports of no loss: 1.7% x 0.7^n; over 0.25% until the sixth.
        for n in 1..=6 {
            read(&mut sender, report(0, 1));
            let expected = if n < 6 { RED } else { OPUS };
            assert_eq!(
                send(&mut sender).header.payload_type,
                expected,
                "report {n}"
            );
        }

        // Without the setting, or with another policy, the loss decides nothing.
        for (builder, expected) in [
            (RedAudioBuilder::new(), OPUS),
            (
                RedAudioBuilder::new()
                    .with_redundancy_on_loss(true)
                    .with_audio_redundancy(AudioRedundancy::Never),
                OPUS,
            ),
            (
                RedAudioBuilder::new()
                    .with_redundancy_on_loss(true)
                    .with_audio_redundancy(AudioRedundancy::Always),
                RED,
            ),
        ] {
            let mut sender = builder.build();
            sender.bind_local_stream(&info(1, "111/111"));
            assert_eq!(sent_payload_type(&mut sender, 1), expected);
            for _ in 0..4 {
                sender.handle_read(report(128, 1)).unwrap();
                while sender.poll_read().is_some() {}
            }
            sender.handle_write(opus(1, 2, b"x")).unwrap();
            assert_eq!(
                rtp(sender.poll_write().unwrap()).header.payload_type,
                expected
            );
        }
    }

    /// RFC 8854 section 4.1: "redundant encoding with reduced-bitrate Opus encodings": a packet
    /// written with a `RedundantEncoding` is carried as that encoding in the RED packets after
    /// it, and a receiver that lost it rebuilds that encoding. One larger than the primary is
    /// not used (RFC 2198 section 3: "MUST NOT be higher bandwidth than the primary").
    #[test]
    fn a_lower_bitrate_encoding_supplied_with_a_packet_is_the_copy_the_next_packet_carries() {
        let mut sender = RedAudioBuilder::new().with_redundancy(2).build();
        let mut receiver = RedAudioBuilder::new().build();
        sender.bind_local_stream(&info_red_first(1, "111/111/111"));
        receiver.bind_remote_stream(&info(1, "111/111/111"));
        let with = |mut msg: TaggedPacket, redundant: &'static [u8]| {
            msg.message
                .add(crate::Attribute::Custom(std::sync::Arc::new(
                    RedundantEncoding::new(Bytes::from_static(redundant)),
                )));
            msg
        };
        let packets = [
            with(opus(1, 1, b"primary one"), b"low1"),
            with(opus(1, 2, b"two"), b"larger than two"),
            opus(1, 3, b"three"),
        ];
        let mut wire = vec![];
        for packet in packets {
            sender.handle_write(packet).unwrap();
            wire.push(rtp(sender.poll_write().unwrap()));
        }
        let third = RedPacket::parse(&wire[2].payload).unwrap();
        let copies: Vec<&[u8]> = third
            .redundant()
            .iter()
            .map(|block| block.data.as_ref())
            .collect();
        assert_eq!(copies, vec![b"low1".as_ref(), b"two".as_ref()]);
        // The first two are lost: the third rebuilds the low-bitrate first and the second.
        receiver
            .handle_read(TaggedPacket {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtp(wire[2].clone())),
            })
            .unwrap();
        let mut delivered = vec![];
        while let Some(out) = receiver.poll_read() {
            let packet = rtp(out);
            delivered.push((packet.header.sequence_number, packet.payload));
        }
        assert_eq!(
            delivered,
            vec![
                (1, Bytes::from_static(b"low1")),
                (2, Bytes::from_static(b"two")),
                (3, Bytes::from_static(b"three")),
            ]
        );
    }

    /// RFC 8854 section 4.1: "When using constant-bitrate codecs, e.g., PCMU [RFC5391],
    /// redundant encoding MAY be used". A PCMU stream whose section negotiated `red/8000`
    /// naming PCMU (an application's registration: the default codecs offer RED for Opus
    /// only, the clause warning that it "will result in a potentially significant bitrate
    /// increase") is sent in RED and a lost packet comes back from the next one.
    #[test]
    fn a_constant_bitrate_codec_gets_redundancy_when_its_section_negotiated_red() {
        const PCMU: u8 = 0;
        const RED_8K: u8 = 98;
        let pcmu = |red_first: bool| {
            let mut formats = vec![
                (PCMU, "audio/PCMU".to_owned()),
                (RED_8K, "audio/red".to_owned()),
            ];
            if red_first {
                formats.reverse();
            }
            StreamInfo {
                ssrc: 1,
                payload_type: PCMU,
                mime_type: "audio/PCMU".to_owned(),
                clock_rate: 8_000,
                channels: 1,
                section_mime_types: formats,
                section_fmtp_lines: vec![(RED_8K, "0/0".to_owned())],
                ..Default::default()
            }
        };
        let mut sender = RedAudioBuilder::new().build();
        let mut receiver = RedAudioBuilder::new().build();
        sender.bind_local_stream(&pcmu(true));
        receiver.bind_remote_stream(&pcmu(false));
        let mut delivered = vec![];
        for (i, payload) in [b"aaaa", b"bbbb", b"cccc", b"dddd"].iter().enumerate() {
            let mut packet = opus(1, i as u16 + 1, payload.as_slice());
            if let Packet::Rtp(rtp) = &mut packet.message.packet {
                rtp.header.payload_type = PCMU;
                rtp.header.timestamp = u32::from(rtp.header.sequence_number) * 160;
            }
            sender.handle_write(packet).unwrap();
            let red = rtp(sender.poll_write().unwrap());
            assert_eq!(red.header.payload_type, RED_8K);
            if i == 1 {
                continue;
            }
            receiver
                .handle_read(TaggedPacket {
                    now: Instant::now(),
                    transport: TransportContext::default(),
                    message: AttributedPacket::new(Packet::Rtp(red)),
                })
                .unwrap();
            while let Some(out) = receiver.poll_read() {
                delivered.push(rtp(out));
            }
        }
        let got: Vec<(u16, u8, &[u8])> = delivered
            .iter()
            .map(|p| {
                (
                    p.header.sequence_number,
                    p.header.payload_type,
                    p.payload.as_ref(),
                )
            })
            .collect();
        assert_eq!(
            got,
            vec![
                (1, PCMU, b"aaaa".as_ref()),
                (2, PCMU, b"bbbb".as_ref()),
                (3, PCMU, b"cccc".as_ref()),
                (4, PCMU, b"dddd".as_ref()),
            ]
        );
    }

    /// Only a stream whose section negotiated a RED format of its own encoding is touched: a
    /// stream without one, and a packet of another payload type, pass as they are.
    #[test]
    fn without_a_negotiated_red_format_packets_pass_unchanged() {
        let mut sender = RedAudioBuilder::new()
            .with_audio_redundancy(AudioRedundancy::Always)
            .build();
        sender.bind_local_stream(&StreamInfo {
            section_mime_types: vec![(OPUS, "audio/opus".to_owned())],
            section_fmtp_lines: vec![(OPUS, String::new())],
            ..info(1, "")
        });
        sender.bind_local_stream(&info(2, "0/0"));
        sender.bind_local_stream(&info(3, "111/111"));
        for ssrc in [1, 2] {
            sender.handle_write(opus(ssrc, 1, b"x")).unwrap();
            assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, OPUS);
        }
        let mut dtmf = opus(3, 1, b"x");
        if let Packet::Rtp(p) = &mut dtmf.message.packet {
            p.header.payload_type = 126;
        }
        sender.handle_write(dtmf).unwrap();
        assert_eq!(rtp(sender.poll_write().unwrap()).header.payload_type, 126);
    }

    /// RFC 3264 sections 5.1 and 6.1: the formats of an m= line are in order of preference and
    /// the sender "SHOULD use the format with the highest preference". By default
    /// ([`AudioRedundancy::WhenPreferred`]) a stream goes in RED only when its section lists
    /// RED ahead of Opus; `Always` sends RED in either order, `Never` in neither.
    #[test]
    fn red_is_sent_by_the_remote_order_unless_the_application_decides() {
        let cases = [
            (AudioRedundancy::WhenPreferred, false, OPUS),
            (AudioRedundancy::WhenPreferred, true, RED),
            (AudioRedundancy::Always, false, RED),
            (AudioRedundancy::Always, true, RED),
            (AudioRedundancy::Never, false, OPUS),
            (AudioRedundancy::Never, true, OPUS),
        ];
        for (policy, red_first, expected) in cases {
            let mut sender = RedAudioBuilder::new().with_audio_redundancy(policy).build();
            sender.bind_local_stream(&if red_first {
                info_red_first(1, "111/111")
            } else {
                info(1, "111/111")
            });
            assert_eq!(
                sent_payload_type(&mut sender, 1),
                expected,
                "{policy:?}, RED first: {red_first}"
            );
        }
        assert_eq!(
            RedAudioBuilder::new().audio_redundancy,
            AudioRedundancy::WhenPreferred
        );
    }

    /// The setting is about sending: a receiver takes RED apart and recovers a loss from the
    /// next packet's copy whatever its own [`AudioRedundancy`] (RFC 8854 section 7: an endpoint
    /// "MUST be able to receive and make use of" the FEC formats it indicated).
    #[test]
    fn received_red_is_taken_apart_in_every_mode() {
        for policy in [
            AudioRedundancy::WhenPreferred,
            AudioRedundancy::Always,
            AudioRedundancy::Never,
        ] {
            let mut sender = RedAudioBuilder::new()
                .with_audio_redundancy(AudioRedundancy::Always)
                .build();
            let mut receiver = RedAudioBuilder::new().with_audio_redundancy(policy).build();
            sender.bind_local_stream(&info(1, "111/111"));
            // The receiver's section in its own order: Opus first.
            receiver.bind_remote_stream(&info(1, "111/111"));
            let mut delivered = vec![];
            for (seq, payload) in [(1u16, b"one" as &'static [u8]), (2, b"two"), (3, b"three")] {
                sender.handle_write(opus(1, seq, payload)).unwrap();
                let red = rtp(sender.poll_write().unwrap());
                assert_eq!(red.header.payload_type, RED, "{policy:?}");
                if seq == 2 {
                    continue;
                }
                receiver
                    .handle_read(TaggedPacket {
                        now: Instant::now(),
                        transport: TransportContext::default(),
                        message: AttributedPacket::new(Packet::Rtp(red)),
                    })
                    .unwrap();
                while let Some(out) = receiver.poll_read() {
                    let p = rtp(out);
                    delivered.push((p.header.sequence_number, p.header.payload_type, p.payload));
                }
            }
            assert_eq!(
                delivered,
                vec![
                    (1, OPUS, Bytes::from_static(b"one")),
                    (2, OPUS, Bytes::from_static(b"two")),
                    (3, OPUS, Bytes::from_static(b"three")),
                ],
                "{policy:?}"
            );
        }
    }
}