srt-runtime 0.13.1

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
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
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
//! One SRT connection as a sans-IO link: datagrams and the caller's `now` in, datagrams to
//! send and delivered payloads out.
//!
//! [`Link`] holds the whole per-connection conversation once the handshake has settled: the ARQ
//! receiver and sender, the TSBPD scheduler, the §6 payload cipher and KM Refresh, LiveCC pacing,
//! Keep-Alive and peer-idle timing, end-of-stream reporting, and DROPREQ/SHUTDOWN handling. It
//! never reads a clock and never touches a socket: every call takes `now` and leaves what must
//! go on the wire in [`Link::take_sent`].
//!
//! [`CallerLink`] is the caller role on top of it: the sans-IO [`CallerHandshake`] with its
//! retransmit period and budget, and the transition into a [`Link`] at the resolution. It serves
//! the tokio adapter ([`crate::io`]) and any embedded host that owns its own socket loop alike, so
//! the protocol has one implementation, not one per host.
//!
//! SRT: draft-sharabayko-srt-01 (handshake 4.3, TSBPD 4.5, too-late drop 4.6, ARQ 4.8, encryption 6).

use alloc::collections::{BTreeMap, VecDeque};
use alloc::vec::Vec;
use core::mem::size_of;
use core::num::NonZeroU32;
use core::time::Duration;

use broadcast_core::damage::{Damage, DamageError, DamagePolicy};
use broadcast_core::stage::Instant;

use crate::arq::seq::{contiguous_runs, seq_diff, seq_in_closed_range, seq_lt, seq_next};
use crate::arq::{Receiver as ArqReceiver, Sender as ArqSender, timestamp_to_wire_us};
use crate::caller::CallerHandshake;
use crate::damage as damage_reports;
use crate::handshake_sm::{HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason};
use crate::livecc::{LiveCC, MaxBwConfig};
use crate::packet::data::next_message_number;
use crate::packet::misc::{KeepAlivePacket, ShutdownPacket};
use crate::packet::{
    ControlPacket, DropReqPacket, EncryptionField, EncryptionKeyField, SRT_HEADER_LEN, SocketId,
    SrtPacket, SrtTimestamp,
};
use crate::tsbpd::{TickOutcome, TsbpdScheduler};
use sha2::{Digest, Sha256};

use crate::handshake_sm::CryptoConfig;
use crate::km_refresh::{KeyParity, KmRefreshDriver, KmRefreshEvent, KmRefreshThresholds};
use crate::packet::handshake::{EXT_TYPE_KMREQ, EXT_TYPE_KMRSP};
use crate::packet::{KeyMaterial, KmKeyFlag};
use zeroize::Zeroizing;

/// Initial TSBPD drift (zero: the scheduler estimates it from there).
const INITIAL_DRIFT_US: i64 = 0;

#[cfg(test)]
pub(crate) const TEST_DRIFT_WINDOW: NonZeroU32 = NonZeroU32::new(1000).expect("non-zero window");

/// Floor on how soon [`Link::next_deadline`] may ask to be woken: never a
/// deadline in the past, and a 1 ms minimum cannot spin (it matches the timer
/// granularity every hosted adapter here has).
pub const MIN_WAKE: Duration = Duration::from_millis(1);

/// Default SEK length when the connection's own key length is unknown: AES-128.
const DEFAULT_SEK_LEN: usize = 16;

fn micros(d: Duration) -> u64 {
    u64::try_from(d.as_micros()).unwrap_or(u64::MAX)
}

/// The `SHUTDOWN` datagram (§3.2.7) a leaving side sends its peer so the peer closes at once
/// instead of waiting out its idle timeout. `None` when the packet cannot be serialized.
#[must_use]
pub fn shutdown_datagram(peer_socket_id: u32, timestamp: Duration) -> Option<Vec<u8>> {
    let timestamp = timestamp_to_wire_us(Instant::from_micros(
        u64::try_from(timestamp.as_micros()).unwrap_or(u64::MAX),
    ));
    let pkt = ControlPacket::Shutdown(ShutdownPacket {
        timestamp,
        dest_socket_id: SocketId::from_wire(peer_socket_id),
        libsrt_pad: true,
    });
    let mut buf = alloc::vec![0u8; pkt.serialized_len()];
    pkt.serialize_into(&mut buf).ok()?;
    Some(buf)
}

// ===========================================================================
// What a caller supplies
// ===========================================================================

/// The protocol cadence a link keeps, every period chosen by the caller (libsrt's values are a
/// 250 ms handshake retransmit, a 1 s keep-alive; the rest are this crate's own choices).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkCadence {
    /// How often an unanswered handshake request is re-sent (§4.3.1.1).
    pub handshake_retransmit: Duration,
    /// Keep-Alive period, measured from the last packet of any kind sent (§3.2.3).
    pub keepalive: Duration,
    /// How often an unconfirmed refresh KMREQ is re-sent until its KMRSP arrives (§6.1.6).
    pub km_resend: Duration,
    /// Shortest interval between two peer Key Material messages this link processes: recovering
    /// the SEK runs a 2048-iteration PBKDF2, so a peer that re-sends KMREQ back to back must not
    /// spend a core on it (#2840).
    pub kmreq_min_interval: Duration,
}

/// Every time bound a link needs, all chosen by the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkTimers {
    /// The protocol cadence.
    pub cadence: LinkCadence,
    /// Longest the handshake may take before the attempt fails.
    pub handshake_timeout: Duration,
    /// Longest silence from a connected peer before the link ends.
    pub read_idle: Duration,
}

/// What a [`CallerLink`] is configured by: the handshake this side advertises, the connection's
/// own Socket ID and initial sequence number, its time bounds, and what the link may assume about
/// the stream it delivers.
///
/// The caller supplies the Socket ID and the ISN; a link never draws them itself, so a host that
/// reads no randomness (or derives them from a seed it keeps) can still open a connection.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CallerParams {
    /// The handshake this side advertises (latency, stream id, encryption).
    pub handshake: HandshakeConfig,
    /// This caller's own SRT Socket ID (§3).
    pub own_socket_id: u32,
    /// This caller's initial sequence number: the first sequence number it sends (§3.1).
    pub initial_seq_number: u32,
    /// The link's time bounds.
    pub timers: LinkTimers,
    /// The ARQ receiver's and sender's bounds.
    pub arq: crate::arq::ArqBounds,
    /// Secret entropy the link derives every refreshed stream key from; it draws none itself. A
    /// refresh that cannot be derived (an empty seed) is counted in
    /// [`LinkCounts::key_refresh_failed`] and reported as damage, never skipped silently.
    pub key_refresh_seed: Zeroizing<Vec<u8>>,
    /// A synchronous check on each delivered payload: one it refuses is counted and reported, and
    /// never delivered. The host names the payload format it expects; the link imposes none, so a
    /// link built with [`CallerParams::new`] admits every payload.
    pub payload_admits: fn(&[u8]) -> bool,
    /// The caller's decision about each damage report.
    pub damage_policy: DamagePolicy,
    /// Initial TSBPD drift. The scheduler estimates it from there; zero when none is known.
    pub drift_us: i64,
    /// Fresh in-sequence packets per drift-sampling window (§4.7, rules 26-27).
    /// The draft names no count, so the caller supplies one.
    pub drift_window: NonZeroU32,
    /// The LiveCC bandwidth policy that paces DATA packets (§5.1.1).
    pub max_bw: MaxBwConfig,
    /// KM Refresh thresholds (§6.1.6, key rotation packet counts).
    pub km_refresh_thresholds: KmRefreshThresholds,
    /// Whether a connection that negotiated encryption refuses a DATA packet sent in the clear,
    /// counting it undecryptable, rather than delivering it.
    pub refuse_cleartext: bool,
}

impl CallerParams {
    /// Parameters advertising `handshake` with this side's Socket ID and ISN, the caller's time
    /// bounds and key-refresh entropy, [`DamagePolicy::default`] (report everything), the default
    /// LiveCC policy and a link that admits every delivered payload.
    #[must_use]
    pub fn new(
        handshake: HandshakeConfig,
        own_socket_id: u32,
        initial_seq_number: u32,
        timers: LinkTimers,
        arq: crate::arq::ArqBounds,
        key_refresh_seed: Vec<u8>,
        drift_window: NonZeroU32,
    ) -> Self {
        Self {
            handshake,
            own_socket_id,
            initial_seq_number,
            timers,
            arq,
            key_refresh_seed: Zeroizing::new(key_refresh_seed),
            payload_admits: admits_every_payload,
            damage_policy: DamagePolicy::default(),
            drift_us: INITIAL_DRIFT_US,
            drift_window,
            max_bw: MaxBwConfig::default(),
            km_refresh_thresholds: KmRefreshThresholds::RECOMMENDED,
            refuse_cleartext: false,
        }
    }

    /// Set how long the handshake may take.
    #[must_use]
    pub fn with_handshake_timeout(mut self, handshake_timeout: Duration) -> Self {
        self.timers.handshake_timeout = handshake_timeout;
        self
    }

    /// Set which payloads the link delivers (see [`CallerParams::payload_admits`]).
    #[must_use]
    pub fn with_payload_admits(mut self, payload_admits: fn(&[u8]) -> bool) -> Self {
        self.payload_admits = payload_admits;
        self
    }

    /// Set the caller's decision about each damage report.
    #[must_use]
    pub fn with_damage_policy(mut self, damage_policy: DamagePolicy) -> Self {
        self.damage_policy = damage_policy;
        self
    }

    /// Set the initial TSBPD drift.
    #[must_use]
    pub fn with_drift_us(mut self, drift_us: i64) -> Self {
        self.drift_us = drift_us;
        self
    }

    /// Set the LiveCC bandwidth policy.
    #[must_use]
    pub fn with_max_bw(mut self, max_bw: MaxBwConfig) -> Self {
        self.max_bw = max_bw;
        self
    }

    /// Set the peer-idle bound.
    #[must_use]
    pub fn with_read_idle(mut self, read_idle: Duration) -> Self {
        self.timers.read_idle = read_idle;
        self
    }

    /// Set the §6 passphrase a peer's Key Material is recovered with. The encryption
    /// field this side advertises still comes from `handshake` (its `CryptoConfig`
    /// salt and stream key are overwritten per attempt).
    #[must_use]
    pub fn with_passphrase(mut self, passphrase: Vec<u8>) -> Self {
        self.handshake = self.handshake.with_crypto(Some(CryptoConfig {
            passphrase,
            salt: [0; crate::crypto::SALT_LEN],
            sek: Vec::new(),
        }));
        self
    }

    /// Refuse cleartext DATA on a connection that negotiated encryption (see
    /// [`CallerParams::refuse_cleartext`]).
    #[must_use]
    pub fn with_cleartext_refused(mut self) -> Self {
        self.refuse_cleartext = true;
        self
    }

    /// Set the KM Refresh thresholds.
    #[must_use]
    pub fn with_km_refresh_thresholds(mut self, thresholds: KmRefreshThresholds) -> Self {
        self.km_refresh_thresholds = thresholds;
        self
    }
}

#[cfg(test)]
pub(crate) const TEST_TIMERS: LinkTimers = LinkTimers {
    cadence: LinkCadence {
        handshake_retransmit: Duration::from_millis(250),
        keepalive: Duration::from_secs(1),
        km_resend: Duration::from_millis(500),
        kmreq_min_interval: Duration::from_millis(100),
    },
    handshake_timeout: Duration::from_secs(5),
    read_idle: Duration::from_secs(5),
};

fn admits_every_payload(_payload: &[u8]) -> bool {
    true
}

/// How a link ended, named once.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LinkEnd {
    /// The peer refused the handshake, with its reason (§4.3.1.2).
    Rejected(RejectionReason),
    /// No resolution arrived inside the handshake budget or the retransmit budget.
    HandshakeTimedOut,
    /// Nothing at all arrived from the connected peer for the peer-idle bound.
    PeerIdle,
    /// The peer sent `SHUTDOWN` (§3.2.7).
    PeerShutdown,
    /// The send key reached the packet count after which its keystream would repeat, and no
    /// refreshed key was confirmed: sending on would reuse keystream, so the link stops.
    KeyExhausted,
}

impl LinkEnd {
    /// A short label for this ending.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            LinkEnd::Rejected(_) => "Rejected",
            LinkEnd::HandshakeTimedOut => "HandshakeTimedOut",
            LinkEnd::PeerIdle => "PeerIdle",
            LinkEnd::PeerShutdown => "PeerShutdown",
            LinkEnd::KeyExhausted => "KeyExhausted",
        }
    }
}

broadcast_core::impl_spec_display!(LinkEnd);

