rtci-interceptor 0.2.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
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
//! Bandwidth probing: short bursts above the target rate, and the capacity their arrival shows.
//!
//! A delay-based controller finds out that a path has room only by using it, and climbs a few
//! percent a second (8% in `Gcc`): from 300 kbit/s to 2.5 Mbit/s takes most of half a minute.
//! A probe asks the question directly. A cluster of packets leaves at a multiple of the target
//! for some milliseconds; if the receiver reports them arriving as closely spaced as they left,
//! the path carries that rate and the estimate moves there at once.
//!
//! RFC 8836 section 2 asks that a congestion controller "adapt as quickly as possible to
//! initial network conditions" and "allow for different modes of adaptation", naming "probing
//! during setup" as one (requirement 4, both SHOULD); draft-ietf-rmcat-gcc-02 has no probing at
//! all. It is what libwebrtc does, in outline. The peer connection's default interceptor set
//! probes (a SHOULD is met by default); `DefaultInterceptorOptions::bandwidth_probing` turns it
//! off, and a chain built by hand probes only with
//! [`CongestionControlBuilder::with_bandwidth_probing`](crate::CongestionControlBuilder::with_bandwidth_probing).
//!
//! The parts:
//!
//! - [`ProbeController`] decides when a cluster is sent and at what rate: two at the start
//!   (three and six times the starting rate), a further one at twice the result while results
//!   keep confirming the rate probed, and one every few seconds while the application sends
//!   less than the target allows, when nothing else would show that the path has grown; and,
//!   for a few seconds after the target dropped by a third or more, the rate before the drop.
//! - [`ProbeRequest`] is what travels through the chain: the congestion controller announces
//!   it on the read leg, the pacer releases the next packets at its rate and marks them
//!   ([`ProbePacket`]), and the NACK responder fills the cluster with padding-only packets on
//!   the RTX stream when the application's own media is not enough: they carry no media, so a
//!   receiver never has a packet twice.
//! - [`probe_estimate`] turns the receiver's reports on a cluster into a bit rate.
//!
//! In a chain without a pacer nothing releases a cluster at its rate. The NACK responder's
//! padding is then the cluster: it leaves as one burst with the cluster's mark, and
//! [`burst_estimate`] reads the rate of the narrowest link from how far apart the burst
//! arrived, never more than the rate asked for. Where nothing sends a cluster at all (no
//! pacer and no RTX stream to pad on), the congestion controller stops asking after the first
//! cluster that no packet left for, until another stream starts to send: a request that can
//! have no result is not made again.

use crate::rtpfb::acknowledgement::PacketReport;
use crate::{Attribute, AttributedPacket, Packet, TaggedPacket, Usage};
use shared::TransportContext;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// How long a cluster lasts at its rate, at least.
pub const PROBE_MIN_DURATION: Duration = Duration::from_millis(15);
/// How many packets a cluster has, at least.
pub const PROBE_MIN_PACKETS: usize = 5;
/// The size a probe packet is taken to have when a cluster is sized.
const PROBE_PACKET_OCTETS: usize = 1200;
/// The most a cluster asks for, whatever its rate.
pub const PROBE_MAX_OCTETS: usize = 64_000;
/// The clusters at the start, as multiples of the starting rate.
const INITIAL_PROBES: [f64; 2] = [3.0, 6.0];
/// The next cluster after a result, as a multiple of it.
const FURTHER_PROBE: f64 = 2.0;
/// A result confirms the rate probed when it reaches this share of it: the path was not the
/// limit, and probing goes on.
const FURTHER_PROBE_THRESHOLD: f64 = 0.7;
/// How often a cluster is sent while the application sends less than the target.
pub const PROBE_APPLICATION_LIMITED_INTERVAL: Duration = Duration::from_secs(5);
/// The share of the target below which the sender counts as application limited.
const APPLICATION_LIMITED_SHARE: f64 = 0.65;
/// How long a cluster's reports are waited for before it is given up.
pub const PROBE_RESULT_TIMEOUT: Duration = Duration::from_secs(1);
/// The least time between two clusters.
const PROBE_SPACING: Duration = Duration::from_millis(100);
/// The target falling below this share of its recent high is a large drop.
const LARGE_DROP_SHARE: f64 = 0.66;
/// How long the recent high of the target is remembered for drop detection.
const LARGE_DROP_WINDOW: Duration = Duration::from_secs(2);
/// How long after a large drop the old rate is probed for.
pub const PROBE_AFTER_DROP_TIMEOUT: Duration = Duration::from_secs(5);
/// The first probe after a large drop waits this long: the back-off has to take effect.
const PROBE_AFTER_DROP_DELAY: Duration = Duration::from_secs(1);
/// And they are this far apart.
const PROBE_AFTER_DROP_INTERVAL: Duration = Duration::from_secs(1);
/// A probe after a drop asks for this share of the rate before it.
const PROBE_AFTER_DROP_SHARE: f64 = 0.85;
/// How long the rate before a large drop is remembered as the rate the path had, for
/// recovery probing ([`ProbeController::with_recovery_probing`]): the highest such rate of
/// this long.
pub const PROBE_DROP_MEMORY: Duration = Duration::from_secs(60);
/// How often a recovery cluster is sent while the target is below the remembered rate
/// ([`ProbeController::with_recovery_probing`]).
pub const PROBE_RECOVERY_INTERVAL: Duration = Duration::from_secs(5);
/// [`AfterDropProbe::Libwebrtc`]: how long after the sender stopped being application limited
/// a drop is still probed (libwebrtc `kAlrEndedTimeout`).
const ALR_ENDED_TIMEOUT: Duration = Duration::from_secs(3);
/// [`AfterDropProbe::Libwebrtc`]: the least time between two probes after a drop (libwebrtc
/// `kMinTimeBetweenAlrProbes`).
const LIBWEBRTC_DROP_PROBE_INTERVAL: Duration = Duration::from_secs(5);
/// [`AfterDropProbe::Libwebrtc`]: the probe is asked only when 95% of it is above the
/// estimate (libwebrtc `kProbeUncertainty`).
const LIBWEBRTC_PROBE_UNCERTAINTY: f64 = 0.05;

/// What is probed for after a large drop of the target
/// ([`ProbeController::with_after_drop_probe`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AfterDropProbe {
    /// The engine's form, and the default. A drop of the target below two thirds of its high
    /// of the last two seconds is followed, from a second on and once a second for five
    /// seconds, by a cluster at 85% of that high while the target is still below it, whether
    /// or not the sender is application limited.
    ///
    /// No specification says how to probe after a drop (RFC 8836 section 2, 1f, asks only
    /// that a flow regain its share quickly), so the default is the form the capacity
    /// instrument measured best (`tests/capacity_instrument.rs`; the default chain, a
    /// 2.5 Mbit/s path that drops to 300 kbit/s for 20 s; 1000 calls in each of the two
    /// reference cells and 200 in six others, each form against this one by the merge-point
    /// rule of `docs/capacity-instrument.md`). Without a probe ([`Off`](Self::Off)) and with
    /// libwebrtc's ([`Libwebrtc`](Self::Libwebrtc), which never fires for a sender that
    /// keeps up with its target, so the two measure alike) seven figures are worse: with
    /// both directions limited the oldest picture is 3.07 s against 2.64 s, with 5% of the
    /// feedback lost the rate is not back within 20 s in 30 (24) of 200 calls against 2, and
    /// the target 15 to 25 s after the limit is 1205 against 1278 kbit/s. Asking for the
    /// highest rate of the last minute instead of the last drop's own high (the rate before
    /// the limit, not the peak of the controller's sawtooth under it) makes fifteen figures
    /// worse (audio packets lost 27 -> 35 a call, behind a 1000 ms queue over 2 s without a
    /// new picture in 33 of 200 calls against 6) and was not taken. What this form costs
    /// against no probe: behind a 1000 ms queue 96 audio packets lost a call against 66, and
    /// under a limit that lasts a minute 74 against 45.
    #[default]
    Repeated,
    /// libwebrtc's form (`ProbeController::RequestProbe`, goog_cc `probe_controller.cc`): a
    /// drop is one update of the estimate below two thirds of the one before it; one cluster
    /// at 85% of the estimate before the drop, asked when the delay-based detector has
    /// returned to normal after the drop ([`ProbeController::set_usage`]: under-use, then
    /// normal), only while the sender is application limited or was within the last three
    /// seconds, within five seconds of the drop, at most once in five seconds, and only when
    /// 95% of that rate is above the estimate.
    Libwebrtc,
    /// No probe after a drop: the climb back is the delay-based controller's.
    Off,
}

