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
//! ECN initiation and failure detection for an RTP stream whose feedback is RFC 8888.
//!
//! RFC 8888 section 7: "When using ECN with RTP, the guidelines in Section 7.2 of [RFC6679]
//! MUST be followed to initiate the use of ECN in an RTP session", section 7.3's ongoing use
//! likewise, and "the guidance in Section 7.4 of [RFC6679] related to detecting failures MUST
//! be followed, with the exception that the necessary information is retrieved from the RTCP
//! Congestion Control Feedback Packets".
//!
//! [`EcnValidation`] is that sender-side procedure for one stream, sans-I/O: it is told of each
//! packet sent ([`EcnValidation::on_send`], which answers whether the packet goes out ECT) and
//! of each RFC 8888 report about one ([`EcnValidation::on_report`]).
//!
//! * **Initiation** (RFC 6679 section 7.2.1, the in-band method every implementation MUST
//!   have): "an RTP sender SHALL mark a small fraction of its RTP traffic as ECT", "a minimum
//!   of two packets with ECT markings per RTCP reporting interval" is RECOMMENDED, and it
//!   "SHOULD NOT mark all RTP packets". Here one packet in [`PROBE_SPACING`], and one at least
//!   every [`PROBE_INTERVAL`], never two in a row. On a unicast transport the initiation "MAY
//!   [be treated] as provisionally successful if it receives [a report] indicating successful
//!   receipt of the ECT-marked packets, with no negative indications": [`CONFIRMATIONS`]
//!   probes reported received ECT (or CE) and none reported Not-ECT. It "is considered to have
//!   failed" when the feedback shows the receiver "should have received multiple (>3)
//!   ECT-marked RTP packets" and none arrived marked: here more than three probes reported
//!   lost while none was reported received, or a probe reported received Not-ECT.
//! * **Ongoing use** (section 7.3.1): after success the sender "SHOULD mark all the RTP data
//!   packets it sends as ECT".
//! * **Failures** (section 7.4): a path that clears the ECN field ("the ratio [...] has become
//!   all not-ECT, or has substantially changed towards not-ECT", section 7.4.2) stops the
//!   marking: more than a quarter of a window of [`WINDOW`] reported ECT packets arrived
//!   Not-ECT. "A sender that detects high packet loss rates for ECT-marked packets SHOULD
//!   immediately switch to sending packets as not-ECT to determine if the losses are
//!   potentially due to the ECT markings. If the losses disappear when the ECT-marking is
//!   discontinued, the RTP sender should go back to initiation procedures": half a window lost
//!   switches to Not-ECT for a window; if the loss falls under a quarter the stream initiates
//!   again, else (the loss is the path's, not ECN's) it resumes marking. After a failed
//!   initiation the sender "periodically [retries] the ECN initiation" (the first option of
//!   section 7.4.1) every [`DEFAULT_RETRY_AFTER`], and "if multiple initiations have been successful, but
//!   the following full usage of ECN has resulted in the fallback procedures, then disabling
//!   of the ECN support is RECOMMENDED": the second such fallback ends ECN for the stream.
//!
//! RTCP is never marked (section 7.2: "SHALL NOT ECT mark their RTCP traffic"); that is the
//! caller's part, as is choosing the codepoint (ECT(1) for L4S, RFC 9331).

use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
use rtcp::transport_feedbacks::ecn_feedback::EcnCounters;
use std::collections::BTreeMap;
use std::time::{Duration, Instant};

/// During initiation one packet in this many is a probe sent ECT.
pub const PROBE_SPACING: u32 = 10;
/// During initiation a probe is sent at least this often (given an unmarked packet since the
/// last one): two per RTCP reporting interval at the shortest regular interval RFC 3550
/// section 6.2 allows a reduced-minimum sender (360 / session kbit/s seconds) is met for any
/// session above 720 kbit/s by the spacing, and below by this.
pub const PROBE_INTERVAL: Duration = Duration::from_millis(500);
/// Probes reported received with an ECN-capable marking that make the initiation succeed.
pub const CONFIRMATIONS: u32 = 2;
/// Probes reported lost, none received, that make the initiation fail (RFC 6679 section 7.2.1:
/// "multiple (>3)").
pub const PROBES_LOST_TO_FAIL: u32 = 4;
/// Reported packets the failure checks of ongoing use are made over.
pub const WINDOW: u32 = 32;
/// How long after a failed initiation the next one starts (RFC 6679 section 7.4.1 option 1).
pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(60);
/// Fallbacks from ongoing use, each confirmed as ECN's doing, after which ECN stays off.
pub const FALLBACKS_TO_DISABLE: u32 = 2;
/// How long after the start of an initiation a provisional success is watched for other
/// receivers (RFC 6679 section 7.2.1: "three RTCP reporting intervals from the time the ECN
/// initiation started"): three of RTP/AVP's 5 s minimum interval, the longest regular
/// interval this engine computes without a configured `trr-int`.
pub const PROVISIONAL_MONITOR: Duration = Duration::from_secs(15);
/// One RTCP reporting interval as [`PROVISIONAL_MONITOR`] counts three of them: the complete
/// interval without a change of the group membership that RFC 6679 section 7.2.1 asks for
/// before the membership is stable.
pub const REPORTING_INTERVAL: Duration = Duration::from_secs(5);
/// The most participants (RTCP CNAMEs) a stream's validation follows; further ones are not
/// waited for.
const MAX_PARTICIPANTS: usize = 16;

/// Sent packets remembered, by sequence number, to match reports with how each was sent.
const HISTORY: usize = 2048;

/// Where a stream is in RFC 6679's procedure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcnState {
    /// Section 7.2.1: a fraction of the packets are probes sent ECT.
    Initiating,
    /// Section 7.3.1: every packet is sent ECT.
    Active,
    /// Section 7.4.1: ECT-marked packets were lost at a high rate; packets go out Not-ECT to
    /// see whether the loss goes with the marking.
    Fallback,
    /// The path does not carry ECN; nothing is marked until `retry_at`.
    Failed {
        /// When the next initiation starts.
        retry_at: Instant,
    },
    /// ECN is off for the stream for good (section 7.4.1).
    Disabled,
}

/// Which ECT codepoint a receiver asks the sender to use: the `ect=` parameter of its
/// `a=ecn-capable-rtp` (RFC 6679 section 6.1). Left out, the sender uses ECT(0).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EctPreference {
    /// `ect=0`.
    Ect0,
    /// `ect=1`.
    Ect1,
    /// `ect=random`: the sender picks ECT(0) or ECT(1) at random for each packet.
    Random,
}

impl EctPreference {
    /// The value of an `ect=` parameter (`0`, `1` or `random`, any case); `None` for any
    /// other, which RFC 6679 section 6.1 has the receiver of the description ignore.
    pub fn from_sdp(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "0" => Some(Self::Ect0),
            "1" => Some(Self::Ect1),
            "random" => Some(Self::Random),
            _ => None,
        }
    }
}