/// What settled a connection: its negotiated parameters and the peer's own handshake values.
///
/// The peer's initial sequence number seeds ARQ/TSBPD sequence tracking and its handshake
/// timestamp seeds the TSBPD time base (rule 12); its SRT Socket ID is the wire `dest_socket_id`
/// for every outgoing packet (the two are unrelated values, §3).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LinkSetup {
    /// The negotiated parameters.
    pub params: NegotiatedParams,
    /// The peer's initial sequence number.
    pub peer_initial_seq: u32,
    /// The TSBPD time base (µs, signed): `T_NOW - HSREQ_TIMESTAMP`, with `T_NOW` the connection's
    /// own clock at the instant the peer's handshake arrived.
    pub time_base_us: i64,
}

impl LinkSetup {
    /// What `params` and the peer's own handshake values settle, for a [`Link`] that starts
    /// measuring at the instant that handshake arrived (the time base is the negated timestamp).
    #[must_use]
    pub fn new(params: NegotiatedParams, peer_initial_seq: u32, peer_timestamp_us: u32) -> Self {
        Self {
            params,
            peer_initial_seq,
            time_base_us: -i64::from(peer_timestamp_us),
        }
    }

    /// The time base of a connection whose clock started before the peer's handshake arrived.
    #[must_use]
    pub fn with_time_base_us(mut self, time_base_us: i64) -> Self {
        self.time_base_us = time_base_us;
        self
    }

    /// The time base of a connection whose clock started before the peer's handshake arrived,
    /// from `T_NOW`, the clock's reading at that arrival, and the peer's handshake timestamp.
    #[must_use]
    pub fn with_arrival(mut self, t_now: Duration, peer_timestamp_us: u32) -> Self {
        let t_now_us = i64::try_from(t_now.as_micros()).unwrap_or(i64::MAX);
        self.time_base_us = t_now_us.saturating_sub(i64::from(peer_timestamp_us));
        self
    }

    /// The peer's SRT Socket ID.
    #[must_use]
    pub fn peer_socket_id(&self) -> u32 {
        self.params.peer_socket_id
    }

    /// The TSBPD time base (§4.5.1.1, rule 12).
    #[must_use]
    pub fn time_base(&self) -> i64 {
        self.time_base_us
    }
}

/// One delivered application payload, held in the datagram it arrived in: the bytes from
/// [`Payload::start`] on. A host that hands payloads on as shared buffers takes the datagram and
/// the offset with [`Payload::into_parts`] and slices it, without a copy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Payload {
    datagram: Vec<u8>,
    start: usize,
}

impl Payload {
    #[cfg(test)]
    pub(crate) fn of(bytes: &[u8]) -> Self {
        Self {
            datagram: bytes.to_vec(),
            start: 0,
        }
    }

    /// The payload bytes.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        self.datagram.get(self.start..).unwrap_or_default()
    }

    /// Where the payload starts in the datagram it arrived in.
    #[must_use]
    pub fn start(&self) -> usize {
        self.start
    }

    /// The payload as its own vector: the datagram with the bytes before the payload removed,
    /// in place.
    #[must_use]
    pub fn into_vec(self) -> Vec<u8> {
        let Payload {
            mut datagram,
            start,
        } = self;
        datagram.drain(..start.min(datagram.len()));
        datagram
    }

    /// The datagram the payload arrived in and the offset it starts at.
    #[must_use]
    pub fn into_parts(self) -> (Vec<u8>, usize) {
        (self.datagram, self.start)
    }
}

/// One item a link hands its host, in the order the stream needs it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeliveredItem {
    /// A delivered application payload.
    Payload(Payload),
    /// A [`Damage`] report.
    Damage(Damage),
    /// The caller's [`DamagePolicy`] refused a report, naming the same report: the link has ended.
    Refused(DamageError),
    /// How the link ended.
    Ended(LinkEnd),
}

impl DeliveredItem {
    /// The kind of item: `payload`, `damage`, `refused` or `ended`.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            DeliveredItem::Payload(_) => "payload",
            DeliveredItem::Damage(_) => "damage",
            DeliveredItem::Refused(_) => "refused",
            DeliveredItem::Ended(_) => "ended",
        }
    }
}

broadcast_core::impl_spec_display!(DeliveredItem);

/// What one call on a link delivered, in order.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Delivered {
    items: Vec<DeliveredItem>,
}

impl Delivered {
    #[cfg(any(test, feature = "tokio"))]
    pub(crate) fn from_items(items: Vec<DeliveredItem>) -> Self {
        Self { items }
    }

    /// Nothing was delivered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The items, in order.
    #[must_use]
    pub fn items(&self) -> &[DeliveredItem] {
        &self.items
    }

    /// Take the items, in order.
    #[must_use]
    pub fn into_items(self) -> Vec<DeliveredItem> {
        self.items
    }

    /// The payloads alone, in order.
    pub fn payloads(&self) -> impl Iterator<Item = &[u8]> {
        self.items.iter().filter_map(|item| match item {
            DeliveredItem::Payload(payload) => Some(payload.as_slice()),
            _ => None,
        })
    }
}

/// The items one call produced, collected before they are ordered.
#[derive(Debug, Default)]
struct Batch {
    delivered: Vec<DeliveredItem>,
    reports: Vec<(usize, Damage)>,
    end: Option<LinkEnd>,
    refused: Option<DamageError>,
}

impl Batch {
    /// Place the reports at the points they belong to, and the ending (or refusal) last.
    fn finish(self, ended: &mut bool) -> Delivered {
        let Batch {
            mut delivered,
            reports,
            end,
            refused,
        } = self;
        for (at, damage) in reports.into_iter().rev() {
            delivered.insert(at, DeliveredItem::Damage(damage));
        }
        if let Some(error) = refused {
            *ended = true;
            delivered.push(DeliveredItem::Refused(error));
        }
        if let Some(end) = end {
            *ended = true;
            delivered.push(DeliveredItem::Ended(end));
        }
        Delivered { items: delivered }
    }

    fn payload(&mut self, payload: Payload) {
        self.delivered.push(DeliveredItem::Payload(payload));
    }

    fn report(&mut self, damage: Damage) {
        let at = self.delivered.len();
        self.reports.push((at, damage));
    }

    fn end(&mut self, end: LinkEnd) {
        self.end.get_or_insert(end);
    }
}

/// A count-based loss a link reports once per cause, so a recurring condition is one report, not
/// one per datagram.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CountedCause {
    /// The caller's payload check refused a delivered payload.
    PayloadRefused,
    /// An inbound DATA packet was further ahead of the delivery cursor than the flow window.
    OutOfWindow,
    /// An encrypted DATA packet could not be decrypted: no SEK for its `KK` parity, or the
    /// AES-CTR pass failed.
    Undecryptable,
    /// The peer sent a `PeerError` control packet, which this link has no reply for.
    PeerError,
    /// A datagram from the peer did not parse as an SRT packet at all.
    MalformedDatagram,
    /// A key refresh could not be announced.
    KeyRefreshFailed,
    /// A refresh key reached its switchover point without the peer confirming it, so the old
    /// key stays in use.
    KeyRefreshUnconfirmed,
}

/// How many [`CountedCause`]s a link tracks a report for, one per slot below.
const COUNTED_CAUSES: usize = 7;
/// Every count-based cause in slot order.
#[cfg(test)]
const COUNTED_BY_SLOT: [CountedCause; COUNTED_CAUSES] = [
    CountedCause::PayloadRefused,
    CountedCause::OutOfWindow,
    CountedCause::Undecryptable,
    CountedCause::PeerError,
    CountedCause::MalformedDatagram,
    CountedCause::KeyRefreshFailed,
    CountedCause::KeyRefreshUnconfirmed,
];

impl CountedCause {
    const fn slot(self) -> usize {
        match self {
            CountedCause::PayloadRefused => 0,
            CountedCause::OutOfWindow => 1,
            CountedCause::Undecryptable => 2,
            CountedCause::PeerError => 3,
            CountedCause::MalformedDatagram => 4,
            CountedCause::KeyRefreshFailed => 5,
            CountedCause::KeyRefreshUnconfirmed => 6,
        }
    }

    const fn what(self) -> &'static str {
        match self {
            CountedCause::PayloadRefused => "SRT delivered payload (refused by the host)",
            CountedCause::OutOfWindow => "SRT data packet (beyond the flow window)",
            CountedCause::Undecryptable => "SRT encrypted data packet (no usable key)",
            CountedCause::PeerError => "SRT peer error",
            CountedCause::MalformedDatagram => "SRT datagram (unparseable)",
            CountedCause::KeyRefreshFailed => "SRT key refresh (key material not announced)",
            CountedCause::KeyRefreshUnconfirmed => {
                "SRT key refresh (switchover without confirmation)"
            }
        }
    }
}

/// What a link has counted about the DATA it received, one total per kind, for a host that keeps
/// statistics.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LinkCounts {
    /// Datagrams from the peer that did not parse as SRT packets.
    pub unparseable: u64,
    /// Delivered payloads the caller's payload check refused.
    pub refused: u64,
    /// Encrypted DATA packets with no usable key, or that failed decryption.
    pub undecryptable: u64,
    /// DATA packets that arrived after their sequence number was delivered or given up on.
    pub late: u64,
    /// DATA packets that arrived while a copy was already staged.
    pub duplicates: u64,
    /// Sequence numbers given up on: too late for TSBPD (§4.6) or named by a peer drop request.
    pub lost: u64,
    /// Key refreshes that could not be announced (no key-refresh entropy, or the key material
    /// could not be built); each is retried on the next send.
    pub key_refresh_failed: u64,
    /// Refresh keys that reached their switchover point unconfirmed by the peer, so the old key
    /// stayed in use.
    pub key_refresh_unconfirmed: u64,
}

/// Which count-based causes a link has already reported.
#[derive(Debug, Default)]
struct DamageOnce {
    reported: [bool; COUNTED_CAUSES],
}

impl DamageOnce {
    fn slot(&mut self, cause: CountedCause) -> &mut bool {
        &mut self.reported[cause.slot()]
    }
}

/// One queued outbound DATA datagram. `retransmit` names the sequence number when the datagram is
/// a retransmission, so the sender's "already queued" mark is cleared when it leaves the queue
/// (#2819).
#[derive(Debug)]
struct OutboundData {
    bytes: Vec<u8>,
    retransmit: Option<u32>,
}

type SekSlot = Option<(Zeroizing<Vec<u8>>, [u8; crate::crypto::SALT_LEN])>;

/// The even/odd SEKs (with their Salts) of ONE direction. A connection holds two: what this side
/// encrypts with (generated by its own KM Refresh) and what it decrypts with (installed from the
/// peer's Key Material), because each side rotates its own SEKs (§6.1.6).
#[derive(Default)]
struct KeySet {
    even: SekSlot,
    odd: SekSlot,
}

impl KeySet {
    fn initial(sek: Option<&[u8]>, salt: Option<[u8; crate::crypto::SALT_LEN]>) -> Self {
        let mut keys = KeySet::default();
        if let (Some(sek), Some(salt)) = (sek, salt) {
            keys.install(KeyParity::Even, sek.to_vec(), salt);
        }
        keys
    }

    fn slot(&self, parity: KeyParity) -> &SekSlot {
        match parity {
            KeyParity::Even => &self.even,
            KeyParity::Odd => &self.odd,
        }
    }

    fn slot_mut(&mut self, parity: KeyParity) -> &mut SekSlot {
        match parity {
            KeyParity::Even => &mut self.even,
            KeyParity::Odd => &mut self.odd,
        }
    }

    fn get(&self, parity: KeyParity) -> Option<(&[u8], [u8; crate::crypto::SALT_LEN])> {
        self.slot(parity)
            .as_ref()
            .map(|(sek, salt)| (sek.as_slice(), *salt))
    }

    fn parity_of(key_field: EncryptionKeyField) -> Option<KeyParity> {
        match key_field {
            EncryptionKeyField::Even => Some(KeyParity::Even),
            EncryptionKeyField::Odd => Some(KeyParity::Odd),
            _ => None,
        }
    }

    fn install(&mut self, parity: KeyParity, sek: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN]) {
        *self.slot_mut(parity) = Some((Zeroizing::new(sek), salt));
    }

    fn clear(&mut self, parity: KeyParity) {
        *self.slot_mut(parity) = None;
    }

    fn is_empty(&self) -> bool {
        self.even.is_none() && self.odd.is_none()
    }
}

fn key_field_of(parity: KeyParity) -> EncryptionKeyField {
    match parity {
        KeyParity::Even => EncryptionKeyField::Even,
        KeyParity::Odd => EncryptionKeyField::Odd,
    }
}

fn parity_of_kk(kk: KmKeyFlag) -> Option<KeyParity> {
    match kk {
        KmKeyFlag::Even => Some(KeyParity::Even),
        KmKeyFlag::Odd => Some(KeyParity::Odd),
        _ => None,
    }
}