/// A probe cluster the congestion controller asks for.
///
/// Carried as an [`Attribute::Custom`] on an empty RTCP packet on the read leg
/// ([`ProbeRequest::into_packet`]), from the congestion controller towards the application:
/// the pacer and the NACK responder read it on its way past.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProbeRequest {
    /// Which cluster this is; the packets sent for it carry the same number.
    pub cluster: u32,
    /// The rate the cluster leaves at, bits per second.
    pub bits_per_second: f64,
    /// How much the cluster holds, octets on the wire.
    pub octets: usize,
}

impl ProbeRequest {
    /// The packet that carries this application-ward from where it is read at `now`.
    pub fn into_packet(self, now: Instant) -> TaggedPacket {
        TaggedPacket {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![]))
                .with(Attribute::Custom(Arc::new(self))),
        }
    }
}

/// How much padding a probe cluster needs, from the pacer that sends it.
///
/// The pacer reads a [`ProbeRequest`] first on its way application-ward and adds this to the
/// same carrier: the cluster's size less the media and retransmissions already waiting in its
/// queue, which leave first, at the cluster's rate and with its mark, and so fill the cluster
/// in place of padding. The NACK responder makes that much padding and no more (none at all
/// while a backlog waits, as during the pacer's pause): padding made for a cluster that media
/// fills never leaves in it, and each such packet uses up a sequence number of the RTX stream.
/// Without a pacer in the chain there is no such attribute and the responder fills the whole
/// cluster.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProbeFill {
    /// The cluster this is about ([`ProbeRequest::cluster`]).
    pub cluster: u32,
    /// The padding wanted, octets on the wire.
    pub octets: usize,
}

/// The mark of an RTP packet the pacer released as part of a probe cluster, as an
/// [`Attribute::Custom`] on its way to the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProbePacket {
    /// The cluster it belongs to.
    pub cluster: u32,
}

/// How much a cluster at `bits_per_second` holds.
pub(crate) fn cluster_octets(bits_per_second: f64) -> usize {
    let by_duration = (bits_per_second * PROBE_MIN_DURATION.as_secs_f64() / 8.0) as usize;
    by_duration.clamp(PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS, PROBE_MAX_OCTETS)
}

/// The bit rate a path showed it carries, from the reports on the packets of one cluster.
///
/// The cluster left at the send rate and arrived at the receive rate; the path carries the
/// lower of the two. The send rate is taken over all but the last packet and the span from
/// the first departure to the last, the receive rate over all but the first packet and the
/// span of the arrivals, so that each is octets over the time they took. When the packets
/// arrived more than a tenth slower than they left, the bottleneck was reached and held them
/// apart: the estimate is 95% of the receive rate, to stay below it.
///
/// `None` when fewer than four packets of the cluster arrived with a time, or their times do
/// not span anything: too little to measure.
pub fn probe_estimate(reports: &[PacketReport]) -> Option<f64> {
    let arrived: Vec<(Instant, Duration, usize)> = reports
        .iter()
        .filter(|report| report.arrived)
        .filter_map(|report| Some((report.departure, report.arrival?, report.size)))
        .collect();
    if arrived.len() < 4 {
        return None;
    }
    let total: usize = arrived.iter().map(|(_, _, size)| size).sum();

    let (first_sent, last_sent) =
        arrived
            .iter()
            .fold(None, |span: Option<(Instant, Instant)>, (sent, _, _)| {
                Some(span.map_or((*sent, *sent), |(first, last)| {
                    (first.min(*sent), last.max(*sent))
                }))
            })?;
    let last_sent_size = arrived
        .iter()
        .filter(|(sent, _, _)| *sent == last_sent)
        .map(|(_, _, size)| *size)
        .next_back()?;
    let (first_arrival, last_arrival) =
        arrived
            .iter()
            .fold(None, |span: Option<(Duration, Duration)>, (_, at, _)| {
                Some(span.map_or((*at, *at), |(first, last)| (first.min(*at), last.max(*at))))
            })?;
    let first_arrival_size = arrived
        .iter()
        .find(|(_, at, _)| *at == first_arrival)
        .map(|(_, _, size)| *size)?;

    let send_span = last_sent
        .saturating_duration_since(first_sent)
        .as_secs_f64();
    let receive_span = last_arrival.saturating_sub(first_arrival).as_secs_f64();
    if receive_span <= 0.0 {
        return None;
    }
    let receive_rate = (total - first_arrival_size) as f64 * 8.0 / receive_span;
    // Packets that left in the same instant have no send rate to compare with: the arrivals
    // alone say what the path did with them.
    if send_span <= 0.0 {
        return Some(receive_rate * 0.95);
    }
    let send_rate = (total - last_sent_size) as f64 * 8.0 / send_span;
    if receive_rate < 0.9 * send_rate {
        Some(receive_rate * 0.95)
    } else {
        Some(send_rate.min(receive_rate))
    }
}

/// The bit rate a path showed it carries, from the reports on a cluster that left as one burst
/// (a chain without a pacer: the NACK responder's padding, written in the same instant).
///
/// Such a cluster has no send rate. What the path did with it is the measurement: packets
/// that left together arrive as far apart as the narrowest link takes to send each, so the
/// octets after the first over the span of the arrivals is that link's rate (95% of it is
/// taken, as [`probe_estimate`] takes of a cluster the bottleneck held apart). The cluster was
/// asked for at `asked` bits per second and nothing was sent to show more than that: the
/// result is never above it, and it is `asked` itself when the arrivals span no time the
/// receiver's clock resolves.
///
/// A known limit of this measurement: a path that delivers the burst as one aggregate (a
/// Wi-Fi or cellular link that hands several packets over at once behind the narrow link)
/// shows no spread, or less than the narrow link made, and is credited with up to the rate
/// asked for although it carries less. Nothing was sent at that rate, so the cluster cannot
/// contradict it; the estimate is then above the path until the delay-based controller's
/// over-use detection brings it down, a few feedback reports after the media follows it. A
/// paced cluster does not have the limit (its packets leave at the rate asked for, and the
/// path either carries them so or delays them). The credit is not held to a multiple of
/// what the path carried in the last second: at the start, which is where the clusters
/// matter, the path has carried next to nothing yet.
///
/// `None` when fewer than four packets of the cluster arrived with a time.
pub fn burst_estimate(reports: &[PacketReport], asked: f64) -> Option<f64> {
    let arrived: Vec<(Duration, usize)> = reports
        .iter()
        .filter(|report| report.arrived)
        .filter_map(|report| Some((report.arrival?, report.size)))
        .collect();
    if arrived.len() < 4 {
        return None;
    }
    let total: usize = arrived.iter().map(|(_, size)| size).sum();
    let first = arrived.iter().min_by_key(|(at, _)| *at)?;
    let last = arrived.iter().max_by_key(|(at, _)| *at)?;
    let span = last.0.saturating_sub(first.0).as_secs_f64();
    if span <= 0.0 {
        return Some(asked);
    }
    Some(((total - first.1) as f64 * 8.0 / span * 0.95).min(asked))
}