/// Which ECT codepoint a stream that marks sends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EcnMarking {
    /// RFC 6679 section 7.3.1: ECT(0), unless the receiver asked for ECT(1) or a random
    /// choice ([`EctPreference`]).
    #[default]
    Rfc6679,
    /// ECT(1), the L4S identifier (RFC 9331), whatever the receiver asked: what browsers that
    /// send L4S do.
    L4s,
}

impl EcnMarking {
    /// The codepoint the next packet goes out with, given the receiver's preference;
    /// `coin` is a random bit, used for [`EctPreference::Random`].
    pub fn codepoint(self, preference: Option<EctPreference>, coin: bool) -> shared::EcnCodepoint {
        match (self, preference) {
            (Self::L4s, _) | (Self::Rfc6679, Some(EctPreference::Ect1)) => {
                shared::EcnCodepoint::Ect1
            }
            (Self::Rfc6679, Some(EctPreference::Random)) if coin => shared::EcnCodepoint::Ect1,
            _ => shared::EcnCodepoint::Ect0,
        }
    }
}

/// How a stream starts using ECN.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EcnInitiation {
    /// RFC 6679 section 7.2.1: probes, then every packet once feedback confirmed them (the
    /// method every implementation MUST have).
    #[default]
    RtpAndRtcp,
    /// RFC 6679 section 7.2.3, leap of faith: every packet is sent ECT from the first, as
    /// browsers that implement L4S do. Failure detection (section 7.4) still applies. The RFC
    /// allows it only for sessions that accept its limitations (the first packets may be lost
    /// on a path that drops ECT traffic).
    LeapOfFaith,
}

impl EcnInitiation {
    /// RFC 6679 section 7.2: "all participants in an RTP session MUST use the same ECN
    /// initiation method". Given each section's transport and the method its negotiation
    /// gave, the method each section's streams use: the first method negotiated on the
    /// transport, for every section on it that uses ECN at all (bundled sections share one
    /// RTP session, RFC 9143). A section without ECN stays without.
    pub fn one_per_transport<K: PartialEq + Copy>(
        sections: &[(K, Option<EcnInitiation>)],
    ) -> Vec<Option<EcnInitiation>> {
        sections
            .iter()
            .map(|(transport, method)| {
                method.and_then(|_| {
                    sections
                        .iter()
                        .find(|(other, m)| other == transport && m.is_some())
                        .and_then(|(_, m)| *m)
                })
            })
            .collect()
    }
}

/// An ECN failure a stream's validation detected (RFC 6679 sections 7.2.1 and 7.4.2: detected
/// failures and erroneous behaviour "should" be logged "to enable follow up"). Each is logged
/// and kept for the application ([`EcnValidation::take_failures`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EcnFailure {
    /// Initiation failed: an ECT probe was reported arriving Not-ECT.
    ProbeArrivedNotEct,
    /// Initiation failed: no ECT probe arrived.
    NoProbeArrived,
    /// Initiation failed: the path clears the ECN field.
    FieldCleared,
    /// Initiation failed: the receiver's counters counted the ECT probes as Not-ECT.
    ProbesCountedNotEct,
    /// Initiation failed: a receiver reported more than three probes in a reception report
    /// without an ECN report (section 7.2.1).
    NoEcnReport,
    /// Leap of faith failed: two receiver reports in a row showed no reception of the stream
    /// (section 7.2.3).
    NoReception,
    /// After initiation, ECT packets were lost where Not-ECT ones were not (section 7.4.2):
    /// the stream falls back and initiates again, or, `disabled`, ECN stays off for it.
    EctLost {
        /// Whether ECN is now off for the stream.
        disabled: bool,
    },
}

impl EcnFailure {
    /// Whether this ends an initiation (section 7.2.1), as against a failure after one.
    pub fn is_initiation_failure(&self) -> bool {
        !matches!(self, EcnFailure::EctLost { .. })
    }
}

impl std::fmt::Display for EcnFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            EcnFailure::ProbeArrivedNotEct => "an ECT probe arrived Not-ECT",
            EcnFailure::NoProbeArrived => "no ECT probe arrived",
            EcnFailure::FieldCleared => "the path clears the ECN field",
            EcnFailure::ProbesCountedNotEct => "ECT probes were counted Not-ECT",
            EcnFailure::NoEcnReport => {
                "a receiver reported more than three probes without an ECN report"
            }
            EcnFailure::NoReception => "two receiver reports in a row showed no reception",
            EcnFailure::EctLost { disabled: true } => {
                "ECT packets were lost again; ECN off for the stream"
            }
            EcnFailure::EctLost { disabled: false } => "ECT packets were lost; initiating again",
        })
    }
}

/// At most this many failures are kept for the application.
const MAX_KEPT_FAILURES: usize = 16;

#[derive(Debug, Clone, Copy, Default)]
struct Sent {
    sequence_number: u16,
    /// Whether this slot describes a packet at all.
    known: bool,
    marked: bool,
    /// Reported so far: received (true), lost (false), not yet (`None`).
    reported: Option<bool>,
}

/// Counts over one window of reported packets.
#[derive(Debug, Clone, Copy, Default)]
struct Window {
    reported: u32,
    lost: u32,
    bleached: u32,
}

/// The participants of a session with more than one RTCP CNAME (RFC 6679 section 7.2.1): "An
/// RTP sender shall consider the group membership to be stable after it has been in the
/// session and sending ECT-marked probe packets for at least three RTCP reporting intervals
/// ... and when a complete RTCP reporting interval has passed without changes to the group
/// membership. ECN initiation is considered successful when the group membership is stable
/// and all known participants have sent one or more RTCP ECN feedback packets or RTCP XR ECN
/// Summary Reports indicating correct receipt of the ECT-marked RTP packets".
#[derive(Debug, Clone, Default)]
struct Group {
    /// Each participant's CNAME and whether it confirmed the current initiation's probes.
    members: BTreeMap<String, bool>,
    /// When the membership last changed; `None`: not since the stream's validation began.
    changed_at: Option<Instant>,
}

/// RFC 6679 sections 7.2-7.4 for one RTP stream, fed from RFC 8888 reports. See the module
/// documentation.
#[derive(Debug, Clone)]
pub struct EcnValidation {
    state: EcnState,
    retry_after: Duration,
    since_probe: u32,
    last_probe: Option<Instant>,
    history: Box<[Sent]>,
    probes_confirmed: u32,
    probes_lost: u32,
    window: Window,
    /// The loss of the window that sent the stream into [`EcnState::Fallback`].
    fallback_from: u32,
    fallbacks: u32,
    /// The last RFC 6679 counters each reporter gave (by its RTCP CNAME, `None` when it is not
    /// known), with the extended highest sequence number they relate to
    /// ([`EcnValidation::on_counters_from`]): each receiver counts on its own.
    last_counters: Vec<(Option<String>, u32, EcnCounters)>,
    /// When the current initiation sent its first probe.
    initiated_at: Option<Instant>,
    /// The success of the initiation is provisional until then (section 7.2.1).
    provisional_until: Option<Instant>,
    /// The RTCP CNAME of the receiver whose reports confirmed the probes.
    receiver_cname: Option<String>,
    /// More than one RTCP CNAME seen: the session is a group, and initiation follows the full
    /// procedure of section 7.2.1 instead of the unicast optimisation.
    group: Option<Group>,
    /// Failures detected and not taken yet.
    failures: Vec<EcnFailure>,
    /// Marking from the first packet without probes (section 7.2.3), until reception is seen.
    leap_of_faith: bool,
    /// Receiver reports in a row that showed no reception of the stream.
    reports_without_reception: u32,
}