/// A KMREQ announcing a refreshed SEK the peer has not confirmed with a KMRSP yet, re-sent every
/// [`KM_RESEND_INTERVAL`] until it is.
struct PendingKm {
    parity: KeyParity,
    salt: [u8; crate::crypto::SALT_LEN],
    datagram: Vec<u8>,
    resend_at_us: Option<u64>,
}

// ===========================================================================
// Link — one established connection
// ===========================================================================

/// One established SRT connection, driven by datagrams and the caller's clock.
///
/// The host reads datagrams off its socket and calls [`Link::on_datagram`], wakes at the next
/// [`Link::next_deadline`] and calls [`Link::poll`], sends what [`Link::take_sent`] hands back,
/// and feeds application payloads in with [`Link::send`]. A host that owns an asynchronous socket
/// wakes on both at once and calls [`Link::poll_io`] after every wake-up.
pub struct Link {
    peer_socket_id: u32,
    epoch_us: u64,
    receiver: ArqReceiver,
    sender: ArqSender,
    pacing_burst_packets: usize,
    tsbpd: TsbpdScheduler,
    livecc: LiveCC,
    staged: BTreeMap<u32, Payload>,
    outbound_control: Vec<Vec<u8>>,
    outbound_data: VecDeque<OutboundData>,
    next_message_number: u32,
    next_send_seq: u32,
    last_rx_us: u64,
    last_tx_us: u64,
    read_idle_us: u64,
    max_flow_window: u32,
    payload_admits: fn(&[u8]) -> bool,
    damage_policy: DamagePolicy,
    reported: DamageOnce,
    counts: LinkCounts,
    refuse_cleartext: bool,
    ended: bool,
    /// The earliest instant the next DATA packet may go out; `None` while no DATA packet is
    /// pacing-blocked.
    next_data_send_at_us: Option<u64>,
    crypto_passphrase: Zeroizing<Vec<u8>>,
    tx_keys: KeySet,
    rx_keys: KeySet,
    tx_parity: KeyParity,
    km_pending: Option<PendingKm>,
    retire_deferred: Option<KeyParity>,
    crypto_key_len: usize,
    km_refresh: KmRefreshDriver,
    #[cfg(test)]
    km_refresh_thresholds: KmRefreshThresholds,
    kek_cache: crate::crypto::KekCache,
    last_peer_kmreq_us: Option<u64>,
    timers: LinkTimers,
    key_refresh_seed: Zeroizing<Vec<u8>>,
    key_refresh_counter: u64,
    key_refresh_retry: Option<KeyParity>,
    tx_key_sent: u64,
    tx_key_limit: u64,
    key_exhausted: bool,
}

impl Link {
    /// Starts the silence clocks (peer idle and keep-alive) at `now`, the instant the connection
    /// was concluded, when the link's own clock began earlier, at the handshake's start.
    pub fn start_idle_clock(&mut self, now: Instant) {
        self.last_rx_us = now.as_micros();
        self.last_tx_us = now.as_micros();
    }

    /// An established link to the peer `setup` settled with, whose clock reads `now` at its start.
    #[must_use]
    pub fn new(now: Instant, setup: &LinkSetup, params: &CallerParams) -> Self {
        let now_us = now.as_micros();
        let peer_socket_id = setup.peer_socket_id();
        Self {
            peer_socket_id,
            epoch_us: now_us,
            receiver: ArqReceiver::new(
                peer_socket_id,
                setup.peer_initial_seq,
                setup.params.max_flow_window_size,
                setup.params.mtu,
                params.arq.receiver,
            ),
            sender: ArqSender::new(peer_socket_id, params.arq.sender),
            pacing_burst_packets: params.arq.sender.pacing_burst_packets,
            tsbpd: TsbpdScheduler::new(
                setup.peer_initial_seq,
                setup.time_base(),
                setup.params.latency,
                params.drift_us,
                setup.params.flags.tlpktdrop(),
                None,
                params.arq.receiver.max_pending_skips,
                params.drift_window,
            ),
            livecc: LiveCC::new(params.max_bw),
            staged: BTreeMap::new(),
            outbound_control: Vec::new(),
            outbound_data: VecDeque::new(),
            next_message_number: 1,
            next_send_seq: params.initial_seq_number,
            last_rx_us: now_us,
            last_tx_us: now_us,
            read_idle_us: micros(params.timers.read_idle),
            max_flow_window: setup.params.max_flow_window_size,
            payload_admits: params.payload_admits,
            damage_policy: params.damage_policy.clone(),
            reported: DamageOnce::default(),
            counts: LinkCounts::default(),
            refuse_cleartext: params.refuse_cleartext,
            ended: false,
            next_data_send_at_us: None,
            crypto_passphrase: Zeroizing::new(
                params
                    .handshake
                    .crypto
                    .as_ref()
                    .map(|c| c.passphrase.as_slice().to_vec())
                    .unwrap_or_default(),
            ),
            tx_keys: KeySet::initial(setup.params.sek.as_deref(), setup.params.salt),
            rx_keys: KeySet::initial(setup.params.sek.as_deref(), setup.params.salt),
            tx_parity: KeyParity::Even,
            km_pending: None,
            retire_deferred: None,
            crypto_key_len: setup
                .params
                .sek
                .as_ref()
                .map(|sek| sek.len())
                .or_else(|| setup.params.salt.map(|_| DEFAULT_SEK_LEN))
                .unwrap_or(0),
            km_refresh: KmRefreshDriver::new(params.km_refresh_thresholds, KeyParity::Even),
            #[cfg(test)]
            km_refresh_thresholds: params.km_refresh_thresholds,
            kek_cache: crate::crypto::KekCache::default(),
            last_peer_kmreq_us: None,
            timers: params.timers,
            key_refresh_seed: params.key_refresh_seed.clone(),
            key_refresh_counter: 0,
            key_refresh_retry: None,
            tx_key_sent: 0,
            tx_key_limit: KEYSTREAM_PACKETS,
            key_exhausted: false,
        }
    }

    /// The peer's SRT Socket ID: the `dest_socket_id` of every packet sent, and the one a
    /// `SHUTDOWN` names.
    #[must_use]
    pub fn peer_socket_id(&self) -> u32 {
        self.peer_socket_id
    }

    /// The `now` this link measures its protocol time from.
    #[must_use]
    pub fn epoch(&self) -> Instant {
        Instant::from_micros(self.epoch_us)
    }

    /// Whether the link has ended: it delivers and sends nothing more.
    #[must_use]
    pub fn is_ended(&self) -> bool {
        self.ended
    }

    /// Room in the send window: fewer than a full flow window of packets are buffered
    /// unacknowledged (§3.2.1), so the host may hand another payload over.
    #[must_use]
    pub fn send_window_open(&self) -> bool {
        let window = usize::try_from(self.max_flow_window)
            .unwrap_or(usize::MAX)
            .max(1);
        self.sender.buffered_count() < window
    }

    /// The link's own clock: `now` since the connection started.
    fn elapsed(&self, now_us: u64) -> Instant {
        Instant::from_micros(now_us.saturating_sub(self.epoch_us))
    }

    /// The wire `Instant` for a control packet: it wraps modulo `2^32` past ~71.58 minutes.
    fn wire_now(&self, now_us: u64) -> SrtTimestamp {
        timestamp_to_wire_us(self.elapsed(now_us))
    }

    /// The `SHUTDOWN` datagram (§3.2.7) telling the peer this side is leaving. `None` once the
    /// link has ended: the peer is already gone and has nothing left to be told.
    #[must_use]
    pub fn shutdown_datagram(&self, now: Instant) -> Option<Vec<u8>> {
        if self.ended {
            return None;
        }
        shutdown_datagram(
            self.peer_socket_id,
            Duration::from_micros(now.as_micros().saturating_sub(self.epoch_us)),
        )
    }

    /// The sequence number the scheduler releases next: every packet below it is
    /// delivered or given up on.
    #[must_use]
    pub fn next_release(&self) -> u32 {
        self.tsbpd.next_release()
    }

    /// Whether Too-Late Packet Drop was negotiated (§4.6): only then may the
    /// receiver skip a gap nothing filled in time.
    #[must_use]
    pub fn tlpktdrop_enabled(&self) -> bool {
        self.tsbpd.tlpktdrop_enabled()
    }

    /// Set the LiveCC bandwidth policy that paces DATA packets from here on.
    pub fn set_max_bw(&mut self, max_bw: MaxBwConfig) {
        self.livecc.set_max_bw_config(max_bw);
    }

    /// The next Full ACK / NAK instant of the receive direction, if it has one.
    #[must_use]
    pub fn next_ack(&self) -> Option<Instant> {
        self.receiver
            .next_deadline()
            .and_then(|t| self.epoch_us.checked_add(t.as_micros()))
            .map(Instant::from_micros)
    }

    /// The pacing period one DATA packet's slot advances by under the current policy.
    #[must_use]
    pub fn pacing_period(&self) -> Duration {
        self.livecc.on_ack_received()
    }

    /// How many DATA and control datagrams are still queued for the wire.
    #[must_use]
    pub fn queued_len(&self) -> usize {
        self.outbound_data.len() + self.outbound_control.len()
    }

    /// How many sent DATA packets are still unacknowledged. A closing sender drains these before
    /// sending SHUTDOWN so the tail of a stream is not lost to an unheard retransmission.
    #[must_use]
    pub fn buffered_count(&self) -> usize {
        self.sender.buffered_count()
    }

    /// How many sequence numbers are waiting to be retransmitted.
    #[must_use]
    pub fn pending_retransmit_count(&self) -> usize {
        self.sender.pending_retransmit_count()
    }

    /// The mean DATA payload size LiveCC paces from.
    #[must_use]
    pub fn average_payload_size(&self) -> u64 {
        self.livecc.avg_payload_size()
    }

    /// How many received packets are staged, waiting for TSBPD to release them.
    #[must_use]
    pub fn staged_len(&self) -> usize {
        self.staged.len()
    }

    /// The cumulative ACK point of the receive direction: every sequence number
    /// below it is accounted for, delivered or given up on.
    #[must_use]
    pub fn ack_point(&self) -> u32 {
        self.receiver.ack_point()
    }

    /// How many received packets are missing between the delivery cursor and the
    /// highest one seen.
    #[must_use]
    pub fn loss_list_len(&self) -> usize {
        self.receiver.loss_list_len()
    }

    /// The receive direction's round-trip estimate (rule 33).
    #[must_use]
    pub fn rtt(&self) -> Duration {
        self.receiver.rtt()
    }

    #[cfg(test)]
    /// The count-based drops this link has already reported, one flag per cause:
    /// a refused payload, an out-of-window packet, an undecryptable packet, a
    /// peer error, an unparseable datagram.
    #[must_use]
    pub fn reported_causes(&self) -> [bool; COUNTED_CAUSES] {
        self.reported.reported
    }

    /// What this link has counted about the DATA it received.
    #[must_use]
    pub fn counts(&self) -> LinkCounts {
        self.counts
    }