/// Decides when a probe cluster is sent and at what rate.
#[derive(Debug)]
pub struct ProbeController {
    next_cluster: u32,
    /// Rates still to probe from the start-up sequence.
    initial: Vec<f64>,
    started: bool,
    /// The cluster awaiting its result: its number, its rate and when it was asked for.
    outstanding: Option<(u32, f64, Instant)>,
    last_probe: Option<Instant>,
    /// A further cluster owed after a result that confirmed its rate.
    further: Option<f64>,
    max_bitrate: f64,
    /// What is probed for after a large drop (see
    /// [`with_after_drop_probe`](Self::with_after_drop_probe)).
    after_drop: AfterDropProbe,
    /// The highest target of the last [`LARGE_DROP_WINDOW`], and when it was.
    peak: Option<(f64, Instant)>,
    /// The last large drop: the target before it, and when it happened.
    drop: Option<(f64, Instant)>,
    /// Whether the outstanding cluster probes for the rate before a drop.
    drop_probe: bool,
    /// When [`poll`](Self::poll) was last called.
    polled_at: Option<Instant>,
    /// Whether clusters leave as bursts of padding ([`set_unpaced`](Self::set_unpaced)).
    unpaced: bool,
    /// The target at the last [`poll`](Self::poll).
    last_target: Option<f64>,
    /// [`AfterDropProbe::Libwebrtc`]: the last update of the target below two thirds of the
    /// one before it: the target before it, and when.
    step_drop: Option<(f64, Instant)>,
    /// [`AfterDropProbe::Libwebrtc`]: when a probe after a drop was last asked for.
    last_drop_probe: Option<Instant>,
    /// Whether the sender is application limited, and when it last stopped being so.
    application_limited: bool,
    application_limited_ended: Option<Instant>,
    /// The estimator's reading of the path ([`set_usage`](Self::set_usage)), and whether it
    /// has returned from under-use to normal since the last poll.
    usage: Usage,
    recovered_from_overuse: bool,
    /// Whether the rate before a large drop is probed back towards for as long as it is
    /// remembered ([`with_recovery_probing`](Self::with_recovery_probing)).
    recovery: bool,
    /// The highest rate the target had before a large drop of the last
    /// [`PROBE_DROP_MEMORY`], and when that drop was.
    remembered: Option<(f64, Instant)>,
    /// When the last recovery cluster was asked for.
    last_recovery: Option<Instant>,
}

impl ProbeController {
    /// A controller for an estimator that starts at `initial_bitrate` and never goes above
    /// `max_bitrate`.
    pub fn new(initial_bitrate: f64, max_bitrate: f64) -> Self {
        Self {
            next_cluster: 1,
            initial: INITIAL_PROBES
                .iter()
                .rev()
                .map(|multiple| initial_bitrate * multiple)
                .collect(),
            started: false,
            outstanding: None,
            last_probe: None,
            further: None,
            max_bitrate,
            after_drop: AfterDropProbe::default(),
            peak: None,
            drop: None,
            drop_probe: false,
            polled_at: None,
            unpaced: false,
            last_target: None,
            step_drop: None,
            last_drop_probe: None,
            application_limited: false,
            application_limited_ended: None,
            usage: Usage::Normal,
            recovered_from_overuse: false,
            recovery: false,
            remembered: None,
            last_recovery: None,
        }
    }

    /// Whether the path is probed back towards the rate it carried before a large drop for as
    /// long as that rate is remembered: recovery probing. Off by default.
    ///
    /// A capacity that fell and comes back (a cellular link out of a tunnel, a competing
    /// transfer that ends after half a minute) leaves a sender that keeps up with its target
    /// at the bottom of the delay-based controller's climb: 8% a second, about 18 s from
    /// 250 kbit/s to 1 Mbit/s. Nothing else asks: the probes after a drop
    /// ([`with_after_drop_probe`](Self::with_after_drop_probe)) end five seconds after it, and
    /// the periodic ones are for a sender that sends less than its target. With this, the
    /// target before a large drop (below two thirds of its high of the last two seconds) is
    /// remembered for [`PROBE_DROP_MEMORY`] (the highest such rate, through the smaller
    /// drops of the time under the limit), and while the target is below 85% of it and the
    /// estimator does not read the path as over-used ([`set_usage`](Self::set_usage)),
    /// a cluster at twice the target is asked for every [`PROBE_RECOVERY_INTERVAL`], with
    /// further ones at twice the result while results confirm the rate probed. A cluster the
    /// path does not carry changes nothing (a probe only ever raises the estimate).
    ///
    /// No specification asks for it (RFC 8836 section 2 names probing at the start only;
    /// draft-ietf-rmcat-gcc-02 has no probing), and libwebrtc does not do it: its periodic
    /// probes are for an application-limited sender, its probe after a drop is one cluster
    /// within five seconds. It is a performance choice: it puts a cluster above the target
    /// into a path that may still be limited, every five seconds for up to a minute. Not for
    /// a chain whose clusters leave as bursts ([`set_unpaced`](Self::set_unpaced)).
    ///
    /// Measured on the capacity instrument (`tests/capacity_instrument.rs`; the default
    /// chain, a 2.5 Mbit/s path that drops to 300 kbit/s for 20 s, 200 calls a cell, without
    /// the setting against with it). WHAT IT GAINS: the target is back at 1 Mbit/s 4.9 s
    /// after the limit went (5.4 s at most) instead of 17.3 s, and at the 2.5 Mbit/s maximum
    /// through the window 15 to 25 s after it instead of 1283 kbit/s on average; the same
    /// behind a 100 ms queue (17.6 -> 5.0 s) and with both directions limited (16.2 -> 4.8 s);
    /// behind a 1000 ms queue in nine calls of ten (median 17.6 -> 5.0 s, the slowest tenth
    /// 17.5 s: the deep queue is still draining when the first clusters come). The five
    /// seconds are the interval: the wait is anywhere up to it. WHAT IT COSTS: under the
    /// limit the target is 238 kbit/s against 246 (3%), behind a 100 ms queue 52 audio
    /// packets are lost a call against 41 and 201 packets dropped at the queue against 159;
    /// the counts of calls with an old picture, a freeze or an audio gap do not move in any
    /// cell. WHERE IT GAINS NOTHING: a limit that outlasts the minute the rate is remembered
    /// (held 60 s: 17.6 s against 16.9 s, and the rate not back within 20 s in 33 of 200
    /// calls against 14). As bursts in a chain without a pacer the gain was the same and
    /// the calls with an old picture rose in every cell that had any (both directions
    /// limited 25 -> 31 of 200), which is why it is the paced chain's only.
    pub fn with_recovery_probing(mut self, enabled: bool) -> Self {
        self.recovery = enabled;
        self
    }

    /// What is probed for after a large drop of the target: [`AfterDropProbe`].
    pub fn with_after_drop_probe(mut self, after_drop: AfterDropProbe) -> Self {
        self.after_drop = after_drop;
        self
    }

    /// The estimator's reading of the path now
    /// ([`BandwidthEstimator::usage`](crate::BandwidthEstimator::usage)).
    /// [`AfterDropProbe::Libwebrtc`] asks for its cluster when the reading returns from
    /// under-use to normal: the queue an over-use left has drained (libwebrtc
    /// `DelayBasedBwe`: `recovered_from_overuse`).
    pub fn set_usage(&mut self, usage: Usage) {
        if self.usage == Usage::Under && usage == Usage::Normal {
            self.recovered_from_overuse = true;
        }
        self.usage = usage;
    }

    /// Whether the rate the target had before a large drop is probed for, for a few seconds
    /// after it: `true` is [`AfterDropProbe::Repeated`] (the default), `false`
    /// [`AfterDropProbe::Off`]; [`with_after_drop_probe`](Self::with_after_drop_probe) names
    /// libwebrtc's form too.
    ///
    /// A short burst of competing traffic, or a moment of loss, makes the delay-based
    /// controller back off by a third or more; once it has passed, the climb back is the
    /// controller's additive increase near the old operating point, half a packet per
    /// response time, and takes tens of seconds (23 s after a 2 s burst at half the capacity,
    /// in `rtci-interceptor/tests/rfc8836_multi_flow.rs`), against RFC 8836 section 2
    /// (requirement 1f: the flow "regains its share quickly"). With this, a drop of the
    /// target below two thirds of its high of the last two seconds is followed, from a second
    /// on and once a second for five seconds, by a cluster at 85% of the rate before the drop
    /// while the target is still below that. A result above the target raises it (as every
    /// probe does); one below it changes nothing: the competing traffic is still there.
    pub fn with_probe_after_drop(mut self, enabled: bool) -> Self {
        self.after_drop = if enabled {
            AfterDropProbe::Repeated
        } else {
            AfterDropProbe::Off
        };
        self
    }