impl Default for EcnValidation {
    fn default() -> Self {
        Self::new(EcnInitiation::default())
    }
}

impl EcnValidation {
    /// A stream about to send its first packet with ECN negotiated.
    pub fn new(initiation: EcnInitiation) -> Self {
        Self {
            state: match initiation {
                EcnInitiation::RtpAndRtcp => EcnState::Initiating,
                EcnInitiation::LeapOfFaith => EcnState::Active,
            },
            retry_after: DEFAULT_RETRY_AFTER,
            since_probe: PROBE_SPACING,
            last_probe: None,
            history: vec![Sent::default(); HISTORY].into_boxed_slice(),
            probes_confirmed: 0,
            probes_lost: 0,
            window: Window::default(),
            fallback_from: 0,
            fallbacks: 0,
            last_counters: Vec::new(),
            initiated_at: None,
            provisional_until: None,
            receiver_cname: None,
            group: None,
            failures: Vec::new(),
            leap_of_faith: initiation == EcnInitiation::LeapOfFaith,
            reports_without_reception: 0,
        }
    }

    /// How long after a failed initiation the next one starts ([`DEFAULT_RETRY_AFTER`]).
    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
        self.retry_after = retry_after;
        self
    }

    /// Where the stream is in the procedure.
    pub fn state(&self) -> EcnState {
        self.state
    }

    /// Whether a packet of the stream that is not one of its own numbered packets (an RTX
    /// retransmission, say) goes out ECT: only in ongoing use, so probes are the stream's own
    /// packets, whose reports name them.
    pub fn marks_all(&self) -> bool {
        self.state == EcnState::Active
    }

    /// Whether the packet `sequence_number` was sent ECT, as far as the history still knows.
    pub fn was_marked(&self, sequence_number: u16) -> bool {
        let slot = &self.history[usize::from(sequence_number) % HISTORY];
        slot.known && slot.sequence_number == sequence_number && slot.marked
    }

    /// A packet of the stream is sent at `now`: whether it goes out ECT.
    pub fn on_send(&mut self, now: Instant, sequence_number: u16) -> bool {
        if let EcnState::Failed { retry_at } = self.state
            && now >= retry_at
        {
            self.initiate();
        }
        let marked = match self.state {
            EcnState::Initiating => {
                let due = self.since_probe + 1 >= PROBE_SPACING
                    || (self.since_probe >= 1
                        && self
                            .last_probe
                            .is_none_or(|at| now.saturating_duration_since(at) >= PROBE_INTERVAL));
                if due {
                    self.since_probe = 0;
                    self.last_probe = Some(now);
                    self.initiated_at.get_or_insert(now);
                } else {
                    self.since_probe += 1;
                }
                if self.group_success(now) { true } else { due }
            }
            EcnState::Active => true,
            EcnState::Fallback | EcnState::Failed { .. } | EcnState::Disabled => false,
        };
        self.history[usize::from(sequence_number) % HISTORY] = Sent {
            sequence_number,
            known: true,
            marked,
            reported: None,
        };
        marked
    }

    /// An RFC 8888 report about the packet `sequence_number` arrived at `now`: whether it was
    /// received, and if so the ECN field it arrived with. The reporter is not known
    /// ([`on_report_from`](Self::on_report_from)).
    pub fn on_report(&mut self, now: Instant, sequence_number: u16, received: bool, ecn: Ecn) {
        self.on_report_from(now, None, sequence_number, received, ecn);
    }

    /// [`on_report`](Self::on_report) from the participant whose RTCP CNAME is `reporter`. In a
    /// group (more than one CNAME seen) a probe reported arriving ECT or CE confirms the
    /// initiation for that participant, even when another reported the packet first.
    pub fn on_report_from(
        &mut self,
        now: Instant,
        reporter: Option<&str>,
        sequence_number: u16,
        received: bool,
        ecn: Ecn,
    ) {
        let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
        if !slot.known || slot.sequence_number != sequence_number {
            return;
        }
        let ecn_capable = matches!(ecn, Ecn::Ect0 | Ecn::Ect1 | Ecn::Ce);
        if self.state == EcnState::Initiating && slot.marked && received && ecn_capable {
            self.confirm(now, reporter);
        }
        let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
        // Each packet counts once; a loss reported and then undone by a later report (the
        // packet was late) is taken back.
        let undo_loss = match slot.reported {
            Some(true) => return,
            Some(false) if !received => return,
            Some(false) => true,
            None => false,
        };
        slot.reported = Some(received);
        let marked = slot.marked;

        match self.state {
            EcnState::Initiating if marked => {
                if undo_loss {
                    self.probes_lost = self.probes_lost.saturating_sub(1);
                }
                if !received {
                    self.probes_lost += 1;
                } else if ecn_capable {
                    self.probes_confirmed += 1;
                } else {
                    // A negative indication: the path cleared the ECN field.
                    self.fail(now, EcnFailure::ProbeArrivedNotEct);
                    return;
                }
                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
                    self.fail(now, EcnFailure::NoProbeArrived);
                } else if self.group.is_none() && self.probes_confirmed >= CONFIRMATIONS {
                    self.provisional_success(now);
                } else {
                    self.group_success(now);
                }
            }
            EcnState::Active if marked => {
                self.count(undo_loss, received, !ecn_capable);
                if self.window.bleached * 4 > WINDOW {
                    self.fail(now, EcnFailure::FieldCleared);
                } else if self.window.lost * 2 >= WINDOW {
                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
                    self.state = EcnState::Fallback;
                    self.fallback_from = self.window.lost;
                    self.window = Window::default();
                } else if self.window.reported >= WINDOW {
                    self.window = Window::default();
                }
            }
            EcnState::Fallback if !marked => {
                self.count(undo_loss, received, false);
                if self.window.reported >= WINDOW {
                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
                        // The loss went with the marking.
                        self.fallbacks += 1;
                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
                            self.record(EcnFailure::EctLost { disabled: true });
                            self.state = EcnState::Disabled;
                        } else {
                            self.record(EcnFailure::EctLost { disabled: false });
                            self.initiate();
                        }
                    } else {
                        // Not-ECT packets were lost as much: the path's loss, not ECN's.
                        self.state = EcnState::Active;
                        self.window = Window::default();
                    }
                }
            }
            _ => {}
        }
    }

    /// An RFC 6679 report about the stream arrived at `now`: the receiver's cumulative ECN
    /// counters (an RTCP ECN Feedback packet, section 5.1, or an XR ECN Summary Report,
    /// section 5.2) and the extended highest sequence number they relate to (the feedback
    /// packet's, or the reception report's in the same compound packet). The procedure is the
    /// one [`on_report`](Self::on_report) runs, on what changed since the last report: the
    /// packets sent up to the new highest sequence number, how many went out ECT, and how many
    /// the receiver counted ECT or CE, not-ECT, lost and duplicated (section 7.4.2).
    ///
    /// * Initiating: ECT or CE counts confirm probes; not-ECT counts beyond the unmarked
    ///   packets sent (and the duplicates) are a negative indication; more than three probes
    ///   sent with no ECT counted is a failure (section 7.2.1).
    /// * Ongoing use: each packet sent ECT is reported; the not-ECT count beyond duplicates is
    ///   bleaching, the lost count is loss; the thresholds are those of per-packet reports.
    pub fn on_counters(&mut self, now: Instant, extended_highest: u32, counters: EcnCounters) {
        self.on_counters_from(now, None, extended_highest, counters);
    }

    /// [`on_counters`](Self::on_counters) from the participant whose RTCP CNAME is `reporter`:
    /// its counters are compared with its own last ones, and in a group, ECT or CE counted with
    /// nothing cleared confirms the initiation for it.
    pub fn on_counters_from(
        &mut self,
        now: Instant,
        reporter: Option<&str>,
        extended_highest: u32,
        counters: EcnCounters,
    ) {
        let known = self
            .last_counters
            .iter()
            .position(|(from, _, _)| from.as_deref() == reporter);
        let (previous_highest, previous) = match known {
            Some(index) => (self.last_counters[index].1, self.last_counters[index].2),
            None => (
                extended_highest.wrapping_sub(self.known_since(extended_highest)),
                EcnCounters::default(),
            ),
        };
        // An older report than the last one says nothing new.
        let span = extended_highest.wrapping_sub(previous_highest);
        if span > 0x8000_0000 {
            return;
        }
        match known {
            Some(index) => {
                self.last_counters[index].1 = extended_highest;
                self.last_counters[index].2 = counters;
            }
            None => {
                if self.last_counters.len() >= MAX_PARTICIPANTS {
                    self.last_counters.remove(0);
                }
                self.last_counters
                    .push((reporter.map(str::to_owned), extended_highest, counters));
            }
        }
        if span == 0 && counters == previous {
            return;
        }
        let ect = u64::from(counters.ect0.wrapping_sub(previous.ect0))
            + u64::from(counters.ect1.wrapping_sub(previous.ect1))
            + u64::from(counters.ce.wrapping_sub(previous.ce));
        let not_ect = u64::from(counters.not_ect.wrapping_sub(previous.not_ect));
        let duplicates = u64::from(counters.duplicates.wrapping_sub(previous.duplicates));
        // The loss counter may fall (late packets) between reports.
        let lost = i64::from(counters.lost.wrapping_sub(previous.lost) as i16).max(0) as u64;

        // What went out in (previous_highest, extended_highest], as far as the history knows.
        let (mut marked, mut unmarked) = (0u64, 0u64);
        let first = previous_highest.wrapping_add(1);
        for offset in 0..span.min(HISTORY as u32) {
            let sequence_number = first.wrapping_add(offset) as u16;
            let slot = &self.history[usize::from(sequence_number) % HISTORY];
            if slot.known && slot.sequence_number == sequence_number {
                if slot.marked {
                    marked += 1;
                } else {
                    unmarked += 1;
                }
            }
        }
        let bleached = not_ect.saturating_sub(unmarked + duplicates);

        match self.state {
            EcnState::Initiating => {
                if bleached > 0 && marked > 0 {
                    self.fail(now, EcnFailure::ProbesCountedNotEct);
                    return;
                }
                self.probes_confirmed += ect.min(u64::from(u32::MAX)) as u32;
                if ect == 0 {
                    self.probes_lost += marked as u32;
                } else if bleached == 0 {
                    self.confirm(now, reporter);
                }
                if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
                    self.fail(now, EcnFailure::NoProbeArrived);
                } else if self.group.is_none()
                    && self.probes_confirmed >= CONFIRMATIONS
                    && bleached == 0
                {
                    self.provisional_success(now);
                } else {
                    self.group_success(now);
                }
            }
            EcnState::Active => {
                self.window.reported += marked as u32;
                self.window.lost += lost.min(marked) as u32;
                self.window.bleached += bleached.min(marked) as u32;
                if self.window.bleached * 4 > WINDOW {
                    self.fail(now, EcnFailure::FieldCleared);
                } else if self.window.lost * 2 >= WINDOW {
                    log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
                    self.state = EcnState::Fallback;
                    self.fallback_from = self.window.lost;
                    self.window = Window::default();
                } else if self.window.reported >= WINDOW {
                    self.window = Window::default();
                }
            }
            EcnState::Fallback => {
                self.window.reported += unmarked as u32;
                self.window.lost += lost.min(unmarked) as u32;
                if self.window.reported >= WINDOW {
                    if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
                        self.fallbacks += 1;
                        if self.fallbacks >= FALLBACKS_TO_DISABLE {
                            self.record(EcnFailure::EctLost { disabled: true });
                            self.state = EcnState::Disabled;
                        } else {
                            self.record(EcnFailure::EctLost { disabled: false });
                            self.initiate();
                        }
                    } else {
                        self.state = EcnState::Active;
                        self.window = Window::default();
                    }
                }
            }
            EcnState::Failed { .. } | EcnState::Disabled => {}
        }
    }

    /// How many sequence numbers before `extended_highest` the history holds sent packets
    /// for: the span the first RFC 6679 report covers.
    fn known_since(&self, extended_highest: u32) -> u32 {
        let mut span = 0u32;
        while span < HISTORY as u32 {
            let sequence_number = extended_highest.wrapping_sub(span) as u16;
            let slot = &self.history[usize::from(sequence_number) % HISTORY];
            if !(slot.known && slot.sequence_number == sequence_number) {
                break;
            }
            span += 1;
        }
        span
    }

    fn count(&mut self, undo_loss: bool, received: bool, bleached: bool) {
        if undo_loss {
            self.window.lost = self.window.lost.saturating_sub(1);
        } else {
            self.window.reported += 1;
        }
        if !received {
            self.window.lost += 1;
        } else if bleached {
            self.window.bleached += 1;
        }
    }

    /// The probes were confirmed by one receiver: every packet is marked from now on, while
    /// the session is watched for other receivers (section 7.2.1's optimisation for a
    /// unicast peer).
    fn provisional_success(&mut self, now: Instant) {
        self.state = EcnState::Active;
        self.window = Window::default();
        let started = self.initiated_at.unwrap_or(now);
        self.provisional_until = Some(started + PROVISIONAL_MONITOR);
    }

    /// RFC 6679 section 7.2.1: a source of the session named its RTCP CNAME at `now`. The
    /// first one is the receiver the probes are confirmed by (the unicast optimisation).
    /// Another CNAME makes the session a group: while the success is provisional "the sender
    /// MUST fallback to only ECT-marking a small fraction of its RTP packets, while it
    /// determines if ECN can be supported following the full procedure" ([`Group`]), and an
    /// initiation in progress follows the full procedure from then on. Each new CNAME is a
    /// change of the membership.
    pub fn on_remote_cname(&mut self, now: Instant, cname: &str) {
        if self.group.is_none() {
            match &self.receiver_cname {
                None => {
                    self.receiver_cname = Some(cname.to_owned());
                    return;
                }
                Some(known) if known == cname => return,
                Some(_) => {}
            }
            let provisional = self.state == EcnState::Active
                && self.provisional_until.is_some_and(|until| now < until);
            let mut group = Group::default();
            if let Some(first) = &self.receiver_cname {
                group.members.insert(first.clone(), false);
            }
            self.group = Some(group);
            if provisional {
                log::info!(
                    "ECN: another RTCP CNAME during a provisional success, probing again \
                     (RFC 6679 section 7.2.1)"
                );
                self.initiate();
            }
        }
        let Some(group) = self.group.as_mut() else {
            return;
        };
        if group.members.contains_key(cname) || group.members.len() >= MAX_PARTICIPANTS {
            return;
        }
        group.members.insert(cname.to_owned(), false);
        group.changed_at = Some(now);
    }

    /// A validation that already knows the session's RTCP CNAMEs (named before the stream
    /// started marking): more than one makes it a group from the start.
    pub fn with_receiver_cnames<'a>(mut self, cnames: impl IntoIterator<Item = &'a str>) -> Self {
        for cname in cnames {
            if self.receiver_cname.is_none() {
                self.receiver_cname = Some(cname.to_owned());
                continue;
            }
            let group = self.group.get_or_insert_with(|| {
                let mut group = Group::default();
                if let Some(first) = &self.receiver_cname {
                    group.members.insert(first.clone(), false);
                }
                group
            });
            if group.members.len() < MAX_PARTICIPANTS {
                group.members.insert(cname.to_owned(), false);
            }
        }
        self
    }

    /// Whether more than one RTCP CNAME has been seen, so that initiation follows the full
    /// procedure of section 7.2.1.
    pub fn is_group(&self) -> bool {
        self.group.is_some()
    }

    /// In a group, `reporter` confirmed the probes of the current initiation. A reporter that
    /// named no CNAME yet joins the membership with it.
    fn confirm(&mut self, now: Instant, reporter: Option<&str>) {
        let (Some(group), Some(reporter)) = (self.group.as_mut(), reporter) else {
            return;
        };
        if let Some(confirmed) = group.members.get_mut(reporter) {
            *confirmed = true;
        } else if group.members.len() < MAX_PARTICIPANTS {
            group.members.insert(reporter.to_owned(), true);
            group.changed_at = Some(now);
        }
    }

    /// RFC 6679 section 7.2.1, the full procedure: in a group, the initiation succeeds once
    /// the stream has sent probes for three reporting intervals, a complete interval has
    /// passed without a change of membership, and every participant confirmed the probes.
    /// Every packet is marked from then on (section 7.3.1).
    fn group_success(&mut self, now: Instant) -> bool {
        let (Some(group), EcnState::Initiating, Some(started)) =
            (&self.group, self.state, self.initiated_at)
        else {
            return false;
        };
        let stable_since = group
            .changed_at
            .map_or(started, |changed| changed.max(started));
        let success = now >= started + PROVISIONAL_MONITOR
            && now >= stable_since + REPORTING_INTERVAL
            && !group.members.is_empty()
            && group.members.values().all(|confirmed| *confirmed);
        if success {
            self.state = EcnState::Active;
            self.window = Window::default();
            self.provisional_until = None;
        }
        success
    }

    /// RFC 6679 section 7.2.1: "ECN initiation is considered to have failed at the instant
    /// the initiating RTP sender received an RTCP packet that doesn't contain an RTCP ECN
    /// Feedback Report or ECN Summary Report from any RTP session participant that has an
    /// RTCP RR with an extended RTP sequence number field that indicates that it should have
    /// received multiple (>3) ECT-marked RTP packets." `extended_highest` is that field of a
    /// reception report about the stream in a compound packet without an ECN report about it.
    pub fn on_reception_report_without_ecn(&mut self, now: Instant, extended_highest: u32) {
        if self.state != EcnState::Initiating {
            return;
        }
        let highest = extended_highest as u16;
        let due = self
            .history
            .iter()
            .filter(|sent| {
                sent.known && sent.marked && {
                    // At or before `highest`, within the history's reach.
                    let behind = highest.wrapping_sub(sent.sequence_number);
                    usize::from(behind) < HISTORY
                }
            })
            .count();
        if due > 3 {
            self.fail(now, EcnFailure::NoEcnReport);
        }
    }

    /// RFC 6679 section 7.2.3, leap of faith: a receiver report (SR or RR) arrived that has no
    /// report block about the stream, or one showing that nothing was received. A path with an
    /// ECN-blocking middlebox shows that way; but "a receiver might generate its first RTCP
    /// packet ... before it has had chance to receive any data packets", so "a sender that
    /// receives an RTCP SR/RR packet indicating lack of reception by a receiver SHOULD ...
    /// wait for a second RTCP report from that receiver": the second such report in a row
    /// ends the marking. Nothing changes once reception was reported, outside the leap of
    /// faith, or before a marked packet was sent.
    pub fn on_report_without_reception(&mut self, now: Instant) {
        if !self.leap_of_faith
            || self.state != EcnState::Active
            || !self.history.iter().any(|sent| sent.known && sent.marked)
        {
            return;
        }
        self.reports_without_reception += 1;
        if self.reports_without_reception >= 2 {
            self.leap_of_faith = false;
            self.fail(now, EcnFailure::NoReception);
        }
    }

    /// A receiver report showed reception of the stream: the path carries its ECT packets.
    pub fn on_reception_reported(&mut self) {
        self.reports_without_reception = 0;
        self.leap_of_faith = false;
    }

    /// A validation that knows the receiver by its RTCP CNAME already (named before the
    /// stream started marking).
    pub fn with_receiver_cname(mut self, cname: &str) -> Self {
        self.receiver_cname = Some(cname.to_owned());
        self
    }

    /// Whether the success of the initiation is still provisional at `now`.
    pub fn is_provisional(&self, now: Instant) -> bool {
        self.state == EcnState::Active && self.provisional_until.is_some_and(|until| now < until)
    }

    fn initiate(&mut self) {
        if let Some(group) = self.group.as_mut() {
            group
                .members
                .values_mut()
                .for_each(|confirmed| *confirmed = false);
        }
        self.provisional_until = None;
        self.initiated_at = None;
        self.state = EcnState::Initiating;
        self.since_probe = PROBE_SPACING;
        self.last_probe = None;
        self.probes_confirmed = 0;
        self.probes_lost = 0;
        self.window = Window::default();
    }

    /// RFC 6679 sections 7.2.1 and 7.4.2: a detected failure is logged ("they should log these
    /// to enable follow up") and kept for the application.
    fn record(&mut self, failure: EcnFailure) {
        if failure.is_initiation_failure() {
            log::warn!("ECN: {failure}; packets go out Not-ECT");
        } else {
            log::warn!("ECN: {failure}");
        }
        if self.failures.len() == MAX_KEPT_FAILURES {
            self.failures.remove(0);
        }
        self.failures.push(failure);
    }

    /// The failures detected since the last call, oldest first (at most sixteen are kept).
    pub fn take_failures(&mut self) -> Vec<EcnFailure> {
        std::mem::take(&mut self.failures)
    }

    fn fail(&mut self, now: Instant, failure: EcnFailure) {
        self.record(failure);
        self.state = EcnState::Failed {
            retry_at: now + self.retry_after,
        };
        self.window = Window::default();
    }
}

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

    /// RFC 6679 counters for `marked` probes and the unmarked rest of `first..=last`, as a
    /// receiver on a path that `ect_arrives` (or clears the field) counts them.
    fn counters_for(
        sent: &[u16],
        marked: &[u16],
        ect_arrives: bool,
        lost: u16,
        base: EcnCounters,
    ) -> EcnCounters {
        let marked_count = marked.len() as u32;
        let unmarked = (sent.len() - marked.len()) as u16;
        let mut c = base;
        if ect_arrives {
            c.ect1 += marked_count - u32::from(lost.min(marked_count as u16));
            c.not_ect += unmarked;
        } else {
            c.not_ect += unmarked + marked_count as u16 - lost;
        }
        c.lost += lost;
        c
    }

    /// RFC 6679 7.2.1 with the counters of section 5: probes counted ECT by the receiver's
    /// ECN Feedback / XR ECN Summary Reports make the initiation succeed, and every packet is
    /// then sent ECT (section 7.3.1).
    /// RFC 6679 section 7.2: one initiation method per RTP session. Bundled sections that
    /// negotiated different methods use the first one's; another transport keeps its own.
    #[test]
    fn bundled_sections_use_one_initiation_method() {
        use EcnInitiation::{LeapOfFaith, RtpAndRtcp};
        let methods = EcnInitiation::one_per_transport(&[
            (0, Some(RtpAndRtcp)),
            (0, Some(LeapOfFaith)),
            (0, None),
            (1, Some(LeapOfFaith)),
        ]);
        assert_eq!(
            methods,
            vec![Some(RtpAndRtcp), Some(RtpAndRtcp), None, Some(LeapOfFaith)]
        );
    }

    #[test]
    fn the_ect_parameter_names_ect0_ect1_or_random_and_nothing_else() {
        assert_eq!(EctPreference::from_sdp("0"), Some(EctPreference::Ect0));
        assert_eq!(EctPreference::from_sdp(" 1"), Some(EctPreference::Ect1));
        assert_eq!(
            EctPreference::from_sdp("Random"),
            Some(EctPreference::Random)
        );
        assert_eq!(EctPreference::from_sdp("2"), None);
        assert_eq!(
            EcnMarking::Rfc6679.codepoint(None, true),
            shared::EcnCodepoint::Ect0,
            "RFC 6679 section 7.3.1: ECT(0) unless asked"
        );
        assert_eq!(
            EcnMarking::L4s.codepoint(Some(EctPreference::Ect0), false),
            shared::EcnCodepoint::Ect1
        );
    }

    #[test]
    fn counted_ect_probes_complete_the_initiation() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let sent: Vec<u16> = (0..40).collect();
        let marked = send(&mut v, &mut at, 0, 40);
        assert!(
            marked.len() >= 2 && marked.len() < 40,
            "probes only: {marked:?}"
        );
        let c = counters_for(&sent, &marked, true, 0, EcnCounters::default());
        v.on_counters(at, 39, c);
        assert_eq!(v.state(), EcnState::Active);
        assert_eq!(
            send(&mut v, &mut at, 40, 10).len(),
            10,
            "all marked once active"
        );
    }

    /// Section 7.2.1: a path that clears the field (probes counted not-ECT) fails the
    /// initiation; section 7.4.1: it is retried later.
    #[test]
    fn probes_counted_not_ect_fail_the_initiation() {
        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
        let mut at = Instant::now();
        let sent: Vec<u16> = (0..40).collect();
        let marked = send(&mut v, &mut at, 0, 40);
        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
        v.on_counters(at, 39, c);
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
        assert!(
            send(&mut v, &mut at, 40, 20).is_empty(),
            "nothing marked after the failure"
        );
        at += Duration::from_secs(11);
        assert!(
            !send(&mut v, &mut at, 60, 20).is_empty(),
            "probing again after the retry time"
        );
    }

    /// Section 7.4.2, ongoing use: once every packet goes out ECT, a receiver counting them
    /// not-ECT means the path clears the field, and marking stops.
    #[test]
    fn bleaching_counted_in_ongoing_use_stops_the_marking() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        let sent: Vec<u16> = (0..40).collect();
        let marked = send(&mut v, &mut at, 0, 40);
        assert_eq!(marked.len(), 40);
        let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
        v.on_counters(at, 39, c);
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
    }

    /// Section 7.4.1: high loss of ECT packets switches to not-ECT to compare.
    #[test]
    fn counted_loss_of_ect_packets_falls_back_to_not_ect() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        let sent: Vec<u16> = (0..40).collect();
        let marked = send(&mut v, &mut at, 0, 40);
        let c = counters_for(&sent, &marked, true, 20, EcnCounters::default());
        v.on_counters(at, 39, c);
        assert_eq!(v.state(), EcnState::Fallback);
        assert!(send(&mut v, &mut at, 40, 10).is_empty());
    }

    /// Sends `count` packets 20 ms apart from `first`; returns which were marked.
    fn send(v: &mut EcnValidation, at: &mut Instant, first: u16, count: u16) -> Vec<u16> {
        let mut marked = vec![];
        for n in 0..count {
            let seq = first.wrapping_add(n);
            if v.on_send(*at, seq) {
                marked.push(seq);
            }
            *at += Duration::from_millis(20);
        }
        marked
    }

    /// [`report`] from the participant `reporter`.
    fn report_from(
        v: &mut EcnValidation,
        at: Instant,
        reporter: Option<&str>,
        first: u16,
        count: u16,
        path: impl Fn(u16, bool) -> Option<Ecn>,
    ) {
        for n in 0..count {
            let seq = first.wrapping_add(n);
            let marked = v.was_marked(seq);
            match path(seq, marked) {
                Some(ecn) => v.on_report_from(at, reporter, seq, true, ecn),
                None => v.on_report_from(at, reporter, seq, false, Ecn::NotEct),
            }
        }
    }

    /// Reports `first..first + count`: `path(seq, marked)` says how each arrived.
    fn report(
        v: &mut EcnValidation,
        at: Instant,
        first: u16,
        count: u16,
        path: impl Fn(u16, bool) -> Option<Ecn>,
    ) {
        for n in 0..count {
            let seq = first.wrapping_add(n);
            let marked = v.was_marked(seq);
            match path(seq, marked) {
                Some(ecn) => v.on_report(at, seq, true, ecn),
                None => v.on_report(at, seq, false, Ecn::NotEct),
            }
        }
    }

    fn carries_ecn(_: u16, marked: bool) -> Option<Ecn> {
        Some(if marked { Ecn::Ect1 } else { Ecn::NotEct })
    }

    /// RFC 6679 section 7.2.1: after a provisional success, another RTCP CNAME within three
    /// reporting intervals of the initiation's start sends the sender back to probing; the
    /// same CNAME again does not.
    #[test]
    fn a_second_cname_during_a_provisional_success_sends_the_stream_back_to_probing() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        v.on_remote_cname(at, "peer");
        send(&mut v, &mut at, 0, 40);
        report(&mut v, at, 0, 40, carries_ecn);
        assert!(v.is_provisional(at));
        v.on_remote_cname(at, "peer");
        assert_eq!(v.state(), EcnState::Active, "the same receiver");
        assert!(!v.is_group());
        v.on_remote_cname(at, "another participant");
        assert_eq!(v.state(), EcnState::Initiating);
        assert!(v.is_group());
        let probes = send(&mut v, &mut at, 40, 40).len();
        assert!((1..40).contains(&probes), "a small fraction only: {probes}");
    }

    /// RFC 6679 section 7.2.1, the full procedure a group of participants needs: "An RTP sender
    /// shall consider the group membership to be stable after it has been in the session and
    /// sending ECT-marked probe packets for at least three RTCP reporting intervals ... and when
    /// a complete RTCP reporting interval has passed without changes to the group membership.
    /// ECN initiation is considered successful when the group membership is stable and all
    /// known participants have sent [reports] indicating correct receipt". Confirmations from
    /// one participant are not enough, nor are all of them before the membership is stable,
    /// and a participant that joins needs its own confirmation and another stable interval.
    #[test]
    fn a_group_initiation_succeeds_only_when_every_participant_confirmed_a_stable_membership() {
        let mut v = EcnValidation::default();
        let start = Instant::now();
        let mut at = start;
        v.on_remote_cname(at, "alice");
        v.on_remote_cname(at, "bob");
        assert!(v.is_group(), "two CNAMEs before the first probe");
        let mut seq = 0u16;
        // 50 packets (one second), reported by `who`.
        fn round(v: &mut EcnValidation, at: &mut Instant, seq: &mut u16, who: &[&str]) {
            send(v, at, *seq, 50);
            for reporter in who {
                report_from(v, *at, Some(reporter), *seq, 50, carries_ecn);
            }
            *seq = seq.wrapping_add(50);
        }

        // Alice confirms, over and over, past three intervals: not enough.
        while at < start + PROVISIONAL_MONITOR + REPORTING_INTERVAL {
            round(&mut v, &mut at, &mut seq, &["alice"]);
        }
        assert_eq!(v.state(), EcnState::Initiating, "bob has not confirmed");
        // Unattributed reports count for no one.
        let first = seq;
        send(&mut v, &mut at, first, 10);
        report(&mut v, at, first, 10, carries_ecn);
        seq = first + 10;
        assert_eq!(v.state(), EcnState::Initiating);

        // A third participant joins; then Bob and Alice confirm.
        v.on_remote_cname(at, "carol");
        let joined = at;
        round(&mut v, &mut at, &mut seq, &["alice", "bob"]);
        assert_eq!(v.state(), EcnState::Initiating, "carol has not confirmed");
        // Carol confirms at once; the membership changed less than an interval ago.
        round(&mut v, &mut at, &mut seq, &["carol"]);
        assert!(at < joined + REPORTING_INTERVAL);
        assert_eq!(v.state(), EcnState::Initiating, "not stable yet");
        // A complete interval without a change: every packet is marked.
        while at < joined + REPORTING_INTERVAL {
            round(&mut v, &mut at, &mut seq, &[]);
        }
        let marked = send(&mut v, &mut at, seq, 10);
        assert_eq!(v.state(), EcnState::Active);
        assert_eq!(marked.len(), 10, "all marked once the group confirmed");
        assert!(
            !v.is_provisional(at),
            "a full success, not a provisional one"
        );
    }

    #[test]
    fn initiation_marks_a_small_fraction_never_all() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let marked = send(&mut v, &mut at, 0, 100);
        assert!(marked.len() >= 4, "probes: {marked:?}");
        assert!(marked.len() <= 100 / 4, "a small fraction: {marked:?}");
        assert!(
            marked.windows(2).all(|w| w[1] - w[0] >= 2),
            "never two in a row: {marked:?}"
        );
        assert_eq!(v.state(), EcnState::Initiating);
    }

    #[test]
    fn a_slow_stream_still_probes_twice_a_second() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let mut marked = 0;
        // Five packets a second for two seconds.
        for seq in 0..10u16 {
            marked += u32::from(v.on_send(at, seq));
            at += Duration::from_millis(200);
        }
        assert!(marked >= 4, "{marked} probes in two seconds");
        assert!(marked < 10);
    }

    #[test]
    fn confirmed_probes_make_every_packet_ect() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        send(&mut v, &mut at, 0, 40);
        report(&mut v, at, 0, 40, carries_ecn);
        assert_eq!(v.state(), EcnState::Active);
        assert_eq!(send(&mut v, &mut at, 40, 20).len(), 20);
        assert!(v.marks_all());
    }

    #[test]
    fn a_ce_marked_probe_confirms_ecn_too() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        send(&mut v, &mut at, 0, 40);
        report(&mut v, at, 0, 40, |_, m| {
            Some(if m { Ecn::Ce } else { Ecn::NotEct })
        });
        assert_eq!(v.state(), EcnState::Active);
    }

    #[test]
    fn a_bleached_probe_fails_the_initiation_and_a_retry_follows() {
        let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
        let mut at = Instant::now();
        send(&mut v, &mut at, 0, 40);
        report(&mut v, at, 0, 40, |_, _| Some(Ecn::NotEct));
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
        assert!(send(&mut v, &mut at, 40, 100).is_empty(), "nothing marked");
        at += Duration::from_secs(10);
        assert!(
            !send(&mut v, &mut at, 140, 20).is_empty(),
            "initiating again"
        );
        assert_eq!(v.state(), EcnState::Initiating);
    }

    #[test]
    fn a_path_that_drops_ect_packets_fails_the_initiation() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let probes = send(&mut v, &mut at, 0, 60);
        assert!(probes.len() >= 4);
        report(&mut v, at, 0, 60, |_, m| (!m).then_some(Ecn::NotEct));
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
    }

    #[test]
    fn three_lost_probes_are_not_yet_a_failure() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let probes = send(&mut v, &mut at, 0, 60);
        let lost: Vec<u16> = probes[..3].to_vec();
        report(&mut v, at, 0, 60, |s, m| {
            if lost.contains(&s) {
                None
            } else {
                carries_ecn(s, m)
            }
        });
        assert_eq!(v.state(), EcnState::Active, "the fourth probe arrived ECT");
    }

    #[test]
    fn a_late_packet_reported_lost_then_received_is_not_a_loss() {
        let mut v = EcnValidation::default();
        let mut at = Instant::now();
        let probes = send(&mut v, &mut at, 0, 60);
        for &p in &probes {
            v.on_report(at, p, false, Ecn::NotEct);
            v.on_report(at, p, true, Ecn::Ect1);
            // A repeat of either report changes nothing.
            v.on_report(at, p, true, Ecn::Ect1);
            v.on_report(at, p, false, Ecn::NotEct);
        }
        assert_eq!(v.state(), EcnState::Active);
    }

    #[test]
    fn bleaching_during_use_stops_the_marking() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        assert_eq!(
            send(&mut v, &mut at, 0, 32).len(),
            32,
            "leap of faith marks all"
        );
        // A few bleached packets are not a failure.
        report(&mut v, at, 0, 32, |s, _| {
            Some(if s % 16 == 0 { Ecn::NotEct } else { Ecn::Ect1 })
        });
        assert_eq!(v.state(), EcnState::Active);
        send(&mut v, &mut at, 32, 32);
        report(&mut v, at, 32, 32, |_, _| Some(Ecn::NotEct));
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
        assert!(send(&mut v, &mut at, 64, 50).is_empty());
    }

    /// RFC 6679 section 7.2.3: under the leap of faith, a receiver report showing no reception
    /// is not enough (the receiver may have reported before any packet reached it); the second
    /// in a row ends the marking. A report showing reception in between starts the count over,
    /// and once reception was shown the path is taken as carrying ECT.
    #[test]
    fn leap_of_faith_waits_for_a_second_report_without_reception() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        // Nothing sent yet: a report says nothing.
        v.on_report_without_reception(at);
        v.on_report_without_reception(at);
        assert_eq!(v.state(), EcnState::Active);
        assert_eq!(send(&mut v, &mut at, 0, 10).len(), 10);
        v.on_report_without_reception(at);
        assert_eq!(v.state(), EcnState::Active, "one report is not enough");
        v.on_report_without_reception(at);
        assert!(
            matches!(v.state(), EcnState::Failed { .. }),
            "{:?}",
            v.state()
        );
        assert_eq!(v.take_failures(), vec![EcnFailure::NoReception]);
        assert!(
            send(&mut v, &mut at, 10, 10).is_empty(),
            "Not-ECT after the failure"
        );

        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        send(&mut v, &mut at, 0, 10);
        v.on_report_without_reception(at);
        v.on_reception_reported();
        v.on_report_without_reception(at);
        v.on_report_without_reception(at);
        assert_eq!(v.state(), EcnState::Active, "reception was reported");

        // The probing initiation does not use the rule.
        let mut v = EcnValidation::new(EcnInitiation::RtpAndRtcp);
        send(&mut v, &mut at, 0, 40);
        v.on_report_without_reception(at);
        v.on_report_without_reception(at);
        assert!(v.take_failures().is_empty());
    }

    #[test]
    fn loss_that_goes_with_the_marking_initiates_again_then_disables() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        let mut seq = 0u16;
        for round in 0..FALLBACKS_TO_DISABLE {
            // In use: ECT packets are dropped.
            if round > 0 {
                // Initiate again: probes go through, so the stream is back in use.
                let n = 40;
                send(&mut v, &mut at, seq, n);
                report(&mut v, at, seq, n, carries_ecn);
                seq += n;
            }
            assert_eq!(v.state(), EcnState::Active, "round {round}");
            send(&mut v, &mut at, seq, 32);
            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
            seq += 32;
            assert_eq!(v.state(), EcnState::Fallback, "round {round}");
            assert!(
                send(&mut v, &mut at, seq, 32).is_empty(),
                "Not-ECT while comparing"
            );
            report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
            seq += 32;
        }
        assert_eq!(v.state(), EcnState::Disabled);
        at += DEFAULT_RETRY_AFTER * 2;
        assert!(
            send(&mut v, &mut at, seq, 40).is_empty(),
            "disabled for good"
        );
        // RFC 6679 section 7.4.2: the erroneous behaviour detected is kept for follow-up, each
        // fallback and the final one.
        let mut expected =
            vec![EcnFailure::EctLost { disabled: false }; FALLBACKS_TO_DISABLE as usize - 1];
        expected.push(EcnFailure::EctLost { disabled: true });
        assert_eq!(v.take_failures(), expected);
        assert!(v.take_failures().is_empty(), "taken once");
    }

    #[test]
    fn loss_that_stays_without_the_marking_resumes_it() {
        let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
        let mut at = Instant::now();
        send(&mut v, &mut at, 0, 32);
        report(&mut v, at, 0, 32, |s, _| (s % 2 == 0).then_some(Ecn::Ect1));
        assert_eq!(v.state(), EcnState::Fallback);
        send(&mut v, &mut at, 32, 32);
        report(&mut v, at, 32, 32, |s, _| {
            (s % 2 == 0).then_some(Ecn::NotEct)
        });
        assert_eq!(v.state(), EcnState::Active, "congestion, not ECN");
    }

    /// A fixed corpus of arbitrary send / report sequences (sequence numbers that jump, wrap,
    /// repeat; reports out of order, duplicated, for unknown packets): nothing panics, a stream
    /// that is initiating never marks two packets in a row nor more than a quarter of them,
    /// and one that is disabled never marks again.
    #[test]
    fn arbitrary_send_and_report_sequences_keep_the_invariants() {
        let mut state = 0x0EC0_0001u32;
        let mut next = move || {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            state >> 8
        };
        for _ in 0..400 {
            let mut v = if next() % 2 == 0 {
                EcnValidation::default()
            } else {
                EcnValidation::new(EcnInitiation::LeapOfFaith)
            }
            .with_retry_after(Duration::from_millis(u64::from(next() % 3000)));
            let mut at = Instant::now();
            let mut seq = next() as u16;
            let mut sent: Vec<u16> = vec![];
            let mut run_marked = 0u32;
            let mut initiating = (0u32, 0u32);
            for _ in 0..600 {
                at += Duration::from_millis(u64::from(next() % 60));
                match next() % 10 {
                    0..=5 => {
                        seq = match next() % 20 {
                            0 => seq.wrapping_add(next() as u16),
                            1 => seq,
                            _ => seq.wrapping_add(1),
                        };
                        let was = v.state();
                        let marked = v.on_send(at, seq);
                        sent.push(seq);
                        if was == EcnState::Disabled {
                            assert!(!marked, "a disabled stream marks nothing");
                        }
                        if v.state() == EcnState::Initiating && was == EcnState::Initiating {
                            initiating.0 += 1;
                            initiating.1 += u32::from(marked);
                            run_marked = if marked { run_marked + 1 } else { 0 };
                            assert!(run_marked <= 1, "two probes in a row");
                        } else {
                            run_marked = 0;
                        }
                    }
                    _ => {
                        let target = if sent.is_empty() || next() % 8 == 0 {
                            next() as u16
                        } else {
                            sent[(next() as usize) % sent.len()]
                        };
                        let ecn = match next() % 4 {
                            0 => Ecn::NotEct,
                            1 => Ecn::Ect1,
                            2 => Ecn::Ect0,
                            _ => Ecn::Ce,
                        };
                        v.on_report(at, target, next() % 5 != 0, ecn);
                    }
                }
            }
            if initiating.0 >= 40 {
                assert!(
                    initiating.1 * 4 <= initiating.0 + 4,
                    "a small fraction while initiating: {initiating:?}"
                );
            }
        }
    }
}