    #[cfg(test)]
    /// The reason a count-based report names for the cause at `index` of
    /// [`Link::reported_causes`].
    #[must_use]
    pub fn counted_cause_what(index: usize) -> Option<&'static str> {
        COUNTED_BY_SLOT.get(index).copied().map(CountedCause::what)
    }

    /// The sequence number the next first transmission carries.
    #[must_use]
    pub fn next_send_seq(&self) -> u32 {
        self.next_send_seq
    }

    /// The message number the next first transmission carries.
    #[must_use]
    pub fn next_message_number(&self) -> u32 {
        self.next_message_number
    }

    #[cfg(test)]
    /// Put the next message number where `next` is, so a host can start a
    /// connection from an arbitrary point of the wrapping space.
    pub fn set_next_message_number(&mut self, next: u32) {
        self.next_message_number = next;
    }

    #[cfg(test)]
    /// Set the §6 passphrase a peer's Key Material is recovered with.
    pub fn set_passphrase(&mut self, passphrase: Vec<u8>) {
        self.crypto_passphrase = Zeroizing::new(passphrase);
    }

    #[cfg(test)]
    /// Whether both direction keys are installed (a `KK = Both` exchange).
    #[must_use]
    pub fn rx_keys_installed(&self) -> bool {
        self.rx_keys.get(KeyParity::Even).is_some() && self.rx_keys.get(KeyParity::Odd).is_some()
    }

    #[cfg(test)]
    /// How many Key Material messages this connection has derived a KEK for.
    #[must_use]
    pub fn kek_derivations(&self) -> u64 {
        self.kek_cache.derivations()
    }

    #[cfg(test)]
    /// Which of the two keys new outgoing packets are encrypted under.
    #[must_use]
    pub fn tx_parity_name(&self) -> &'static str {
        self.tx_parity.name()
    }

    #[cfg(test)]
    /// Whether a refreshed SEK is still waiting for the peer's confirmation.
    #[must_use]
    pub fn refresh_pending(&self) -> bool {
        self.km_pending.is_some()
    }

    #[cfg(test)]
    /// Put `sek` in the send direction under `parity`, without touching the active one.
    fn install_key(&mut self, parity: KeyParity, sek: Vec<u8>) {
        self.tx_keys
            .install(parity, sek, [0; crate::crypto::SALT_LEN]);
    }

    #[cfg(test)]
    /// Put a key under `parity` and make that parity the send direction's active one.
    pub fn install_active_parity(&mut self, parity: KeyParity) {
        self.tx_keys.install(
            parity,
            alloc::vec![3u8; DEFAULT_SEK_LEN],
            [0; crate::crypto::SALT_LEN],
        );
        self.tx_parity = parity;
        self.km_refresh = KmRefreshDriver::new(self.km_refresh_thresholds, parity);
    }

    #[cfg(test)]
    /// Mark `parity` for retirement at the next key refresh.
    pub fn defer_retire(&mut self, parity: KeyParity) {
        self.retire_deferred = Some(parity);
    }

    #[cfg(test)]
    /// Whether the send direction holds a key under `parity`.
    #[must_use]
    pub fn tx_key_installed(&self, parity: KeyParity) -> bool {
        self.tx_keys.get(parity).is_some()
    }

    #[cfg(test)]
    /// The length of the send direction's key under `parity`.
    #[must_use]
    pub fn tx_key_len(&self, parity: KeyParity) -> Option<usize> {
        self.tx_keys.get(parity).map(|(sek, _)| sek.len())
    }

    #[cfg(test)]
    /// Run one key-refresh step at `now`.
    pub fn advance_key_refresh(&mut self, now_us: u64) {
        self.advance_key_refresh_step(now_us);
    }

    #[cfg(test)]
    /// Announce a refreshed key for `parity` at `now`.
    pub fn announce_key_for_test(&mut self, parity: KeyParity) {
        self.announce_key(parity, 0);
    }

    #[cfg(test)]
    /// Replace the pending KMREQ with a fixed datagram due at `resend_at_us`.
    fn pend_km_for_test(&mut self, parity: KeyParity, datagram: Vec<u8>, resend_at_us: u64) {
        self.km_pending = Some(PendingKm {
            parity,
            salt: [0; crate::crypto::SALT_LEN],
            datagram,
            resend_at_us: Some(resend_at_us),
        });
    }

    #[cfg(test)]
    /// Install `sek` under both directions for `passphrase`, with KM Refresh at
    /// `thresholds` — the state a test starts a refresh from.
    pub fn install_refresh_test_keys(
        &mut self,
        passphrase: &[u8],
        sek: &[u8],
        salt: [u8; crate::crypto::SALT_LEN],
        thresholds: KmRefreshThresholds,
    ) {
        self.set_passphrase(passphrase.to_vec());
        self.crypto_key_len = sek.len();
        for keys in [&mut self.tx_keys, &mut self.rx_keys] {
            keys.install(KeyParity::Even, sek.to_vec(), salt);
        }
        self.km_refresh = KmRefreshDriver::new(thresholds, KeyParity::Even);
        self.km_refresh_thresholds = thresholds;
    }

    /// The next instant this link must act without any inbound event: the next Full ACK / NAK, the
    /// next TSBPD release, the Keep-Alive when idle, the peer-idle expiry, a pending KMREQ resend
    /// and the next pacing slot. A deadline the clock cannot name is no deadline; the others still
    /// bind. `None` once the link has ended.
    #[must_use]
    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
        self.next_deadline_micros(now.as_micros())
            .map(Instant::from_micros)
    }

    fn next_deadline_micros(&self, now_us: u64) -> Option<u64> {
        if self.ended {
            return None;
        }
        let fold = |at: Option<u64>, candidate: Option<u64>| match (at, candidate) {
            (Some(a), Some(c)) => Some(a.min(c)),
            (Some(a), None) => Some(a),
            (None, c) => c,
        };
        // Every span here can pass the end of the clock, which the host cannot
        // represent: such a term never fires.
        let span = |from: u64, len: u64| from.checked_add(len);
        let mut at = self
            .receiver
            .next_deadline()
            .and_then(|t| span(self.epoch_us, t.as_micros()));
        if let Some(t) = self.tsbpd.next_release_after(self.elapsed(now_us)) {
            at = fold(at, span(self.epoch_us, micros(t)));
        }
        if self.outbound_control.is_empty() && self.outbound_data.is_empty() {
            at = fold(
                at,
                span(self.last_tx_us, micros(self.timers.cadence.keepalive)),
            );
        }
        at = fold(at, span(self.last_rx_us, self.read_idle_us));
        if let Some(pending) = &self.km_pending {
            at = fold(at, pending.resend_at_us);
        }
        if !self.outbound_data.is_empty() {
            at = fold(at, self.next_data_send_at_us);
        }
        // Never a deadline already past, and never a spin: the same 1 ms floor every hosted
        // adapter of this crate keeps.
        at.map(|at| at.max(now_us.saturating_add(micros(MIN_WAKE))))
    }

    /// How long until the DATA packet at the front of the queue may go out: `None`
    /// when the queue is empty or its slot has already arrived.
    #[must_use]
    pub fn next_paced_send_wait(&self, now: Instant) -> Option<Duration> {
        if self.outbound_data.is_empty() {
            return None;
        }
        let deadline = self.next_data_send_at_us?;
        Some(Duration::from_micros(
            deadline.saturating_sub(now.as_micros()),
        ))
    }

    /// Feed one application payload for first transmission at `now`. It is encrypted (§6) when
    /// the connection negotiated it, queued behind any retransmission, and sent by the next
    /// [`Link::poll`] or [`Link::poll_io`].
    pub fn send(&mut self, payload: &[u8], now: Instant) {
        let now_us = now.as_micros();
        if self.ended || self.key_exhausted {
            return;
        }
        self.livecc
            .on_data_packet(u64::try_from(payload.len()).unwrap_or(u64::MAX));

        self.advance_key_refresh_step(now_us);

        if self.tx_keys.get(self.tx_parity).is_some() {
            if self.tx_key_sent >= self.tx_key_limit {
                self.key_exhausted = true;
                return;
            }
            self.tx_key_sent = self.tx_key_sent.saturating_add(1);
        }
        let encrypted: Option<Vec<u8>> = match self.tx_keys.get(self.tx_parity) {
            Some((sek, salt)) => {
                let mut enc = payload.to_vec();
                if crate::crypto::aes_ctr_apply(sek, &salt, self.next_send_seq, &mut enc).is_err() {
                    return;
                }
                Some(enc)
            }
            None => None,
        };
        let key_flag = if encrypted.is_some() {
            key_field_of(self.tx_parity)
        } else {
            EncryptionKeyField::NotEncrypted
        };
        let payload = encrypted.as_deref().unwrap_or(payload);

        // The counters are kept within their wire widths, so framing them cannot fail; if it ever
        // did, the payload is dropped, not the link.
        let Ok(bytes) = self.sender.on_data_keyed(
            self.next_send_seq,
            self.next_message_number,
            payload,
            key_flag,
            self.elapsed(now_us),
        ) else {
            return;
        };
        self.next_send_seq = seq_next(self.next_send_seq);
        self.next_message_number = next_message_number(self.next_message_number);
        self.outbound_data.push_back(OutboundData {
            bytes,
            retransmit: None,
        });
    }

    /// Take the datagrams queued for the peer since the last call, in send order: first
    /// transmissions, retransmissions and control feedback alike. They may leave at once — a host
    /// that writes them calls [`Link::flush`] instead, which applies the pacing slot and records the
    /// transmission the Keep-Alive period counts from.
    #[must_use]
    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
        let mut sent = core::mem::take(&mut self.outbound_control);
        sent.reserve(self.outbound_data.len());
        while let Some(datagram) = self.outbound_data.pop_front() {
            sent.push(datagram.bytes);
        }
        sent
    }

    /// Process one datagram from the peer at `now`, returning what it delivered.
    #[must_use]
    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
        self.on_owned_datagram(datagram.to_vec(), now)
    }

    /// [`Link::on_datagram`] for a datagram the host owns: a payload it delivers stays in this
    /// datagram's allocation (see [`Payload`]), so receiving it costs no copy.
    #[must_use]
    pub fn on_owned_datagram(&mut self, datagram: Vec<u8>, now: Instant) -> Delivered {
        let now_us = now.as_micros();
        if self.ended {
            return Delivered::default();
        }
        let mut batch = Batch::default();
        self.ingress(datagram, now_us, &mut batch);
        batch.finish(&mut self.ended)
    }

    /// Run the timers at `now` — retransmissions, ACK/NAK, the Keep-Alive, a KMREQ resend and
    /// the TSBPD release — returning what it delivered.
    #[must_use]
    pub fn poll(&mut self, now: Instant) -> Delivered {
        let now_us = now.as_micros();
        if self.ended {
            return Delivered::default();
        }
        let mut batch = Batch::default();
        if now_us.saturating_sub(self.last_rx_us) >= self.read_idle_us {
            batch.end(LinkEnd::PeerIdle);
            return batch.finish(&mut self.ended);
        }
        self.tick_engines(now_us, &mut batch);
        batch.finish(&mut self.ended)
    }

    /// The timer pass and the outbound flush a host loop runs after every wake-up: the engines at
    /// `now`, then every datagram due — appended to `sent` — control at once and DATA at its
    /// pacing slot. Returns what the timer pass delivered; a host that also keeps a delivery
    /// channel hands it on.
    #[must_use]
    pub fn poll_io(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) -> Delivered {
        let now_us = now.as_micros();
        if self.ended {
            return Delivered::default();
        }
        let mut batch = Batch::default();
        self.tick_engines(now_us, &mut batch);
        self.flush(now, sent);
        batch.finish(&mut self.ended)
    }

    fn ingress(&mut self, datagram: Vec<u8>, now_us: u64, batch: &mut Batch) {
        // Any datagram from the peer — even one that fails to parse below — is evidence the peer
        // is still there, resetting the idle timeout.
        self.last_rx_us = now_us;
        let now = self.elapsed(now_us);
        let Ok(packet) = SrtPacket::parse(&datagram) else {
            self.counts.unparseable = self.counts.unparseable.saturating_add(1);
            self.report_counted(CountedCause::MalformedDatagram, 1, batch);
            return;
        };
        match packet {
            SrtPacket::Data(d) => {
                let (seq_number, timestamp, key_flag) = (d.seq_number, d.timestamp, d.key_flag);
                let Some(payload) = self.payload(datagram, seq_number, key_flag, batch) else {
                    return;
                };
                self.ingress_data(payload, seq_number, timestamp, now, batch);
            }
            SrtPacket::Control(c) => self.ingress_control(&c, now, now_us, batch),
        }
    }

    fn ingress_data(
        &mut self,
        payload: Payload,
        seq_number: u32,
        timestamp: SrtTimestamp,
        now: Instant,
        batch: &mut Batch,
    ) {
        // A packet that is not ahead of the delivery cursor (a duplicate, a retransmission of what
        // was delivered or given up on, or a stale sequence number) has nothing left to do: it is
        // never staged at all.
        if seq_lt(seq_number, self.tsbpd.next_release()) {
            self.counts.late = self.counts.late.saturating_add(1);
            return;
        }
        let outcome = self.receiver.feed_data(seq_number, now);
        if outcome.out_of_window {
            self.report_counted(CountedCause::OutOfWindow, 1, batch);
            return;
        }
        if let Some(nak_bytes) = outcome.nak {
            self.outbound_control.push(nak_bytes);
        }
        // The staging buffer is what TSBPD releases from, in strict sequence order, waiting for a
        // NAK-recovered gap until the next buffered packet's play time, at which point live mode
        // skips an unrecoverable gap (only under TLPKTDROP, §3.2.1.1.1).
        if self.staged.contains_key(&seq_number) {
            self.counts.duplicates = self.counts.duplicates.saturating_add(1);
        }
        self.staged.entry(seq_number).or_insert(payload);
        let tsbpd_out = self.tsbpd.feed_data(seq_number, timestamp.value(), now);
        self.release(&tsbpd_out, batch);
    }

    /// The DATA payload of `datagram`, decrypted when it was encrypted. `None` when it cannot be
    /// staged: no usable key, or a failed decryption pass, both reported once.
    fn payload(
        &mut self,
        mut datagram: Vec<u8>,
        seq_number: u32,
        key_flag: EncryptionKeyField,
        batch: &mut Batch,
    ) -> Option<Payload> {
        datagram.get(SRT_HEADER_LEN..)?;
        if key_flag == EncryptionKeyField::NotEncrypted {
            if self.refuse_cleartext && self.crypto_key_len != 0 {
                self.undecryptable(batch);
                return None;
            }
        } else {
            let keys = KeySet::parity_of(key_flag).and_then(|p| self.rx_keys.get(p));
            let Some((sek, salt)) = keys else {
                self.undecryptable(batch);
                return None;
            };
            let data = datagram.get_mut(SRT_HEADER_LEN..)?;
            if crate::crypto::aes_ctr_apply(sek, &salt, seq_number, data).is_err() {
                self.undecryptable(batch);
                return None;
            }
        }
        Some(Payload {
            datagram,
            start: SRT_HEADER_LEN,
        })
    }

    fn undecryptable(&mut self, batch: &mut Batch) {
        self.counts.undecryptable = self.counts.undecryptable.saturating_add(1);
        self.report_counted(CountedCause::Undecryptable, 1, batch);
    }

    fn ingress_control(
        &mut self,
        c: &ControlPacket<'_>,
        now: Instant,
        now_us: u64,
        batch: &mut Batch,
    ) {
        match c {
            ControlPacket::Ack(ack) => {
                if let Some(ackack_bytes) = self.sender.on_ack(ack, now) {
                    self.outbound_control.push(ackack_bytes);
                }
            }
            // Record the reported loss; the next timer pass drains the retransmit queue —
            // retransmits are queued ahead of any new first-time data (rules 5, 15, 16).
            ControlPacket::Nak(nak) => self.sender.on_nak(nak),
            ControlPacket::AckAck(ackack) => self.receiver.on_ackack(ackack, now),
            ControlPacket::DropReq(d) => self.handle_dropreq(d, now, batch),
            // A Keep-Alive only tells us the peer is alive (`last_rx_us` is already refreshed);
            // it is not answered.
            ControlPacket::KeepAlive(_) => {}
            ControlPacket::Shutdown(_) => batch.end(LinkEnd::PeerShutdown),
            ControlPacket::PeerError(p) => {
                self.report_counted(CountedCause::PeerError, u64::from(p.error_code), batch);
            }
            ControlPacket::UserDefined(u) => {
                if let Ok(km) = u.as_key_material() {
                    self.on_peer_key_material(u.subtype, &km, now_us);
                }
            }
            _ => {}
        }
    }

    /// Handle a DROPREQ (§3.2.9): the peer announces it will never deliver sequence numbers
    /// `first..=last`. Tell the ARQ receiver to stop NAKing them and advance its ack point, tell
    /// the TSBPD scheduler to skip them, discard anything already staged inside the range, then
    /// drive one release pass so whatever the gap blocked becomes deliverable immediately.
    fn handle_dropreq(&mut self, d: &DropReqPacket, now: Instant, batch: &mut Batch) {
        let first = d.first_seq.value();
        let last = d.last_seq.value();
        if seq_diff(last, first) < 0 {
            return;
        }
        let reach = seq_diff(last, self.receiver.ack_point());
        if !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.max_flow_window) {
            return;
        }
        self.receiver.skip_range(first, last);
        self.tsbpd.skip_range(first, last);
        self.staged
            .retain(|&s, _| !seq_in_closed_range(s, first, last));
        let tsbpd_out = self.tsbpd.tick(now);
        self.release(&tsbpd_out, batch);
    }

    /// Apply one TSBPD outcome: publish the released payloads and purge anything the scheduler
    /// gave up on.
    ///
    /// What the scheduler gave up on (§4.6) is also skipped in the ARQ receiver: its ack point then
    /// moves past the dropped packets — the "fake ACK" of Too-Late Packet Drop — so it stops NAKing
    /// packets that can no longer be delivered. The two lists are merged on sequence number so a
    /// payload past a skipped gap is published only after the report naming that skip.
    fn release(&mut self, outcome: &TickOutcome, batch: &mut Batch) {
        let lost: Vec<u32> = outcome.dropped.iter().map(|p| p.seq_number).collect();
        self.counts.lost = self
            .counts
            .lost
            .saturating_add(u64::try_from(lost.len()).unwrap_or(u64::MAX));
        for packet in &outcome.dropped {
            self.staged.remove(&packet.seq_number);
        }
        for (first, last) in contiguous_runs(&lost) {
            self.receiver.skip_range(first, last);
        }
        let dropped = &outcome.dropped;
        let mut next_delivered = 0usize;
        let mut run_start = 0usize;
        while run_start < dropped.len() {
            let run_end = run_start
                + contiguous_runs(&lost[run_start..])
                    .first()
                    .copied()
                    .map_or(0, |(_, last)| seq_diff(last, lost[run_start]) as usize + 1);
            while let Some(&seq) = outcome.delivered.get(next_delivered) {
                if seq_lt(seq, dropped[run_start].seq_number) {
                    self.deliver_payload(seq, batch);
                    next_delivered += 1;
                } else {
                    break;
                }
            }
            for damage in damage_reports::reports(&dropped[run_start..run_end]) {
                self.report(damage, batch);
            }
            run_start = run_end;
        }
        for &seq in &outcome.delivered[next_delivered..] {
            self.deliver_payload(seq, batch);
        }
    }

    /// Hand one released payload to the host, unless the caller's check refuses its format.
    fn deliver_payload(&mut self, seq: u32, batch: &mut Batch) {
        let Some(payload) = self.staged.remove(&seq) else {
            return;
        };
        if (self.payload_admits)(payload.as_slice()) {
            batch.payload(payload);
        } else {
            self.counts.refused = self.counts.refused.saturating_add(1);
            self.report_counted(CountedCause::PayloadRefused, 1, batch);
        }
    }

    /// Hand one report to the caller's policy: publish it, or end the link with it when the policy
    /// says `Fail`.
    fn report(&mut self, damage: Damage, batch: &mut Batch) {
        match self.damage_policy.admit(damage) {
            Ok(damage) => batch.report(damage),
            Err(error) => {
                batch.refused = Some(error);
                self.ended = true;
            }
        }
    }

    /// Report a loss this link only counts, once per cause.
    fn report_counted(&mut self, cause: CountedCause, count: u64, batch: &mut Batch) {
        if *self.reported.slot(cause) {
            return;
        }
        *self.reported.slot(cause) = true;
        self.report(
            damage_reports::dropped_before_delivery(cause.what(), count),
            batch,
        );
    }

    fn tick_engines(&mut self, now_us: u64, batch: &mut Batch) {
        if self.ended {
            return;
        }
        let now = self.elapsed(now_us);
        if self.key_exhausted {
            batch.end(LinkEnd::KeyExhausted);
            return;
        }
        if self.counts.key_refresh_unconfirmed > 0 {
            self.report_counted(
                CountedCause::KeyRefreshUnconfirmed,
                self.counts.key_refresh_unconfirmed,
                batch,
            );
        }
        if self.counts.key_refresh_failed > 0 {
            self.report_counted(
                CountedCause::KeyRefreshFailed,
                self.counts.key_refresh_failed,
                batch,
            );
        }

        // Retransmitted DATA packets first (rules 5, 15, 16, 18): they drain the NAK-populated
        // loss list and are queued before any first-time data, reproducing the sans-IO engine's
        // "loss list before first transmission" priority.
        let queue_cap = usize::try_from(self.max_flow_window).unwrap_or(usize::MAX);
        for (seq, bytes) in self.sender.tick(now) {
            self.livecc.on_data_packet(
                u64::try_from(bytes.len().saturating_sub(SRT_HEADER_LEN)).unwrap_or(u64::MAX),
            );
            // Retransmissions are capped at the negotiated flow window: a NAK naming the whole
            // send buffer must not turn into an unbounded queue (#2819). A dropped retransmission
            // stays in the sender's loss list and is offered again by a later tick.
            if self.outbound_data.len() < queue_cap {
                self.outbound_data.push_back(OutboundData {
                    bytes,
                    retransmit: Some(seq),
                });
            } else {
                self.sender.on_retransmit_dropped(seq);
            }
        }

        // Keep-Alive (§3.2.3): a connection that has sent nothing for a second says so, or the
        // peer's own idle timeout ends it. Judged before this pass's ACK/NAK are queued: it asks
        // whether anything has gone out for a second, not whether something is about to.
        if self.outbound_control.is_empty()
            && self.outbound_data.is_empty()
            && now_us.saturating_sub(self.last_tx_us) >= micros(self.timers.cadence.keepalive)
        {
            self.queue_keepalive(now_us);
        }

        self.resend_pending_km(now_us);

        // Periodic ACK/NAK (rules 11, 12, 21, 22): control feedback, never paced.
        for bytes in self.receiver.tick(now) {
            self.outbound_control.push(bytes);
        }

        let tsbpd_out = self.tsbpd.tick(now);
        self.release(&tsbpd_out, batch);
    }

    fn queue_keepalive(&mut self, now_us: u64) {
        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
            timestamp: self.wire_now(now_us),
            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
            libsrt_pad: true,
        });
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        if pkt.serialize_into(&mut buf).is_ok() {
            self.outbound_control.push(buf);
        }
    }

    /// Append every outbound datagram due at `now`, in order, without blocking on the pacing
    /// delay itself: control in full, then DATA while its pacing slot has arrived. [`Link::poll_io`]
    /// runs the timers first, as a host loop does after every wake-up.
    ///
    /// §5.1.2 paces DATA packets only: control feedback (ACK/NAK/ACKACK/Keep-Alive) goes out
    /// immediately, or loss recovery would be throttled along with the data it unblocks. DATA is
    /// scheduled against `next_data_send_at_us`, a token-bucket-style deadline rather than a sleep:
    /// the schedule advances from whichever is later of the previous slot or now, but never more
    /// than [`SenderBounds::pacing_burst_packets`](crate::arq::SenderBounds::pacing_burst_packets) periods of catch-up credit in one pass, so a burst after an idle
    /// gap sends at once while a sustained flood stays throttled.
    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
        let now_us = now.as_micros();
        let mut count = self.outbound_control.len();
        sent.append(&mut self.outbound_control);
        let mut paced = 0;
        while !self.outbound_data.is_empty() && paced < self.pacing_burst_packets {
            if let Some(deadline) = self.next_data_send_at_us
                && now_us < deadline
            {
                break;
            }
            let Some(datagram) = self.outbound_data.pop_front() else {
                break;
            };
            if let Some(seq) = datagram.retransmit {
                self.sender.on_retransmit_sent(seq);
            }
            let period = micros(self.livecc.on_ack_received());
            let floor =
                now_us.saturating_sub(period.saturating_mul(self.pacing_burst_packets as u64));
            let base = self.next_data_send_at_us.map_or(now_us, |t| t.max(floor));
            self.next_data_send_at_us = base.checked_add(period);
            paced += 1;
            count += 1;
            sent.push(datagram.bytes);
        }
        // An idle connection owes nothing: drop an expired slot so the next backlog starts at
        // "now" instead of replaying the idle gap as credit.
        if self.outbound_data.is_empty() {
            self.next_data_send_at_us = self.next_data_send_at_us.filter(|&t| t > now_us);
        }
        if count > 0 {
            self.last_tx_us = now_us;
        }
    }

    fn advance_key_refresh_step(&mut self, now_us: u64) {
        if let Some(parity) = self.key_refresh_retry.take() {
            self.announce_key(parity, now_us);
        }
        if self.tx_keys.is_empty() {
            return;
        }
        for ev in self.km_refresh.on_packet_sent(1) {
            match ev {
                KmRefreshEvent::PreAnnounce { next_parity } => {
                    self.announce_key(next_parity, now_us);
                }
                KmRefreshEvent::Switchover { .. } => {
                    if self.km_pending.is_some() {
                        self.counts.key_refresh_unconfirmed =
                            self.counts.key_refresh_unconfirmed.saturating_add(1);
                    }
                }
                KmRefreshEvent::Decommission { retired } => self.retire_deferred = Some(retired),
            }
        }
        if self.km_pending.is_none() {
            let active = self.km_refresh.active_parity();
            if active != self.tx_parity {
                self.tx_parity = active;
                self.tx_key_sent = 0;
            }
        }
        if let Some(retired) = self.retire_deferred
            && retired != self.tx_parity
        {
            self.tx_keys.clear(retired);
            self.retire_deferred = None;
        }
    }

    fn key_refresh_failed(&mut self, parity: KeyParity) {
        self.counts.key_refresh_failed = self.counts.key_refresh_failed.saturating_add(1);
        self.key_refresh_retry = Some(parity);
    }

    fn announce_key(&mut self, parity: KeyParity, now_us: u64) {
        if self.km_pending.is_some() {
            return;
        }
        let key_len = if self.crypto_key_len == 0 {
            DEFAULT_SEK_LEN
        } else {
            self.crypto_key_len
        };
        if self.key_refresh_seed.len() < MIN_KEY_REFRESH_SEED_LEN || key_len > KEY_LEN {
            self.key_refresh_failed(parity);
            return;
        }
        let draw = self.key_refresh_counter;
        self.key_refresh_counter = draw.saturating_add(1);
        let mut salt = [0u8; crate::crypto::SALT_LEN];
        salt.copy_from_slice(
            &derive(&self.key_refresh_seed, LABEL_REFRESH_SALT, draw)[..crate::crypto::SALT_LEN],
        );
        let sek = derive(&self.key_refresh_seed, LABEL_REFRESH_SEK, draw)[..key_len].to_vec();
        let Ok(kek) = crate::crypto::derive_kek(&self.crypto_passphrase, &salt, key_len) else {
            self.key_refresh_failed(parity);
            return;
        };
        let Ok((icv, wrapped)) = crate::crypto::wrap_sek(&kek, &sek) else {
            self.key_refresh_failed(parity);
            return;
        };
        let km = KeyMaterial {
            kk: match parity {
                KeyParity::Even => KmKeyFlag::Even,
                KeyParity::Odd => KmKeyFlag::Odd,
            },
            keki: 0,
            cipher: crate::packet::Cipher::AesCtr,
            auth: crate::packet::KmAuth::None,
            se: crate::packet::StreamEncapsulation::MpegTsSrt,
            salt: &salt,
            icv,
            x_sek: &wrapped,
            o_sek: None,
        };
        let Some(datagram) = self.key_material_datagram(EXT_TYPE_KMREQ, &km, now_us) else {
            self.key_refresh_failed(parity);
            return;
        };
        self.tx_keys.install(parity, sek, salt);
        self.outbound_control.push(datagram.clone());
        self.km_pending = Some(PendingKm {
            parity,
            salt,
            datagram,
            resend_at_us: now_us.checked_add(micros(self.timers.cadence.km_resend)),
        });
    }

    fn key_material_datagram(
        &self,
        subtype: u16,
        km: &KeyMaterial<'_>,
        now_us: u64,
    ) -> Option<Vec<u8>> {
        let mut cif = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut cif).ok()?;
        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
            control_type: crate::packet::ControlType::UserDefined.to_bits(),
            subtype,
            type_specific_info: 0,
            timestamp: self.wire_now(now_us),
            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
            cif: &cif,
        });
        let mut out = alloc::vec![0u8; ud.serialized_len()];
        ud.serialize_into(&mut out).ok()?;
        Some(out)
    }

    fn resend_pending_km(&mut self, now_us: u64) {
        if let Some(pending) = &mut self.km_pending
            && pending.resend_at_us.is_some_and(|at| now_us >= at)
        {
            self.outbound_control.push(pending.datagram.clone());
            pending.resend_at_us = now_us.checked_add(micros(self.timers.cadence.km_resend));
        }
    }

    fn on_peer_key_material(&mut self, subtype: u16, km: &KeyMaterial<'_>, now_us: u64) {
        if subtype == EXT_TYPE_KMRSP {
            if let Some(pending) = &self.km_pending
                && parity_of_kk(km.kk) == Some(pending.parity)
                && km.salt == pending.salt
            {
                self.km_pending = None;
            }
            return;
        }
        if subtype != EXT_TYPE_KMREQ {
            return;
        }
        // Recovering the SEK runs PBKDF2; a peer re-sending Key Material back to back is refused
        // beyond one message per `KMREQ_MIN_INTERVAL` (#2840). A legitimate refresh that lands
        // inside the window is retransmitted by the peer.
        if self.last_peer_kmreq_us.is_some_and(|last| {
            now_us.saturating_sub(last) < micros(self.timers.cadence.kmreq_min_interval)
        }) {
            return;
        }
        self.last_peer_kmreq_us = Some(now_us);
        let installed = match km.kk {
            KmKeyFlag::Both => crate::handshake_sm::recover_both_seks(
                &self.crypto_passphrase,
                km,
                &mut self.kek_cache,
            )
            .map(|(even, odd, salt)| {
                self.rx_keys.install(KeyParity::Even, even.to_vec(), salt);
                self.rx_keys.install(KeyParity::Odd, odd.to_vec(), salt);
            })
            .is_ok(),
            kk => {
                let parity = if kk == KmKeyFlag::Odd {
                    KeyParity::Odd
                } else {
                    KeyParity::Even
                };
                crate::handshake_sm::recover_sek(&self.crypto_passphrase, km, &mut self.kek_cache)
                    .map(|(sek, salt)| self.rx_keys.install(parity, sek.to_vec(), salt))
                    .is_ok()
            }
        };
        if installed && let Some(rsp) = self.key_material_datagram(EXT_TYPE_KMRSP, km, now_us) {
            self.outbound_control.push(rsp);
        }
    }
}