    /// Whether this chain's clusters leave as one burst of padding (no pacer: the congestion
    /// controller says so when it measures a cluster whose packets left in one instant).
    ///
    /// Then the rate before a large drop is not probed for. A paced cluster is the media
    /// already waiting, released faster for a few milliseconds, with padding only for what
    /// is missing; a burst is five packets of padding on top of the media, at once. After a
    /// drop that is 160 ms of a 300 kbit/s link put into the queue that caused the drop, once
    /// a second. Measured on the capacity instrument (200 calls a cell, a 2.5 Mbit/s path
    /// that drops to 300 kbit/s): with such bursts 7 of 200 calls of ParolNet's chain were
    /// over 2 s without a new picture against 3 without them, 172 retransmissions a call
    /// against 142, and behind a 1000 ms queue the audio paused for over a second in 72 of
    /// 200 calls against 21. The start-up clusters and those of an application-limited
    /// sender are still asked for.
    pub fn set_unpaced(&mut self, unpaced: bool) {
        self.unpaced = unpaced;
    }

    /// The path changed and the estimator started over at `start_bitrate`: probing starts over
    /// too, as at the beginning of the call, and what was noted of the old path is dropped.
    ///
    /// The start-up clusters are owed again, at three and six times `start_bitrate` and on
    /// while the new path carries what is asked (RFC 8836 section 2, requirement 4: the
    /// conditions of a new path are initial conditions). The target's recent high, the drop
    /// below it and the cluster awaiting its result belong to the path that was left: the
    /// estimator's fall back to its starting rate is not a drop of the path's capacity, and
    /// the rate "before" it is the old path's.
    ///
    /// Without this an outage ended by an ICE restart left the call at the estimator's 8% a
    /// second on the new path (traced on the capacity instrument's outage cell, the default
    /// chain: 1 Mbit/s 15.1 s after the new pair). While nothing is acknowledged the
    /// estimator halves at every feedback timeout, each halving a large drop, and the probe
    /// for the rate before the last of them (133 kbit/s, asked into the dead path half a
    /// second before the new pair) was still awaiting its result when the path changed. It
    /// held the controller's one slot for the half second in which the sender, still sending
    /// at the old path's floor, counted as application limited against the new starting
    /// rate; after it nothing was due. Without the probe after a drop that
    /// application-limited cluster did find the path (1.0 s), but only in the calls where
    /// one happened to be due (134 of 200; 12 to 13 s in the others).
    ///
    /// libwebrtc does the same on a network route change: `ProbeController::Reset`
    /// (goog_cc `probe_controller.cc`) returns to its initial state and forgets the rate
    /// before the last large drop, and the constraints set next start the exponential probes
    /// again (`GoogCcNetworkController::OnNetworkRouteChange`).
    pub fn on_path_change(&mut self, now: Instant, start_bitrate: f64) {
        self.initial = INITIAL_PROBES
            .iter()
            .rev()
            .map(|multiple| start_bitrate * multiple)
            .collect();
        self.started = false;
        self.outstanding = None;
        self.last_probe = None;
        self.further = None;
        self.peak = None;
        self.drop = None;
        self.drop_probe = false;
        self.last_target = None;
        self.step_drop = None;
        // libwebrtc's `Reset` counts the change as the time of its last probe after a drop.
        self.last_drop_probe = Some(now);
        self.application_limited_ended = None;
        self.usage = Usage::Normal;
        self.recovered_from_overuse = false;
        // The rate remembered for recovery probing was the old path's.
        self.remembered = None;
        self.last_recovery = None;
    }

    /// The ceiling of what is probed for: the estimator's own maximum, or a limit from
    /// outside it (REMB, TMMBR, the session bit rate).
    pub fn set_max_bitrate(&mut self, max_bitrate: f64) {
        self.max_bitrate = max_bitrate;
    }

    /// The cluster to send now, if one is due.
    ///
    /// `target` is the current target bit rate and `sending` the rate the application is
    /// sending at; `media_flowing` is whether a packet has left yet (a probe before the
    /// first one would measure nothing the receiver reports).
    pub fn poll(
        &mut self,
        now: Instant,
        target: f64,
        sending: f64,
        media_flowing: bool,
    ) -> Option<ProbeRequest> {
        self.polled_at = Some(now);
        if !media_flowing {
            return None;
        }
        self.track_drops(now, target);
        self.track_application_limited(now, target, sending);
        let recovered_from_overuse = std::mem::take(&mut self.recovered_from_overuse);
        if let Some((_, _, asked)) = self.outstanding {
            if now.saturating_duration_since(asked) < PROBE_RESULT_TIMEOUT {
                return None;
            }
            // Its reports never came: the cluster is given up, and with it the sequence it
            // was part of.
            self.outstanding = None;
            self.further = None;
            self.drop_probe = false;
        }
        if self
            .last_probe
            .is_some_and(|last| now.saturating_duration_since(last) < PROBE_SPACING)
        {
            return None;
        }

        self.started = true;
        let rate = if let Some(rate) = self.initial.pop() {
            Some(rate)
        } else if let Some(rate) = self.further.take() {
            Some(rate)
        } else if let Some((before, at)) = self.drop
            && self.after_drop == AfterDropProbe::Repeated
            && !self.unpaced
            && now.saturating_duration_since(at) >= PROBE_AFTER_DROP_DELAY
            && target < PROBE_AFTER_DROP_SHARE * before
            && self
                .last_probe
                .is_none_or(|last| now.saturating_duration_since(last) >= PROBE_AFTER_DROP_INTERVAL)
        {
            // The rate before a large drop, while the drop is recent: if what caused it has
            // gone, the path carries it again.
            self.drop_probe = true;
            Some(PROBE_AFTER_DROP_SHARE * before)
        } else if let Some(rate) = self.libwebrtc_drop_probe(now, target, recovered_from_overuse) {
            self.drop_probe = true;
            self.last_drop_probe = Some(now);
            Some(rate)
        } else if self.recovery_due(now, target) {
            // Below the rate the path carried before a large drop that is still remembered:
            // what limited it may have gone, and a sender at its target is not asked by
            // anything else.
            self.last_recovery = Some(now);
            Some(target * FURTHER_PROBE)
        } else if sending < APPLICATION_LIMITED_SHARE * target
            && self.last_probe.is_none_or(|last| {
                now.saturating_duration_since(last) >= PROBE_APPLICATION_LIMITED_INTERVAL
            })
        {
            // Sending less than the target allows, the delay-based controller learns nothing
            // about the room above what is sent.
            Some(target * FURTHER_PROBE)
        } else {
            None
        }?;

        let rate = rate.min(self.max_bitrate);
        if rate <= target {
            // Nothing above the target is allowed, so there is nothing to ask.
            self.drop_probe = false;
            return None;
        }
        let cluster = self.next_cluster;
        self.next_cluster = self.next_cluster.wrapping_add(1).max(1);
        self.outstanding = Some((cluster, rate, now));
        self.last_probe = Some(now);
        Some(ProbeRequest {
            cluster,
            bits_per_second: rate,
            octets: cluster_octets(rate),
        })
    }

    /// Whether a recovery cluster is due: the setting, paced clusters, a remembered rate the
    /// target is well below, no over-use, and the interval since the drop or the last one.
    fn recovery_due(&self, now: Instant, target: f64) -> bool {
        let Some(at) = self.recovery_deadline() else {
            return false;
        };
        let Some((before, _)) = self.remembered else {
            return false;
        };
        now >= at && self.usage != Usage::Over && target < PROBE_AFTER_DROP_SHARE * before
    }

    /// When the next recovery cluster may be asked for, while a rate is remembered.
    fn recovery_deadline(&self) -> Option<Instant> {
        if !self.recovery || self.unpaced {
            return None;
        }
        let (_, dropped) = self.remembered?;
        let since = self.last_recovery.map_or(dropped, |last| last.max(dropped));
        Some(since + PROBE_RECOVERY_INTERVAL)
    }

    /// libwebrtc's probe after a drop (`ProbeController::RequestProbe`), when it is due: the
    /// detector has just returned to normal, the sender is or was lately application limited,
    /// the drop is under five seconds old, the last such probe over five seconds, and 95% of
    /// the rate to ask for is above the target.
    fn libwebrtc_drop_probe(
        &self,
        now: Instant,
        target: f64,
        recovered_from_overuse: bool,
    ) -> Option<f64> {
        if self.after_drop != AfterDropProbe::Libwebrtc || self.unpaced || !recovered_from_overuse {
            return None;
        }
        let limited = self.application_limited
            || self
                .application_limited_ended
                .is_some_and(|ended| now.saturating_duration_since(ended) < ALR_ENDED_TIMEOUT);
        let (before, at) = self.step_drop?;
        let rate = PROBE_AFTER_DROP_SHARE * before;
        (limited
            && (1.0 - LIBWEBRTC_PROBE_UNCERTAINTY) * rate > target
            && now.saturating_duration_since(at) < PROBE_AFTER_DROP_TIMEOUT
            && self.last_drop_probe.is_none_or(|last| {
                now.saturating_duration_since(last) > LIBWEBRTC_DROP_PROBE_INTERVAL
            }))
        .then_some(rate)
    }

    /// Whether the sender is application limited, and when it stopped being so.
    fn track_application_limited(&mut self, now: Instant, target: f64, sending: f64) {
        let limited = sending < APPLICATION_LIMITED_SHARE * target;
        if self.application_limited && !limited {
            self.application_limited_ended = Some(now);
        }
        self.application_limited = limited;
    }