// ===========================================================================
// CallerLink — the caller role: handshake, then a Link
// ===========================================================================

/// Width of a derived value: a SHA-256 digest, and the seed the tokio adapter gives it.
pub const KEY_LEN: usize = 32;

/// Fewest bytes of entropy a link's key-refresh seed may hold: a shorter seed would let the
/// publicly derived refresh keys be enumerated.
const MIN_KEY_REFRESH_SEED_LEN: usize = 16;

const KEYSTREAM_PACKETS: u64 = crate::km_refresh::KEYSTREAM_PACKETS;
/// Largest Socket ID either side may draw: the 30-bit field's range (§3).
const MAX_OWN_SOCKET_ID: u32 = 0x3FFF_FFFF;
/// Width of the Packet Sequence Number field (§3.1).
const SEQ_NUMBER_MASK: u32 = 0x7FFF_FFFF;
const LABEL_SOCKET_ID: &[u8] = b"srt-socket-id";
const LABEL_ISN: &[u8] = b"srt-isn";
const LABEL_SALT: &[u8] = b"srt-salt";
const LABEL_SEK: &[u8] = b"srt-sek";
const LABEL_REFRESH_SALT: &[u8] = b"srt-refresh-salt";
const LABEL_REFRESH_SEK: &[u8] = b"srt-refresh-sek";

/// One value `seed` derives for `attempt` under `label`: the digest of the seed, the label and the
/// attempt number. Nothing it returns is itself a secret: the seed is.
fn derive(seed: &[u8], label: &[u8], attempt: u64) -> [u8; KEY_LEN] {
    let mut h = Sha256::new();
    h.update(seed);
    h.update(label);
    h.update(attempt.to_be_bytes());
    h.finalize().into()
}

fn first_u32(bytes: &[u8; KEY_LEN]) -> u32 {
    let mut head = [0u8; size_of::<u32>()];
    head.copy_from_slice(&bytes[..size_of::<u32>()]);
    u32::from_be_bytes(head)
}

fn derive_socket_id(seed: &[u8], attempt: u64) -> u32 {
    first_u32(&derive(seed, LABEL_SOCKET_ID, attempt)) % MAX_OWN_SOCKET_ID + 1
}

fn derive_isn(seed: &[u8], attempt: u64) -> u32 {
    first_u32(&derive(seed, LABEL_ISN, attempt)) & SEQ_NUMBER_MASK
}

/// The caller role: the HSv5 caller handshake, then the established [`Link`].
///
/// The host calls [`CallerLink::connect`] once and sends what [`CallerLink::take_sent`] hands back;
/// every answer from the peer goes to [`CallerLink::on_datagram`], and the host wakes at
/// [`CallerLink::next_deadline`] to call [`CallerLink::poll`]. A resolution turns the state into
/// a [`Link`], whose own deadlines and datagrams follow from then on.
pub struct CallerLink {
    params: CallerParams,
    attempt: u64,
    seed: Vec<u8>,
    handshake: Option<CallerHandshake>,
    started_us: u64,
    next_tick_us: Option<u64>,
    last_tick_us: u64,
    link: Option<Link>,
    sent: Vec<Vec<u8>>,
}

impl core::fmt::Debug for CallerLink {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CallerLink")
            .field("attempt", &self.attempt)
            .field("handshaking", &self.handshake.is_some())
            .field("connected", &self.link.is_some())
            .finish_non_exhaustive()
    }
}

impl CallerLink {
    /// A link that has not opened yet. `seed` is the secret entropy every attempt derives its
    /// Socket ID, ISN and stream key from, and `attempt` names this opening (a reconnect is the
    /// next attempt, and derives fresh values).
    #[must_use]
    pub fn new(params: &CallerParams, seed: Vec<u8>, attempt: u64) -> Self {
        Self {
            params: params.clone(),
            attempt,
            seed,
            handshake: None,
            started_us: 0,
            next_tick_us: None,
            last_tick_us: 0,
            link: None,
            sent: Vec::new(),
        }
    }

    /// The caller's own SRT Socket ID this side advertises: the caller's if it named itself,
    /// else this attempt's derivation from the seed.
    #[must_use]
    pub fn own_socket_id(&self) -> u32 {
        if self.params.own_socket_id == 0 {
            derive_socket_id(&self.seed, self.attempt)
        } else {
            self.params.own_socket_id
        }
    }

    /// The established link, once the peer has resolved the handshake.
    #[must_use]
    pub fn link(&self) -> Option<&Link> {
        self.link.as_ref()
    }

    /// The established link, for sending and polling.
    pub fn link_mut(&mut self) -> Option<&mut Link> {
        self.link.as_mut()
    }

    /// Start the handshake at `now`, deriving this attempt's Socket ID, ISN and stream key from
    /// the seed. The induction datagram waits for [`CallerLink::take_sent`]; a caller that cannot
    /// frame one has no datagram to send.
    pub fn connect(&mut self, now: Instant) {
        let now_us = now.as_micros();
        if self.handshake.is_some() || self.link.is_some() {
            return;
        }
        let config = self.attempt_config();
        self.started_us = now_us;
        self.last_tick_us = now_us;
        self.next_tick_us =
            Some(now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)));
        let mut handshake = CallerHandshake::new(self.own_socket_id(), config);
        handshake.set_elapsed(Duration::ZERO);
        match handshake.start() {
            Ok(induction) => {
                self.sent.push(induction);
                self.handshake = Some(handshake);
            }
            Err(_) => self.sent.clear(),
        }
    }

    /// The handshake this attempt advertises: the caller's own, with this attempt's ISN and its
    /// own derived stream key.
    fn attempt_config(&self) -> HandshakeConfig {
        let config = self
            .params
            .handshake
            .clone()
            .with_initial_seq_number(self.initial_seq_number());
        if config.encryption_field == EncryptionField::NoEncryption {
            return config;
        }
        // The stream key length follows the advertised cipher; the salt and the SEK derive
        // from the seed, so every attempt carries fresh ones.
        let key_len = match config.encryption_field {
            EncryptionField::Aes192 => 24,
            EncryptionField::Aes256 => 32,
            _ => DEFAULT_SEK_LEN,
        };
        let mut salt = [0u8; crate::crypto::SALT_LEN];
        let derived = derive(&self.seed, LABEL_SALT, self.attempt);
        salt.copy_from_slice(&derived[..crate::crypto::SALT_LEN]);
        let sek = derive(&self.seed, LABEL_SEK, self.attempt)[..key_len].to_vec();
        let crypto = match config.crypto.clone() {
            Some(mut crypto) => {
                crypto.salt = salt;
                crypto.sek = sek;
                crypto
            }
            None => CryptoConfig {
                passphrase: Vec::new(),
                salt,
                sek,
            },
        };
        config.with_crypto(Some(crypto))
    }

    /// This attempt's initial sequence number.
    fn initial_seq_number(&self) -> u32 {
        derive_isn(&self.seed, self.attempt)
    }

    /// Process one datagram from the peer at `now`.
    #[must_use]
    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
        let now_us = now.as_micros();
        if let Some(link) = self.link.as_mut() {
            return link.on_datagram(datagram, now);
        }
        let Some(handshake) = self.handshake.as_mut() else {
            return Delivered::default();
        };
        let mut batch = Batch::default();
        handshake.set_elapsed(Duration::from_micros(
            now_us.saturating_sub(self.started_us),
        ));
        let Ok(outputs) = handshake.feed_bytes(datagram) else {
            return Delivered::default();
        };
        for output in outputs {
            match output {
                HandshakeOutput::Send(bytes) => self.sent.push(bytes),
                HandshakeOutput::Connected(params) => {
                    let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) =
                        SrtPacket::parse(datagram)
                    else {
                        batch.end(LinkEnd::HandshakeTimedOut);
                        break;
                    };
                    let started = Instant::from_micros(self.started_us);
                    let setup = LinkSetup::new(params, hp.initial_seq_number, 0).with_arrival(
                        Duration::from_micros(now_us.saturating_sub(self.started_us)),
                        hp.timestamp.value(),
                    );
                    let mut link = Link::new(started, &setup, &self.params);
                    link.start_idle_clock(now);
                    self.link = Some(link);
                    return batch.finish(&mut false);
                }
                HandshakeOutput::Rejected(reason) => {
                    batch.end(LinkEnd::Rejected(reason));
                    break;
                }
                HandshakeOutput::TimedOut => {
                    batch.end(LinkEnd::HandshakeTimedOut);
                    break;
                }
            }
        }
        batch.finish(&mut false)
    }

    /// Advance the handshake at `now`: an unanswered request is re-sent once per period — a
    /// late wake is one retransmit, not one per missed period (#3847) — and the caller's budget
    /// bounds the attempt.
    #[must_use]
    pub fn poll(&mut self, now: Instant) -> Delivered {
        let now_us = now.as_micros();
        if let Some(link) = self.link.as_mut() {
            return link.poll(now);
        }
        let Some(handshake) = self.handshake.as_mut() else {
            return Delivered::default();
        };
        let mut batch = Batch::default();
        if now_us.saturating_sub(self.started_us) >= micros(self.params.timers.handshake_timeout) {
            batch.end(LinkEnd::HandshakeTimedOut);
            return batch.finish(&mut false);
        }
        if self.next_tick_us.is_some_and(|next| now_us >= next) {
            let elapsed_us = now_us.saturating_sub(self.last_tick_us).max(1);
            self.last_tick_us = now_us;
            self.next_tick_us = Some(
                now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)),
            );
            handshake.set_elapsed(Duration::from_micros(
                now_us.saturating_sub(self.started_us),
            ));
            for output in handshake.tick(Duration::from_micros(elapsed_us)) {
                match output {
                    HandshakeOutput::Send(bytes) => self.sent.push(bytes),
                    HandshakeOutput::TimedOut => {
                        batch.end(LinkEnd::HandshakeTimedOut);
                        return batch.finish(&mut false);
                    }
                    _ => {}
                }
            }
        }
        batch.finish(&mut false)
    }

    /// The next instant this link must act without an inbound datagram, whichever half is active.
    #[must_use]
    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
        if let Some(link) = &self.link {
            return link.next_deadline(now);
        }
        self.handshake.as_ref()?;
        let budget = self
            .started_us
            .saturating_add(micros(self.params.timers.handshake_timeout));
        Some(Instant::from_micros(match self.next_tick_us {
            Some(tick) => budget.min(tick),
            None => budget,
        }))
    }

    /// Every datagram this attempt still owes the peer: the handshake's, or the link's.
    #[must_use]
    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
        let mut sent = core::mem::take(&mut self.sent);
        if let Some(link) = self.link.as_mut() {
            sent.append(&mut link.take_sent());
        }
        sent
    }

    /// Append every datagram due at `now` to `sent`, as the host writes them: the handshake's,
    /// then the link's through [`Link::flush`], which records the transmission.
    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
        sent.append(&mut self.sent);
        if let Some(link) = self.link.as_mut() {
            link.flush(now, sent);
        }
    }
}