    /// Follows the target's recent high, and notes a large drop below it.
    fn track_drops(&mut self, now: Instant, target: f64) {
        // libwebrtc's drop: one update below two thirds of the one before it.
        if let Some(last) = self.last_target
            && target < LARGE_DROP_SHARE * last
        {
            self.step_drop = Some((last, now));
        }
        self.last_target = Some(target);
        if self
            .remembered
            .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_DROP_MEMORY)
        {
            self.remembered = None;
        }
        match self.peak {
            Some((peak, at))
                if target < peak && now.saturating_duration_since(at) <= LARGE_DROP_WINDOW =>
            {
                if target < LARGE_DROP_SHARE * peak {
                    self.drop = Some((peak, now));
                    self.peak = Some((target, now));
                    // The highest rate before a drop of the last minute stays the one
                    // remembered: the smaller drops under a limit (the controller's own
                    // sawtooth) do not replace the rate the path had before it.
                    if self.remembered.is_none_or(|(before, _)| peak >= before) {
                        self.remembered = Some((peak, now));
                    }
                }
            }
            _ => self.peak = Some((target, now)),
        }
        if self
            .drop
            .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_AFTER_DROP_TIMEOUT)
        {
            self.drop = None;
        }
    }

    /// The number of the cluster whose result is awaited.
    pub fn outstanding(&self) -> Option<u32> {
        self.outstanding.map(|(cluster, _, _)| cluster)
    }

    /// The rate `cluster` was asked for at, while its result is awaited.
    pub fn asked_rate(&self, cluster: u32) -> Option<f64> {
        self.outstanding
            .filter(|(outstanding, _, _)| *outstanding == cluster)
            .map(|(_, rate, _)| rate)
    }

    /// The result of `cluster`: `estimate` bits per second. Returns the estimate when it is
    /// the outstanding cluster's, for the estimator to take.
    pub fn on_result(&mut self, cluster: u32, estimate: f64) -> Option<f64> {
        let (outstanding, rate, _) = self.outstanding?;
        if outstanding != cluster {
            return None;
        }
        self.outstanding = None;
        // The path carried what was asked of it: it may carry more. Not after a probe for the
        // rate before a drop: that asks only whether the path is back where it was.
        let drop_probe = std::mem::take(&mut self.drop_probe);
        if !drop_probe && estimate >= FURTHER_PROBE_THRESHOLD * rate && self.initial.is_empty() {
            let next = estimate * FURTHER_PROBE;
            if next <= self.max_bitrate * FURTHER_PROBE {
                self.further = Some(next);
            }
        }
        Some(estimate)
    }

    /// When [`poll`](Self::poll) next has something to say without anything else happening.
    ///
    /// Never an instant `poll` has already been called at or after: a deadline that passed
    /// with nothing to send (no media flowing, a sender that is no longer application
    /// limited, a target that recovered by itself) waits for the next write instead of
    /// asking to be woken again at once.
    pub fn poll_timeout(&self) -> Option<Instant> {
        self.deadlines()
            .into_iter()
            .flatten()
            .filter(|deadline| self.polled_at.is_none_or(|polled| *deadline > polled))
            .min()
    }

    /// The instants something may be due: a result to give up, the next cluster of a
    /// sequence or of an application-limited sender, the next probe after a drop, the next
    /// recovery cluster.
    fn deadlines(&self) -> [Option<Instant>; 3] {
        if !self.started {
            return [None, None, None];
        }
        if let Some((_, _, asked)) = self.outstanding {
            return [Some(asked + PROBE_RESULT_TIMEOUT), None, None];
        }
        let Some(last) = self.last_probe else {
            return [None, None, None];
        };
        let next = if !self.initial.is_empty() || self.further.is_some() {
            last + PROBE_SPACING
        } else {
            last + PROBE_APPLICATION_LIMITED_INTERVAL
        };
        let after_drop = self
            .drop
            .filter(|_| self.after_drop == AfterDropProbe::Repeated && !self.unpaced)
            .map(|(_, at)| (at + PROBE_AFTER_DROP_DELAY).max(last + PROBE_AFTER_DROP_INTERVAL));
        let recovery = self
            .recovery_deadline()
            .map(|at| at.max(last + PROBE_SPACING));
        [Some(next), after_drop, recovery]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;

    fn report(id: u64, departure: Instant, arrival_us: u64, size: usize) -> PacketReport {
        PacketReport {
            ssrc: 1,
            id,
            rtp_sequence_number: id as u16,
            is_twcc: true,
            twcc_sequence_number: id as u16,
            size,
            arrived: true,
            departure,
            arrival: Some(Duration::from_micros(arrival_us)),
            ecn: Ecn::NotEct,
        }
    }

    /// Six 1200-octet packets sent 2 ms apart (4.8 Mbit/s) that arrive 2 ms apart: the path
    /// carried the cluster, and the estimate is the rate it was sent at.
    #[test]
    fn a_cluster_that_arrives_as_it_left_shows_its_own_rate() {
        let epoch = Instant::now();
        let reports: Vec<PacketReport> = (0..6u64)
            .map(|i| {
                report(
                    i,
                    epoch + Duration::from_millis(2 * i),
                    50_000 + 2_000 * i,
                    1200,
                )
            })
            .collect();
        let estimate = probe_estimate(&reports).expect("measurable");
        assert!((estimate - 4_800_000.0).abs() < 1_000.0, "{estimate}");
    }

    /// The same cluster through a 2.4 Mbit/s bottleneck arrives 4 ms apart: the estimate is
    /// 95% of the rate it arrived at, not the rate it was sent at.
    #[test]
    fn a_cluster_spread_out_by_the_bottleneck_shows_the_bottleneck() {
        let epoch = Instant::now();
        let reports: Vec<PacketReport> = (0..6u64)
            .map(|i| {
                report(
                    i,
                    epoch + Duration::from_millis(2 * i),
                    50_000 + 4_000 * i,
                    1200,
                )
            })
            .collect();
        let estimate = probe_estimate(&reports).expect("measurable");
        assert!(
            (estimate - 0.95 * 2_400_000.0).abs() < 1_000.0,
            "{estimate}"
        );
    }

    /// Three arrivals are not a measurement, and neither are packets without arrival times.
    #[test]
    fn too_few_arrivals_give_no_estimate() {
        let epoch = Instant::now();
        let mut reports: Vec<PacketReport> = (0..3u64)
            .map(|i| {
                report(
                    i,
                    epoch + Duration::from_millis(2 * i),
                    50_000 + 2_000 * i,
                    1200,
                )
            })
            .collect();
        assert_eq!(None, probe_estimate(&reports));
        let mut lost = report(3, epoch + Duration::from_millis(6), 0, 1200);
        lost.arrived = false;
        lost.arrival = None;
        reports.push(lost);
        assert_eq!(None, probe_estimate(&reports));
    }

    /// At the start: three times the starting rate, then six times, each once its predecessor
    /// has a result, and nothing before media flows.
    #[test]
    fn the_start_probes_at_three_and_six_times_the_starting_rate() {
        let epoch = Instant::now();
        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
        assert_eq!(None, controller.poll(epoch, 300_000.0, 0.0, false));

        let first = controller
            .poll(epoch, 300_000.0, 300_000.0, true)
            .expect("first cluster");
        assert_eq!(900_000.0, first.bits_per_second);
        assert_eq!(
            PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS,
            first.octets,
            "five packets at least"
        );
        assert_eq!(
            None,
            controller.poll(
                epoch + Duration::from_millis(200),
                300_000.0,
                300_000.0,
                true
            ),
            "one cluster at a time"
        );

        assert_eq!(
            Some(900_000.0),
            controller.on_result(first.cluster, 900_000.0)
        );
        let second = controller
            .poll(
                epoch + Duration::from_millis(200),
                900_000.0,
                300_000.0,
                true,
            )
            .expect("second cluster");
        assert_eq!(1_800_000.0, second.bits_per_second);
    }

    /// A result that confirms the rate probed is followed by a cluster at twice the result; one
    /// that shows the bottleneck is not.
    #[test]
    fn probing_goes_on_while_the_path_carries_what_is_asked() {
        let epoch = Instant::now();
        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
        let mut now = epoch;
        let mut target = 300_000.0;
        let mut asked = Vec::new();
        // The path carries 2.5 Mbit/s.
        for _ in 0..8 {
            if let Some(request) = controller.poll(now, target, target, true) {
                asked.push(request.bits_per_second);
                let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
                target = controller
                    .on_result(request.cluster, estimate)
                    .expect("the outstanding cluster");
            }
            now += Duration::from_millis(150);
        }
        assert_eq!(
            vec![900_000.0, 1_800_000.0, 3_600_000.0],
            asked,
            "the third cluster found the bottleneck (2.375 of 3.6 Mbit/s) and ended the sequence"
        );
        assert_eq!(2_375_000.0, target);
    }

    /// While the application sends less than the target allows, a cluster goes out every five
    /// seconds; at the target, none.
    #[test]
    fn an_application_limited_sender_probes_every_few_seconds() {
        let epoch = Instant::now();
        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
        // The start-up sequence, answered with the bottleneck at once.
        for at in [epoch, epoch + Duration::from_millis(150)] {
            let request = controller
                .poll(at, 300_000.0, 300_000.0, true)
                .expect("start-up cluster");
            controller.on_result(request.cluster, 500_000.0);
        }

        let later = epoch + Duration::from_secs(6);
        assert_eq!(
            None,
            controller.poll(later, 1_000_000.0, 1_000_000.0, true),
            "sending at the target: the delay-based controller is asking already"
        );
        let request = controller
            .poll(later, 1_000_000.0, 200_000.0, true)
            .expect("application limited");
        assert_eq!(2_000_000.0, request.bits_per_second);
        controller.on_result(request.cluster, 1_200_000.0);
        assert_eq!(
            None,
            controller.poll(later + Duration::from_secs(1), 1_000_000.0, 200_000.0, true),
            "not again within five seconds"
        );
    }

    /// Nothing is probed above the ceiling, and a cluster whose reports never come is given up.
    #[test]
    fn the_ceiling_and_the_timeout_end_a_probe() {
        let epoch = Instant::now();
        let mut controller = ProbeController::new(300_000.0, 600_000.0);
        let request = controller
            .poll(epoch, 300_000.0, 300_000.0, true)
            .expect("capped cluster");
        assert_eq!(600_000.0, request.bits_per_second);
        assert_eq!(Some(request.cluster), controller.outstanding());
        assert_eq!(
            Some(epoch + PROBE_RESULT_TIMEOUT),
            controller.poll_timeout()
        );

        let after = epoch + PROBE_RESULT_TIMEOUT;
        // Given up; the next of the start-up sequence is capped at the ceiling too, which the
        // target has reached by then.
        assert_eq!(None, controller.poll(after, 600_000.0, 600_000.0, true));
        assert_eq!(None, controller.outstanding());
    }

    /// Settles a controller after its start-up sequence: two clusters answered at the
    /// bottleneck, so no further cluster is owed.
    fn settled(epoch: Instant) -> ProbeController {
        let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
        for at in [epoch, epoch + Duration::from_millis(150)] {
            let request = controller
                .poll(at, 300_000.0, 300_000.0, true)
                .expect("start-up cluster");
            controller.on_result(request.cluster, 500_000.0);
        }
        controller
    }

    /// RFC 8836 section 2 (1f): after a large drop of the target (a burst of competing
    /// traffic), the rate before it is probed for, from a second after the drop and once a
    /// second, and a result never asks for a further cluster above it.
    #[test]
    fn a_large_drop_is_followed_by_a_probe_at_the_rate_before_it() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        // At 2 Mbit/s, sending at the target, for a while.
        for ms in (1_000..2_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 2_000_000.0, 2_000_000.0, true)
            );
        }
        // Down to 900 kbit/s: a drop of more than a third.
        assert_eq!(None, controller.poll(at(2_000), 900_000.0, 900_000.0, true));
        assert_eq!(
            None,
            controller.poll(at(2_500), 900_000.0, 900_000.0, true),
            "the back-off is given a second first"
        );
        assert_eq!(Some(at(3_000)), controller.poll_timeout());
        let request = controller
            .poll(at(3_000), 900_000.0, 900_000.0, true)
            .expect("the rate before the drop");
        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
        // The path carries it again: the estimator takes it, and nothing above it is asked.
        assert_eq!(
            Some(1_700_000.0),
            controller.on_result(request.cluster, 1_700_000.0)
        );
        assert_eq!(
            None,
            controller.poll(at(3_200), 1_700_000.0, 1_700_000.0, true)
        );
        assert_eq!(
            None,
            controller.poll(at(4_500), 1_700_000.0, 1_700_000.0, true)
        );
    }

    /// While the competing traffic is still there the probe shows less than the rate before
    /// the drop: it is asked again a second later, and not after the drop is five seconds old.
    #[test]
    fn probes_after_a_drop_stop_after_a_few_seconds() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
        let mut probes = 0;
        for ms in (1_200..9_000).step_by(100) {
            if let Some(request) = controller.poll(at(ms), 900_000.0, 900_000.0, true) {
                probes += 1;
                assert!(ms <= 1_100 + 5_000, "at {ms} ms");
                controller.on_result(request.cluster, 950_000.0);
            }
        }
        assert!((3..=5).contains(&probes), "{probes} probes");
    }

    /// A chain whose clusters leave as bursts ([`ProbeController::set_unpaced`]) is not probed
    /// after a large drop, and names no deadline for it; the same drop is probed once the
    /// clusters are paced.
    #[test]
    fn a_drop_is_not_probed_while_clusters_leave_as_bursts() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        controller.set_unpaced(true);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        for ms in (1_100..4_000).step_by(100) {
            assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
            assert!(
                controller
                    .poll_timeout()
                    .is_none_or(|next| next > at(ms) + Duration::from_secs(1)),
                "a deadline for a probe that will not be asked for, at {ms} ms"
            );
        }
        controller.set_unpaced(false);
        let request = controller
            .poll(at(4_000), 900_000.0, 900_000.0, true)
            .expect("paced clusters: the rate before the drop");
        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
    }

    /// A path change starts probing over: the start-up clusters again, from the rate the
    /// estimator starts over at, and nothing of the old path's drop. The script is an outage
    /// ended by an ICE restart, as the default chain's estimator goes through it: at
    /// 2.5 Mbit/s, then halved every half second while nothing is acknowledged (each halving
    /// a large drop), a probe for the rate before the last one asked into the dead path, and
    /// the new path while that probe still awaits its result.
    #[test]
    fn a_path_change_starts_probing_over_and_forgets_the_drop() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        for ms in (1_000..2_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
            );
        }
        // The outage: 1250, 625, 312, 156 kbit/s, then the floor.
        let mut target = 2_500_000.0;
        for ms in (2_000..4_500).step_by(500) {
            target = f64::max(target / 2.0, 100_000.0);
            assert_eq!(None, controller.poll(at(ms), target, target, true));
        }
        assert_eq!(100_000.0, target);
        let stale = controller
            .poll(at(5_000), target, target, true)
            .expect("the rate before the last halving");
        assert_eq!(0.85 * 156_250.0, stale.bits_per_second);

        // The new path, 300 ms later: the estimator starts over at 300 kbit/s.
        controller.on_path_change(at(5_300), 300_000.0);
        assert_eq!(None, controller.outstanding(), "the old path's cluster");
        assert_eq!(None, controller.poll_timeout(), "nothing of the old path");
        let first = controller
            .poll(at(5_300), 300_000.0, 100_000.0, true)
            .expect("the first start-up cluster, at once");
        assert_eq!(900_000.0, first.bits_per_second);
        assert_eq!(
            None,
            controller.on_result(stale.cluster, 120_000.0),
            "a late result of the old path's cluster is nobody's"
        );
        assert_eq!(
            Some(900_000.0),
            controller.on_result(first.cluster, 900_000.0)
        );
        let second = controller
            .poll(at(5_450), 900_000.0, 300_000.0, true)
            .expect("the second start-up cluster");
        assert_eq!(1_800_000.0, second.bits_per_second);
        // The new path carries it: a further cluster, as at the start of the call.
        assert_eq!(
            Some(1_800_000.0),
            controller.on_result(second.cluster, 1_800_000.0)
        );
        let third = controller
            .poll(at(5_600), 1_800_000.0, 900_000.0, true)
            .expect("a further cluster");
        assert_eq!(3_600_000.0, third.bits_per_second);
        // It found the bottleneck. From here on the sender is at its target, and nothing of
        // the old path's drops is probed for in the seconds that follow.
        assert_eq!(
            Some(2_375_000.0),
            controller.on_result(third.cluster, 2_375_000.0)
        );
        for ms in (5_700..12_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 2_375_000.0, 2_375_000.0, true),
                "at {ms} ms"
            );
        }
    }

    /// The estimator's fall to its starting rate at a path change is not a drop to probe
    /// after: from 2.5 Mbit/s to 300 kbit/s on a new path that carries no more than the
    /// start-up clusters show, no cluster asks for the old path's rate.
    #[test]
    fn the_fall_to_the_starting_rate_at_a_path_change_is_not_a_drop() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        for ms in (1_000..2_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
            );
        }
        controller.on_path_change(at(2_000), 300_000.0);
        let mut asked = Vec::new();
        for ms in (2_000..10_000).step_by(100) {
            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
                asked.push(request.bits_per_second);
                // The new path is narrow: every cluster shows 350 kbit/s.
                controller.on_result(request.cluster, 350_000.0);
            }
        }
        assert_eq!(
            vec![900_000.0, 1_800_000.0],
            asked,
            "the start-up clusters, and no probe for 85% of 2.5 Mbit/s"
        );
    }

    /// [`AfterDropProbe::Libwebrtc`] across a path change: neither the old path's drop nor the
    /// estimator's fall to its starting rate is probed after, however often the new path's
    /// detector returns from under-use to normal (libwebrtc's `Reset` forgets the rate before
    /// the drop and counts the change as the time of its last such probe). The start-up
    /// clusters are all that is asked in the five seconds a drop stays eligible.
    #[test]
    fn libwebrtcs_probe_after_a_drop_is_not_asked_across_a_path_change() {
        let epoch = Instant::now();
        let mut controller = dropped_libwebrtc(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        controller.set_usage(Usage::Over);
        assert_eq!(None, controller.poll(at(1_200), 900_000.0, 450_000.0, true));
        controller.on_path_change(at(1_300), 300_000.0);
        let mut asked = Vec::new();
        for ms in (1_300..6_300).step_by(100) {
            recover_from_overuse(&mut controller);
            if let Some(request) = controller.poll(at(ms), 300_000.0, 150_000.0, true) {
                asked.push(request.bits_per_second);
                controller.on_result(request.cluster, 350_000.0);
            }
        }
        assert_eq!(vec![900_000.0, 1_800_000.0], asked);
    }

    /// A controller with libwebrtc's probe after a drop, settled, application limited (it
    /// sends half its target) at 2 Mbit/s until 1 s and dropped to 900 kbit/s at 1.1 s.
    fn dropped_libwebrtc(epoch: Instant) -> ProbeController {
        let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 1_000_000.0, true)
        );
        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 450_000.0, true));
        controller
    }

    /// The detector's way back to normal after an over-use: over, under, normal.
    fn recover_from_overuse(controller: &mut ProbeController) {
        controller.set_usage(Usage::Over);
        controller.set_usage(Usage::Under);
        controller.set_usage(Usage::Normal);
    }

    /// [`AfterDropProbe::Libwebrtc`]: nothing is asked until the detector has returned from
    /// under-use to normal; then one cluster at 85% of the target before the drop, which is
    /// not followed up, and no second one within five seconds.
    #[test]
    fn libwebrtcs_probe_after_a_drop_is_one_cluster_once_overuse_has_ended() {
        let epoch = Instant::now();
        let mut controller = dropped_libwebrtc(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        controller.set_usage(Usage::Over);
        for ms in (1_200..3_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 900_000.0, 450_000.0, true),
                "still over-used at {ms} ms"
            );
        }
        controller.set_usage(Usage::Under);
        assert_eq!(None, controller.poll(at(3_000), 900_000.0, 450_000.0, true));
        controller.set_usage(Usage::Normal);
        let request = controller
            .poll(at(3_100), 900_000.0, 450_000.0, true)
            .expect("back to normal: the rate before the drop");
        assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
        assert_eq!(
            Some(1_700_000.0),
            controller.on_result(request.cluster, 1_700_000.0)
        );
        assert_eq!(
            None,
            controller.poll(at(3_300), 1_700_000.0, 850_000.0, true),
            "no further cluster above it"
        );
        // A second drop and recovery a moment later: not within five seconds of the probe.
        assert_eq!(None, controller.poll(at(3_400), 900_000.0, 450_000.0, true));
        recover_from_overuse(&mut controller);
        assert_eq!(None, controller.poll(at(3_600), 900_000.0, 450_000.0, true));
    }

    /// [`AfterDropProbe::Libwebrtc`] does not probe a sender that keeps up with its target
    /// (not application limited, nor lately), nor one whose target is within 5% of the rate
    /// it would ask for, nor a drop that is five seconds old.
    #[test]
    fn libwebrtcs_probe_after_a_drop_has_its_conditions() {
        let epoch = Instant::now();
        let at = |ms: u64| epoch + Duration::from_millis(ms);

        // A sender at its target.
        let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
        recover_from_overuse(&mut controller);
        assert_eq!(None, controller.poll(at(1_300), 900_000.0, 900_000.0, true));

        // The target is back at 1.65 Mbit/s: 95% of 1.7 Mbit/s is not above it.
        let mut controller = dropped_libwebrtc(epoch);
        recover_from_overuse(&mut controller);
        assert_eq!(
            None,
            controller.poll(at(1_300), 1_650_000.0, 825_000.0, true)
        );

        // The detector is back to normal only once the drop is over five seconds old: no
        // cluster at the rate before the drop (the one asked meanwhile is the
        // application-limited sender's, at twice the target).
        let mut controller = dropped_libwebrtc(epoch);
        let mut asked = Vec::new();
        for ms in (1_200..7_000).step_by(100) {
            if ms == 6_200 {
                recover_from_overuse(&mut controller);
            }
            if let Some(request) = controller.poll(at(ms), 900_000.0, 450_000.0, true) {
                asked.push(request.bits_per_second);
                controller.on_result(request.cluster, 950_000.0);
            }
        }
        assert_eq!(vec![1_800_000.0], asked);
    }

    /// `with_probe_after_drop(false)`: a drop is left to the delay-based controller's climb.
    #[test]
    fn without_the_option_a_drop_is_not_probed() {
        let epoch = Instant::now();
        let mut controller = settled(epoch).with_probe_after_drop(false);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        for ms in (1_100..8_000).step_by(100) {
            assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
        }
    }

    /// A controller with recovery probing and without the probes after a drop (so that every
    /// cluster seen is a recovery cluster), settled, at 2 Mbit/s until 1 s and dropped to
    /// 300 kbit/s at 1.1 s.
    fn dropped_with_recovery(epoch: Instant) -> ProbeController {
        let mut controller = settled(epoch)
            .with_probe_after_drop(false)
            .with_recovery_probing(true);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        assert_eq!(None, controller.poll(at(1_100), 300_000.0, 300_000.0, true));
        controller
    }

    /// Recovery probing: after a large drop a sender at its target is asked for a cluster at
    /// twice the target every five seconds, from five seconds after the drop, for as long as
    /// the rate before the drop is remembered (a minute), and not after.
    #[test]
    fn recovery_probing_asks_twice_the_target_every_five_seconds_for_a_minute() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        let mut asked = Vec::new();
        for ms in (1_200..90_000).step_by(100) {
            if ms == 5_300 {
                assert_eq!(
                    Some(at(6_100)),
                    controller.poll_timeout(),
                    "the first recovery cluster's instant is a deadline"
                );
            }
            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
                assert_eq!(600_000.0, request.bits_per_second, "at {ms} ms");
                asked.push(ms);
                // The path is still limited: the cluster shows less than the target.
                controller.on_result(request.cluster, 285_000.0);
            }
        }
        let expected: Vec<u64> = (0..12).map(|n| 6_100 + 5_000 * n).collect();
        assert_eq!(
            expected, asked,
            "every 5 s from 5 s after the drop, for 60 s"
        );
    }

    /// The rate remembered for recovery probing is the path's: after a path change the
    /// start-up clusters look for the new path's rate, and when they show it to be narrow
    /// nothing goes on asking for the rate the old path had.
    #[test]
    fn recovery_probing_forgets_the_old_paths_rate_at_a_path_change() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        controller.on_path_change(at(2_000), 300_000.0);
        let mut asked = Vec::new();
        for ms in (2_000..30_000).step_by(100) {
            if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
                asked.push(request.bits_per_second);
                controller.on_result(request.cluster, 285_000.0);
            }
        }
        assert_eq!(
            vec![900_000.0, 1_800_000.0],
            asked,
            "the start-up clusters, and no recovery cluster for the old path's 2 Mbit/s"
        );
    }

    /// Without the setting (the default) nothing is asked of a sender at its target once the
    /// probes after the drop have ended.
    #[test]
    fn without_recovery_probing_a_sender_at_its_target_is_not_probed_after_the_drop() {
        let epoch = Instant::now();
        let mut controller = settled(epoch).with_probe_after_drop(false);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        assert_eq!(
            None,
            controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
        );
        for ms in (1_100..30_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 300_000.0, 300_000.0, true),
                "at {ms} ms"
            );
        }
    }

    /// A recovery cluster the path carries is followed by clusters at twice the result until
    /// one shows the bottleneck: the rate before the drop is back within a second.
    #[test]
    fn a_recovery_cluster_the_path_carries_is_followed_up() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        let mut target = 300_000.0;
        let mut asked = Vec::new();
        // The path carries 2.5 Mbit/s again.
        for ms in (1_200..8_000).step_by(100) {
            if let Some(request) = controller.poll(at(ms), target, target, true) {
                asked.push((ms, request.bits_per_second));
                let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
                target = controller
                    .on_result(request.cluster, estimate)
                    .expect("the outstanding cluster");
            }
        }
        assert_eq!(
            vec![
                (6_100, 600_000.0),
                (6_200, 1_200_000.0),
                (6_300, 2_400_000.0),
                (6_400, 4_750_000.0)
            ],
            asked
        );
        assert_eq!(2_375_000.0, target);
    }

    /// No recovery cluster while the estimator reads over-use; the one that was due goes out
    /// when it no longer does.
    #[test]
    fn recovery_probing_waits_while_the_path_is_overused() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        controller.set_usage(Usage::Over);
        for ms in (1_200..9_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 300_000.0, 300_000.0, true),
                "at {ms} ms"
            );
        }
        controller.set_usage(Usage::Normal);
        let request = controller
            .poll(at(9_000), 300_000.0, 300_000.0, true)
            .expect("no over-use: the cluster that was due");
        assert_eq!(600_000.0, request.bits_per_second);
    }

    /// The smaller drops under a limit (the controller's own sawtooth) do not replace the
    /// rate remembered from before it: a target above 85% of the sawtooth's peak is still
    /// probed, and one above 85% of the rate before the limit is not.
    #[test]
    fn recovery_probing_remembers_the_rate_before_the_limit_through_smaller_drops() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        // A sawtooth under the limit: up to 350 kbit/s, cut to 220 kbit/s (a large drop).
        assert_eq!(None, controller.poll(at(2_000), 350_000.0, 350_000.0, true));
        assert_eq!(None, controller.poll(at(2_100), 220_000.0, 220_000.0, true));
        // 400 kbit/s is above the sawtooth's peak and far below the 2 Mbit/s before the limit.
        let request = (2_200..8_000)
            .step_by(100)
            .find_map(|ms| controller.poll(at(ms), 400_000.0, 400_000.0, true))
            .expect("still below the remembered rate");
        assert_eq!(800_000.0, request.bits_per_second);
        controller.on_result(request.cluster, 380_000.0);
        // At 1.8 Mbit/s (over 85% of 2 Mbit/s) there is nothing left to recover.
        for ms in (8_000..20_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 1_800_000.0, 1_800_000.0, true),
                "at {ms} ms"
            );
        }
    }

    /// A chain whose clusters leave as bursts is not probed for recovery, and names no
    /// deadline for it.
    #[test]
    fn recovery_probing_is_not_for_clusters_that_leave_as_bursts() {
        let epoch = Instant::now();
        let mut controller = dropped_with_recovery(epoch);
        controller.set_unpaced(true);
        let at = |ms: u64| epoch + Duration::from_millis(ms);
        for ms in (1_200..20_000).step_by(100) {
            assert_eq!(
                None,
                controller.poll(at(ms), 300_000.0, 300_000.0, true),
                "at {ms} ms"
            );
            // The one deadline left is the application-limited cluster's, five seconds after
            // the start-up sequence.
            assert!(
                controller
                    .poll_timeout()
                    .is_none_or(|next| next == at(5_150)),
                "a deadline for a cluster that will not be asked for, at {ms} ms"
            );
        }
    }

    /// A deadline that came with nothing to send (here: an application-limited probe falls due
    /// while the sender has caught up with its target) is not asked for again: a driver that
    /// sleeps until `poll_timeout` would otherwise be woken at once, over and over.
    #[test]
    fn a_deadline_that_passed_with_nothing_due_is_not_asked_again() {
        let epoch = Instant::now();
        let mut controller = settled(epoch);
        let due = controller
            .poll_timeout()
            .expect("the next application-limited probe");
        assert_eq!(None, controller.poll(due, 1_000_000.0, 1_000_000.0, true));
        assert!(
            controller.poll_timeout().is_none_or(|next| next > due),
            "{:?}",
            controller.poll_timeout()
        );
        // Not flowing at all: nothing to wake for either.
        let later = due + Duration::from_secs(10);
        assert_eq!(None, controller.poll(later, 1_000_000.0, 0.0, false));
        assert!(controller.poll_timeout().is_none_or(|next| next > later));
    }
}