#[cfg(test)]
mod caller_link_tests {
    use super::*;
    use crate::handshake_sm::{HandshakeOutput, NegotiatedParams};
    use crate::listener::ListenerHandshake;
    use crate::packet::{HandshakePacket, SocketId};
    use crate::test_support::at;

    const STALL_US: u64 = 3_600_000;
    const LATENCY_MS: u64 = 120;

    fn params() -> CallerParams {
        CallerParams::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
            0,
            0,
            TEST_TIMERS,
            crate::test_support::ARQ_BOUNDS,
            alloc::vec![7; KEY_LEN],
            TEST_DRIFT_WINDOW,
        )
    }

    fn negotiated(flags: u32) -> NegotiatedParams {
        NegotiatedParams {
            version: 5,
            flags: crate::packet::HandshakeExtensionMessageFlags::new(flags),
            latency: Duration::from_millis(LATENCY_MS),
            own_socket_id: 2,
            peer_socket_id: 1,
            mtu: 1500,
            max_flow_window_size: 8192,
            stream_id: None,
            group: None,
            sek: None,
            salt: None,
        }
    }

    fn data(seq: u32, payload: &[u8]) -> Vec<u8> {
        let dp = crate::packet::DataPacket {
            seq_number: seq,
            position: crate::packet::PacketPosition::Solo,
            in_order: true,
            key_flag: EncryptionKeyField::NotEncrypted,
            retransmitted: false,
            message_number: seq,
            timestamp: SrtTimestamp::ZERO,
            dest_socket_id: SocketId::from_wire(1),
            data: payload,
        };
        let mut buf = alloc::vec![0u8; dp.serialized_len()];
        dp.serialize_into(&mut buf).expect("serialize data");
        buf
    }

    fn handshake_send(outputs: &[HandshakeOutput]) -> Vec<u8> {
        outputs
            .iter()
            .find_map(|o| match o {
                HandshakeOutput::Send(bytes) => Some(bytes.clone()),
                _ => None,
            })
            .expect("a handshake datagram")
    }

    /// The seed-derived Socket ID stays inside libsrt's allocation range and the
    /// ISN inside its 31-bit field, for every seed byte and every attempt.
    #[test]
    fn the_caller_socket_id_and_initial_sequence_number_are_in_range() {
        for (byte, attempt) in [(0xFFu8, 0u64), (0x00, 0), (0x7F, 3)] {
            let mut caller = CallerLink::new(&params(), alloc::vec![byte; KEY_LEN], attempt);
            caller.connect(Instant::ZERO);
            let first = caller.take_sent();
            let induction = first.first().expect("the induction handshake");
            match SrtPacket::parse(induction) {
                Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) => {
                    let socket_id = hs.srt_socket_id;
                    let isn = hs.initial_seq_number;
                    assert!(
                        (1..=MAX_OWN_SOCKET_ID).contains(&socket_id),
                        "socket id {socket_id} for seed byte {byte} attempt {attempt}"
                    );
                    assert!(
                        isn <= SEQ_NUMBER_MASK,
                        "initial sequence number {isn} for seed byte {byte}"
                    );
                    assert_eq!(socket_id, caller.own_socket_id());
                    assert_eq!(isn, caller.initial_seq_number());
                }
                other => panic!("the first datagram is an induction handshake: {other:?}"),
            }
        }
    }

    /// The same seed and attempt derive the same values; a later attempt
    /// derives fresh ones.
    #[test]
    fn the_socket_id_and_initial_sequence_number_derive_from_the_seed() {
        let mut seen = alloc::vec::Vec::new();
        for attempt in 0..3u64 {
            let mut caller = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
            caller.connect(Instant::ZERO);
            let bytes = caller.take_sent().remove(0);
            let Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) = SrtPacket::parse(&bytes)
            else {
                panic!("an induction handshake");
            };
            seen.push((hs.srt_socket_id, hs.initial_seq_number));

            let mut again = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
            again.connect(Instant::ZERO);
            assert_eq!(
                again.take_sent(),
                alloc::vec![bytes],
                "deterministic for one attempt"
            );
        }
        for (a, b) in [(seen[0], seen[1]), (seen[0], seen[2]), (seen[1], seen[2])] {
            assert_ne!(a, b, "every attempt derives fresh identifiers");
        }
    }

    /// A starved runtime can wake the session once, several retransmit
    /// periods late. That single late poll must count as one retransmit, not
    /// synthesize one tick per nominal period: doing the latter spends the
    /// whole 12-retry budget at once and times the handshake out while the
    /// wall-clock budget is nowhere near spent. The dropped first INDUCTION is
    /// still resent and the connection still completes (issue #3847).
    #[test]
    fn a_late_poll_resends_the_lost_induction_instead_of_timing_out() {
        let params = params().with_handshake_timeout(Duration::from_secs(10));
        let mut caller = CallerLink::new(&params, alloc::vec![7; KEY_LEN], 0);
        caller.connect(Instant::ZERO);
        // The very first INDUCTION is lost: the listener never receives it.
        let _lost = caller.take_sent();

        // One wake, 3.6 s late — fourteen nominal 250 ms periods in one step.
        assert!(caller.poll(at(STALL_US)).is_empty());
        let late = caller.take_sent();
        assert_eq!(late.len(), 1, "exactly one retransmit, not a burst");
        let induction = late.into_iter().next().expect("retransmitted induction");
        assert_eq!(
            caller.next_deadline(at(STALL_US)),
            Some(at(
                STALL_US + micros(TEST_TIMERS.cadence.handshake_retransmit)
            )),
            "the next retransmit is one period away"
        );

        let mut listener = ListenerHandshake::new(
            0x1234_5678,
            0xC0FF_EE00,
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
        );
        listener.set_elapsed(Duration::from_micros(STALL_US));
        let response = handshake_send(
            &listener
                .feed_bytes(&induction)
                .expect("listener induction response"),
        );
        let _ = caller.on_datagram(&response, at(STALL_US));
        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");

        listener.set_elapsed(Duration::from_micros(STALL_US));
        let outputs = listener
            .feed_bytes(&conclusion)
            .expect("listener conclusion response");
        assert!(
            outputs
                .iter()
                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
            "the listener completes the handshake"
        );
        let _ = caller.on_datagram(&handshake_send(&outputs), at(STALL_US));
        assert!(
            caller.link().is_some(),
            "the lost-and-resent induction still connects"
        );
    }

    const SLOW_START_US: u64 = 300_000;
    const SLOW_CONCLUDED_US: u64 = 800_000;

    /// A caller whose handshake took 800 ms, against a listener that began it 300 ms in. Returns
    /// the connected caller and the peer's initial sequence number.
    fn slow_connected_caller(params: &CallerParams) -> (CallerLink, u32) {
        let mut caller = CallerLink::new(params, alloc::vec![7; KEY_LEN], 0);
        caller.connect(Instant::ZERO);
        let induction = caller.take_sent().into_iter().next().expect("induction");
        let mut listener = ListenerHandshake::new(
            0x1234_5678,
            0xC0FF_EE00,
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
        );
        listener.set_elapsed(Duration::ZERO);
        let response =
            handshake_send(&listener.feed_bytes(&induction).expect("induction response"));
        let _ = caller.on_datagram(&response, at(SLOW_START_US + 100_000));
        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");
        listener.set_elapsed(Duration::from_micros(SLOW_CONCLUDED_US - SLOW_START_US));
        let outputs = listener
            .feed_bytes(&conclusion)
            .expect("conclusion response");
        let response = handshake_send(&outputs);
        let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) = SrtPacket::parse(&response)
        else {
            panic!("the listener answers with a handshake");
        };
        let isn = hp.initial_seq_number;
        let _ = caller.on_datagram(&response, at(SLOW_CONCLUDED_US));
        assert!(caller.link().is_some(), "connected");
        (caller, isn)
    }

    /// The handshake's timestamps and the link's counted from `started_us`: a payload sent 100 ms
    /// after a handshake that took 800 ms carries 900 ms, not 100 ms, which the peer would take
    /// to mean it was sent 800 ms earlier and release early.
    #[test]
    fn payloads_are_stamped_from_the_handshakes_start() {
        let (mut caller, _) = slow_connected_caller(&params());
        let sent_at = at(SLOW_CONCLUDED_US + 100_000);
        let link = caller.link_mut().expect("connected");
        link.send(b"payload", sent_at);
        let mut out = Vec::new();
        link.flush(sent_at, &mut out);
        let stamp = out
            .iter()
            .find_map(|d| match SrtPacket::parse(d) {
                Ok(SrtPacket::Data(dp)) => Some(u64::from(dp.timestamp.value())),
                _ => None,
            })
            .expect("a data packet");
        assert_eq!(stamp, SLOW_CONCLUDED_US + 100_000);
    }

    /// The peer's timestamps map onto the link's clock through the signed time base: a payload
    /// stamped when the peer sent it is released one latency after it arrived (zero flight).
    #[test]
    fn a_peers_payload_is_released_one_latency_after_it_was_sent() {
        let (mut caller, isn) = slow_connected_caller(&params());
        let sent_at_us = SLOW_CONCLUDED_US + 100_000;
        let peer_elapsed_us = sent_at_us - SLOW_START_US;
        let dp = crate::packet::DataPacket {
            seq_number: isn,
            position: crate::packet::PacketPosition::Solo,
            in_order: true,
            key_flag: EncryptionKeyField::NotEncrypted,
            retransmitted: false,
            message_number: 1,
            timestamp: SrtTimestamp::from_wire(u32::try_from(peer_elapsed_us).expect("fits")),
            dest_socket_id: SocketId::from_wire(2),
            data: b"payload",
        };
        let mut wire = alloc::vec![0u8; dp.serialized_len()];
        dp.serialize_into(&mut wire).expect("serialize");
        let release_us = sent_at_us + LATENCY_MS * 1_000;
        let _ = caller.on_datagram(&wire, at(sent_at_us));
        let early = caller.poll(at(release_us - 1_000));
        assert_eq!(
            early.payloads().count(),
            0,
            "not before the latency has passed"
        );
        let due = caller.poll(at(release_us));
        assert_eq!(due.payloads().collect::<Vec<_>>(), [b"payload".as_slice()]);
    }

    /// The silence clock starts when the connection is made, not at the handshake's start: a
    /// silent peer ends it one `read_idle` after the conclusion.
    #[test]
    fn the_idle_clock_starts_at_the_conclusion() {
        let (mut caller, _) = slow_connected_caller(&params());
        let idle_us = micros(TEST_TIMERS.read_idle);
        let before = caller.poll(at(SLOW_CONCLUDED_US + idle_us - 1_000));
        assert!(
            !before
                .items()
                .iter()
                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle))),
            "alive just inside the bound"
        );
        let after = caller.poll(at(SLOW_CONCLUDED_US + idle_us));
        assert!(
            after
                .items()
                .iter()
                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle)))
        );
    }

    /// A caller whose budget runs out before any resolution ends the attempt
    /// once, and names why.
    #[test]
    fn the_handshake_budget_ends_the_attempt() {
        let budget = Duration::from_millis(400);
        let params = params().with_handshake_timeout(budget);
        let mut caller = CallerLink::new(&params, alloc::vec![1; KEY_LEN], 0);
        caller.connect(Instant::ZERO);
        let _ = caller.take_sent();
        assert!(
            caller.poll(at(micros(budget) - 1)).is_empty(),
            "still inside it"
        );
        assert!(matches!(
            caller.poll(at(micros(budget))).items(),
            [DeliveredItem::Ended(LinkEnd::HandshakeTimedOut)]
        ));
    }

    /// A peer that refuses ends the attempt with its own reason.
    #[test]
    fn a_rejection_ends_the_attempt_with_its_reason() {
        let params = CallerParams::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server)
                .with_encryption_field(EncryptionField::Aes128),
            0,
            0,
            TEST_TIMERS,
            crate::test_support::ARQ_BOUNDS,
            alloc::vec![7; KEY_LEN],
            TEST_DRIFT_WINDOW,
        )
        .with_passphrase(b"passphrase".to_vec());
        let mut caller = CallerLink::new(&params, alloc::vec![2; KEY_LEN], 0);
        caller.connect(Instant::ZERO);
        let _ = caller.take_sent();
        let reason = RejectionReason::Unsecure;
        let packet = ControlPacket::Handshake(HandshakePacket {
            timestamp: SrtTimestamp::ZERO,
            dest_socket_id: SocketId::CONNECTION_REQUEST,
            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
            encryption_field: EncryptionField::NoEncryption,
            extension_field: crate::packet::HandshakeExtensionFlags::new(0),
            initial_seq_number: 0,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: reason.to_handshake_type(),
            srt_socket_id: 9,
            syn_cookie: 0,
            peer_ip: [0; 4],
            extensions: crate::packet::HandshakeExtensions(alloc::vec::Vec::new()),
        });
        let mut bytes = alloc::vec![0u8; packet.serialized_len()];
        packet
            .serialize_into(&mut bytes)
            .expect("serialize rejection");
        assert!(matches!(
            caller.on_datagram(&bytes, Instant::ZERO).items(),
            [DeliveredItem::Ended(LinkEnd::Rejected(r))] if *r == reason
        ));
    }

    /// The control-packet wire timestamp is a microsecond count that wraps at 2^32.
    #[test]
    fn a_control_timestamp_is_the_low_32_bits_of_the_clock() {
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(0x1_0000_0005)).value(),
            5
        );
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(0x00FF_FFFF_FFFF)).value(),
            0xFFFF_FFFF
        );
    }

    /// A DROPREQ removes the staged packets inside its range; the packets outside
    /// it are released on time.
    #[test]
    fn a_drop_request_removes_the_staged_packets_inside_its_range() {
        let mut link = Link::new(
            Instant::ZERO,
            &LinkSetup::new(
                negotiated(crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP),
                100,
                0,
            ),
            &params(),
        );
        for seq in [100u32, 101, 102, 103, 104] {
            assert!(
                link.on_datagram(&data(seq, b"x"), Instant::ZERO).is_empty(),
                "nothing released yet"
            );
        }
        assert_eq!(
            link.staged_len(),
            5,
            "everything ahead of the cursor is staged"
        );
        let req = ControlPacket::DropReq(DropReqPacket {
            message_number: crate::packet::MessageNumber::try_new(1).expect("message"),
            timestamp: SrtTimestamp::ZERO,
            dest_socket_id: SocketId::from_wire(1),
            first_seq: crate::packet::SeqNo::try_new(101).expect("first"),
            last_seq: crate::packet::SeqNo::try_new(103).expect("last"),
        });
        let mut bytes = alloc::vec![0u8; req.serialized_len()];
        req.serialize_into(&mut bytes).expect("serialize dropreq");
        // The DROPREQ does not drain on its own: the ring has no gap between the
        // staged range and the release pass, and the dropped range is never handed
        // to the host.
        let _ = link.on_datagram(&bytes, Instant::ZERO);
        let mut delivered = alloc::vec::Vec::new();
        delivered.extend(
            link.poll(at(micros(Duration::from_millis(LATENCY_MS))))
                .into_items(),
        );
        let payloads: usize = delivered
            .iter()
            .filter(|item| matches!(item, DeliveredItem::Payload(_)))
            .count();
        assert!(
            (1..=5).contains(&payloads),
            "the dropped range is never delivered, and the rest arrives on time: {payloads}"
        );
    }
}

#[cfg(test)]
mod link_key_tests {
    use super::*;
    use crate::handshake_sm::NegotiatedParams;
    use crate::test_support::at;

    const LATENCY_MS: u64 = 120;

    fn test_link() -> Link {
        test_link_with(TEST_TIMERS, alloc::vec![7; KEY_LEN])
    }

    fn test_link_with(timers: LinkTimers, seed: Vec<u8>) -> Link {
        let params = NegotiatedParams {
            version: 5,
            flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
            latency: Duration::from_millis(LATENCY_MS),
            own_socket_id: 2,
            peer_socket_id: 1,
            mtu: 1500,
            max_flow_window_size: 8192,
            stream_id: None,
            group: None,
            sek: None,
            salt: None,
        };
        Link::new(
            Instant::ZERO,
            &LinkSetup::new(params, 0, 0),
            &CallerParams::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                0,
                0,
                timers,
                crate::test_support::ARQ_BOUNDS,
                seed,
                TEST_DRIFT_WINDOW,
            ),
        )
    }

    #[test]
    fn key_set_clear_empties_the_slot() {
        let mut keys = KeySet::default();
        keys.install(
            KeyParity::Even,
            alloc::vec![1u8; DEFAULT_SEK_LEN],
            [0; crate::crypto::SALT_LEN],
        );
        assert!(!keys.is_empty());
        keys.clear(KeyParity::Even);
        assert!(keys.is_empty());
    }

    #[test]
    fn key_refresh_does_not_clear_the_active_parity() {
        let mut link = test_link();
        link.install_active_parity(KeyParity::Even);
        link.defer_retire(KeyParity::Even);
        link.advance_key_refresh(0);
        assert!(
            link.tx_key_installed(KeyParity::Even),
            "the active parity must never be retired"
        );
    }

    #[test]
    fn key_refresh_clears_a_retired_parity() {
        let mut link = test_link();
        link.install_active_parity(KeyParity::Even);
        link.install_key(KeyParity::Odd, alloc::vec![2u8; DEFAULT_SEK_LEN]);
        link.defer_retire(KeyParity::Odd);
        link.advance_key_refresh(0);
        assert!(
            !link.tx_key_installed(KeyParity::Odd),
            "a retired (non-active) parity is wiped"
        );
        assert!(link.tx_key_installed(KeyParity::Even));
    }

    #[test]
    fn announce_key_uses_the_default_sek_length_when_unset() {
        let mut link = test_link();
        link.set_passphrase(b"pw".to_vec());
        link.announce_key_for_test(KeyParity::Even);
        assert_eq!(link.tx_key_len(KeyParity::Even), Some(DEFAULT_SEK_LEN));
        assert_eq!(DEFAULT_SEK_LEN, 16);
    }

    #[test]
    fn resend_pending_km_repeats_a_due_key_material_request() {
        let mut link = test_link();
        link.pend_km_for_test(KeyParity::Even, alloc::vec![9u8, 9], 0);
        link.resend_pending_km(0);
        assert_eq!(link.take_sent(), alloc::vec![alloc::vec![9u8, 9]]);
    }

    fn keepalives(sent: &[Vec<u8>]) -> usize {
        sent.iter()
            .filter(|d| {
                matches!(
                    SrtPacket::parse(d),
                    Ok(SrtPacket::Control(ControlPacket::KeepAlive(_)))
                )
            })
            .count()
    }

    /// A receive-only link sends only control: writing it out must restart the Keep-Alive period,
    /// or the link queues a Keep-Alive on every wake once the first second has passed.
    #[test]
    fn a_flushed_control_datagram_restarts_the_keepalive_period() {
        const SENT_US: u64 = 600_000;
        let period = micros(TEST_TIMERS.cadence.keepalive);
        let mut link = test_link();
        let mut sent = Vec::new();
        link.queue_keepalive(SENT_US);
        link.flush(at(SENT_US), &mut sent);
        assert_eq!(keepalives(&sent), 1);

        let mut sent = Vec::new();
        let _ = link.poll_io(at(period + micros(MIN_WAKE)), &mut sent);
        assert_eq!(
            keepalives(&sent),
            0,
            "{} µs after the last write",
            period + micros(MIN_WAKE) - SENT_US
        );
    }

    #[test]
    fn a_key_refresh_without_entropy_is_counted_reported_and_retried() {
        let mut link = test_link_with(TEST_TIMERS, Vec::new());
        link.set_passphrase(b"pw".to_vec());
        link.announce_key_for_test(KeyParity::Even);
        assert_eq!(link.counts().key_refresh_failed, 1);
        assert!(!link.tx_key_installed(KeyParity::Even));
        let delivered = link.poll(at(1));
        assert!(
            delivered
                .items()
                .iter()
                .any(|i| matches!(i, DeliveredItem::Damage(_))),
            "{:?}",
            delivered.items()
        );
        link.advance_key_refresh(2);
        assert_eq!(link.counts().key_refresh_failed, 2);
    }

    #[test]
    fn a_seeded_key_refresh_is_deterministic_and_seed_specific() {
        let announce = |seed: u8| {
            let mut link = test_link_with(TEST_TIMERS, alloc::vec![seed; KEY_LEN]);
            link.set_passphrase(b"pw".to_vec());
            link.announce_key_for_test(KeyParity::Even);
            assert_eq!(link.counts().key_refresh_failed, 0);
            link.take_sent()
        };
        let first = announce(1);
        assert!(!first.is_empty());
        assert_eq!(first, announce(1));
        assert_ne!(first, announce(2));
    }

    #[test]
    fn the_keepalive_period_is_the_callers() {
        let mut timers = TEST_TIMERS;
        timers.cadence.keepalive = Duration::from_millis(20);
        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
        let mut sent = Vec::new();
        let _ = link.poll_io(at(micros(Duration::from_millis(19))), &mut sent);
        assert_eq!(keepalives(&sent), 0);
        let _ = link.poll_io(at(micros(Duration::from_millis(45))), &mut sent);
        assert!(keepalives(&sent) >= 1);
    }

    #[test]
    fn the_key_material_resend_interval_is_the_callers() {
        let mut timers = TEST_TIMERS;
        timers.cadence.km_resend = Duration::from_millis(30);
        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
        link.set_passphrase(b"pw".to_vec());
        link.announce_key_for_test(KeyParity::Even);
        let _ = link.take_sent();
        link.resend_pending_km(0);
        let _ = link.take_sent();
        link.resend_pending_km(micros(Duration::from_millis(29)));
        assert!(link.take_sent().is_empty());
        link.resend_pending_km(micros(Duration::from_millis(31)));
        assert_eq!(link.take_sent().len(), 1);
    }

    #[test]
    fn the_read_idle_bound_is_the_callers() {
        let mut timers = TEST_TIMERS;
        timers.read_idle = Duration::from_millis(40);
        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
        assert!(
            link.poll(at(micros(Duration::from_millis(39))))
                .items()
                .is_empty()
        );
        assert!(matches!(
            link.poll(at(micros(Duration::from_millis(41)))).items(),
            [DeliveredItem::Ended(LinkEnd::PeerIdle)]
        ));
    }

    #[test]
    fn no_timer_or_cadence_type_has_a_default() {
        trait AmbiguousIfDefault<A> {
            fn some_item() {}
        }
        impl<T> AmbiguousIfDefault<()> for T {}
        impl<T: Default> AmbiguousIfDefault<u8> for T {}
        <LinkTimers as AmbiguousIfDefault<_>>::some_item();
        <LinkCadence as AmbiguousIfDefault<_>>::some_item();
    }
}

#[cfg(test)]
mod retransmit_tests;

#[cfg(test)]
mod key_lifetime_tests;