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
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
//! Async real-socket UDP adapter over the sans-IO SRT engine.
//!
//! The sans-IO [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]
//! engines never touch a socket — they turn state transitions into typed events
//! and byte buffers. The ARQ sender/receiver, TSBPD scheduler, and LiveCC
//! pacing controller follow the same contract: all take caller-supplied
//! `now: core::time::Duration` and never read a wall clock.
//!
//! This module is the thin tokio layer that actually moves bytes over a
//! [`tokio::net::UdpSocket`], drives the handshake to completion, and then
//! runs a **background driver task** per connection that pumps socket RX →
//! engines → socket TX and, crucially, drives the timers (retransmit, ACK,
//! NAK, TSBPD release, keep-alive, pacing) from the connection's own next
//! deadline (`Driver::poll_timeout`) — so loss recovery keeps making progress
//! even when the application is neither sending nor receiving at that instant,
//! without a fixed tick. The sans-IO core stays `no_std`; the adapter is pure
//! plumbing.
//!
//! Timeouts and the datagram size are explicit: [`IoConfig`]
//! (`connect`/`handshake`/`read_idle`/`write`, `max_datagram`). Datagrams are
//! [`bytes::Bytes`], one exactly-sized allocation per received datagram (never a
//! view into a shared chunk, which would pin the whole chunk while one packet
//! is held); the payload handed to the application is a slice of it, so there
//! is no further copy.
//!
//! # Why a background task
//!
//! SRT reliability is bidirectional and continuous: a receiver that detects a
//! gap emits a NAK, and the *sender* must react to that NAK by retransmitting
//! — long after the application handed it the original payload. A purely
//! pull-based `send`/`recv` (one that only advances the protocol while the
//! app is blocked inside a call) deadlocks the moment a fire-and-forget sender
//! stops calling `send`: the inbound NAK is never drained and the lost packet
//! is never resent. The driver task decouples protocol progress from
//! application call timing: [`SrtSocket::send`] enqueues a payload,
//! [`SrtSocket::recv`] awaits a delivered payload, and the task in between
//! runs the select loop (RX / app-send / next deadline) until the peer shuts
//! down, falls silent, or the [`SrtSocket`] is dropped.
//!
//! # Connection lifetime
//!
//! - **Keep-alive** (§3.2.3): after one second without sending anything, the
//!   driver sends a Keep-Alive, so a quiet sender is not mistaken for a dead
//!   one by a peer's own idle timeout (libsrt's default is five seconds).
//! - **Peer idle timeout**: five seconds without *any* packet from the peer
//!   ends the connection ([`SrtSocket::recv`] then returns `None`).
//! - **Shutdown** (§3.2.7): dropping an [`SrtSocket`] sends the peer a
//!   SHUTDOWN so it closes at once instead of waiting out its idle timeout;
//!   a received SHUTDOWN ends the connection.
//! - **Backpressure**: [`SrtSocket::send`] waits while the sender already
//!   holds a full flow window of unacknowledged packets, so a stalled or dead
//!   peer cannot make the send buffer grow without bound.
//!
//! # Structure
//!
//! - [`SrtListener`] — binds a UDP port and accepts incoming SRT connections,
//!   returning a [`SrtSocket`] per connected peer.
//! - [`SrtSocket`] — a handle to an established SRT connection (caller or
//!   listener role) with async [`send`](SrtSocket::send) and
//!   [`recv`](SrtSocket::recv) for application payloads; the actual protocol
//!   runs on the background driver task the handle owns.
//!
//! # Feature gate
//!
//! Only available with `features = ["tokio"]` (implies `std`). Without the
//! `tokio` feature, the crate stays `no_std`+`alloc` and nothing in this
//! module is compiled.

use broadcast_core::damage::{Damage, DamageError, DamageKind, DamagePolicy, Severity};
use broadcast_core::error::InvalidField;
use broadcast_core::stage::Instant as LinkInstant;
use broadcast_net::net::UdpOptions;
use broadcast_net::timeouts::Timeouts;
use broadcast_net::udp_bind;
use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use alloc::collections::VecDeque;
use core::time::Duration;

use bytes::Bytes;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

use crate::caller::CallerHandshake;
use crate::cookie::{derive_cookie, derive_listener_ids, validate_cookie};
use crate::error::{Error, Result};
use crate::handshake_sm::{self, HandshakeConfig, HandshakeOutput, RejectionReason};
use crate::link::{CallerParams, Link, LinkCadence, LinkSetup, LinkTimers, shutdown_datagram};
use crate::listener::{ListenerHandshake, ListenerHandshakeState};
use crate::livecc::MaxBwConfig;
use crate::packet::{
    ControlPacket, EncryptionField, HandshakeExtensionFlags, HandshakeExtensions, HandshakePacket,
    HandshakeType, SEQ_NUMBER_MASK, SrtPacket,
};

// ===========================================================================
// Constants
// ===========================================================================

/// Smallest accepted [`IoConfig::max_datagram`]: a full SRT header (16 bytes)
/// plus room for a control CIF. A smaller value is refused with
/// [`Error::InvalidConfig`], as is one above [`MAX_MAX_DATAGRAM`].
pub const MIN_MAX_DATAGRAM: usize = 64;
/// Largest accepted [`IoConfig::max_datagram`]: the biggest UDP payload.
pub const MAX_MAX_DATAGRAM: usize = 65_535;

/// Everything one SRT connection or listener is configured by: the handshake
/// this side advertises and the adapter's timeouts and sizes. Every
/// `SrtSocket` and `SrtListener` constructor takes the config:
/// `SrtSocketConfig::new(handshake, io, udp)`. It is
/// named for its role, not `SrtClientConfig`, because one config serves both
/// the caller (`SrtSocket::connect`) and the listener (`SrtListener::bind`).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SrtSocketConfig {
    /// The handshake values this side advertises.
    pub handshake: HandshakeConfig,
    /// The tokio adapter's timeouts and sizes.
    pub io: IoConfig,
    /// The socket options every socket this config binds is created with
    /// (`SO_RCVBUF`, address and port reuse, a multicast join). Required: the
    /// library chooses none. [`UdpOptions::new`] is the explicit "leave every
    /// option at the system's value"; a link at broadcast bitrates needs a
    /// receive buffer sized for the longest burst the application can be late
    /// by (see the crate docs). Not applied to a socket the caller built and
    /// hands to [`SrtSocket::connect_from_socket`],
    /// [`SrtSocket::rendezvous_from_socket`]: that socket keeps the options the
    /// caller gave it.
    pub udp: UdpOptions,
    /// What each damage report means for this connection: `Report` (the
    /// default for everything) publishes it as [`SrtEvent::Damage`] and keeps
    /// delivering; `Fail` ends the connection with [`Error::Damage`]
    /// carrying the same report.
    pub damage_policy: DamagePolicy,
}

impl SrtSocketConfig {
    /// A config with `handshake`, the caller's [`IoConfig`] and the socket
    /// options `udp` for every socket it binds.
    pub fn new(handshake: HandshakeConfig, io: IoConfig, udp: UdpOptions) -> Self {
        SrtSocketConfig {
            handshake,
            io,
            udp,
            damage_policy: DamagePolicy::default(),
        }
    }

    /// Set what each damage report means (see [`SrtSocketConfig::damage_policy`]).
    #[must_use]
    pub fn with_damage_policy(mut self, damage_policy: DamagePolicy) -> Self {
        self.damage_policy = damage_policy;
        self
    }

    /// Replace [`SrtSocketConfig::handshake`].
    #[must_use]
    pub fn with_handshake(mut self, handshake: HandshakeConfig) -> Self {
        self.handshake = handshake;
        self
    }

    /// Replace [`SrtSocketConfig::udp`].
    #[must_use]
    pub fn with_udp(mut self, udp: UdpOptions) -> Self {
        self.udp = udp;
        self
    }

    /// Replace [`SrtSocketConfig::io`].
    #[must_use]
    pub fn with_io(mut self, io: IoConfig) -> Self {
        self.io = io;
        self
    }
}

/// Timeouts and sizes for the tokio adapter, carried by [`SrtSocketConfig`] into
/// [`SrtSocket::connect`] and [`SrtListener::bind`].
///
/// Every value is the caller's: the library supplies none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct IoConfig {
    /// Largest datagram accepted from the network (bytes). A
    /// larger datagram is dropped and counted in [`SocketStats::rx_oversize`]
    /// (UDP would otherwise truncate it silently). A value outside
    /// [`MIN_MAX_DATAGRAM`]..=[`MAX_MAX_DATAGRAM`] is refused by
    /// [`IoConfig::validate`], never clamped.
    pub max_datagram: usize,
    /// The bounds on every awaited I/O: `connect` (resolving the remote
    /// address and binding the local socket), `handshake` (the whole caller
    /// handshake), `read_idle` (longest silence from a connected peer before the
    /// connection is torn down) and `write` (longest a single `send_to` may
    /// take).
    pub timeouts: Timeouts,
    /// KM Refresh thresholds (key rotation); [`IoConfig::new`] starts from the
    /// spec-recommended `2^25` / `4000` values. The type carries no crypto
    /// dependency; the value is held in every feature configuration.
    pub km_refresh_thresholds: crate::km_refresh::KmRefreshThresholds,
    /// The link's protocol cadence (handshake retransmit, Keep-Alive, KM resend, KMREQ floor).
    pub cadence: LinkCadence,
    /// The listener's handshake and cookie bounds.
    pub listener: ListenerLimits,
    /// The ARQ receiver's and sender's bounds on every connection.
    pub arq: crate::arq::ArqBounds,
    /// Fresh in-sequence packets per drift-sampling window (§4.7, rules 26-27).
    /// The draft gives no number; zero is refused by [`IoConfig::validate`].
    pub drift_sample_count: u32,
    /// The capacity of every bounded channel the adapter owns.
    pub channels: ChannelCapacities,
    /// How long a closing sender waits for ACKs of its unacknowledged packets. The caller's;
    /// expiry is reported as damage rather than silently dropping the tail.
    pub close: CloseTimings,
    /// The LiveCC bandwidth cap each connection paces its DATA packets to.
    pub max_bw: MaxBwConfig,
}

/// The bound on a closing sender's wait for ACKs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CloseTimings {
    /// Longest wait from the close request to SHUTDOWN.
    pub linger: Duration,
}

/// One bound, equal on every deployment profile: a close is a close, whatever the program size.
const CLOSE_LINGER_EMBEDDED: Duration = Duration::from_secs(3);
const CLOSE_LINGER_DEVICE: Duration = Duration::from_secs(3);
const CLOSE_LINGER_SERVER: Duration = Duration::from_secs(3);
const CLOSE_LINGER_HEADEND: Duration = Duration::from_secs(3);

impl CloseTimings {
    /// A caller-supplied linger bound.
    #[must_use]
    pub const fn new(linger: Duration) -> Self {
        Self { linger }
    }

    /// A complete preset, equal on all four profiles.
    #[must_use]
    pub const fn for_profile(profile: broadcast_core::Profile) -> Self {
        Self::new(profile.select(
            CLOSE_LINGER_EMBEDDED,
            CLOSE_LINGER_DEVICE,
            CLOSE_LINGER_SERVER,
            CLOSE_LINGER_HEADEND,
        ))
    }

    /// Replace the linger bound.
    #[must_use]
    pub const fn with_linger(mut self, linger: Duration) -> Self {
        self.linger = linger;
        self
    }
}

impl IoConfig {
    /// A config with the caller's datagram size, `timeouts`, link `cadence`
    /// and `listener` bounds, `arq` bounds and channel capacities, and the spec-recommended KM
    /// refresh thresholds.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidConfig`] naming the field, for a value [`IoConfig::validate`] refuses.
    pub fn new(
        max_datagram: usize,
        timeouts: Timeouts,
        cadence: LinkCadence,
        listener: ListenerLimits,
        arq: crate::arq::ArqBounds,
        drift_sample_count: u32,
        channels: ChannelCapacities,
        max_bw: MaxBwConfig,
        close: CloseTimings,
    ) -> Result<Self> {
        let config = IoConfig {
            max_datagram,
            timeouts,
            km_refresh_thresholds: crate::km_refresh::KmRefreshThresholds::RECOMMENDED,
            cadence,
            listener,
            arq,
            drift_sample_count,
            channels,
            max_bw,
            close,
        };
        config.validate()?;
        Ok(config)
    }

    /// Refuse a value that cannot work: a datagram size outside
    /// [`MIN_MAX_DATAGRAM`]..=[`MAX_MAX_DATAGRAM`], a zero listener bound or tick, or an
    /// ARQ bound [`crate::arq::ArqBounds::validate`] refuses. Channel capacities cannot be zero
    /// by type. Run by [`IoConfig::new`] and again by every connect and bind, so a field set
    /// afterwards is refused too.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidConfig`] naming the field and the rule.
    pub fn validate(&self) -> Result<()> {
        if !(MIN_MAX_DATAGRAM..=MAX_MAX_DATAGRAM).contains(&self.max_datagram) {
            return Err(Error::invalid_config(
                "max_datagram",
                "must be within MIN_MAX_DATAGRAM..=MAX_MAX_DATAGRAM",
            ));
        }
        let rule = "must be at least 1";
        if self.listener.max_pending == 0 {
            return Err(Error::invalid_config("listener.max_pending", rule));
        }
        if self.listener.pending_tick.is_zero() {
            return Err(Error::invalid_config(
                "listener.pending_tick",
                "must not be zero",
            ));
        }
        if self.listener.cookie_key_rotation.is_zero() {
            return Err(Error::invalid_config(
                "listener.cookie_key_rotation",
                "must not be zero",
            ));
        }
        if self.drift_sample_count == 0 {
            return Err(Error::invalid_config(
                "drift_sample_count",
                "must be at least 1",
            ));
        }
        self.arq.validate()
    }

    /// Set [`max_datagram`](Self::max_datagram); [`IoConfig::validate`] refuses an out-of-range
    /// value when the socket is built.
    #[must_use]
    pub fn with_max_datagram(mut self, n: usize) -> Self {
        self.max_datagram = n;
        self
    }

    /// Set [`timeouts`](Self::timeouts).
    #[must_use]
    pub fn with_timeouts(mut self, timeouts: Timeouts) -> Self {
        self.timeouts = timeouts;
        self
    }

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

/// Reads one datagram into the reusable `scratch` buffer (length
/// `max + 1`) and returns it as an exactly-sized `Bytes`, or `None` for an
/// oversize datagram (which has been counted and dropped).
///
/// The copy-out is deliberate: a `Bytes` that was a view into a shared receive
/// chunk would keep the WHOLE chunk alive for as long as that one packet is
/// staged behind a gap, queued for the application or held by it (on a shared
/// listener socket, interleaved connections multiply that). One small
/// allocation per datagram bounds retained memory to the datagrams actually
/// held; the payload is still not copied again on its way to the application
/// (`Driver::release` slices it).
async fn recv_datagram(
    udp: &UdpSocket,
    scratch: &mut [u8],
    max: usize,
    oversize: &AtomicU64,
) -> std::io::Result<Option<(Bytes, std::net::SocketAddr)>> {
    // `scratch` is `max + 1` long: a datagram of max+1 bytes proves "larger
    // than max" (UDP would otherwise truncate it silently).
    let (n, src) = udp.recv_from(scratch).await?;
    if n > max {
        oversize.fetch_add(1, Ordering::Relaxed);
        return Ok(None);
    }
    Ok(Some((Bytes::copy_from_slice(&scratch[..n]), src)))
}

/// One [`RouteTable`] entry: the accepted connection's ingress channel, plus
/// the source address it was accepted from. libsrt demultiplexes its
/// multiplexed listener socket by Destination Socket ID, not source address
/// (draft §4.3.1) — the address is kept here only to *check* it against the datagram that
/// claims this ID (see [`routing_pump`]), so a spoofed ID from
/// the wrong peer cannot be injected into someone else's session.
#[derive(Debug, Clone)]
struct RouteEntry {
    addr: std::net::SocketAddr,
    tx: mpsc::Sender<Bytes>,
    /// Shared with that connection's [`Driver`]/[`SrtSocket`], so a drop
    /// here (channel full) is counted where [`SrtSocket::stats`] can see it.
    stats: Arc<Counters>,
}

/// Shared per-socket demultiplexing table (issue #1029): maps an accepted
/// connection's own Socket ID to its [`RouteEntry`]. A [`SrtListener`]'s
/// single bound socket is used by every connection it has accepted, so —
/// unlike a [`SrtSocket::connect`]'s own dedicated, unshared socket — the
/// listener needs exactly one task reading the socket and routing each
/// datagram, never one `recv_from` call per connection racing another's on
/// the same socket (see the module doc on [`SrtListener`]).
type RouteTable = Arc<Mutex<std::collections::HashMap<u32, RouteEntry>>>;

/// Lock `mutex`, recovering the guard if a previous holder panicked.
///
/// A poisoned lock must never turn into a second panic — least of all inside
/// a `Drop` (see [`RouteCleanup`]) or the routing pump, which would then take
/// the whole listener down for one panicking connection task. Every critical
/// section here is a single `HashMap` insert/remove/get that cannot leave the
/// map half-updated, so the state behind a poisoned lock is still consistent
/// (issue #1134).
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// RAII guard that removes this connection's entry from the listener's shared
/// [`RouteTable`] when dropped. A stale route was a real leak: dropping a
/// listener-accepted [`SrtSocket`] runs `Drop::drop` → `handle.abort()`,
/// which cancels the driver task at its next await point and drops its
/// future (and everything the future owns) without ever reaching the
/// explicit cleanup that used to sit at the tail of [`Driver::run`]'s loop —
/// that code only ran on a *normal* return, never on abort. A `Drop` impl
/// runs either way, since it fires when this guard's owner (the future) is
/// dropped, not only when the function body finishes.
struct RouteCleanup(Option<(u32, RouteTable)>);

impl Drop for RouteCleanup {
    fn drop(&mut self) {
        if let Some((id, routes)) = self.0.take() {
            lock(&routes).remove(&id);
        }
    }
}

/// Aborts the wrapped background task when dropped. A [`SrtSocket::connect`]ed
/// caller's dedicated-socket forwarder task (`spawn_dedicated_socket_forwarder`)
/// holds its own `Arc<UdpSocket>` clone and loops on `recv_from` forever —
/// dropping the `Driver`'s own reference alone does not stop it, so without
/// this guard the forwarder keeps the local port bound indefinitely after the
/// `SrtSocket` is dropped, and a later attempt to bind that same port fails
/// with `AddrInUse` (item 3). `None` for a listener-accepted connection,
/// which has no per-connection forwarder to abort.
struct TaskGuard(Option<tokio::task::JoinHandle<()>>);

impl Drop for TaskGuard {
    fn drop(&mut self) {
        if let Some(handle) = self.0.take() {
            handle.abort();
        }
    }
}

/// The capacity of every bounded channel the adapter owns, all the caller's: a channel of
/// zero slots is unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChannelCapacities {
    /// A per-connection inbound-datagram channel (the dedicated forwarder for a
    /// [`SrtSocket::connect`]ed caller, or a [`SrtListener`]'s per-accepted-connection route):
    /// bounded so a peer that floods faster than the driver task's tick loop can drain does not
    /// grow the queue without bound; excess datagrams are dropped, not buffered.
    pub rx: NonZeroUsize,
    /// A [`SrtListener`]'s candidate-new-connection queue (datagrams the routing pump could not
    /// match to any accepted connection): bounded for the same reason, even though
    /// [`ListenerLimits::max_pending`] already caps how many candidates hold engine state.
    pub unrouted: NonZeroUsize,
    /// The application-to-driver payload channel ([`SrtSocket::send`]). Bounded so the
    /// application is paced by the driver instead of queueing without limit; the driver
    /// additionally stops draining it while the sender holds a full flow window of
    /// unacknowledged packets (see `Driver::send_window_open`).
    pub send: NonZeroUsize,
    /// The driver-to-application delivery channel ([`SrtSocket::recv_event`]). A full channel
    /// drops payloads (counted in [`SocketStats::deliver_dropped`] and reported as one coalesced
    /// damage report once space frees); damage reports and a policy refusal are never lost.
    pub deliver: NonZeroUsize,
    /// A [`SrtListener`]'s pending-`accept` queue: handshakes that finished while `accept` was
    /// not being polled.
    pub accept: NonZeroUsize,
}

/// One item the driver hands the application handle, in delivery order.
///
/// SRT had no event channel before the damage report: [`SrtSocket::recv`]
/// returned payloads only. [`SrtSocket::recv_event`] is that channel now, and
/// `recv` stays the payload-only convenience over it. A refused report (the
/// caller's [`DamagePolicy`] saying `Fail`) is not an item: it ends the
/// connection and `recv_event` returns it as the error.
#[non_exhaustive]
#[derive(Debug)]
pub enum SrtEvent {
    /// A delivered application payload.
    Payload(Bytes),
    /// Content this connection gave up on — the one
    /// [`Damage`] report, in order with the payloads around it.
    Damage(Damage),
}

/// What the driver sends the handle.
enum Delivered {
    Event(SrtEvent),
}

/// The next item for the application: what the channel holds, then what it could not carry (a
/// coalesced report, a held damage report), then, once the driver is gone, the policy's refusal
/// as the error, and only after all of those the clean end.
async fn next_event(
    from_driver: &mut mpsc::Receiver<Delivered>,
    control: &Mutex<DeliverControl>,
) -> Result<Option<SrtEvent>> {
    let next = match from_driver.try_recv() {
        Ok(item) => Some(item),
        Err(mpsc::error::TryRecvError::Empty) => {
            if let Some(event) = lock(control).take_event() {
                return Ok(Some(event));
            }
            from_driver.recv().await
        }
        Err(mpsc::error::TryRecvError::Disconnected) => None,
    };
    match next {
        Some(Delivered::Event(event)) => Ok(Some(event)),
        None => {
            let mut held = lock(control);
            if let Some(event) = held.take_event() {
                return Ok(Some(event));
            }
            held.refusal
                .take()
                .map_or(Ok(None), |e| Err(Error::Damage(e)))
        }
    }
}

/// What the delivery channel could not carry, held beside it so that nothing the application
/// must learn is lost to a full channel: a coalesced report for the dropped payloads, the
/// first damage report that found the channel full, and the policy's refusal, which ends the
/// stream as an error and is never queued behind payloads.
#[derive(Debug, Default)]
struct DeliverControl {
    dropped_run: u64,
    first_dropped_ordinal: u64,
    delivered_ordinal: u64,
    held_damage: Option<Damage>,
    refusal: Option<DamageError>,
}

impl DeliverControl {
    fn take_event(&mut self) -> Option<SrtEvent> {
        if let Some(damage) = self.held_damage.take() {
            return Some(SrtEvent::Damage(damage));
        }
        if self.dropped_run > 0 {
            self.dropped_run = 0;
            return Some(SrtEvent::Damage(
                Damage::new(
                    DamageKind::MediaUnitDropped,
                    Severity::Degraded,
                    "SRT payloads dropped, delivery channel full",
                )
                .with_ordinal(self.first_dropped_ordinal),
            ));
        }
        None
    }

    fn hold(&mut self, damage: Damage) {
        if self.held_damage.is_none() {
            self.held_damage = Some(damage);
            return;
        }
        if self.dropped_run == 0 {
            self.first_dropped_ordinal = self.delivered_ordinal;
        }
        self.dropped_run += 1;
    }
}

/// Floor on how soon [`Driver::poll_timeout`] may ask to be woken: never a
/// deadline in the past, and a 1 ms minimum cannot spin (it matches tokio's
/// timer granularity).
const MIN_WAKE: Duration = Duration::from_millis(1);
/// The listener's own bounds, chosen by the caller of [`SrtListener::bind`] through
/// [`IoConfig::listener`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ListenerLimits {
    /// Upper bound on concurrently in-progress handshakes, and on remembered CONCLUSION
    /// responses (one per recently accepted source address). Every new source address that sends
    /// an INDUCTION allocates an entry; without a cap a flood of (possibly spoofed) handshake
    /// packets exhausts memory before any of them times out.
    pub max_pending: usize,
    /// How often accept drives pending-handshake expiry and retransmits, independent of receive
    /// activity.
    pub pending_tick: Duration,
    /// How often the SYN-cookie key is replaced (§4.3.1.1 buckets the cookie's time input to one
    /// minute).
    pub cookie_key_rotation: Duration,
    /// How long an accepted connection's CONCLUSION response is remembered so a repeated
    /// CONCLUSION (the response was lost) can be answered again.
    pub recent_accept_ttl: Duration,
}

// Release and pacing both live in [`crate::link::Link`]: §5.1.2 paces DATA packets only, so
// control feedback is never queued behind a not-yet-due DATA packet, and the pacing slot is the
// link's own `next_deadline_us`. The driver here only writes what the link hands it.

/// Per-connection counters for datagrams a bounded internal channel dropped
/// because it was full (item 4) — this adapter's own internal backpressure,
/// distinct from wire-level loss ARQ/TLPKTDROP already account for. Shared
/// (via `Arc`) between a [`Driver`] and the [`SrtSocket`] handle so
/// [`SrtSocket::stats`] reads live counts, not a snapshot frozen at spawn.
#[derive(Debug, Default)]
struct Counters {
    control: Mutex<DeliverControl>,
    damage_coalesced: AtomicU64,
    rx_dropped: AtomicU64,
    deliver_dropped: AtomicU64,
    late_dropped: AtomicU64,
    too_late_dropped: AtomicU64,
    rx_oversize: AtomicU64,
}

/// A snapshot of one connection's `Counters`, returned by
/// [`SrtSocket::stats`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SocketStats {
    /// Inbound datagrams dropped because the per-connection ingress channel
    /// was full (the peer sent faster than this connection's driver task
    /// could drain).
    pub rx_dropped: u64,
    /// TSBPD-released payloads dropped because the application wasn't
    /// calling [`SrtSocket::recv`] fast enough to keep the delivery channel
    /// from filling.
    pub deliver_dropped: u64,
    /// Damage reports that found the delivery channel full while another was already held
    /// for the application: their count is this, the first is delivered, none is silent.
    pub damage_coalesced: u64,
    /// DATA packets ignored because they were not ahead of the delivery
    /// cursor: duplicates, retransmissions of what was already delivered or
    /// given up on, and stale sequence numbers (never staged).
    pub late_dropped: u64,
    /// Sequence numbers the TSBPD scheduler gave up on: packets that arrived
    /// after their play time by more than the too-late threshold, and gaps
    /// skipped as unrecoverable when the next buffered packet reached its
    /// play time (§4.6, too-late packet drop). Each one is a delivered
    /// stream's payload that no retransmission can recover.
    pub too_late_dropped: u64,
    /// Datagrams larger than [`IoConfig::max_datagram`], dropped rather than
    /// truncated.
    pub rx_oversize: u64,
}

// ===========================================================================
// SrtSocket — a handle to an established SRT connection
// ===========================================================================

/// One payload on its way to the driver task, with the instant the application handed it over:
/// its wire timestamp is that instant, however long it then waits in the queue.
struct Outgoing {
    payload: Bytes,
    handed_over_at: Instant,
}

/// What [`SrtSocket::spawn`] needs to build one connection's engines and
/// driver task.
struct ConnParams {
    udp: Arc<UdpSocket>,
    peer_addr: std::net::SocketAddr,
    rx: mpsc::Receiver<Bytes>,
    stats: Arc<Counters>,
    route_cleanup: RouteCleanup,
    forwarder_guard: TaskGuard,
    /// For a listener-accepted connection: keeps the listener's tasks (and so
    /// its socket) alive for as long as this connection is.
    life: Option<Arc<ListenerLife>>,
    /// [`IoConfig::read_idle`] for this connection.
    read_idle: Duration,
    /// [`IoConfig::write`] for this connection.
    write: Duration,
    our_initial_seq: u32,
    peer_initial_seq: u32,
    peer_socket_id: u32,
    /// The instant the handshake began: the origin of every timestamp this connection puts on the
    /// wire, handshake or data, and of `T_NOW` below.
    epoch: Instant,
    /// `TsbpdTimeBase` (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP`, with `T_NOW` measured from
    /// `epoch` — so the negation of the peer's handshake timestamp when `epoch` is the instant
    /// that handshake packet arrived.
    tsbpd_time_base: i64,
    /// Everything the handshake settled, as the sans-IO link takes it.
    negotiated: crate::handshake_sm::NegotiatedParams,
    /// The caller's decision about each damage report.
    damage_policy: DamagePolicy,
    /// KM Refresh thresholds (§6.1.6, key rotation packet counts).
    crypto_thresholds: crate::km_refresh::KmRefreshThresholds,
    cadence: LinkCadence,
    close: CloseTimings,
    arq: crate::arq::ArqBounds,
    drift_window: NonZeroU32,
    send_channel_capacity: NonZeroUsize,
    deliver_channel_capacity: NonZeroUsize,
    max_bw: MaxBwConfig,
    handshake: Duration,
    key_refresh_seed: Vec<u8>,
}

/// A handle to an established SRT connection over UDP.
///
/// Created by [`SrtSocket::connect`] (caller role) or
/// [`SrtListener::accept`] (listener role). The protocol itself runs on a
/// background [`tokio`] task the handle owns; [`send`](Self::send) enqueues an
/// application payload and [`recv`](Self::recv) awaits a delivered one.
/// Dropping the handle sends the peer a SHUTDOWN (§3.2.7) and aborts the
/// driver task.
#[derive(Debug)]
pub struct SrtSocket {
    peer_addr: std::net::SocketAddr,
    /// Application payloads flowing to the driver task for transmission.
    to_driver: mpsc::Sender<Outgoing>,
    /// TSBPD/ARQ-delivered payloads and damage reports flowing back from the
    /// driver task, in delivery order.
    from_driver: mpsc::Receiver<Delivered>,
    /// Damage reports received ahead of a payload the caller asked for with
    /// [`SrtSocket::recv`], held for [`SrtSocket::next_damage`].
    pending_damage: VecDeque<Damage>,
    /// The driver task; joined by [`Self::close`] and detached on drop after a close request.
    driver: Option<tokio::task::JoinHandle<()>>,
    stats: Arc<Counters>,
    /// The connection's socket, for the receive-buffer query.
    udp: Arc<UdpSocket>,
    /// Signals the graceful close, independent of the data channel's backpressure.
    close_tx: mpsc::Sender<()>,
    /// Set by the driver when a close linger expires with packets still unacknowledged.
    close_damage: Arc<std::sync::Mutex<Option<Damage>>>,
    /// Keeps a listener's background tasks alive while this accepted
    /// connection is; `None` for a [`connect`](Self::connect)ed caller.
    _life: Option<Arc<ListenerLife>>,
}

impl SrtSocket {
    /// Connect to a remote SRT peer as a Caller.
    ///
    /// # Encryption
    /// With `crypto` set in the [`HandshakeConfig`], the adapter negotiates
    /// keys in the handshake and encrypts outgoing / decrypts incoming data
    /// packets (AES-CTR, draft section 6) on this connection.
    ///
    /// # Errors
    /// [`Error::Rejected`] carries the peer's [`RejectionReason`];
    /// [`Error::HandshakeTimedOut`] means the peer never answered within the
    /// handshake budget; [`Error::Handshake`] wraps an engine failure with the
    /// stage it happened in.
    pub async fn connect<A: tokio::net::ToSocketAddrs>(
        remote_addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let peer = bounded(
            config.io.timeouts.connect,
            "resolve",
            resolve_one(remote_addr, None),
        )
        .await?;
        let unspecified = if peer.is_ipv4() {
            std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
        } else {
            std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED)
        };
        let local = std::net::SocketAddr::new(unspecified, 0);
        Self::connect_from(local, peer, config).await
    }

    /// Connect from a specific local address.
    ///
    /// # Encryption
    /// Like [`Self::connect`], negotiates and applies payload encryption when
    /// `crypto` is set in the [`HandshakeConfig`].
    pub async fn connect_from<A: tokio::net::ToSocketAddrs>(
        local_addr: std::net::SocketAddr,
        remote_addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let socket = bounded(config.io.timeouts.connect, "bind", async {
            bind_socket(local_addr, &config.udp)
        })
        .await?;
        Self::connect_from_socket(socket, remote_addr, config).await
    }

    /// Like [`Self::connect_from`], but takes an already-bound UDP socket
    /// instead of binding one. The socket's own local address is used as the
    /// connection's local endpoint, which lets a caller hold the port from
    /// bind to use and avoid a bind/read/drop/rebind race.
    ///
    /// # Errors
    /// Same as [`Self::connect_from`].
    pub async fn connect_from_socket<A: tokio::net::ToSocketAddrs>(
        socket: tokio::net::UdpSocket,
        remote_addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let SrtSocketConfig {
            handshake: config,
            io,
            damage_policy,
            ..
        } = config;
        io.validate()?;
        let max_datagram = io.max_datagram;
        let local_addr = socket.local_addr().map_err(|e| io_err("local_addr", e))?;
        let peer = bounded(
            io.timeouts.connect,
            "resolve",
            resolve_one(remote_addr, Some(local_addr)),
        )
        .await?;
        let socket = Arc::new(socket);

        // Both this Caller's own Socket ID and its ISN must be freshly
        // generated per connection, not carried over from `config` (whose
        // `initial_seq_number` a caller may leave at its `0` default) —
        // `draft-sharabayko-srt-01` §3/§4.3.1.1 expects both random, and a
        // fixed or predictable pair lets an off-path party that knows the
        // 4-tuple guess a live connection's wire identifiers outright.
        let own_socket_id = random_socket_id()?;
        let mut config = config;
        config.initial_seq_number = random_isn()?;
        let mut hs = CallerHandshake::new(own_socket_id, config.clone());

        let epoch = Instant::now();
        hs.set_elapsed(epoch.elapsed());
        let induction = hs.start().map_err(|e| handshake_err("caller start", e))?;
        send_bounded(
            &socket,
            &induction,
            peer,
            io.timeouts.write,
            "send induction",
        )
        .await?;

        // Re-send an unanswered request every `IoConfig::cadence`
        // (each tick hands the engine its own elapsed time), and give up at
        // `IoConfig::handshake` whatever the retry budget says.
        let tick_period = io.cadence.handshake_retransmit;
        let mut ticker = tokio::time::interval_at(Instant::now() + tick_period, tick_period);
        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        let deadline = Instant::now() + io.timeouts.handshake;
        let mut scratch = vec![0u8; max_datagram + 1];
        // The handshake loop has no `SocketStats` yet; oversize datagrams are
        // simply ignored (the real peer retransmits).
        let hs_oversize = AtomicU64::new(0);

        loop {
            enum Event {
                Datagram(Bytes, std::net::SocketAddr),
                Oversize,
                Tick,
                Deadline,
            }
            let event = tokio::select! {
                r = recv_datagram(&socket, &mut scratch, max_datagram, &hs_oversize) => {
                    match r.map_err(|e| io_err("recv hs", e))? {
                        Some((bytes, src)) => Event::Datagram(bytes, src),
                        None => Event::Oversize,
                    }
                }
                _ = ticker.tick() => Event::Tick,
                _ = tokio::time::sleep_until(deadline) => Event::Deadline,
            };

            let (outputs, received) = match event {
                Event::Deadline => {
                    return Err(Error::HandshakeTimedOut {
                        stage: "caller connect",
                    });
                }
                Event::Oversize => continue,
                Event::Tick => {
                    hs.set_elapsed(epoch.elapsed());
                    (hs.tick(tick_period), None)
                }
                Event::Datagram(bytes, src) => {
                    // A packet from anyone but the peer we're connecting to
                    // (some unrelated traffic that happened to land on this
                    // freshly bound port) must not fail the connect — ignore
                    // it and keep waiting for the real peer.
                    if src != peer {
                        continue;
                    }
                    // Likewise, a packet that isn't a well-formed Handshake
                    // control packet right now (a stray Keep-Alive, a
                    // resent/duplicate reply, garbage) must not fail the
                    // connect either — only a genuine handshake rejection or
                    // timeout does that.
                    hs.set_elapsed(epoch.elapsed());
                    let Ok(outputs) = hs.feed_bytes(&bytes) else {
                        continue;
                    };
                    (outputs, Some(bytes))
                }
            };

            for outcome in outputs {
                match outcome {
                    HandshakeOutput::Send(bytes) => {
                        send_bounded(&socket, &bytes, peer, io.timeouts.write, "send hs").await?;
                    }
                    HandshakeOutput::Connected(params) => {
                        // `Connected` only ever comes out of `feed_bytes`, so
                        // the datagram that completed the handshake is still
                        // in `buf`. The peer's ISN (seeds ARQ/TSBPD sequence
                        // tracking) and handshake timestamp (seeds the TSBPD
                        // time base, rule 12) are carried in those bytes; the
                        // peer's SRT Socket ID (the wire `dest_socket_id`
                        // for every outgoing packet) is the negotiated
                        // `params.peer_socket_id` — the two ids are unrelated
                        // values (§3).
                        //
                        // `peer_handshake` errors (rather than defaulting to
                        // 0) if the very bytes that just drove the handshake
                        // state machine to `Connected` fail to re-parse as a
                        // Handshake control packet — an internal
                        // inconsistency. A silent `0` fallback would be
                        // indistinguishable from a genuine ISN of 0 and would
                        // seed ARQ/TSBPD sequence tracking wrong for the life
                        // of the connection.
                        let received = received.ok_or(Error::InvalidField(InvalidField::new(
                            "handshake",
                            "Connected without a received datagram",
                        )))?;
                        let peer_hs = peer_handshake(&received)?;
                        return Self::established(
                            socket,
                            peer,
                            config.initial_seq_number,
                            &params,
                            peer_hs,
                            epoch,
                            max_datagram,
                            &io,
                            damage_policy,
                        );
                    }
                    HandshakeOutput::Rejected(reason) => return Err(Error::Rejected(reason)),
                    HandshakeOutput::TimedOut => {
                        return Err(Error::HandshakeTimedOut {
                            stage: "caller retransmit budget",
                        });
                    }
                }
            }
        }
    }

    /// Wire up a connected socket from a completed handshake (Caller or
    /// Rendezvous): a dedicated-socket forwarder feeding the same
    /// `Driver::rx` path a listener-accepted connection uses (issue #1029),
    /// seeded from the peer's ISN and handshake timestamp (TSBPD rule 12).
    fn established(
        socket: Arc<UdpSocket>,
        peer: std::net::SocketAddr,
        our_initial_seq: u32,
        params: &handshake_sm::NegotiatedParams,
        peer_hs: PeerHandshake,
        epoch: Instant,
        max_datagram: usize,
        io: &IoConfig,
        damage_policy: DamagePolicy,
    ) -> Result<SrtSocket> {
        // This socket is exclusively this connection's own (bound fresh by
        // the connect/rendezvous call, never shared) - no demux table needed.
        let stats = Arc::new(Counters::default());
        let (rx, forwarder) = spawn_dedicated_socket_forwarder(
            Arc::clone(&socket),
            peer,
            Arc::clone(&stats),
            max_datagram,
            io.channels.rx,
        );
        Ok(SrtSocket::spawn(ConnParams {
            udp: socket,
            peer_addr: peer,
            rx,
            stats,
            route_cleanup: RouteCleanup(None),
            forwarder_guard: TaskGuard(Some(forwarder)),
            life: None,
            read_idle: io.timeouts.read_idle,
            write: io.timeouts.write,
            our_initial_seq,
            peer_initial_seq: peer_hs.initial_seq_number,
            peer_socket_id: params.peer_socket_id,
            epoch,
            tsbpd_time_base: tsbpd_time_base_at(epoch, Instant::now(), peer_hs.timestamp_us),
            negotiated: params.clone(),
            damage_policy,
            crypto_thresholds: io.km_refresh_thresholds,
            cadence: io.cadence,
            close: io.close,
            arq: io.arq,
            drift_window: NonZeroU32::new(io.drift_sample_count)
                .ok_or_else(|| Error::invalid_config("drift_sample_count", "must be at least 1"))?,
            send_channel_capacity: io.channels.send,
            deliver_channel_capacity: io.channels.deliver,
            max_bw: io.max_bw,
            handshake: io.timeouts.handshake,
            key_refresh_seed: random_seed()?,
        }))
    }

    /// Establish a connection with a peer in **Rendezvous** mode
    /// (`draft-sharabayko-srt-01` §4.3.2): both sides bind a known local port
    /// and send to each other's address at the same time, so neither is
    /// Caller or Listener; the cookie contest picks Initiator / Responder.
    /// Runs the sans-IO [`crate::rendezvous::RendezvousHandshake`] over a UDP
    /// socket bound to `local_addr` (its port must be the one the peer targets).
    ///
    /// # Errors
    /// [`Error::Rejected`] carries the peer's [`RejectionReason`];
    /// [`Error::HandshakeTimedOut`] means the peer never completed the
    /// exchange within the handshake budget.
    pub async fn rendezvous<A: tokio::net::ToSocketAddrs>(
        local_addr: std::net::SocketAddr,
        remote_addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let socket = bounded(config.io.timeouts.connect, "bind", async {
            bind_socket(local_addr, &config.udp)
        })
        .await?;
        Self::rendezvous_from_socket(socket, remote_addr, config).await
    }

    /// Like [`Self::rendezvous`], but takes an already-bound UDP socket
    /// instead of binding one. The socket's own local address is used as the
    /// connection's local endpoint, which lets a caller hold the port from
    /// bind to use and avoid a bind/read/drop/rebind race.
    ///
    /// # Errors
    /// Same as [`Self::rendezvous`].
    pub async fn rendezvous_from_socket<A: tokio::net::ToSocketAddrs>(
        socket: tokio::net::UdpSocket,
        remote_addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let SrtSocketConfig {
            handshake: config,
            io,
            damage_policy,
            ..
        } = config;
        io.validate()?;
        let max_datagram = io.max_datagram;
        let local_addr = socket.local_addr().map_err(|e| io_err("local_addr", e))?;
        let peer = bounded(
            io.timeouts.connect,
            "resolve",
            resolve_one(remote_addr, Some(local_addr)),
        )
        .await?;
        let socket = Arc::new(socket);

        // Fresh per-connection Socket ID, ISN and cookie (a zero cookie is
        // never drawn: it is the "no cookie yet" value on the wire).
        let own_socket_id = random_socket_id()?;
        let mut config = config;
        config.initial_seq_number = random_isn()?;
        let mut own_cookie = random_u32()?;
        while own_cookie == 0 {
            own_cookie = random_u32()?;
        }
        let mut hs =
            crate::rendezvous::RendezvousHandshake::new(own_socket_id, own_cookie, config.clone());
        let epoch = Instant::now();
        hs.set_elapsed(epoch.elapsed());
        let first = hs
            .start()
            .map_err(|e| handshake_err("rendezvous start", e))?;
        send_bounded(&socket, &first, peer, io.timeouts.write, "send waveahand").await?;

        let tick_period = io.cadence.handshake_retransmit;
        let mut ticker = tokio::time::interval_at(Instant::now() + tick_period, tick_period);
        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        let deadline = Instant::now() + io.timeouts.handshake;
        let mut scratch = vec![0u8; max_datagram + 1];
        let hs_oversize = AtomicU64::new(0);
        // The newest Handshake packet the peer sent: every one carries the
        // peer's ISN, and the freshest timestamp seeds the TSBPD time base.
        // (A Responder promoted to Connected by a data packet, recovery
        // rule 3, completes on a non-handshake datagram.)
        let mut last_peer_hs: Option<PeerHandshake> = None;

        loop {
            enum Event {
                Datagram(Bytes, std::net::SocketAddr),
                Oversize,
                Tick,
                Deadline,
            }
            let event = tokio::select! {
                r = recv_datagram(&socket, &mut scratch, max_datagram, &hs_oversize) => {
                    match r.map_err(|e| io_err("recv hs", e))? {
                        Some((bytes, src)) => Event::Datagram(bytes, src),
                        None => Event::Oversize,
                    }
                }
                _ = ticker.tick() => Event::Tick,
                _ = tokio::time::sleep_until(deadline) => Event::Deadline,
            };

            let outputs = match event {
                Event::Deadline => {
                    return Err(Error::HandshakeTimedOut {
                        stage: "rendezvous connect",
                    });
                }
                Event::Oversize => continue,
                Event::Tick => {
                    hs.set_elapsed(epoch.elapsed());
                    hs.tick(tick_period)
                }
                Event::Datagram(bytes, src) => {
                    if src != peer {
                        continue;
                    }
                    hs.set_elapsed(epoch.elapsed());
                    match SrtPacket::parse(&bytes) {
                        Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) => {
                            let fed = hs.feed_bytes(&bytes);
                            if hs.peer_socket_id() == Some(hp.srt_socket_id) {
                                last_peer_hs = Some(PeerHandshake {
                                    initial_seq_number: hp.initial_seq_number,
                                    timestamp_us: hp.timestamp.value(),
                                });
                            }
                            match fed {
                                Ok(o) => o,
                                Err(_) => continue,
                            }
                        }
                        // A data packet before we are Connected: missing-
                        // packet recovery rule 3 (a Responder stuck in
                        // Initiated is promoted; anything else is a no-op).
                        Ok(SrtPacket::Data(_)) => match hs.on_recovery_trigger() {
                            Ok(o) => o,
                            Err(_) => continue,
                        },
                        // Any other control packet is fed straight to the
                        // engine, which applies the same recovery rule.
                        Ok(SrtPacket::Control(c)) => match hs.feed(&c) {
                            Ok(o) => o,
                            Err(_) => continue,
                        },
                        Err(_) => continue,
                    }
                }
            };

            for outcome in outputs {
                match outcome {
                    HandshakeOutput::Send(bytes) => {
                        send_bounded(&socket, &bytes, peer, io.timeouts.write, "send hs").await?;
                    }
                    HandshakeOutput::Connected(params) => {
                        let peer_hs =
                            last_peer_hs.ok_or(Error::InvalidField(InvalidField::new(
                                "handshake",
                                "Connected without having received a peer Handshake packet",
                            )))?;
                        return Self::established(
                            socket,
                            peer,
                            config.initial_seq_number,
                            &params,
                            peer_hs,
                            epoch,
                            max_datagram,
                            &io,
                            damage_policy,
                        );
                    }
                    HandshakeOutput::Rejected(reason) => return Err(Error::Rejected(reason)),
                    HandshakeOutput::TimedOut => {
                        return Err(Error::HandshakeTimedOut {
                            stage: "rendezvous retransmit budget",
                        });
                    }
                }
            }
        }
    }

    /// Build the engine state, spawn its background driver task, and return
    /// the [`SrtSocket`] handle wired to it.
    fn spawn(p: ConnParams) -> Self {
        let (to_driver, app_out) = mpsc::channel::<Outgoing>(p.send_channel_capacity.get());
        let (deliver, from_driver) = mpsc::channel::<Delivered>(p.deliver_channel_capacity.get());
        let (close_tx, close_rx) = mpsc::channel::<()>(1);

        let udp = Arc::clone(&p.udp);
        let peer_addr = p.peer_addr;
        let stats = Arc::clone(&p.stats);
        let life = p.life.clone();
        let close_damage = Arc::new(std::sync::Mutex::new(None));
        let epoch = p.epoch;
        let mut driver = Driver::new(epoch, p, deliver);
        driver.close_rx = close_rx;
        driver.close_keepalive = Some(close_tx.clone());
        driver.close_damage = Arc::clone(&close_damage);
        let handle = tokio::spawn(driver.run(app_out));

        SrtSocket {
            peer_addr,
            to_driver,
            from_driver,
            pending_damage: VecDeque::new(),
            driver: Some(handle),
            stats,
            udp,
            close_tx,
            close_damage,
            _life: life,
        }
    }

    /// Enqueue a payload for transmission to the peer.
    ///
    /// Returns once the payload is handed to the driver task — actual
    /// transmission, ACK/NAK handling, and retransmission all happen on that
    /// task. Waits (applying backpressure) while the sender already holds a
    /// full flow window of unacknowledged packets or the hand-off queue is
    /// full. Fails only if the driver task has stopped (peer shut down, went
    /// silent, or a connection error).
    pub async fn send(&mut self, payload: &[u8]) -> Result<()> {
        self.send_bytes(Bytes::copy_from_slice(payload)).await
    }

    /// Like [`send`](Self::send) but takes ownership of an already-built
    /// [`Bytes`], so the hand-off to the driver task does not copy it.
    pub async fn send_bytes(&mut self, payload: Bytes) -> Result<()> {
        let handed_over_at = Instant::now();
        let outgoing = Outgoing {
            payload,
            handed_over_at,
        };
        self.to_driver.send(outgoing).await.map_err(|_| Error::Io {
            kind: std::io::ErrorKind::BrokenPipe,
            context: "send",
        })
    }

    /// Close this connection after every handed-over packet has been acknowledged, or the
    /// caller's [`CloseTimings`] bound has expired. Returns the damage report when the linger
    /// expired with packets still unacknowledged; the same report travels through
    /// [`Self::recv_event`]. Sending SHUTDOWN and ending the driver are waited for before this
    /// returns.
    ///
    /// # Errors
    /// [`Error::Io`] when the driver task can no longer be reached or it failed.
    pub async fn close(&mut self) -> Result<Option<Damage>> {
        if let Some(handle) = self.driver.take() {
            let _ = self.close_tx.send(()).await;
            handle
                .await
                .map_err(|_| Error::io(std::io::ErrorKind::Other, "srt close"))?;
        }
        let damage = self
            .close_damage
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        Ok(damage)
    }

    /// The peer's socket address.
    pub fn peer_addr(&self) -> std::net::SocketAddr {
        self.peer_addr
    }

    /// Receive the next item in delivery order: a payload or a damage report.
    ///
    /// Returns `None` once the peer has shut down (or the driver task has
    /// stopped) and no further items will arrive. The caller's
    /// [`DamagePolicy`] failing a report (`Fail`) ends the connection here
    /// with [`Error::Damage`] carrying the same report.
    pub async fn recv_event(&mut self) -> Result<Option<SrtEvent>> {
        next_event(&mut self.from_driver, &self.stats.control).await
    }

    /// Receive the next payload, waiting until one is available.
    /// Returns `None` once the peer has shut down (or the driver task has
    /// stopped) and no further payloads will arrive.
    ///
    /// Damage reports that arrive before the next payload are held (they are
    /// not dropped): drain them with [`Self::next_damage`], or use
    /// [`Self::recv_event`] to see both in order.
    pub async fn recv(&mut self) -> Result<Option<Bytes>> {
        loop {
            match self.recv_event().await? {
                Some(SrtEvent::Payload(payload)) => return Ok(Some(payload)),
                Some(SrtEvent::Damage(damage)) => self.pending_damage.push_back(damage),
                None => return Ok(None),
            }
        }
    }

    /// The next damage report already received by a [`Self::recv`] call.
    pub fn next_damage(&mut self) -> Option<Damage> {
        self.pending_damage.pop_front()
    }

    /// The receive buffer the kernel granted this connection's socket
    /// (`SO_RCVBUF`), in bytes; see [`SrtListener::recv_buffer_size`] for why
    /// it can differ from what was requested. For a connection accepted from a
    /// listener this is the listener's socket.
    ///
    /// # Errors
    /// [`Error::Io`] when the socket option cannot be read.
    pub fn recv_buffer_size(&self) -> Result<usize> {
        udp_bind::recv_buffer_size(&*self.udp).map_err(|e| io_err("recv_buffer_size", e))
    }

    /// A snapshot of this connection's internal-backpressure drop counters
    /// (item 4) — datagrams or delivered payloads this adapter's own bounded
    /// channels dropped because they were full, not wire-level loss.
    pub fn stats(&self) -> SocketStats {
        SocketStats {
            rx_dropped: self.stats.rx_dropped.load(Ordering::Relaxed),
            deliver_dropped: self.stats.deliver_dropped.load(Ordering::Relaxed),
            damage_coalesced: self.stats.damage_coalesced.load(Ordering::Relaxed),
            late_dropped: self.stats.late_dropped.load(Ordering::Relaxed),
            too_late_dropped: self.stats.too_late_dropped.load(Ordering::Relaxed),
            rx_oversize: self.stats.rx_oversize.load(Ordering::Relaxed),
        }
    }
}

impl Drop for SrtSocket {
    fn drop(&mut self) {
        if self.driver.is_some() {
            let _ = self.close_tx.try_send(());
        }
    }
}

// ===========================================================================
// Driver — the per-connection background task
// ===========================================================================

/// The engine state driven by one connection's background task. The protocol itself is
/// [`crate::link::Link`]: this owns the socket, the inbound channel and the application
/// hand-off, and runs the RX / app-send / next-deadline select loop in [`Driver::run`].
struct Driver {
    udp: Arc<UdpSocket>,
    peer_addr: std::net::SocketAddr,
    peer_socket_id: u32,
    /// Shared with the [`SrtSocket`] handle (for [`SrtSocket::stats`]) and
    /// whichever task feeds `rx` (the dedicated forwarder, or the listener's
    /// routing pump via its `RouteEntry`), so a drop on either side of that
    /// channel is counted in the one place the application can read it.
    stats: Arc<Counters>,

    // Inbound datagrams for *this* connection only (issue #1029). Fed by
    // exactly one upstream demultiplexer: a per-connection forwarder task
    // reading a dedicated socket ([`SrtSocket::connect_from`]), or the
    // [`SrtListener`]'s single shared-socket routing pump. Never
    // `udp.recv_from` directly — that would race every other task reading
    // the same socket for whichever datagram arrives next, handing some of
    // this connection's own traffic to a different connection (or the
    // listener's own accept loop) at random. Bounded (item 4): a peer that
    // floods faster than this task's tick loop drains gets its excess
    // datagrams dropped, not buffered without bound.
    rx: mpsc::Receiver<Bytes>,
    // For a listener-accepted connection: removes this connection's entry
    // from the shared route table on drop — including on `SrtSocket::Drop`'s
    // task abort, not only a normal `run()` return (see [`RouteCleanup`]).
    // Holds `None` for a `SrtSocket::connect`ed connection (no shared table).
    _route_cleanup: RouteCleanup,
    // For a `SrtSocket::connect`ed connection: aborts the dedicated-socket
    // forwarder task on drop, so it stops holding the local UDP port open
    // (see [`TaskGuard`]). `None` for a listener-accepted connection (no
    // per-connection forwarder — the listener's routing pump outlives it).
    _forwarder_guard: TaskGuard,

    /// The connection's protocol state: handshake-settled engines, ARQ, TSBPD, pacing and the
    /// payload cipher, all driven by datagrams and `now_us`.
    link: Link,
    // Absolute time the last datagram (of any kind, valid or not) was
    // received from the peer — the basis for the peer-idle timeout below.
    last_rx_at: Instant,
    // The instant the link's own epoch names, so `now_us` derives from the wall clock it started
    // from rather than from each call.
    epoch: Instant,

    // Delivered payloads (and damage reports) flowing back to the
    // application handle. Bounded (item 4): see [`DELIVER_CHANNEL_CAPACITY`].
    deliver: mpsc::Sender<Delivered>,

    /// The caller's decision about each damage report: [`crate::link::Link`] applies it, and
    /// says here whether it ended the connection.
    stopped: bool,

    /// Longest silence from the peer before the connection ends
    /// ([`IoConfig::read_idle`]).
    read_idle: Duration,
    /// Longest a single `send_to` may take ([`IoConfig::write`]).
    write_timeout: Duration,
    /// How long a close drains unacknowledged packets before reporting damage.
    close_linger: CloseTimings,
    /// A close request from the handle, independent of payload backpressure.
    close_rx: mpsc::Receiver<()>,
    /// Keeps the request channel open: a closed channel would masquerade as a close request.
    close_keepalive: Option<mpsc::Sender<()>>,
    /// Set when the linger expires with packets still unacknowledged.
    close_damage: Arc<std::sync::Mutex<Option<Damage>>>,
    /// [`LinkCadence::keepalive`]: how long the run loop may sleep when the link names no deadline.
    keepalive: Duration,

    /// Test hook: counts `tick_engines` calls, so a test can prove the run
    /// loop wakes at deadlines rather than on a fixed tick.
    #[cfg(test)]
    tick_counter: Option<Arc<AtomicU64>>,
}

impl Driver {
    fn new(epoch: Instant, p: ConnParams, deliver: mpsc::Sender<Delivered>) -> Self {
        #[cfg(test)]
        let link_epoch = LinkInstant::ZERO;
        #[cfg(not(test))]
        let link_epoch = now_epoch();
        let setup = LinkSetup::new(p.negotiated.clone(), p.peer_initial_seq, 0)
            .with_time_base_us(p.tsbpd_time_base);
        let settled_handshake = HandshakeConfig::new(
            p.negotiated.latency,
            p.negotiated.mtu,
            p.negotiated.max_flow_window_size,
            p.cadence.handshake_retransmit,
            0,
        );
        let params = CallerParams::new(
            settled_handshake,
            p.negotiated.own_socket_id,
            p.our_initial_seq,
            LinkTimers {
                cadence: p.cadence,
                handshake_timeout: p.handshake,
                read_idle: p.read_idle,
            },
            p.arq,
            p.key_refresh_seed,
            p.drift_window,
        )
        .with_damage_policy(p.damage_policy.clone())
        .with_max_bw(p.max_bw)
        .with_km_refresh_thresholds(p.crypto_thresholds);
        let mut link = Link::new(link_epoch, &setup, &params);
        let concluded_at = Instant::now();
        link.start_idle_clock(LinkInstant::from_micros(
            link_epoch.as_micros().saturating_add(
                u64::try_from(concluded_at.saturating_duration_since(epoch).as_micros())
                    .unwrap_or(u64::MAX),
            ),
        ));
        let (close_tx, close_rx) = mpsc::channel(1);
        Driver {
            udp: p.udp,
            peer_addr: p.peer_addr,
            peer_socket_id: p.peer_socket_id,
            stats: p.stats,
            rx: p.rx,
            _route_cleanup: p.route_cleanup,
            _forwarder_guard: p.forwarder_guard,
            link,
            last_rx_at: concluded_at,
            epoch,
            deliver,
            stopped: false,
            read_idle: p.read_idle,
            write_timeout: p.write,
            close_linger: p.close,
            close_rx,
            close_keepalive: Some(close_tx),
            close_damage: Arc::new(std::sync::Mutex::new(None)),
            keepalive: p.cadence.keepalive,
            #[cfg(test)]
            tick_counter: None,
        }
    }

    /// The next instant at which this connection must act without any inbound
    /// event: the next Full ACK / NAK, the next TSBPD release (or too-late
    /// skip), the Keep-Alive when idle, the peer-idle expiry and the next
    /// pacing slot. Never in the past (floored at [`MIN_WAKE`]).
    fn poll_timeout(&self) -> Option<Instant> {
        let now = Instant::now();
        self.link
            .next_deadline(self.link_now(now))
            .map(|at| {
                self.epoch
                    + Duration::from_micros(
                        at.as_micros().saturating_sub(self.link.epoch().as_micros()),
                    )
            })
            .map(|at| at.max(now + MIN_WAKE))
    }

    /// The link's clock reading at `now`: its epoch plus the time since the connection began.
    fn link_now(&self, now: Instant) -> LinkInstant {
        LinkInstant::from_micros(
            self.link.epoch().as_micros().saturating_add(
                u64::try_from(now.saturating_duration_since(self.epoch).as_micros())
                    .unwrap_or(u64::MAX),
            ),
        )
    }

    /// Hand every payload the application already queued to the link before a close arms its
    /// deadline. `SrtSocket::send` returns once a payload is in that queue, so dropping any of
    /// them here would lose a tail the caller was told had been sent.
    fn drain_app_out(&mut self, app_out: &mut mpsc::Receiver<Outgoing>) {
        while let Ok(outgoing) = app_out.try_recv() {
            let handed_over_at = self.link_now(outgoing.handed_over_at);
            self.link.send(&outgoing.payload, handed_over_at);
        }
    }

    /// Arm a close from a request already taken from the channel or one still queued on it, so
    /// an exit chosen by another select arm cannot lose the tail.
    fn arm_close(
        &mut self,
        app_out: &mut mpsc::Receiver<Outgoing>,
        app_open: &mut bool,
        close_deadline: &mut Option<Instant>,
        request_seen: bool,
    ) -> bool {
        if !request_seen && self.close_rx.try_recv().is_err() {
            return false;
        }
        *app_open = false;
        self.drain_app_out(app_out);
        close_deadline.get_or_insert(Instant::now() + self.close_linger.linger);
        true
    }

    /// Report packets left unacknowledged when a close ends for any reason.
    fn report_close_damage(&mut self) {
        let unacked = self.link.buffered_count();
        if unacked == 0 {
            return;
        }
        let damage = crate::damage::dropped_before_delivery(
            "SRT close left packets unacknowledged",
            u64::try_from(unacked).unwrap_or(u64::MAX),
        );
        if let Ok(mut slot) = self.close_damage.lock() {
            *slot = Some(damage.clone());
        }
        self.deliver(crate::link::Delivered::from_items(vec![
            crate::link::DeliveredItem::Damage(damage),
        ]));
    }

    /// The select loop: socket RX, application-send, and a periodic engine
    /// tick — the tick arm is what keeps retransmit/ACK/NAK progressing when
    /// neither peer is actively sending application data.
    async fn run(mut self, mut app_out: mpsc::Receiver<Outgoing>) {
        let mut app_open = true;
        let mut close_deadline: Option<Instant> = None;

        loop {
            let now = Instant::now();
            let engine_at = self.poll_timeout().unwrap_or(now + self.keepalive);
            let wake_at = close_deadline.map_or(engine_at, |deadline| deadline.min(engine_at));
            let accept_app_data =
                app_open && close_deadline.is_none() && self.link.send_window_open();

            tokio::select! {
                biased;
                maybe = self.close_rx.recv() => {
                    if maybe.is_some() {
                        self.arm_close(
                            &mut app_out,
                            &mut app_open,
                            &mut close_deadline,
                            true,
                        );
                    }
                }
                maybe = app_out.recv(), if accept_app_data => {
                    match maybe {
                        Some(outgoing) => {
                            let handed_over_at = self.link_now(outgoing.handed_over_at);
                            self.link.send(&outgoing.payload, handed_over_at);
                        }
                        None => {
                            self.arm_close(
                                &mut app_out,
                                &mut app_open,
                                &mut close_deadline,
                                true,
                            );
                        }
                    }
                }
                maybe = self.rx.recv() => {
                    match maybe {
                        Some(bytes) => self.ingress(bytes),
                        None => {
                            self.arm_close(
                                &mut app_out,
                                &mut app_open,
                                &mut close_deadline,
                                false,
                            );
                            if close_deadline.is_some() {
                                self.report_close_damage();
                            }
                            break;
                        }
                    }
                }
                _ = tokio::time::sleep_until(wake_at) => {}
            }

            let now = self.link_now(Instant::now());
            let mut sent = Vec::new();
            let delivered = self.link.poll_io(now, &mut sent);
            self.deliver(delivered);
            #[cfg(test)]
            if let Some(counter) = &self.tick_counter {
                counter.fetch_add(1, Ordering::Relaxed);
            }
            if self.flush_outbound(sent).await.is_err() {
                self.arm_close(&mut app_out, &mut app_open, &mut close_deadline, false);
                if close_deadline.is_some() {
                    self.report_close_damage();
                }
                break;
            }
            if self.peer_idle(Instant::now()) {
                self.arm_close(&mut app_out, &mut app_open, &mut close_deadline, false);
                if close_deadline.is_some() {
                    self.report_close_damage();
                }
                break;
            }
            if close_deadline.is_some_and(|deadline| {
                self.link.buffered_count() == 0 || Instant::now() >= deadline
            }) {
                self.report_close_damage();
                break;
            }
            if self.link.is_ended() || self.stopped {
                self.arm_close(&mut app_out, &mut app_open, &mut close_deadline, false);
                if close_deadline.is_some() {
                    self.report_close_damage();
                }
                break;
            }
        }
        if close_deadline.is_some()
            && !self.link.is_ended()
            && let Some(buf) = shutdown_datagram(
                self.peer_socket_id,
                Instant::now().saturating_duration_since(self.epoch),
            )
        {
            let _ = send_bounded(&self.udp, &buf, self.peer_addr, self.write_timeout, "send").await;
        }
    }

    /// Hand one datagram from the peer to the link at the current instant and deliver what it
    /// released. The datagram's allocation is handed over, so a payload reaches the application
    /// as a view into it.
    fn ingress(&mut self, bytes: Bytes) {
        self.last_rx_at = Instant::now();
        let now = self.link_now(self.last_rx_at);
        let delivered = self.link.on_owned_datagram(Vec::from(bytes), now);
        self.deliver(delivered);
    }

    /// Hand what the link delivered to the application handle, in order. A
    /// policy-refused report ends the connection with [`Error::Damage`] carrying
    /// the same report.
    fn deliver(&mut self, delivered: crate::link::Delivered) {
        self.flush_held();
        for item in delivered.into_items() {
            match item {
                crate::link::DeliveredItem::Payload(payload) => {
                    let (datagram, start) = payload.into_parts();
                    let event = SrtEvent::Payload(Bytes::from(datagram).slice(start..));
                    if self.deliver.try_send(Delivered::Event(event)).is_err() {
                        self.stats.deliver_dropped.fetch_add(1, Ordering::Relaxed);
                        let mut control = lock(&self.stats.control);
                        if control.dropped_run == 0 {
                            control.first_dropped_ordinal = control.delivered_ordinal;
                        }
                        control.dropped_run += 1;
                    }
                    lock(&self.stats.control).delivered_ordinal += 1;
                }
                crate::link::DeliveredItem::Damage(damage) => {
                    if let Err(refused) = self
                        .deliver
                        .try_send(Delivered::Event(SrtEvent::Damage(damage)))
                    {
                        let Delivered::Event(event) = refused.into_inner();
                        if let SrtEvent::Damage(damage) = event {
                            let mut control = lock(&self.stats.control);
                            if control.held_damage.is_some() {
                                self.stats.damage_coalesced.fetch_add(1, Ordering::Relaxed);
                            }
                            control.hold(damage);
                        }
                    }
                }
                crate::link::DeliveredItem::Refused(error) => {
                    self.stopped = true;
                    lock(&self.stats.control).refusal = Some(error);
                }
                crate::link::DeliveredItem::Ended(_) => {}
            }
        }
        self.flush_held();
    }

    fn flush_held(&mut self) {
        loop {
            let Some(event) = lock(&self.stats.control).take_event() else {
                return;
            };
            if let Err(refused) = self.deliver.try_send(Delivered::Event(event)) {
                let Delivered::Event(event) = refused.into_inner();
                let mut control = lock(&self.stats.control);
                match event {
                    SrtEvent::Damage(damage) if control.held_damage.is_none() => {
                        control.held_damage = Some(damage);
                    }
                    _ => control.dropped_run += 1,
                }
                return;
            }
        }
    }

    /// No packet at all has arrived from the peer for [`IoConfig::read_idle`].
    fn peer_idle(&self, now: Instant) -> bool {
        now.saturating_duration_since(self.last_rx_at) >= self.read_idle
    }

    /// Write every datagram the link handed over, in order.
    async fn flush_outbound(&mut self, sent: Vec<Vec<u8>>) -> Result<()> {
        for bytes in sent {
            send_bounded(
                &self.udp,
                &bytes,
                self.peer_addr,
                self.write_timeout,
                "send",
            )
            .await?;
        }
        Ok(())
    }
}

/// The clock reading a fresh link starts at in a host build: a link treats it as an opaque reading it
/// only ever subtracts its own epoch from, so the monotonic clock since the standard epoch serves,
/// and it keeps every link's wire timestamps on the scale libsrt and the other hosts use. A test
/// starts at zero and names instants as offsets from `Driver::epoch`.
#[cfg(not(test))]
fn now_epoch() -> LinkInstant {
    LinkInstant::after_epoch(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default(),
    )
}

/// Spawn the forwarder task for a connection with its own **dedicated,
/// unshared** socket (a [`SrtSocket::connect`]ed caller): reads that socket
/// directly (no demux table needed — nothing else ever reads it) and
/// forwards only datagrams from `peer`, matching the filtering
/// `Driver::run`'s old direct-`recv_from` arm used to do inline (issue
/// #1029; see the module doc on [`SrtListener`] for the shared-socket case,
/// which needs actual demultiplexing, not just this filter).
///
/// Returns the receiver the [`Driver`] reads plus the task's own
/// [`tokio::task::JoinHandle`] — the caller must abort it (via
/// [`TaskGuard`]) once the connection ends, or this loop keeps the socket's
/// local port bound forever (item 3): dropping the `Driver`'s `Arc<UdpSocket>`
/// reference alone does not stop this task, which holds its own clone and
/// stays parked in `recv_from` waiting for a datagram that may never come.
fn spawn_dedicated_socket_forwarder(
    udp: Arc<UdpSocket>,
    peer: std::net::SocketAddr,
    stats: Arc<Counters>,
    max_datagram: usize,
    rx_channel_capacity: NonZeroUsize,
) -> (mpsc::Receiver<Bytes>, tokio::task::JoinHandle<()>) {
    let (tx, rx) = mpsc::channel(rx_channel_capacity.get());
    let handle = tokio::spawn(async move {
        let mut scratch = vec![0u8; max_datagram + 1];
        loop {
            match recv_datagram(&udp, &mut scratch, max_datagram, &stats.rx_oversize).await {
                Ok(Some((bytes, src))) if src == peer => {
                    if tx.try_send(bytes).is_err() {
                        if tx.is_closed() {
                            break; // Driver is gone.
                        }
                        // Full — the driver isn't draining fast enough; drop
                        // this datagram rather than buffer without bound
                        // (item 4) and count it.
                        stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
                    }
                }
                Ok(_) => {} // datagram from another peer, or oversize (counted); ignore.
                Err(_) => break,
            }
        }
    });
    (rx, handle)
}

// ===========================================================================
// SrtListener
// ===========================================================================

/// An SRT listener that accepts incoming Caller connections.
///
/// # One socket, many connections (issue #1029)
///
/// Every connection this listener accepts shares its single bound socket —
/// unlike [`SrtSocket::connect`], which binds a fresh, unshared socket per
/// connection. `recv_from` on a shared socket delivers each datagram to
/// whichever waiting caller happens to be polled next, *not* whichever
/// caller the datagram is actually addressed to: if both this listener's own
/// `accept` loop and one or more accepted connections' driver tasks each
/// called `recv_from` on the same socket, a datagram belonging to one
/// connection could be handed to a completely different one (which would
/// then just discard it as foreign), silently losing it for its rightful
/// recipient. So exactly one task ever calls `recv_from` on `udp`: the
/// routing pump spawned once in [`SrtListener::bind`]. It demultiplexes the
/// way libsrt does (item 2, draft §4.3.1): a Destination Socket ID of `0`
/// (every handshake packet this crate's Caller ever sends, per the
/// `dest_socket_id` fix in `caller.rs`) always means "not yet an established
/// connection" and goes to `unrouted_rx` (`accept`'s own input); any other ID
/// must match an entry in `routes` *and* that entry's accepted source
/// address, or the datagram is dropped — a stray packet naming an ID that was
/// never accepted (or accepted from a different address) has nowhere
/// legitimate to go.
///
/// A repeated CONCLUSION from an already-accepted Caller (its copy of our
/// response was lost) carries Destination Socket ID `0` too, so it reaches
/// the listener's background task, which answers it again — no one has to be
/// polling [`accept`](Self::accept) for that.
///
/// # Lifetime (defect 3)
///
/// Handshakes advance in a tracked background task, not inside
/// [`accept`](Self::accept); the routing pump is a second tracked task. Both end
/// on a [`CancellationToken`], fired when the last of {this handle, every
/// accepted [`SrtSocket`]} is dropped — so an idle listener releases its UDP
/// port the moment the handle is dropped, while connections it already
/// accepted keep being routed until they too are gone.
pub struct SrtListener {
    /// Held only so its `Drop` (cancel the tasks) runs with the handle.
    _life: Arc<ListenerLife>,
    local: std::net::SocketAddr,
    udp: Arc<UdpSocket>,
    accepted: mpsc::Receiver<Result<SrtSocket>>,
    /// Shared demux table (see [`RouteTable`]); the core and the routing pump
    /// hold the same `Arc`. Read by tests only.
    #[cfg(test)]
    routes: RouteTable,
    unrouted_dropped: Arc<AtomicU64>,
    overflow_dropped: Arc<AtomicU64>,
    send_errors: Arc<AtomicU64>,
}

/// Owns the listener's background tasks. Dropped when the last of the
/// [`SrtListener`] handle and every accepted [`SrtSocket`] is gone; that
/// cancels the tasks, which closes the UDP socket.
#[derive(Debug)]
struct ListenerLife {
    cancel: CancellationToken,
    tasks: TaskTracker,
}

impl Drop for ListenerLife {
    fn drop(&mut self) {
        self.cancel.cancel();
        self.tasks.close();
    }
}

/// The listener's handshake state, driven by one tracked background task
/// ([`ListenerCore::run`]).
struct ListenerCore {
    udp: Arc<UdpSocket>,
    config: HandshakeConfig,
    io: IoConfig,
    /// The caller's decision about each damage report, inherited by every
    /// connection this listener accepts.
    damage_policy: DamagePolicy,
    /// Per-listener 128-bit key for [`derive_cookie`] (`draft-sharabayko-srt-01`
    /// §4.3.1.1: "a cookie that is crafted based on host, port and current
    /// time"), drawn from the OS at [`SrtListener::bind`] and rotated every
    /// [`ListenerLimits::cookie_key_rotation`], so a cookie is neither shared across listeners
    /// nor valid for the life of the process.
    cookie_keys: CookieKeys,
    pending: std::collections::HashMap<std::net::SocketAddr, PendingListener>,
    outbound_queue: std::collections::HashMap<std::net::SocketAddr, VecDeque<Vec<u8>>>,
    /// CONCLUSION responses of recently accepted connections, by source
    /// address, so a repeated CONCLUSION can be answered again (see
    /// [`RecentAccept`]).
    recent_accepts: std::collections::HashMap<std::net::SocketAddr, RecentAccept>,
    /// Shared demux table the routing pump task consults for every inbound
    /// datagram; `drain_completed` registers a new entry for each freshly
    /// accepted connection.
    routes: RouteTable,
    /// Datagrams the routing pump could not match to any entry in `routes`
    /// — candidate new-connection (handshake) traffic. Bounded (item 4): see
    /// [`ChannelCapacities::unrouted`].
    unrouted_rx: mpsc::Receiver<(std::net::SocketAddr, Bytes)>,
    /// Weak, so the core never keeps the listener alive: a connection is only
    /// handed over while a handle (or another connection) still holds the
    /// `Arc`.
    life: std::sync::Weak<ListenerLife>,
    /// Finished handshakes, for [`SrtListener::accept`].
    accepted_tx: mpsc::Sender<Result<SrtSocket>>,
    /// Connections dropped because `accepted_tx` was full.
    overflow_dropped: Arc<AtomicU64>,
    /// Send failures met while answering peers (counted, never queued: they
    /// must not compete with finished connections for `accepted_tx` slots).
    send_errors: Arc<AtomicU64>,
    /// `false` once the handle is gone: no new handshakes are served, but the
    /// task keeps draining `unrouted_rx` so the routing pump (which accepted
    /// connections still depend on) is never starved into exiting.
    accepting: bool,
    /// When `tick_pending` last ran: the basis of [`ListenerCore::poll_timeout`].
    last_pending_tick: Instant,
}

/// The listener's SYN-cookie key and when it was drawn. A stateless INDUCTION
/// answer stores no per-peer cookie, so the CONCLUSION is validated against
/// the current key and the one it replaced: a handshake that began just
/// before a rotation still completes.
struct CookieKeys {
    current: u128,
    previous: Option<u128>,
    drawn_at: Instant,
    rotation: Duration,
}

impl CookieKeys {
    fn new(now: Instant, rotation: Duration) -> Result<Self> {
        Ok(CookieKeys {
            current: random_u128()?,
            previous: None,
            drawn_at: now,
            rotation,
        })
    }

    fn current(&self) -> u128 {
        self.current
    }

    /// Every key a CONCLUSION-phase cookie may have been issued under: the
    /// current one and the one it replaced on the last rotation.
    fn acceptable(&self) -> impl Iterator<Item = u128> + Clone + '_ {
        core::iter::once(self.current).chain(self.previous)
    }

    /// Replace the key once it is [`ListenerLimits::cookie_key_rotation`] old. Returns whether
    /// it did. A failing OS random source keeps the old key (and is retried on
    /// the next call) rather than ending the listener.
    fn rotate_if_due(&mut self, now: Instant) -> bool {
        if now.saturating_duration_since(self.drawn_at) < self.rotation {
            return false;
        }
        match random_u128() {
            Ok(key) => {
                self.previous = Some(self.current);
                self.current = key;
                self.drawn_at = now;
                true
            }
            Err(_) => false,
        }
    }
}

impl core::fmt::Debug for CookieKeys {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CookieKeys")
            .field("current", &format_args!("<redacted>"))
            .field("drawn_at", &self.drawn_at)
            .finish()
    }
}

impl core::fmt::Debug for ListenerCore {
    // Manual: the cookie key must never reach a log via `{:?}` (#1142).
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ListenerCore")
            .field("local_addr", &self.udp.local_addr().ok())
            .field("cookie_keys", &self.cookie_keys)
            .field("pending", &self.pending.len())
            .field("recent_accepts", &self.recent_accepts.len())
            .finish_non_exhaustive()
    }
}

impl core::fmt::Debug for SrtListener {
    // Manual: only the address — the cookie key lives in `ListenerCore`,
    // which is never printed from here (#1142).
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SrtListener")
            .field("local_addr", &self.local)
            .finish_non_exhaustive()
    }
}

#[derive(Debug)]
struct PendingListener {
    handshake: ListenerHandshake,
    params: Option<HandshakeOutput>,
    /// The peer's ISN, extracted from the INDUCTION handshake packet.
    peer_initial_seq: u32,
    /// The `Timestamp` of the peer's CONCLUSION, which seeds the TSBPD time
    /// base (§4.5.1.1: `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP`).
    peer_timestamp_us: u32,
    /// When that CONCLUSION arrived: `T_NOW` of the same formula, hence the
    /// connection epoch (not the later moment `accept` happens to hand the
    /// connection over).
    concluded_at: Option<Instant>,
    /// When this entry was created: the instant the connection started, the
    /// epoch every handshake and data timestamp counts from.
    created_at: Instant,
    /// The last handshake datagram this entry produced — on completion, the
    /// CONCLUSION response a lost-response retransmit must be answered with.
    last_response: Option<Vec<u8>>,
    /// This listener's own ISN for this connection, generated once when the
    /// entry was created and echoed back here (rather than re-read from
    /// `self.config` at completion) so it is guaranteed to be the exact
    /// value the [`ListenerHandshake`] was constructed with — see
    /// [`SrtListener::handle_datagram`].
    our_initial_seq: u32,
}

/// The CONCLUSION response of an accepted connection, kept for
/// [`ListenerLimits::recent_accept_ttl`] so that when the Caller repeats its CONCLUSION (our
/// response was lost, so it never saw the handshake finish) the identical
/// response is sent again — libsrt re-answers a repeated CONCLUSION the same
/// way. Without it the repeat reaches a listener that has already forgotten
/// the handshake, nothing is sent, and the Caller times out against a
/// connection the application is already using.
#[derive(Debug)]
struct RecentAccept {
    /// The Caller's SRT Socket ID — a repeat must carry the same one.
    peer_socket_id: u32,
    response: Vec<u8>,
    accepted_at: Instant,
}

impl SrtListener {
    /// Bind an SRT listener on `addr`.
    ///
    /// # Encryption
    /// A listener configured without a passphrase rejects any peer that asks
    /// for encryption (a Key Material extension or a non-zero `Encryption
    /// Field`). A listener configured with one negotiates keys and encrypts /
    /// decrypts the data path.
    pub async fn bind<A: tokio::net::ToSocketAddrs>(
        addr: A,
        config: SrtSocketConfig,
    ) -> Result<Self> {
        let SrtSocketConfig {
            handshake: config,
            io,
            udp,
            damage_policy,
        } = config;
        io.validate()?;
        let addrs = bounded(io.timeouts.connect, "resolve", resolve_all(addr)).await?;
        let socket = Arc::new(bind_first(&addrs, &udp)?);
        let local = socket.local_addr().map_err(|e| io_err("local_addr", e))?;
        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
        let (unrouted_tx, unrouted_rx) = mpsc::channel(io.channels.unrouted.get());
        let (accepted_tx, accepted) = mpsc::channel(io.channels.accept.get());
        let unrouted_dropped = Arc::new(AtomicU64::new(0));
        let overflow_dropped = Arc::new(AtomicU64::new(0));
        let send_errors = Arc::new(AtomicU64::new(0));
        let life = Arc::new(ListenerLife {
            cancel: CancellationToken::new(),
            tasks: TaskTracker::new(),
        });

        let core = ListenerCore {
            udp: Arc::clone(&socket),
            config,
            io,
            damage_policy,
            cookie_keys: CookieKeys::new(Instant::now(), io.listener.cookie_key_rotation)?,
            pending: std::collections::HashMap::new(),
            outbound_queue: std::collections::HashMap::new(),
            recent_accepts: std::collections::HashMap::new(),
            routes: Arc::clone(&routes),
            unrouted_rx,
            life: Arc::downgrade(&life),
            accepted_tx,
            overflow_dropped: Arc::clone(&overflow_dropped),
            send_errors: Arc::clone(&send_errors),
            accepting: true,
            last_pending_tick: Instant::now(),
        };
        life.tasks.spawn(routing_pump(
            Arc::clone(&socket),
            Arc::clone(&routes),
            unrouted_tx,
            Arc::clone(&unrouted_dropped),
            io.max_datagram,
            life.cancel.clone(),
        ));
        life.tasks.spawn(core.run(life.cancel.clone()));
        #[cfg(test)]
        let listener_routes = Arc::clone(&routes);
        #[cfg(test)]
        let _ = &listener_routes;
        Ok(SrtListener {
            _life: life,
            local,
            udp: socket,
            accepted,
            #[cfg(test)]
            routes: listener_routes,
            unrouted_dropped,
            overflow_dropped,
            send_errors,
        })
    }

    /// Datagrams dropped because the candidate-new-connection queue was full
    /// (item 4) — a handshake flood outrunning the listener's handshake task —
    /// or because they exceeded [`IoConfig::max_datagram`].
    pub fn unrouted_dropped(&self) -> u64 {
        self.unrouted_dropped.load(Ordering::Relaxed)
    }

    /// Connections that completed their handshake but were dropped because
    /// [`accept`](Self::accept) was not keeping up (the pending-accept queue
    /// holds 64); each dropped peer is sent a SHUTDOWN.
    pub fn accept_overflow_dropped(&self) -> u64 {
        self.overflow_dropped.load(Ordering::Relaxed)
    }

    /// Send failures the background task met while answering peers (for
    /// example an unreachable spoofed source). They are counted here and never
    /// surface from [`accept`](Self::accept), so a flood of them cannot displace
    /// finished connections or end an `accept` loop.
    pub fn send_errors(&self) -> u64 {
        self.send_errors.load(Ordering::Relaxed)
    }

    /// The receive buffer the kernel granted the listener's socket
    /// (`SO_RCVBUF`), in bytes. The kernel may grant less or more than
    /// [`UdpOptions::recv_buffer_bytes`] asked for (it clamps to a system
    /// maximum, and Linux doubles the request for its own bookkeeping), so a
    /// deployment checks this value rather than trusting the request.
    ///
    /// # Errors
    /// [`Error::Io`] when the socket option cannot be read.
    pub fn recv_buffer_size(&self) -> Result<usize> {
        udp_bind::recv_buffer_size(&*self.udp).map_err(|e| io_err("recv_buffer_size", e))
    }

    /// The local socket address the listener is bound to.
    pub fn local_addr(&self) -> Result<std::net::SocketAddr> {
        Ok(self.local)
    }

    /// Accept the next incoming SRT connection.
    ///
    /// Handshakes progress in the background whether or not this is being
    /// polled; this only waits for a finished one. Send errors met while
    /// answering peers are counted ([`send_errors`](Self::send_errors)), not
    /// returned.
    pub async fn accept(&mut self) -> Result<SrtSocket> {
        self.accepted.recv().await.unwrap_or(Err(Error::Io {
            kind: std::io::ErrorKind::BrokenPipe,
            context: "listener task ended",
        }))
    }
}

impl ListenerCore {
    /// Next instant a pending handshake needs a tick; `None` when nothing is
    /// pending (an idle listener has no timer at all).
    fn poll_timeout(&self) -> Option<Instant> {
        (self.accepting && !self.pending.is_empty())
            .then(|| self.last_pending_tick + self.io.listener.pending_tick)
    }

    /// The handshake task: answer unrouted datagrams, tick pending handshakes
    /// on a deadline, hand finished connections to [`SrtListener::accept`].
    async fn run(mut self, cancel: CancellationToken) {
        loop {
            while self.accepting
                && let Some(conn) = self.drain_completed()
            {
                match self.accepted_tx.try_send(conn) {
                    Ok(()) => {}
                    Err(mpsc::error::TrySendError::Full(_dropped)) => {
                        // Dropping the SrtSocket sends the peer a SHUTDOWN.
                        self.overflow_dropped.fetch_add(1, Ordering::Relaxed);
                    }
                    Err(mpsc::error::TrySendError::Closed(_)) => {
                        // The handle is gone but accepted connections may
                        // still be alive: stop serving new handshakes, keep
                        // draining so the routing pump keeps running.
                        self.accepting = false;
                        self.pending.clear();
                        self.outbound_queue.clear();
                    }
                }
            }
            let deadline = self.poll_timeout();
            tokio::select! {
                _ = cancel.cancelled() => return,
                r = self.unrouted_rx.recv() => match r {
                    Some((src, bytes)) => {
                        if !self.accepting {
                            continue;
                        }
                        // Cookie rotation no longer rides a tick: do it whenever a
                        // datagram arrives.
                        self.cookie_keys.rotate_if_due(Instant::now());
                        let _ = self.handle_datagram(src, &bytes);
                        // Raced against cancellation: a stuck send must not
                        // delay releasing the port by up to `io.timeouts.write`.
                        tokio::select! {
                            _ = cancel.cancelled() => return,
                            r = self.flush_for_peer(src) => self.count_send_error(r),
                        }
                    }
                    None => return,
                },
                _ = async {
                    match deadline {
                        Some(d) => tokio::time::sleep_until(d).await,
                        None => std::future::pending::<()>().await,
                    }
                } => {
                    self.last_pending_tick = Instant::now();
                    self.tick_pending();
                    tokio::select! {
                        _ = cancel.cancelled() => return,
                        r = self.flush_all() => self.count_send_error(r),
                    }
                }
            }
        }
    }

    /// Count a send failure (one unreachable peer must neither end the
    /// listener nor reach `accept`).
    fn count_send_error(&self, r: Result<()>) {
        if r.is_err() {
            self.send_errors.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Whether this listener has its own crypto config (feature-gated: with
    /// the `crypto` feature compiled out there is no such field, and the
    /// adapter can never accept an encrypted connection).
    fn local_crypto_enabled(&self) -> bool {
        #[cfg(feature = "crypto")]
        {
            self.config.crypto.is_some()
        }
        #[cfg(not(feature = "crypto"))]
        {
            false
        }
    }

    fn handle_datagram(&mut self, src: std::net::SocketAddr, bytes: &[u8]) -> Result<()> {
        let packet = SrtPacket::parse(bytes).map_err(|e| handshake_err("parse", e))?;

        let ctrl = match packet {
            SrtPacket::Control(c) => c,
            _ => return Ok(()),
        };

        // A repeated CONCLUSION from a Caller we already accepted means our
        // response never reached it: send the very same response again. A
        // fresh INDUCTION from the same address starts over instead.
        if let ControlPacket::Handshake(hp) = &ctrl {
            match hp.handshake_type {
                HandshakeType::Conclusion => {
                    if let Some(recent) = self.recent_accepts.get(&src)
                        && recent.peer_socket_id == hp.srt_socket_id
                        && recent.accepted_at.elapsed() < self.io.listener.recent_accept_ttl
                    {
                        let response = recent.response.clone();
                        self.outbound_queue
                            .entry(src)
                            .or_default()
                            .push_back(response);
                        return Ok(());
                    }
                }
                HandshakeType::Induction => {
                    self.recent_accepts.remove(&src);
                    // §4.3.1.1's SYN Cookie exists so an unverified Caller
                    // allocates nothing: answer, and keep no state (#2820).
                    return self.answer_induction(src, hp);
                }
                _ => {}
            }
        }

        // A listener without its own crypto config refuses a peer that asks
        // for encryption (a non-zero `Encryption Field` or a `KMREQ` bit),
        // since it has no passphrase to recover the SEK with. A listener that
        // does have crypto configured leaves this to the sans-IO engine, which
        // performs the Key Material exchange. (On an INDUCTION the extension
        // field is the legacy UDT socket-type value, not the Table 3 bitmask
        // — see `handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE`.)
        if !self.local_crypto_enabled()
            && let ControlPacket::Handshake(hp) = &ctrl
        {
            let asks_cipher = hp.encryption_field != EncryptionField::NoEncryption;
            let asks_kmreq =
                hp.handshake_type == HandshakeType::Conclusion && hp.extension_field.kmreq();
            if asks_cipher || asks_kmreq {
                // Refuse before allocating handshake state for the
                // source; `own_socket_id` is 0 because no socket was ever
                // assigned to this refused connection.
                let rejection = build_encryption_rejection(hp, 0, &self.config)?;
                self.outbound_queue
                    .entry(src)
                    .or_default()
                    .push_back(rejection);
                self.pending.remove(&src);
                return Ok(());
            }
        }

        let is_new = !self.pending.contains_key(&src);

        if is_new {
            // Only a CONCLUSION that echoes a cookie this listener issued may
            // allocate anything: an INDUCTION was answered statelessly above,
            // so a flood of guessed or spoofed ones holds no slots (#2820).
            let ControlPacket::Handshake(hp) = &ctrl else {
                return Ok(());
            };
            if hp.handshake_type != HandshakeType::Conclusion {
                return Ok(());
            }
            let Some((own_socket_id, our_initial_seq)) =
                self.validated_conclusion_ids(src, hp.srt_socket_id, hp.syn_cookie)
            else {
                return Ok(());
            };
            // The cookie proves the round trip but the table is still bounded
            // against a flood of genuinely answered Callers.
            if self.pending.len() >= self.io.listener.max_pending {
                return Ok(());
            }
            let mut per_conn_config = self.config.clone();
            per_conn_config.initial_seq_number = our_initial_seq;
            let created_at = Instant::now();
            self.pending.insert(
                src,
                PendingListener {
                    handshake: ListenerHandshake::awaiting_conclusion(
                        own_socket_id,
                        hp.syn_cookie,
                        per_conn_config,
                    ),
                    params: None,
                    peer_initial_seq: hp.initial_seq_number,
                    peer_timestamp_us: 0,
                    concluded_at: None,
                    created_at,
                    last_response: None,
                    our_initial_seq,
                },
            );
        }

        let entry = self
            .pending
            .get_mut(&src)
            .ok_or(Error::InvalidField(InvalidField::new(
                "pending",
                "no pending entry",
            )))?;

        if let ControlPacket::Handshake(hp) = &ctrl
            && hp.handshake_type == HandshakeType::Conclusion
        {
            // The first CONCLUSION fixes the pair (a repeat must not move it).
            if entry.concluded_at.is_none() {
                entry.peer_timestamp_us = hp.timestamp.value();
                entry.concluded_at = Some(Instant::now());
            }
        }

        entry.handshake.set_elapsed(entry.created_at.elapsed());
        let outcomes = match entry.handshake.feed(&ctrl) {
            Ok(outcomes) => outcomes,
            Err(e) => {
                if is_new {
                    self.pending.remove(&src);
                }
                return Err(handshake_err("listener feed", e));
            }
        };

        for outcome in outcomes {
            match outcome {
                HandshakeOutput::Send(bytes) => {
                    entry.last_response = Some(bytes.clone());
                    self.outbound_queue.entry(src).or_default().push_back(bytes);
                }
                HandshakeOutput::Connected(negotiated) => {
                    entry.params = Some(HandshakeOutput::Connected(negotiated));
                }
                HandshakeOutput::Rejected(reason) => {
                    self.pending.remove(&src);
                    return Err(Error::Rejected(reason));
                }
                HandshakeOutput::TimedOut => {
                    self.pending.remove(&src);
                    return Err(Error::HandshakeTimedOut { stage: "listener" });
                }
            }
        }

        Ok(())
    }

    /// Answer an INDUCTION without retaining any per-peer state
    /// (`draft-sharabayko-srt-01` §4.3.1.1). The response is built by the same
    /// sans-IO machine the stateful path used, then dropped: the connection's
    /// Socket ID and ISN are re-derived from the same keyed inputs when a
    /// CONCLUSION proves the Caller received this answer (#2820).
    fn answer_induction(
        &mut self,
        src: std::net::SocketAddr,
        hp: &HandshakePacket<'_>,
    ) -> Result<()> {
        let time_bucket = unix_time_bucket();
        let secret = self.cookie_keys.current();
        let syn_cookie = derive_cookie(&src, hp.srt_socket_id, time_bucket, secret);
        let (own_socket_id, our_initial_seq) =
            self.connection_ids(&src, hp.srt_socket_id, time_bucket, secret);
        let mut per_conn_config = self.config.clone();
        per_conn_config.initial_seq_number = our_initial_seq;
        let mut handshake = ListenerHandshake::new(own_socket_id, syn_cookie, per_conn_config);
        for outcome in handshake.feed(&ControlPacket::Handshake(hp.clone()))? {
            if let HandshakeOutput::Send(bytes) = outcome {
                self.outbound_queue.entry(src).or_default().push_back(bytes);
            }
        }
        Ok(())
    }

    /// Validate a CONCLUSION's SYN Cookie against this listener's current and
    /// previous key, across the current and previous one-minute bucket, and
    /// return the `(own socket id, our ISN)` the stateless INDUCTION answer
    /// carried for that `(peer, bucket, key)`. `None` means no state may be
    /// allocated (§4.3.1.1).
    fn validated_conclusion_ids(
        &self,
        src: std::net::SocketAddr,
        caller_socket_id: u32,
        syn_cookie: u32,
    ) -> Option<(u32, u32)> {
        if syn_cookie == 0 {
            return None;
        }
        let origin = validate_cookie(
            &src,
            caller_socket_id,
            syn_cookie,
            unix_time_bucket(),
            self.cookie_keys.acceptable(),
        )?;
        Some(self.connection_ids(&src, caller_socket_id, origin.time_bucket, origin.secret))
    }

    /// This listener's per-connection Socket ID and ISN for a cookie issued
    /// over `(peer, caller socket id, time_bucket, secret)`, kept in libsrt's allocation
    /// range for the Socket ID (see [`MAX_SRT_SOCKET_ID`]).
    fn connection_ids(
        &self,
        peer: &std::net::SocketAddr,
        caller_socket_id: u32,
        time_bucket: u32,
        secret: u128,
    ) -> (u32, u32) {
        let (socket_id, initial_seq) =
            derive_listener_ids(peer, caller_socket_id, time_bucket, secret);
        (socket_id % MAX_SRT_SOCKET_ID + 1, initial_seq)
    }

    fn tick_pending(&mut self) {
        let mut to_remove = Vec::new();
        for (addr, entry) in self.pending.iter_mut() {
            entry.handshake.set_elapsed(entry.created_at.elapsed());
            for outcome in entry.handshake.tick(self.io.listener.pending_tick) {
                match outcome {
                    HandshakeOutput::Send(bytes) => {
                        self.outbound_queue
                            .entry(*addr)
                            .or_default()
                            .push_back(bytes);
                    }
                    HandshakeOutput::TimedOut => {
                        to_remove.push(*addr);
                    }
                    _ => {}
                }
            }
        }
        for addr in to_remove {
            self.pending.remove(&addr);
            // A timed-out peer will never see another packet: drop its queued
            // handshake bytes too, so `outbound_queue` cannot grow per-source
            // without bound under a flood.
            self.outbound_queue.remove(&addr);
        }
        self.recent_accepts
            .retain(|_, r| r.accepted_at.elapsed() < self.io.listener.recent_accept_ttl);
    }

    /// Remember an accepted connection's CONCLUSION response (bounded: expired
    /// entries are reaped first, then the oldest is evicted if still full).
    fn remember_accept(&mut self, addr: std::net::SocketAddr, recent: RecentAccept) {
        self.recent_accepts
            .retain(|_, r| r.accepted_at.elapsed() < self.io.listener.recent_accept_ttl);
        if self.recent_accepts.len() >= self.io.listener.max_pending
            && let Some(oldest) = self
                .recent_accepts
                .iter()
                .min_by_key(|(_, r)| r.accepted_at)
                .map(|(a, _)| *a)
        {
            self.recent_accepts.remove(&oldest);
        }
        self.recent_accepts.insert(addr, recent);
    }

    fn drain_completed(&mut self) -> Option<Result<SrtSocket>> {
        // Every handle is gone: nothing may be handed over (the cancel token
        // ends this task right after).
        let life = self.life.upgrade()?;
        let addr = self
            .pending
            .iter()
            .find(|(_, p)| {
                p.params.is_some()
                    && matches!(p.handshake.state(), ListenerHandshakeState::Connected)
            })
            .map(|(addr, _)| *addr)?;

        let entry = self.pending.remove(&addr)?;
        // `Connected` entries always carry negotiated parameters, but a
        // missing one must not panic the accept loop.
        let Some(negotiated) = entry.handshake.negotiated() else {
            return Some(Err(Error::InvalidField(InvalidField::new(
                "listener handshake",
                "Connected without negotiated parameters",
            ))));
        };
        let peer_initial_seq = entry.peer_initial_seq;
        // The peer's negotiated SRT Socket ID (distinct from its ISN above).
        let peer_socket_id = negotiated.peer_socket_id;
        // This listener's own Socket ID for this connection — the value a
        // real peer's packets carry as `dest_socket_id` from here on, and so
        // the key the routing pump demultiplexes by (item 2; see
        // [`routing_pump`]).
        let own_socket_id = negotiated.own_socket_id;
        // The exact ISN this listener generated for `entry` at INDUCTION
        // time (`handle_datagram`) — not `self.config.initial_seq_number`,
        // which is the listener-wide template and no longer carries the
        // per-connection value once randomized.
        let our_initial_seq = entry.our_initial_seq;
        let concluded_at = entry.concluded_at.unwrap_or_else(Instant::now);
        let epoch = entry.created_at;
        let tsbpd_time_base = tsbpd_time_base_at(epoch, concluded_at, entry.peer_timestamp_us);
        let drift_window = NonZeroU32::new(self.io.drift_sample_count)?;

        if let Some(response) = entry.last_response.clone() {
            self.remember_accept(
                addr,
                RecentAccept {
                    peer_socket_id,
                    response,
                    accepted_at: concluded_at,
                },
            );
        }

        // Register this connection's own route in the shared demux table
        // (issue #1029) *before* handing off to its driver task — the
        // routing pump must never see a datagram naming this connection's
        // Socket ID land in `unrouted_rx` again once this connection exists.
        let (tx, rx) = mpsc::channel(self.io.channels.rx.get());
        let stats = Arc::new(Counters::default());
        lock(&self.routes).insert(
            own_socket_id,
            RouteEntry {
                addr,
                tx,
                stats: Arc::clone(&stats),
            },
        );

        // Share the listener's Arc<UdpSocket> with the connection's driver.
        let conn = SrtSocket::spawn(ConnParams {
            udp: Arc::clone(&self.udp),
            peer_addr: addr,
            rx,
            stats,
            route_cleanup: RouteCleanup(Some((own_socket_id, Arc::clone(&self.routes)))),
            forwarder_guard: TaskGuard(None),
            life: Some(life),
            read_idle: self.io.timeouts.read_idle,
            write: self.io.timeouts.write,
            our_initial_seq,
            peer_initial_seq,
            peer_socket_id,
            epoch,
            tsbpd_time_base,
            negotiated: negotiated.clone(),
            damage_policy: self.damage_policy.clone(),
            crypto_thresholds: self.io.km_refresh_thresholds,
            cadence: self.io.cadence,
            close: self.io.close,
            arq: self.io.arq,
            drift_window,
            send_channel_capacity: self.io.channels.send,
            deliver_channel_capacity: self.io.channels.deliver,
            max_bw: self.io.max_bw,
            handshake: self.io.timeouts.handshake,
            key_refresh_seed: random_seed().ok()?,
        });
        Some(Ok(conn))
    }

    /// Remove and return what is queued for `addr`: a queue is a staging area, so a source that
    /// is not pending keeps no entry once it is sent (or fails to be).
    fn take_queued(&mut self, addr: &std::net::SocketAddr) -> VecDeque<Vec<u8>> {
        self.outbound_queue.remove(addr).unwrap_or_default()
    }

    async fn flush_for_peer(&mut self, addr: std::net::SocketAddr) -> Result<()> {
        for bytes in self.take_queued(&addr) {
            send_bounded(&self.udp, &bytes, addr, self.io.timeouts.write, "send_to").await?;
        }
        Ok(())
    }

    async fn flush_all(&mut self) -> Result<()> {
        let addrs: Vec<std::net::SocketAddr> = self.outbound_queue.keys().copied().collect();
        for addr in addrs {
            self.flush_for_peer(addr).await?;
        }
        Ok(())
    }
}

/// The single task that ever calls `recv_from` on a [`SrtListener`]'s
/// shared socket, demultiplexing every datagram the way libsrt does (item 2,
/// draft §4.3.1): Destination Socket ID `0` always means "not yet
/// an established connection" and goes to `unrouted_tx` (`accept`'s own
/// input — every handshake packet this crate's Caller sends carries `0`
/// there, see `caller.rs`); any other ID must match a `routes` entry *and*
/// that entry's accepted source address, or the datagram is dropped — an ID
/// nothing accepted, or one accepted from a different address, has no
/// legitimate connection to reach. This is what makes it safe for the
/// listener's `accept` loop and every accepted connection's driver task to
/// run concurrently without racing each other for the same socket's
/// `recv_from`.
async fn routing_pump(
    udp: Arc<UdpSocket>,
    routes: RouteTable,
    unrouted_tx: mpsc::Sender<(std::net::SocketAddr, Bytes)>,
    unrouted_dropped: Arc<AtomicU64>,
    max_datagram: usize,
    cancel: CancellationToken,
) {
    let mut scratch = vec![0u8; max_datagram + 1];
    loop {
        let received = tokio::select! {
            _ = cancel.cancelled() => break,
            r = recv_datagram(&udp, &mut scratch, max_datagram, &unrouted_dropped) => r,
        };
        let (bytes, src) = match received {
            Ok(Some(v)) => v,
            Ok(None) => continue, // oversize: dropped and counted.
            Err(_) => break,      // socket error — end the pump.
        };
        match crate::packet::peek_dest_socket_id(&bytes) {
            Some(0) | None => {
                // `0` (candidate new connection) or too short to carry a
                // full header at all — either way, not a routable
                // established-connection packet; hand it to the handshake
                // task, which parses (and rejects malformed bytes) properly.
                if unrouted_tx.try_send((src, bytes)).is_err() {
                    if unrouted_tx.is_closed() {
                        // The handshake task is gone; nothing more this pump can do.
                        break;
                    }
                    unrouted_dropped.fetch_add(1, Ordering::Relaxed);
                }
            }
            Some(id) => {
                let route = lock(&routes).get(&id).cloned();
                // No `route` entry (no connection was ever accepted with
                // this ID), or one exists but from a different source
                // address, is never routed — spoofed-source packets
                // included.
                if let Some(entry) = route
                    && entry.addr == src
                    && entry.tx.try_send(bytes).is_err()
                    && !entry.tx.is_closed()
                {
                    // A closed channel would instead mean the
                    // connection's driver has already exited (it
                    // removes its own entry on the way out — see
                    // `RouteCleanup`), a benign race, not counted; a
                    // still-open-but-full channel is this connection's
                    // own backpressure (item 4).
                    entry.stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
    }
}

// ===========================================================================
// Helpers
// ===========================================================================

/// Builds a Handshake rejection packet (`Handshake Type` = `1000 + code`,
/// §4.3 Table 7) refusing an encryption request with
/// [`RejectionReason::Unsecure`] ("password required or unexpected", code
/// 1011) — the same wire shape `listener.rs` emits for its own rejections.
/// The adapter needs it because a peer can advertise encryption via the
/// `Encryption Field` / `KMREQ` flag bits without ever sending a Key Material
/// extension block for the engine to notice.
fn build_encryption_rejection(
    hp: &HandshakePacket<'_>,
    own_socket_id: u32,
    config: &HandshakeConfig,
) -> Result<Vec<u8>> {
    let hp_out = HandshakePacket {
        timestamp: crate::packet::SrtTimestamp::ZERO,
        dest_socket_id: crate::packet::SocketId::from_wire(hp.srt_socket_id),
        version: handshake_sm::HANDSHAKE_VERSION_5,
        encryption_field: EncryptionField::NoEncryption,
        extension_field: HandshakeExtensionFlags::new(0),
        initial_seq_number: 0,
        mtu: config.mtu,
        max_flow_window_size: config.max_flow_window_size,
        handshake_type: RejectionReason::Unsecure.to_handshake_type(),
        srt_socket_id: own_socket_id,
        syn_cookie: 0,
        peer_ip: config.local_ip,
        extensions: HandshakeExtensions(Vec::new()),
    };
    handshake_sm::build_bytes(hp_out)
}

/// Runs `fut` for at most `limit`; expiry is `Error::Io { kind: TimedOut, context }`.
async fn bounded<T>(
    limit: Duration,
    context: &'static str,
    fut: impl core::future::Future<Output = Result<T>>,
) -> Result<T> {
    tokio::time::timeout(limit, fut)
        .await
        .map_err(|_| Error::Io {
            kind: std::io::ErrorKind::TimedOut,
            context,
        })?
}

/// `send_to` bounded by `limit` (the [`IoConfig::write`] timeout).
async fn send_bounded(
    udp: &UdpSocket,
    bytes: &[u8],
    to: std::net::SocketAddr,
    limit: Duration,
    context: &'static str,
) -> Result<()> {
    bounded(limit, context, async {
        udp.send_to(bytes, to)
            .await
            .map(|_| ())
            .map_err(|e| io_err(context, e))
    })
    .await
}

/// Maps an OS I/O failure to a structured [`Error::Io`], preserving the
/// `std::io::ErrorKind` (bind failures are then distinguishable from
/// mid-connection resets, etc.) and the call site that failed. `std::io::Error`
/// itself is not `Clone`/`Eq` (this crate's [`Error`] derives both), so only
/// its `kind()` is kept — see the `S4` release-audit finding.
/// Binds the one UDP socket of a connection or listener with the caller's
/// options and hands it to tokio.
fn bind_socket(addr: std::net::SocketAddr, options: &UdpOptions) -> Result<UdpSocket> {
    let socket = udp_bind::bind_udp(addr, options).map_err(|e| io_err("bind", e))?;
    UdpSocket::from_std(socket).map_err(|e| io_err("bind", e))
}

fn io_err(context: &'static str, e: std::io::Error) -> Error {
    Error::Io {
        kind: e.kind(),
        context,
    }
}

/// Wraps an engine/codec failure with the handshake stage it happened in,
/// keeping the underlying error as the source (r08-SRT-W12) rather than
/// flattening it to a generic invalid-field error.
fn handshake_err(stage: &'static str, source: Error) -> Error {
    Error::Handshake {
        stage,
        source: alloc::boxed::Box::new(source),
    }
}

/// Bits a `u64` must be shifted to occupy a `u128`'s high half.
const U128_HIGH_SHIFT: u32 = 64;

/// Seconds in the SYN cookie's one-minute time bucket (§4.3.1.1).
const SECONDS_PER_MINUTE: u64 = 60;

/// The current UNIX time, bucketed to 1-minute accuracy — the `time_bucket`
/// input `derive_cookie` expects (§4.3.1.1: "...and current time with 1
/// minute accuracy").
fn unix_time_bucket() -> u32 {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    u32::try_from(secs / SECONDS_PER_MINUTE).unwrap_or(u32::MAX)
}

/// A random `u64` from the OS randomness source (`getrandom`), used as
/// `derive_cookie`'s `secret` input and to draw the per-connection Socket ID
/// and ISN (SRT-W11). A failing OS source is reported, never panicked on.
fn random_u64() -> Result<u64> {
    let mut bytes = [0u8; core::mem::size_of::<u64>()];
    getrandom::fill(&mut bytes).map_err(|_| Error::Io {
        kind: std::io::ErrorKind::Other,
        context: "getrandom",
    })?;
    Ok(u64::from_ne_bytes(bytes))
}

/// Fresh key-refresh entropy for one connection, drawn here because the sans-IO link draws none.
fn random_seed() -> Result<Vec<u8>> {
    let mut seed = vec![0u8; crate::link::KEY_LEN];
    getrandom::fill(&mut seed).map_err(|_| Error::Io {
        kind: std::io::ErrorKind::Other,
        context: "getrandom",
    })?;
    Ok(seed)
}

/// A random `u128` (two OS draws).
fn random_u128() -> Result<u128> {
    Ok((u128::from(random_u64()?) << U128_HIGH_SHIFT) | u128::from(random_u64()?))
}

/// The low 32 bits of a fresh random `u64`.
fn random_u32() -> Result<u32> {
    Ok(u32::try_from(random_u64()? & u64::from(u32::MAX)).unwrap_or(0))
}

/// The largest SRT Socket ID this adapter will ever generate.
///
/// `draft-sharabayko-srt-01` §3/§4.3.1.1 gives the wire field only as "32
/// bits" (this crate's own `private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`, e.g. its
/// Handshake Packet description — no transcription in this crate's `docs/`
/// narrows that range further; there is no `docs/` directory at all yet). A
/// real libsrt peer, though, only ever *allocates* an ID in `1..=`
/// [`MAX_SRT_SOCKET_ID`] (observed on the wire from `srt-live-transmit`): bit 30
/// (`0x40000000`) marks a socket group there, and bit 31 would make the ID
/// negative as a signed 32-bit value. Generating
/// outside that range is wire-legal per the draft but not a value any real
/// SRT implementation would ever send or expect, so this adapter matches
/// libsrt's allocation range rather than exercising the full 32 bits.
const MAX_SRT_SOCKET_ID: u32 = 0x3FFF_FFFF;

/// A random SRT Socket ID for a new connection, drawn from the same
/// OS-seeded source as [`random_u64`], in `1..=`[`MAX_SRT_SOCKET_ID`] (see
/// its doc). Never `0` — that value marks "no socket assigned" elsewhere in
/// this adapter (see [`build_encryption_rejection`]'s `own_socket_id`
/// argument for a refused, pre-handshake peer) and is reserved for that
/// meaning here too — the `% MAX_SRT_SOCKET_ID` reduction followed by `+ 1`
/// makes both guarantees (never `0`, never above the cap) hold by
/// construction, with no retry loop needed.
fn random_socket_id() -> Result<u32> {
    Ok(random_u32()? % MAX_SRT_SOCKET_ID + 1)
}

/// A random Initial Sequence Number in the legal 31-bit SRT sequence-number
/// range (`SEQ_NUMBER_MASK`, §3) for a new connection. Every new Caller
/// connect and every new accepted Listener connection must draw a fresh
/// value here rather than reuse a fixed/default `HandshakeConfig::initial_seq_number`
/// (SRT-W11): `draft-sharabayko-srt-01` §3/§4.3.1.1 expects the ISN
/// unpredictable per connection, same as the Socket ID above.
fn random_isn() -> Result<u32> {
    Ok(random_u32()? & SEQ_NUMBER_MASK)
}

async fn resolve_all<A: tokio::net::ToSocketAddrs>(addr: A) -> Result<Vec<std::net::SocketAddr>> {
    Ok(tokio::net::lookup_host(addr)
        .await
        .map_err(|e| io_err("resolve", e))?
        .collect())
}

fn bind_first(addrs: &[std::net::SocketAddr], udp: &UdpOptions) -> Result<UdpSocket> {
    let mut last = Error::Io {
        kind: std::io::ErrorKind::AddrNotAvailable,
        context: "resolve: no addresses",
    };
    for addr in addrs {
        match bind_socket(*addr, udp) {
            Ok(socket) => return Ok(socket),
            Err(e) => last = e,
        }
    }
    Err(last)
}

/// The first address `addr` resolves to that the socket bound to `local` can reach (the same
/// family), or the first of all when no socket is named.
async fn resolve_one<A: tokio::net::ToSocketAddrs>(
    addr: A,
    local: Option<std::net::SocketAddr>,
) -> Result<std::net::SocketAddr> {
    let mut addrs = tokio::net::lookup_host(addr)
        .await
        .map_err(|e| io_err("resolve", e))?;
    addrs
        .find(|candidate| local.is_none_or(|local| local.is_ipv4() == candidate.is_ipv4()))
        .ok_or(Error::Io {
            kind: std::io::ErrorKind::AddrNotAvailable,
            context: "resolve: no address the local socket can reach",
        })
}

/// The fields of the peer's final handshake packet the adapter seeds its
/// engines from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PeerHandshake {
    /// The peer's Initial Packet Sequence Number (§3.2.1).
    initial_seq_number: u32,
    /// The packet's `Timestamp` (§3), microseconds since the peer's
    /// connection start — `HSREQ_TIMESTAMP` of `TsbpdTimeBase = T_NOW -
    /// HSREQ_TIMESTAMP` (§4.5.1.1).
    timestamp_us: u32,
}

/// Extract the peer's `initial_seq_number` and timestamp from a handshake
/// control packet's bytes. These seed ARQ and TSBPD sequence/time tracking for
/// the entire connection, so "the bytes didn't parse as a Handshake" must be a
/// distinct, caller-visible outcome from "the peer's ISN is genuinely 0" — the
/// two are otherwise indistinguishable to a caller that only sees a `u32`.
/// Returns [`Error::InvalidField`] rather than defaulting to `0` on any parse
/// failure.
fn peer_handshake(bytes: &[u8]) -> Result<PeerHandshake> {
    match SrtPacket::parse(bytes) {
        Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) => Ok(PeerHandshake {
            initial_seq_number: hp.initial_seq_number,
            timestamp_us: hp.timestamp.value(),
        }),
        _ => Err(Error::InvalidField(InvalidField::new(
            "peer handshake",
            "handshake reached Connected but its final packet did not re-parse as a \
                     Handshake control packet; refusing to seed ARQ/TSBPD with a fabricated ISN",
        ))),
    }
}

/// `TsbpdTimeBase` seed (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP` with
/// `T_NOW` = 0 at the connection epoch (the instant the handshake packet
/// arrived), i.e. minus the peer's handshake timestamp. Signed: the
/// timestamp, counted from the peer's own start, is generally positive, so
/// the base is generally negative.
fn tsbpd_time_base_from(peer_timestamp_us: u32) -> i64 {
    -i64::from(peer_timestamp_us)
}

/// [`tsbpd_time_base_from`] for a connection whose epoch is the instant the
/// handshake began: `T_NOW` is how long after `epoch` the peer's handshake
/// packet arrived.
fn tsbpd_time_base_at(epoch: Instant, arrived: Instant, peer_timestamp_us: u32) -> i64 {
    let t_now =
        i64::try_from(arrived.saturating_duration_since(epoch).as_micros()).unwrap_or(i64::MAX);
    t_now.saturating_add(tsbpd_time_base_from(peer_timestamp_us))
}

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

    /// Bite test: run against the unfixed `random_socket_id` (a bare
    /// `random_u64() as u32`, only ever excluding `0`) and this fails —
    /// values above `MAX_SRT_SOCKET_ID` come up immediately (bit 31 alone is
    /// set on ~50% of draws). Fixed, every draw is folded into
    /// `1..=MAX_SRT_SOCKET_ID` by construction.
    #[test]
    fn random_socket_id_stays_in_the_libsrt_allocation_range() {
        for _ in 0..10_000 {
            let id = random_socket_id().expect("OS randomness");
            assert!(id != 0, "socket id must never be 0");
            assert!(
                id <= MAX_SRT_SOCKET_ID,
                "socket id {id:#010x} exceeds the libsrt allocation range {MAX_SRT_SOCKET_ID:#010x}"
            );
        }
    }
}

#[cfg(test)]
mod isn_tests {
    use broadcast_core::error::InvalidField;

    use super::*;
    use crate::packet::{
        EncryptionField, HandshakeExtensionFlags, HandshakeExtensions, HandshakePacket,
        HandshakeType,
    };

    fn handshake_bytes(initial_seq_number: u32) -> Vec<u8> {
        let hp = HandshakePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
            version: 5,
            encryption_field: EncryptionField::NoEncryption,
            extension_field: HandshakeExtensionFlags::new(0),
            initial_seq_number,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: HandshakeType::Conclusion,
            srt_socket_id: 42,
            syn_cookie: 0,
            peer_ip: [0; 4],
            extensions: HandshakeExtensions(Vec::new()),
        };
        crate::handshake_sm::build_bytes(hp).expect("build handshake bytes")
    }

    #[test]
    fn peer_handshake_extracts_nonzero_isn() {
        let bytes = handshake_bytes(0xABCD_1234);
        assert_eq!(
            peer_handshake(&bytes).unwrap().initial_seq_number,
            0xABCD_1234
        );
    }

    #[test]
    fn peer_handshake_distinguishes_genuine_zero_from_parse_failure() {
        // A genuine ISN of 0 is a valid, well-formed handshake and must
        // succeed as Ok(0) — not be conflated with "couldn't parse".
        let bytes = handshake_bytes(0);
        assert_eq!(peer_handshake(&bytes).unwrap().initial_seq_number, 0);

        // Bytes that don't parse as a Handshake control packet at all
        // (too short to even carry the fixed SRT header) must error, never
        // silently produce a plausible-looking 0.
        let err = peer_handshake(&[0u8; 4]).unwrap_err();
        assert!(matches!(
            err,
            Error::InvalidField(InvalidField {
                field: "peer handshake",
                ..
            })
        ));
    }

    #[test]
    fn peer_handshake_rejects_non_handshake_control_packet() {
        // A well-formed control packet of the WRONG type (Keep-Alive, not
        // Handshake) must also error rather than default to 0.
        let ka = ControlPacket::KeepAlive(crate::packet::KeepAlivePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(7),
            libsrt_pad: false,
        });
        let mut buf = alloc::vec![0u8; ka.serialized_len()];
        ka.serialize_into(&mut buf).expect("serialize keepalive");
        let err = peer_handshake(&buf).unwrap_err();
        assert!(matches!(
            err,
            Error::InvalidField(InvalidField {
                field: "peer handshake",
                ..
            })
        ));
    }
}

// ===========================================================================
// Adapter security tests (r08-SRT-C2 / C6 / C7)
// ===========================================================================

#[cfg(test)]
#[cfg(feature = "tokio")]
mod adapter_tests {
    use super::*;
    use crate::packet::SRT_HEADER_LEN;
    use crate::packet::{
        AckCif, AckPacket, DataPacket, DropReqPacket, EncryptionKeyField, HandshakeExtensionFlags,
        HandshakeExtensions, HandshakePacket, PacketPosition,
    };
    use broadcast_core::error::BufferTooShort;

    const PEER: &str = "10.0.0.1:9999";
    /// TSBPD latency used by the test drivers (the spec minimum, §4.5.1).
    const LATENCY_MS: u64 = 120;

    fn peer_addr() -> std::net::SocketAddr {
        PEER.parse().unwrap()
    }

    /// The default peer-idle bound (libsrt's `SRTO_PEERIDLETIMEO`).
    const PEER_IDLE_TIMEOUT: Duration = Duration::from_secs(5);

    /// `epoch` plus `span`.
    fn instant_after(epoch: LinkInstant, span: Duration) -> LinkInstant {
        epoch.checked_add(span).expect("fits")
    }

    fn data_of(datagram: &[u8]) -> DataPacket<'_> {
        match SrtPacket::parse(datagram) {
            Ok(SrtPacket::Data(d)) => d,
            other => panic!("expected a DATA packet, got {other:?}"),
        }
    }

    fn control_of(datagram: &[u8]) -> ControlPacket<'_> {
        match SrtPacket::parse(datagram) {
            Ok(SrtPacket::Control(c)) => c,
            other => panic!("expected a control packet, got {other:?}"),
        }
    }

    fn seq_of(datagram: &[u8]) -> u32 {
        data_of(datagram).seq_number
    }

    /// Advance the paused clock and run the driver's timer pass at the new instant.
    async fn tick(driver: &mut Driver) {
        let now = driver.link_now(Instant::now());
        let delivered = driver.link.poll(now);
        driver.deliver(delivered);
    }

    /// Hand one datagram to the link and collect what it delivered.
    fn ingress(driver: &mut Driver, datagram: Vec<u8>) {
        let now = driver.link_now(Instant::now());
        let delivered = driver.link.on_datagram(&datagram, now);
        driver.deliver(delivered);
    }

    /// Queue one application payload for transmission at the link's current instant.
    fn send_one(driver: &mut Driver, payload: &[u8]) {
        let now = driver.link_now(Instant::now());
        driver.link.send(payload, now);
    }

    /// Everything the link has queued, in send order.
    fn pending(driver: &mut Driver) -> Vec<Vec<u8>> {
        driver.link.take_sent()
    }

    /// Write everything the link holds out to the socket at the link's current instant.
    async fn flush(driver: &mut Driver) {
        let now = driver.link_now(Instant::now());
        let mut sent = Vec::new();
        let delivered = driver.link.poll_io(now, &mut sent);
        driver.deliver(delivered);
        driver.flush_outbound(sent).await.expect("flush");
    }

    /// The next DATA packet's body when the sender holds one, else the whole queue.
    fn data_sent(sent: &[Vec<u8>]) -> Vec<Vec<u8>> {
        sent.iter()
            .filter(|d| matches!(SrtPacket::parse(d), Ok(SrtPacket::Data(_))))
            .cloned()
            .collect()
    }

    /// How many of `sent` are DATA packets.
    fn data_count(sent: &[Vec<u8>]) -> usize {
        sent.iter()
            .filter(|d| matches!(SrtPacket::parse(d), Ok(SrtPacket::Data(_))))
            .count()
    }

    /// The caller-side settings a test connection runs with.
    fn test_params(read_idle: Duration) -> CallerParams {
        CallerParams::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
            2,
            0,
            LinkTimers {
                cadence: crate::test_support::DEFAULT_CADENCE,
                handshake_timeout: Duration::from_secs(5),
                read_idle,
            },
            crate::test_support::ARQ_BOUNDS,
            vec![7; crate::link::KEY_LEN],
            crate::test_support::TEST_DRIFT_WINDOW,
        )
    }

    /// What a test connection settled: these values on both sides, peer ISN 0.
    fn test_setup(max_flow_window: u32, tlpkt_drop: bool, peer_timestamp_us: u32) -> LinkSetup {
        let socket_id = 1;
        let mut flags = crate::packet::HandshakeExtensionMessageFlags::new(0);
        if tlpkt_drop {
            flags = crate::packet::HandshakeExtensionMessageFlags::new(
                crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP,
            );
        }
        let params = handshake_sm::NegotiatedParams {
            version: 5,
            flags,
            latency: Duration::from_millis(LATENCY_MS),
            own_socket_id: socket_id + 1,
            peer_socket_id: socket_id,
            mtu: 1500,
            max_flow_window_size: max_flow_window,
            stream_id: None,
            group: None,
            #[cfg(feature = "crypto")]
            sek: None,
            #[cfg(feature = "crypto")]
            salt: None,
        };
        LinkSetup::new(params, 0, peer_timestamp_us)
    }

    /// A `Driver` wired to a throwaway bound socket and an unbounded delivery
    /// channel, with the same engine defaults `spawn` uses — so the connection
    /// can be driven directly through its link without a live handshake.
    async fn test_driver(max_flow_window: u32) -> (Driver, mpsc::Receiver<Delivered>) {
        let (driver, rx, _datagram_tx) = test_driver_with_ingress(max_flow_window).await;
        // The inbound-datagram sender is dropped here: the tests that use this
        // drive the link directly, never `Driver::run`'s select loop (which
        // would see the closed channel as "upstream gone").
        (driver, rx)
    }

    /// Like [`test_driver`], but also returns the live sender of the
    /// driver's inbound-datagram channel, so `Driver::run` can be spawned.
    async fn test_driver_with_ingress(
        max_flow_window: u32,
    ) -> (Driver, mpsc::Receiver<Delivered>, mpsc::Sender<Bytes>) {
        test_driver_with_flags(max_flow_window, true, 0, PEER_IDLE_TIMEOUT).await
    }

    /// A driver whose connection negotiated `tlpkt_drop`, whose peer handshake carried
    /// `peer_timestamp_us`, and whose peer may stay silent for `read_idle`.
    async fn test_driver_with_flags(
        max_flow_window: u32,
        tlpkt_drop: bool,
        peer_timestamp_us: u32,
        read_idle: Duration,
    ) -> (Driver, mpsc::Receiver<Delivered>, mpsc::Sender<Bytes>) {
        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
        // Make the socket's writability known up front. Without it the first
        // `send_to` yields to the reactor, and under a paused clock the
        // runtime would then auto-advance time to the (new) write-timeout
        // timer before the real send completes.
        udp.writable().await.unwrap();
        let (deliver, rx) = mpsc::channel(crate::test_support::DELIVER_CHANNEL_CAPACITY.get());
        let (datagram_tx, datagram_rx) =
            mpsc::channel(crate::test_support::RX_CHANNEL_CAPACITY.get());
        let epoch = Instant::now();
        let (close_tx, close_rx) = mpsc::channel(1);
        let driver = Driver {
            udp,
            peer_addr: peer_addr(),
            peer_socket_id: 1,
            stats: Arc::new(Counters::default()),
            rx: datagram_rx,
            _route_cleanup: RouteCleanup(None),
            _forwarder_guard: TaskGuard(None),
            link: Link::new(
                LinkInstant::ZERO,
                &test_setup(max_flow_window, tlpkt_drop, peer_timestamp_us),
                &test_params(read_idle),
            ),
            last_rx_at: epoch,
            epoch,
            deliver,
            stopped: false,
            read_idle,
            write_timeout: crate::test_support::io_config().timeouts.write,
            keepalive: crate::test_support::DEFAULT_CADENCE.keepalive,
            close_linger: CloseTimings::for_profile(broadcast_core::Profile::Server),
            close_rx,
            close_keepalive: Some(close_tx),
            close_damage: Arc::new(std::sync::Mutex::new(None)),
            #[cfg(test)]
            tick_counter: None,
        };
        (driver, rx, datagram_tx)
    }

    fn data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
        let dp = DataPacket {
            seq_number: seq,
            position: PacketPosition::Solo,
            in_order: true,
            key_flag: EncryptionKeyField::NotEncrypted,
            retransmitted: false,
            message_number: seq & crate::packet::data::MESSAGE_NUMBER_MASK,
            timestamp: crate::packet::SrtTimestamp::from_wire(timestamp),
            dest_socket_id: crate::packet::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 encrypted_data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
        let mut buf = data_bytes(seq, timestamp, payload);
        // Flip the `KK` field of word 1 from `00b` to `01b` (even key).
        let word1 = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
        let word1 = (word1 & !(0b11 << 27)) | (u32::from(EncryptionKeyField::Even.to_bits()) << 27);
        buf[4..8].copy_from_slice(&word1.to_be_bytes());
        buf
    }

    fn dropreq_bytes(first: u32, last: u32) -> Vec<u8> {
        let pkt = ControlPacket::DropReq(DropReqPacket {
            message_number: crate::packet::MessageNumber::try_new(0).expect("fits"),
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            first_seq: crate::packet::SeqNo::from_wire_masked(first),
            last_seq: crate::packet::SeqNo::from_wire_masked(last),
        });
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        pkt.serialize_into(&mut buf).expect("serialize dropreq");
        buf
    }

    pub(super) fn induction_bytes(socket_id: u32) -> Vec<u8> {
        let hp = HandshakePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
            version: crate::handshake_sm::HANDSHAKE_VERSION_4,
            encryption_field: crate::packet::EncryptionField::NoEncryption,
            extension_field: HandshakeExtensionFlags::new(
                crate::handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE,
            ),
            initial_seq_number: 0,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: crate::packet::HandshakeType::Induction,
            srt_socket_id: socket_id,
            syn_cookie: 0,
            peer_ip: [0; 4],
            extensions: HandshakeExtensions(Vec::new()),
        };
        let pkt = ControlPacket::Handshake(hp);
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        pkt.serialize_into(&mut buf).expect("serialize induction");
        buf
    }

    /// A CONCLUSION with no extensions and `cookie` — either a stray (cookie
    /// 0 never validates) or a probe with a chosen cookie.
    fn conclusion_bytes(socket_id: u32, cookie: u32) -> Vec<u8> {
        let hp = HandshakePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
            encryption_field: crate::packet::EncryptionField::NoEncryption,
            extension_field: HandshakeExtensionFlags::new(0),
            initial_seq_number: 0,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: crate::packet::HandshakeType::Conclusion,
            srt_socket_id: socket_id,
            syn_cookie: cookie,
            peer_ip: [0; 4],
            extensions: HandshakeExtensions(Vec::new()),
        };
        let pkt = ControlPacket::Handshake(hp);
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        pkt.serialize_into(&mut buf).expect("serialize conclusion");
        buf
    }

    /// Drives a real [`CallerHandshake`] through its INDUCTION against `core`
    /// and returns the CONCLUSION bytes it produces, leaving `core` with no
    /// queued handshake datagram for `src`.
    pub(super) fn listener_conclusion(
        core: &mut ListenerCore,
        src: std::net::SocketAddr,
        caller_socket_id: u32,
    ) -> Vec<u8> {
        let mut caller = CallerHandshake::new(
            caller_socket_id,
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
        );
        let induction = caller.start().expect("caller induction");
        core.handle_datagram(src, &induction)
            .expect("the listener answers an induction");
        let answer = core
            .outbound_queue
            .get(&src)
            .and_then(|queue| queue.back())
            .expect("an INDUCTION response")
            .clone();
        core.outbound_queue.remove(&src);
        let parsed = ControlPacket::parse(&answer).expect("parse induction response");
        let mut conclusion = None;
        for outcome in caller.feed(&parsed).expect("caller feed") {
            if let HandshakeOutput::Send(bytes) = outcome {
                conclusion = Some(bytes);
            }
        }
        conclusion.expect("the caller sends a conclusion")
    }

    /// Review-focus 2. UDP truncates a datagram larger than the receive buffer
    /// without telling the reader; a truncated DATA packet then parses as a
    /// shorter, valid packet and its payload is delivered corrupted. The
    /// forwarder must read `max + 1` bytes, drop anything longer than `max`,
    /// and count it.
    #[tokio::test]
    async fn an_oversize_datagram_is_dropped_and_counted_never_truncated() {
        let local = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let stats = Arc::new(Counters::default());
        let (mut rx, _guard) = spawn_dedicated_socket_forwarder(
            Arc::clone(&local),
            peer.local_addr().unwrap(),
            Arc::clone(&stats),
            300,
            crate::test_support::RX_CHANNEL_CAPACITY,
        );
        let local_addr = local.local_addr().unwrap();
        peer.send_to(&[1u8; 250], local_addr).await.unwrap();
        peer.send_to(&[2u8; 400], local_addr).await.unwrap(); // > 300
        peer.send_to(&[3u8; 300], local_addr).await.unwrap(); // exactly max: accepted
        let a = rx.recv().await.unwrap();
        let b = rx.recv().await.unwrap();
        assert_eq!((a.len(), a[0]), (250, 1));
        assert_eq!(
            (b.len(), b[0]),
            (300, 3),
            "the 400-byte datagram must not appear, truncated or not"
        );
        assert_eq!(stats.rx_oversize.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn io_config_refuses_a_datagram_size_out_of_range() {
        let base = crate::test_support::io_config();
        assert_eq!(base.max_datagram, 1500);
        for bad in [0, 1, MIN_MAX_DATAGRAM - 1, MAX_MAX_DATAGRAM + 1, usize::MAX] {
            assert!(
                matches!(
                    base.with_max_datagram(bad).validate(),
                    Err(Error::InvalidConfig {
                        field: "max_datagram",
                        ..
                    })
                ),
                "{bad}"
            );
        }
        for good in [MIN_MAX_DATAGRAM, 1500, MAX_MAX_DATAGRAM] {
            assert!(base.with_max_datagram(good).validate().is_ok(), "{good}");
        }
    }

    #[test]
    fn io_config_new_refuses_every_zero_bound() {
        use crate::test_support as t;
        let make = |listener: ListenerLimits, arq: crate::arq::ArqBounds, drift: u32| {
            IoConfig::new(
                1500,
                t::SRT_TIMEOUTS,
                t::DEFAULT_CADENCE,
                listener,
                arq,
                drift,
                t::CHANNELS,
                crate::livecc::MaxBwConfig::Set(125_000_000),
                CloseTimings::for_profile(broadcast_core::Profile::Server),
            )
        };
        let listener = t::DEFAULT_LISTENER_LIMITS;
        let arq = t::ARQ_BOUNDS;
        assert!(make(listener, arq, t::TEST_DRIFT_SAMPLE_COUNT).is_ok());

        let mut table: Vec<(&str, ListenerLimits, crate::arq::ArqBounds)> = Vec::new();
        let mut l = listener;
        l.max_pending = 0;
        table.push(("listener.max_pending", l, arq));
        let mut l = listener;
        l.pending_tick = Duration::ZERO;
        table.push(("listener.pending_tick", l, arq));
        let mut l = listener;
        l.cookie_key_rotation = Duration::ZERO;
        table.push(("listener.cookie_key_rotation", l, arq));
        let mut a = arq;
        a.receiver.max_tracked_window = 0;
        table.push(("receiver.max_tracked_window", listener, a));
        let mut a = arq;
        a.receiver.max_pending_skips = 0;
        table.push(("receiver.max_pending_skips", listener, a));
        let mut a = arq;
        a.receiver.max_outstanding_acks = 0;
        table.push(("receiver.max_outstanding_acks", listener, a));
        let mut a = arq;
        a.sender.max_nak_seqs_per_packet = 0;
        table.push(("sender.max_nak_seqs_per_packet", listener, a));
        let mut a = arq;
        a.sender.pacing_burst_packets = 0;
        table.push(("sender.pacing_burst_packets", listener, a));
        match make(listener, arq, 0) {
            Err(Error::InvalidConfig { field, .. }) => assert_eq!(field, "drift_sample_count"),
            other => panic!("zero drift window: {other:?}"),
        }
        for (field, l, a) in table {
            match make(l, a, t::TEST_DRIFT_SAMPLE_COUNT) {
                Err(Error::InvalidConfig { field: got, .. }) => assert_eq!(got, field),
                other => panic!("{field}: {other:?}"),
            }
        }
        let mut a = arq;
        a.sender.min_retransmit_interval = Duration::ZERO;
        assert!(
            make(listener, a, t::TEST_DRIFT_SAMPLE_COUNT).is_ok(),
            "zero means no floor"
        );
    }

    fn payload_item(byte: u8) -> crate::link::DeliveredItem {
        crate::link::DeliveredItem::Payload(crate::link::Payload::of(&[byte]))
    }

    fn damage_item(what: &'static str) -> crate::link::DeliveredItem {
        crate::link::DeliveredItem::Damage(Damage::new(
            DamageKind::MediaUnitDropped,
            Severity::Degraded,
            what,
        ))
    }

    async fn slow_reader_driver(slots: usize) -> (Driver, mpsc::Receiver<Delivered>) {
        let (mut driver, _rx) = test_driver(8192).await;
        let (tx, rx) = mpsc::channel(slots);
        driver.deliver = tx;
        (driver, rx)
    }

    async fn all_events(
        rx: &mut mpsc::Receiver<Delivered>,
        control: &Mutex<DeliverControl>,
    ) -> (Vec<SrtEvent>, Result<Option<SrtEvent>>) {
        let mut events = Vec::new();
        loop {
            match next_event(rx, control).await {
                Ok(Some(event)) => events.push(event),
                other => return (events, other),
            }
        }
    }

    #[tokio::test]
    async fn a_reader_that_stops_reading_still_gets_the_damage_and_the_refusal() {
        let (mut driver, mut rx) = slow_reader_driver(2).await;
        let refusal = DamageError::new(Damage::new(
            DamageKind::MediaUnitDropped,
            Severity::Degraded,
            "refused",
        ));
        let mut items: Vec<_> = (0..10u8).map(payload_item).collect();
        items.insert(5, damage_item("first damage"));
        items.insert(6, damage_item("second damage"));
        items.push(crate::link::DeliveredItem::Refused(refusal));
        driver.deliver(crate::link::Delivered::from_items(items));
        assert!(driver.stopped);
        let control_stats = Arc::clone(&driver.stats);
        drop(driver);

        let (events, end) = all_events(&mut rx, &control_stats.control).await;
        let payloads = events
            .iter()
            .filter(|e| matches!(e, SrtEvent::Payload(_)))
            .count();
        let damages: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                SrtEvent::Damage(d) => Some(d.what()),
                _ => None,
            })
            .collect();
        assert_eq!(payloads, 2, "only the two slots' payloads were deliverable");
        assert!(damages.contains(&"first damage"), "{damages:?}");
        assert!(
            damages.contains(&"SRT payloads dropped, delivery channel full"),
            "{damages:?}"
        );
        assert_eq!(
            control_stats.damage_coalesced.load(Ordering::Relaxed),
            1,
            "the second damage report is counted, not silent"
        );
        assert!(
            matches!(end, Err(Error::Damage(_))),
            "the refusal ends the stream as an error, never as a clean end: {end:?}"
        );
    }

    #[tokio::test]
    async fn dropped_payloads_are_reported_once_space_frees() {
        let (mut driver, mut rx) = slow_reader_driver(1).await;
        driver.deliver(crate::link::Delivered::from_items(
            (0..4u8).map(payload_item).collect(),
        ));
        assert_eq!(driver.stats.deliver_dropped.load(Ordering::Relaxed), 3);
        let first = next_event(&mut rx, &driver.stats.control).await;
        assert!(matches!(first, Ok(Some(SrtEvent::Payload(_)))));
        let report = next_event(&mut rx, &driver.stats.control).await;
        match report {
            Ok(Some(SrtEvent::Damage(d))) => {
                assert_eq!(d.kind(), DamageKind::MediaUnitDropped);
                assert_eq!(
                    d.location().ordinal(),
                    Some(1),
                    "the first payload not delivered"
                );
            }
            other => panic!("{other:?}"),
        }
    }

    #[tokio::test(start_paused = true)]
    async fn an_idle_driver_deadline_is_the_ack_period_not_a_two_ms_tick() {
        let (driver, _rx) = test_driver(8192).await;
        let d = driver
            .poll_timeout()
            .expect("a connected driver always has a deadline");
        assert_eq!(d - driver.epoch, crate::arq::FULL_ACK_PERIOD);
    }

    /// The old fixed 2 ms ticker ran `tick_engines` ~50 times per 100 ms of idle time; the
    /// deadline-driven loop wakes for the 10 ms ACK cadence only.
    #[tokio::test(start_paused = true)]
    async fn the_run_loop_wakes_at_deadlines_not_on_a_fixed_two_ms_tick() {
        let (mut driver, _rx, _tx) = test_driver_with_ingress(8192).await;
        // The loop really sends its ACKs: a loopback address accepts them, where
        // the default non-routable test peer errors on some hosts and ends the loop.
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        let ticks = Arc::new(AtomicU64::new(0));
        driver.tick_counter = Some(Arc::clone(&ticks));
        let (_app_tx, app_rx) = mpsc::channel(8);
        let handle = tokio::spawn(driver.run(app_rx));
        // `advance` jumps the clock in ONE step, so walk it 1 ms at a time to let every timer fire in order.
        for _ in 0..100 {
            tokio::time::advance(Duration::from_millis(1)).await;
            tokio::task::yield_now().await;
        }
        let n = ticks.load(Ordering::Relaxed);
        assert!(
            (8..=14).contains(&n),
            "expected ~10 wake-ups in 100 ms (10 ms ACK cadence), got {n}"
        );
        handle.abort();
    }

    /// A payload handed over while the loop sits in its wait is stamped with the time it
    /// arrived, not the time the wait began (the field stores the packet send time,
    /// `private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt` §3): a stale
    /// stamp makes the receiver's TSBPD release the packet early, or drop it as too late.
    #[tokio::test(start_paused = true)]
    async fn a_payload_is_stamped_with_the_time_it_was_handed_over() {
        const HANDED_OVER_AFTER: Duration = Duration::from_millis(7);
        let (mut driver, _rx, _tx) = test_driver_with_ingress(8192).await;
        let peer = UdpSocket::bind("127.0.0.1:0").await.expect("peer bind");
        driver.peer_addr = peer.local_addr().expect("peer addr");
        let (app_tx, app_rx) = mpsc::channel(8);
        let handle = tokio::spawn(driver.run(app_rx));
        for _ in 0..HANDED_OVER_AFTER.as_millis() {
            tokio::time::advance(Duration::from_millis(1)).await;
            tokio::task::yield_now().await;
        }
        app_tx
            .send(Outgoing {
                payload: Bytes::from_static(b"payload"),
                handed_over_at: Instant::now(),
            })
            .await
            .expect("hand over");
        let mut buf = [0u8; 2048];
        let stamp = loop {
            peer.readable().await.expect("readable");
            let Ok((n, _)) = peer.try_recv_from(&mut buf) else {
                continue;
            };
            if let Ok(SrtPacket::Data(data)) = SrtPacket::parse(&buf[..n]) {
                break Duration::from_micros(u64::from(data.timestamp.value()));
            }
        };
        handle.abort();
        assert!(
            stamp >= HANDED_OVER_AFTER,
            "the payload handed over {HANDED_OVER_AFTER:?} into the connection is stamped {stamp:?}"
        );
    }

    /// Payloads queued while the driver cannot take them keep the spacing they were handed over
    /// with: a queue wait is not part of the timestamp, so the receiver's latency stays constant.
    #[tokio::test(start_paused = true)]
    async fn queued_payloads_keep_their_hand_over_spacing() {
        const SPACING: Duration = Duration::from_millis(10);
        const QUEUE_WAIT: Duration = Duration::from_millis(500);
        const PAYLOADS: u32 = 3;
        let (mut driver, _rx, _tx) = test_driver_with_ingress(8192).await;
        let peer = UdpSocket::bind("127.0.0.1:0").await.expect("peer bind");
        driver.peer_addr = peer.local_addr().expect("peer addr");
        let (app_tx, app_rx) = mpsc::channel(8);
        let first = Instant::now();
        for index in 0..PAYLOADS {
            app_tx
                .try_send(Outgoing {
                    payload: Bytes::from_static(b"payload"),
                    handed_over_at: first + SPACING * index,
                })
                .expect("queue");
        }
        tokio::time::advance(QUEUE_WAIT).await;
        let handle = tokio::spawn(driver.run(app_rx));
        let mut stamps = Vec::new();
        let mut buf = [0u8; 2048];
        while stamps.len() < PAYLOADS as usize {
            peer.readable().await.expect("readable");
            let Ok((n, _)) = peer.try_recv_from(&mut buf) else {
                continue;
            };
            if let Ok(SrtPacket::Data(data)) = SrtPacket::parse(&buf[..n]) {
                stamps.push(Duration::from_micros(u64::from(data.timestamp.value())));
            }
        }
        handle.abort();
        assert_eq!(
            stamps,
            (0..PAYLOADS)
                .map(|index| SPACING * index)
                .collect::<Vec<_>>(),
            "stamps follow the hand-over instants, not the {QUEUE_WAIT:?} the queue held them"
        );
    }

    /// A name that resolves to an address the local socket cannot reach first is not the one used.
    #[tokio::test]
    async fn a_resolved_address_of_another_family_is_skipped() {
        let mut listener = SrtListener::bind(
            "127.0.0.1:0",
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                crate::test_support::io_config(),
                UdpOptions::new(),
            ),
        )
        .await
        .expect("bind");
        let listener_addr = listener.local_addr().expect("local addr");
        let unreachable: std::net::SocketAddr = "[::1]:9".parse().expect("address");
        let candidates = [unreachable, listener_addr];
        let accept = tokio::spawn(async move { listener.accept().await.map(|s| (listener, s)) });
        let _caller = SrtSocket::connect_from(
            "0.0.0.0:0".parse().expect("address"),
            &candidates[..],
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                crate::test_support::io_config(),
                UdpOptions::new(),
            ),
        )
        .await
        .expect("connect to the IPv4 address");
        accept.await.expect("join").expect("accept");
    }

    /// A [`ListenerCore`] over a throwaway socket, never spawned: tests drive
    /// `handle_datagram`/`tick_pending` and read its state directly.
    pub(super) async fn test_core(config: HandshakeConfig) -> ListenerCore {
        test_core_with_channels(config).await.0
    }

    /// [`test_core`] plus the live ends of its channels: the unrouted-datagram
    /// sender and the accepted-connection receiver.
    async fn test_core_with_channels(
        config: HandshakeConfig,
    ) -> (
        ListenerCore,
        mpsc::Sender<(std::net::SocketAddr, Bytes)>,
        mpsc::Receiver<Result<SrtSocket>>,
    ) {
        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
        let (unrouted_tx, unrouted_rx) =
            mpsc::channel(crate::test_support::UNROUTED_CHANNEL_CAPACITY.get());
        let (accepted_tx, accepted) = mpsc::channel(crate::test_support::ACCEPT_CAPACITY.get());
        let core = ListenerCore {
            udp,
            config,
            io: crate::test_support::io_config(),
            damage_policy: DamagePolicy::default(),
            cookie_keys: CookieKeys::new(
                Instant::now(),
                crate::test_support::DEFAULT_COOKIE_KEY_ROTATION,
            )
            .unwrap(),
            pending: std::collections::HashMap::new(),
            outbound_queue: std::collections::HashMap::new(),
            recent_accepts: std::collections::HashMap::new(),
            routes: Arc::new(Mutex::new(std::collections::HashMap::new())),
            unrouted_rx,
            life: std::sync::Weak::new(),
            accepted_tx,
            overflow_dropped: Arc::new(AtomicU64::new(0)),
            send_errors: Arc::new(AtomicU64::new(0)),
            accepting: true,
            last_pending_tick: Instant::now(),
        };
        (core, unrouted_tx, accepted)
    }

    #[tokio::test(start_paused = true)]
    async fn recent_accepts_stop_at_the_callers_small_cap() {
        const CAP: usize = 3;
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        core.io.listener.max_pending = CAP;
        for i in 0..32u32 {
            let addr = format!("127.0.0.1:{}", 10_000 + i).parse().unwrap();
            core.remember_accept(
                addr,
                RecentAccept {
                    peer_socket_id: 1,
                    response: alloc::vec![0u8; 4],
                    accepted_at: Instant::now(),
                },
            );
        }
        assert_eq!(core.recent_accepts.len(), CAP);
    }

    /// #2860: remembered CONCLUSION responses stay at the listener's `max_pending`
    /// under a flood of accepted addresses.
    #[tokio::test(start_paused = true)]
    async fn recent_accepts_stop_at_the_cap_under_a_flood() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        for i in 0..u32::try_from(crate::test_support::DEFAULT_MAX_PENDING).unwrap() + 64 {
            let addr = format!("127.0.0.1:{}", 10_000 + i).parse().unwrap();
            core.remember_accept(
                addr,
                RecentAccept {
                    peer_socket_id: 1,
                    response: alloc::vec![0u8; 4],
                    accepted_at: Instant::now(),
                },
            );
        }
        assert_eq!(
            core.recent_accepts.len(),
            crate::test_support::DEFAULT_MAX_PENDING
        );
    }

    #[tokio::test(start_paused = true)]
    async fn bounded_turns_a_stuck_future_into_a_timed_out_io_error() {
        let r: Result<()> = bounded(
            Duration::from_secs(3),
            "send",
            std::future::pending::<Result<()>>(),
        )
        .await;
        assert!(
            matches!(
                r,
                Err(Error::Io {
                    kind: std::io::ErrorKind::TimedOut,
                    context: "send"
                })
            ),
            "{r:?}"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn the_configured_read_idle_replaces_the_five_second_constant() {
        let (mut driver, _rx, _datagrams) =
            test_driver_with_flags(8192, true, 0, Duration::from_secs(2)).await;
        assert!(!driver.peer_idle(Instant::now()));
        tokio::time::advance(Duration::from_secs(2)).await;
        assert!(
            driver.peer_idle(Instant::now()),
            "idle after the configured 2 s, not 5 s"
        );
        assert!(
            driver
                .link
                .poll(driver.link_now(Instant::now()))
                .items()
                .iter()
                .any(|item| matches!(
                    item,
                    crate::link::DeliveredItem::Ended(crate::link::LinkEnd::PeerIdle)
                )),
            "the link itself ends at the same bound"
        );
    }

    /// Real time, real socket: a paused clock would auto-advance past the
    /// timers while the first `send_to` waits on the reactor.
    #[tokio::test]
    async fn the_handshake_budget_comes_from_the_config() {
        // black hole: bound UDP socket that never answers
        let hole = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let budget = Duration::from_millis(400);
        let io = crate::test_support::io_config()
            .with_timeouts(crate::test_support::SRT_TIMEOUTS.with_handshake(budget));
        let t0 = Instant::now();
        let err = SrtSocket::connect(
            hole.local_addr().unwrap(),
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                crate::test_support::io_config(),
                UdpOptions::new(),
            )
            .with_io(io),
        )
        .await
        .expect_err("nobody answers");
        // The default retransmit budget (12 x 250 ms) would end an unanswered connect at ~3 s with
        // stage "caller retransmit budget"; only the configured deadline yields "caller connect".
        assert!(
            matches!(
                err,
                Error::HandshakeTimedOut {
                    stage: "caller connect"
                }
            ),
            "{err:?}"
        );
        let took = Instant::now() - t0;
        assert!(
            took >= budget && took < Duration::from_secs(2),
            "the configured {budget:?} deadline, got {took:?}"
        );
        drop(hole);
    }

    // -----------------------------------------------------------------------
    // Each `Driver::poll_timeout` term, with every EARLIER term pushed out of
    // the way, so deleting any one of them changes the asserted deadline.
    // -----------------------------------------------------------------------

    async fn quiet_driver() -> Driver {
        let (mut driver, _rx) = test_driver(8192).await;
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        driver
    }

    /// TSBPD release: a packet due at 120 ms, the Full ACK just ticked at
    /// 118 ms (next ACK 128 ms), so the release is the earliest deadline.
    #[tokio::test(start_paused = true)]
    async fn the_deadline_is_the_tsbpd_release_when_it_is_the_earliest_term() {
        let mut driver = quiet_driver().await;
        let start = Instant::now();
        ingress(&mut driver, data_bytes(0, 0, b"p"));
        tokio::time::advance(Duration::from_millis(118)).await;
        tick(&mut driver).await;
        assert_eq!(
            driver.poll_timeout().unwrap(),
            start + Duration::from_millis(LATENCY_MS),
            "the TSBPD release must be the next wake-up"
        );
    }

    /// With no ACK deadline left (its timestamp cannot represent another
    /// period), the TSBPD release alone sets the wake-up.
    #[tokio::test(start_paused = true)]
    async fn the_tsbpd_release_alone_sets_the_deadline_without_an_ack_term() {
        let mut driver = quiet_driver().await;
        let clock = driver.link_now(Instant::now());
        ingress(&mut driver, data_bytes(0, 0, b"p"));
        let release = instant_after(clock, Duration::from_millis(LATENCY_MS));
        assert!(
            driver.link.next_deadline(clock) <= Some(release),
            "the TSBPD release must be among the next wake-ups"
        );
        assert!(
            driver.link.next_ack() < Some(release),
            "the ACK cadence is the earlier term here: {:?} vs {release:?}",
            driver.link.next_ack()
        );
    }

    /// With no earlier deadline, the Keep-Alive alone sets the wake-up.
    #[tokio::test(start_paused = true)]
    async fn the_keepalive_alone_sets_the_deadline_without_an_ack_term() {
        let mut driver = quiet_driver().await;
        assert!(pending(&mut driver).is_empty(), "nothing is queued");
        tokio::time::advance(Duration::from_millis(20)).await;
        let clock = driver.link_now(Instant::now());
        let keepalive = driver
            .link
            .epoch()
            .checked_add(crate::test_support::DEFAULT_CADENCE.keepalive);
        assert!(
            driver.link.next_deadline(clock) <= keepalive,
            "the keep-alive must be among the next wake-ups"
        );
    }

    /// Pacing: a queued DATA packet whose slot is 3 ms away beats the 10 ms ACK.
    #[tokio::test(start_paused = true)]
    async fn the_deadline_is_the_pacing_slot_when_it_is_the_earliest_term() {
        let mut driver = quiet_driver().await;
        // A pacing period far beyond the 10 ms ACK cadence and the 1 s keep-alive.
        driver.link.set_max_bw(MaxBwConfig::Set(1));
        let clock = driver.link_now(Instant::now());
        send_one(&mut driver, &[0u8; 100]);
        send_one(&mut driver, &[0u8; 100]);
        let mut sent = Vec::new();
        driver.link.flush(clock, &mut sent);
        assert!(
            !data_sent(&sent).is_empty(),
            "the first packet goes at once"
        );
        let slot = instant_after(clock, driver.link.pacing_period());
        assert!(
            driver.link.next_deadline(clock) <= Some(slot),
            "the pacing slot must be among the next wake-ups"
        );
    }

    /// Peer idle: a 4 ms read-idle limit beats the 10 ms ACK and the 1 s keep-alive.
    #[tokio::test(start_paused = true)]
    async fn the_deadline_is_the_peer_idle_expiry_when_it_is_the_earliest_term() {
        let (driver, _rx, _datagrams) =
            test_driver_with_flags(8192, true, 0, Duration::from_millis(4)).await;
        let clock = driver.link_now(Instant::now());
        assert!(
            driver.link.next_deadline(clock).is_some_and(
                |at| at <= instant_after(driver.link.epoch(), Duration::from_millis(4))
            ),
            "the peer-idle expiry must be among the next wake-ups"
        );
    }

    /// Keep-Alive: nothing sent for 995 ms and nothing queued, so the keep-alive
    /// at +5 ms beats the 10 ms ACK.
    #[tokio::test(start_paused = true)]
    async fn the_deadline_is_the_keepalive_when_it_is_the_earliest_term() {
        let mut driver = quiet_driver().await;
        tokio::time::advance(Duration::from_millis(995)).await;
        assert!(pending(&mut driver).is_empty());
        let clock = driver.link_now(Instant::now());
        let keepalive = driver
            .link
            .epoch()
            .checked_add(crate::test_support::DEFAULT_CADENCE.keepalive);
        assert!(
            driver.link.next_deadline(clock) <= keepalive,
            "the keep-alive must be among the next wake-ups"
        );
        // ... and it is NOT a term while something is queued: the queued packet's
        // own pacing slot is due immediately, so the ACK cadence is the next term.
        send_one(&mut driver, b"queued");
        let clock = driver.link_now(Instant::now());
        assert!(
            driver.link.next_deadline(clock).is_some_and(
                |at| at <= instant_after(clock, crate::test_support::DEFAULT_CADENCE.keepalive)
            ),
            "a queued packet must not push the wake-up past the ACK cadence"
        );
    }

    /// Wake the loop exactly as `run` would (at `poll_timeout`) for `window`
    /// of virtual time, returning how many DATA packets left the queue.
    async fn drain_for(driver: &mut Driver, window: Duration) -> usize {
        let start = Instant::now();
        let before = driver.link.queued_len();
        while Instant::now() - start < window {
            let at = driver.poll_timeout().unwrap();
            tokio::time::advance(at - Instant::now()).await;
            tick(driver).await;
            flush(driver).await;
        }
        before - driver.link.queued_len()
    }

    /// A backlog with NO inbound events and no application traffic (retransmit
    /// burst after a NAK, idle app) drains at wake-up granularity: the old
    /// one-packet-per-wake ceiling was ~10.5 Mbit/s.
    #[tokio::test(start_paused = true)]
    async fn an_idle_backlog_drains_faster_than_one_packet_per_wake() {
        let mut driver = quiet_driver().await;
        for _ in 0..3000 {
            send_one(&mut driver, &[0u8; 1316]);
        }
        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
        let mbit_s = sent as f64 * 1316.0 * 8.0 / 0.1 / 1e6;
        assert!(
            mbit_s >= 20.0,
            "drained {sent} packets in 100 ms = {mbit_s:.1} Mbit/s"
        );
    }

    /// Pacing still holds with catch-up: at 2.5 MB/s (20 Mbit/s) 100 ms is ~190
    /// packets plus at most one burst, never an instantaneous dump.
    #[tokio::test(start_paused = true)]
    async fn catch_up_never_exceeds_the_paced_rate_by_more_than_one_burst() {
        let mut driver = quiet_driver().await;
        driver.link.set_max_bw(MaxBwConfig::Set(2_500_000));
        for _ in 0..3000 {
            send_one(&mut driver, &[0u8; 1316]);
        }
        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
        let allowed = (2_500_000.0_f64 * 0.1 / 1316.0).ceil() as usize
            + crate::test_support::ARQ_BOUNDS.sender.pacing_burst_packets
            + 1;
        assert!(
            sent <= allowed,
            "sent {sent} packets, paced allowance {allowed}"
        );
        assert!(sent >= 100, "pacing starved the drain: {sent}");
    }

    // -----------------------------------------------------------------------
    // Listener: the deadline wiring and send-error handling
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn the_listener_deadline_exists_only_while_a_handshake_is_pending() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        assert_eq!(core.poll_timeout(), None, "an idle listener has no timer");
        core.handle_datagram(peer_addr(), &induction_bytes(7))
            .expect("induction");
        assert_eq!(
            core.poll_timeout(),
            None,
            "an INDUCTION allocates no pending handshake (#2820)"
        );
        let src = peer_addr();
        let conclusion = listener_conclusion(&mut core, src, 7);
        core.handle_datagram(src, &conclusion)
            .expect("cookie-validated conclusion");
        assert!(core.pending.contains_key(&src));
        assert_eq!(
            core.poll_timeout(),
            Some(core.last_pending_tick + crate::test_support::DEFAULT_PENDING_TICK_INTERVAL)
        );
        core.accepting = false;
        assert_eq!(
            core.poll_timeout(),
            None,
            "a handle-less core serves nobody"
        );
    }

    /// A lost INDUCTION response is recovered by the Caller re-sending its
    /// INDUCTION, which the stateless listener answers identically — not by a
    /// listener-side retransmit tick (#2820). No pending state is created.
    #[tokio::test]
    async fn a_repeated_induction_is_answered_again_without_state() {
        let config = HandshakeConfig {
            retransmit_after: Duration::from_millis(1),
            max_retries: 5,
            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
        };
        let mut core = test_core(config).await;
        let src = peer_addr();
        let induction = induction_bytes(7);

        core.handle_datagram(src, &induction).expect("induction");
        let first = core
            .outbound_queue
            .get(&src)
            .and_then(|queue| queue.back())
            .cloned()
            .expect("an INDUCTION response");
        core.handle_datagram(src, &induction).expect("repeat");
        let second = core
            .outbound_queue
            .get(&src)
            .and_then(|queue| queue.back())
            .cloned()
            .expect("the repeat is answered too");
        assert_eq!(first, second, "the stateless answer is identical");
        assert!(core.pending.is_empty(), "neither answer allocated state");
    }

    /// #2820: a CONCLUSION is validated against the key that issued its
    /// cookie even after that key has rotated, and against the previous
    /// one-minute bucket.
    #[tokio::test(start_paused = true)]
    async fn a_conclusion_cookie_survives_a_key_rotation_and_a_bucket_boundary() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let bucket = unix_time_bucket();
        let old_secret = core.cookie_keys.current();
        let old_key_cookie = derive_cookie(&src, 5, bucket, old_secret);

        core.cookie_keys.drawn_at =
            Instant::now() - crate::test_support::DEFAULT_COOKIE_KEY_ROTATION;
        assert!(core.cookie_keys.rotate_if_due(Instant::now()));
        assert_ne!(core.cookie_keys.current(), old_secret);

        assert!(
            core.validated_conclusion_ids(src, 5, old_key_cookie)
                .is_some(),
            "the previous key must still validate a cookie it issued"
        );

        let previous_bucket_cookie =
            derive_cookie(&src, 5, bucket.wrapping_sub(1), core.cookie_keys.current());
        assert!(
            core.validated_conclusion_ids(src, 5, previous_bucket_cookie)
                .is_some(),
            "a cookie issued a minute ago is still within its window"
        );

        let truncated = conclusion_bytes(5, 0);
        core.handle_datagram(src, &truncated)
            .expect("an unvalidated conclusion is ignored");
        assert!(core.pending.is_empty());
    }

    /// Send errors are counted, never queued: a flood of them must not touch
    /// the accept queue that finished connections depend on.
    #[tokio::test]
    async fn a_flood_of_send_errors_does_not_displace_completed_connections() {
        let (core, _tx, mut accepted) = test_core_with_channels(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        for _ in 0..(crate::test_support::ACCEPT_CAPACITY.get() * 20) {
            core.count_send_error(Err(Error::Io {
                kind: std::io::ErrorKind::HostUnreachable,
                context: "send_to",
            }));
        }
        assert_eq!(
            core.send_errors.load(Ordering::Relaxed),
            (crate::test_support::ACCEPT_CAPACITY.get() * 20) as u64
        );
        assert_eq!(
            core.accepted_tx.capacity(),
            crate::test_support::ACCEPT_CAPACITY.get(),
            "every accept-queue slot is still free for a real connection"
        );
        assert!(accepted.try_recv().is_err());
    }

    fn drain_deliveries(rx: &mut mpsc::Receiver<Delivered>) -> Vec<Bytes> {
        let mut out = Vec::new();
        while let Ok(item) = rx.try_recv() {
            if let Delivered::Event(SrtEvent::Payload(payload)) = item {
                out.push(payload);
            }
        }
        out
    }

    /// Everything queued for the application, split into payloads and damage
    /// reports (one pass: a second drain would find the channel empty).
    fn drain_all(rx: &mut mpsc::Receiver<Delivered>) -> (Vec<Bytes>, Vec<Damage>) {
        let mut payloads = Vec::new();
        let mut damages = Vec::new();
        while let Ok(item) = rx.try_recv() {
            match item {
                Delivered::Event(SrtEvent::Payload(payload)) => payloads.push(payload),
                Delivered::Event(SrtEvent::Damage(damage)) => damages.push(damage),
            }
        }
        (payloads, damages)
    }

    // -----------------------------------------------------------------------
    // Item 1 — encryption in the tokio adapter
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn encrypted_data_packet_is_never_staged_or_delivered() {
        let (mut driver, mut rx) = test_driver(8192).await;
        let ts = 0u32;
        // The unencrypted packet at seq 0 is staged normally.
        ingress(&mut driver, data_bytes(0, ts, b"plain"));
        // An encrypted packet (KK != 0) can never reach `staged` or the app:
        // this link holds no key, so it is undecryptable, counted once.
        ingress(&mut driver, encrypted_data_bytes(1, ts, b"ciphertext"));

        assert!(
            driver.link.reported_causes()[2],
            "a KK != 0 data packet must be counted as undecryptable"
        );
        assert_eq!(
            crate::link::Link::counted_cause_what(2),
            Some("SRT encrypted data packet (no usable key)")
        );
        let delivered = drain_deliveries(&mut rx);
        assert!(
            delivered.iter().all(|p| &p[..] != b"ciphertext"),
            "ciphertext must never be delivered to the application"
        );
    }

    // -----------------------------------------------------------------------
    // Issue #1062 — sequence/message-number wrap must not panic
    // -----------------------------------------------------------------------

    /// Pre-fix, `send_one` incremented both counters with a plain
    /// `u32::wrapping_add(1)` (wraps at `u32::MAX`, not the wire field's own
    /// bit width). Starting both counters two steps below their real 31-bit
    /// (sequence) / 26-bit (message number) boundaries and sending four
    /// packets crosses both wraps; pre-fix this panicked inside
    /// `DataPacket::serialize_into`'s `.expect("buffer sized from
    /// serialized_len")` call sites in `arq::sender` with `FieldTooWide`
    /// (verified via a copied pre-fix `io.rs`, `git show HEAD:srt-runtime/src/io.rs`,
    /// never `git stash` — shared worktree — swapped back immediately after:
    /// `panicked ... buffer sized from serialized_len: FieldTooWide { what:
    /// "Packet Sequence Number", value: 2147483648, bits: 31 }`).
    #[tokio::test]
    async fn send_one_wraps_seq_and_message_number_without_panicking() {
        let (mut driver, _rx, _datagrams) =
            test_driver_with_flags(8192, true, 0, PEER_IDLE_TIMEOUT).await;
        let mut setup = test_setup(8192, true, 0);
        setup.params.latency = Duration::from_millis(LATENCY_MS);
        let params = CallerParams::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
            2,
            SEQ_NUMBER_MASK - 1,
            crate::link::TEST_TIMERS,
            crate::test_support::ARQ_BOUNDS,
            vec![7; crate::link::KEY_LEN],
            crate::test_support::TEST_DRIFT_WINDOW,
        );
        let mut link = Link::new(LinkInstant::ZERO, &setup, &params);
        link.set_next_message_number(crate::packet::data::MESSAGE_NUMBER_MASK - 1);

        // Four sends: seq goes MASK-1, MASK, 0, 1 (wrapping at 2^31); message
        // number goes MASK-1, MASK, 1, 2 (wrapping at 2^26 but skipping 0 —
        // libsrt's `SRT_MSGNO_CONTROL` sentinel, see `next_message_number`).
        // Each call re-derives the wire bytes through the exact
        // `serialize_into` path the panic was in — reaching here without
        // panicking is the test.
        for _ in 0..4 {
            link.send(b"payload", LinkInstant::ZERO);
        }

        assert_eq!(
            link.next_send_seq(),
            2,
            "sequence number must wrap at 2^31, not 2^32"
        );
        assert_eq!(
            link.next_message_number(),
            3,
            "message number must wrap at 2^26 (skipping 0), not 2^32"
        );

        // Every enqueued DATA packet must itself carry a legal (in-range)
        // seq/message number — not just the counter that produced it.
        for datagram in link.take_sent() {
            let dp = DataPacket::parse(&datagram).expect("parse enqueued data packet");
            assert!(dp.seq_number <= SEQ_NUMBER_MASK);
            assert!(dp.message_number <= crate::packet::data::MESSAGE_NUMBER_MASK);
        }
        let _ = &mut driver;
    }

    // -----------------------------------------------------------------------
    // Item 6 — ACK/NAK must not queue behind a not-yet-due paced DATA packet
    // -----------------------------------------------------------------------

    /// Pre-fix, a single FIFO `outbound` queue (each item tagged `is_data`)
    /// meant `flush_outbound` stopped at the first not-yet-due DATA packet
    /// and never looked past it — so an AckAck enqueued *behind* one (the
    /// ordinary case: `send_one` queues DATA, then the peer's own Ack —
    /// handled by `ingress` — queues the reply) sat there just as
    /// pacing-throttled as the DATA in front of it, even though §5.1.2 paces
    /// DATA only.
    #[tokio::test]
    async fn ackack_is_not_queued_behind_a_not_yet_due_paced_data_packet() {
        let (mut driver, _rx) = test_driver(8192).await;
        // `flush` does a real `send_to` below — a loopback address accepts it
        // without needing an actual listener there, unlike `test_driver`'s
        // default non-routable `PEER` test address.
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        // A near-zero bandwidth cap pushes each DATA packet's pacing slot far
        // into the future. The very first send establishes that pacing
        // schedule (there is no deadline yet before anything has been sent);
        // the second one is the packet this test actually checks stays
        // queued behind its own not-yet-arrived slot.
        driver.link.set_max_bw(MaxBwConfig::Set(1));
        send_one(&mut driver, &[0u8; 200]);
        flush(&mut driver).await;
        send_one(&mut driver, &[0u8; 200]);
        let queued = pending(&mut driver);
        assert_eq!(queued.len(), 1, "second DATA must be queued");
        assert!(
            data_sent(&queued).len().eq(&0) || seq_of(&queued[0]) == 1,
            "the queued packet is the second DATA packet"
        );

        let ack = ControlPacket::Ack(AckPacket {
            ack_number: crate::packet::AckNumber::from_wire(1),
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            cif: AckCif::Full {
                last_ack_seq: crate::packet::SeqNo::from_wire_masked(0),
                rtt_us: 0,
                rtt_var_us: 0,
                avail_buf_size: 8192,
                pkt_recv_rate: 0,
                est_link_capacity: 0,
                recv_rate_bps: 0,
            },
        });
        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
        ingress(&mut driver, ack_bytes);

        let now = driver.link_now(Instant::now());
        let mut sent = Vec::new();
        driver.link.flush(now, &mut sent);
        assert!(
            sent.iter()
                .any(|d| matches!(control_of(d), ControlPacket::AckAck(_))),
            "the AckAck must leave even though the DATA packet's pacing slot \
             has not arrived yet"
        );
        assert!(
            sent.iter()
                .all(|d| !matches!(SrtPacket::parse(d), Ok(SrtPacket::Data(_)))),
            "the still-not-due DATA packet must remain queued, untouched"
        );
    }

    // -----------------------------------------------------------------------
    // Item 2 — one loss must not freeze delivery or grow memory
    // -----------------------------------------------------------------------

    // Paused-clock tests: `Driver` reads `tokio::time::Instant`, so
    // `tokio::time::advance` moves its notion of "now" exactly and instantly —
    // no real sleeping, no dependence on scheduler timing.

    #[tokio::test(start_paused = true)]
    async fn delivery_resumes_after_permanent_loss_once_latency_passes() {
        let (mut driver, mut rx) = test_driver(8192).await;
        let ts0 = 0u32; // the driver epoch is "now" under the paused clock

        // seq 1 is lost and never retransmitted.
        for seq in [0u32, 2, 3] {
            ingress(
                &mut driver,
                data_bytes(seq, ts0, &[u8::try_from(seq).unwrap()]),
            );
        }
        assert!(
            drain_deliveries(&mut rx).is_empty(),
            "play time not yet due"
        );

        // §4.6 / rule 21: at the successor's play time (one latency after
        // send) the gap is skipped and packets 2 and 3 are DELIVERED — not
        // thrown away with the lost packet. Step the clock like the driver's
        // ticker would, finishing well inside the too-late threshold window.
        let mut delivered = Vec::new();
        for _ in 0..40 {
            tokio::time::advance(Duration::from_millis(10)).await;
            tick(&mut driver).await;
            delivered.extend(drain_deliveries(&mut rx));
            if delivered.len() >= 3 {
                break;
            }
        }
        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
        assert_eq!(
            seqs,
            vec![0, 2, 3],
            "the gap must be skipped at the successor's play time and its \
             packets delivered (live mode, §4.6/rule 21)"
        );
    }

    /// A gap TSBPD skips is one damage report for the whole run, delivered
    /// before the payloads that continue past it, and the run's first
    /// sequence number is the ordinal.
    #[tokio::test(start_paused = true)]
    async fn a_skipped_gap_is_one_damage_report() {
        let (mut driver, mut rx) = test_driver(8192).await;
        // 0 arrives, 1..=3 never do, 4 arrives: a run of three is skipped.
        for seq in [0u32, 4] {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;

        let (payloads, reports) = drain_all(&mut rx);
        assert_eq!(reports.len(), 1, "one report per contiguous run");
        assert_eq!(
            reports[0].kind(),
            broadcast_core::damage::DamageKind::MediaUnitDropped
        );
        assert_eq!(
            reports[0].severity(),
            broadcast_core::damage::Severity::Degraded
        );
        assert_eq!(reports[0].location().ordinal(), Some(1));
        assert!(
            reports[0].what().contains("unrecoverable gap"),
            "the report names the reason: {}",
            reports[0].what()
        );
        assert_eq!(payloads.len(), 2, "playback continued past the skipped run");
    }

    /// r08-SRT-W2 (adapter side): when TSBPD gives up on a packet (§4.6), the
    /// ARQ receiver's ack point follows it — the "fake ACK" of Too-Late
    /// Packet Drop. Otherwise it keeps NAKing a packet nobody will ever
    /// deliver, the ACKs never let the peer free anything past it, and the
    /// flow window it measures arrivals against stalls at the lost packet.
    #[tokio::test(start_paused = true)]
    async fn a_tsbpd_skip_advances_the_arq_ack_point() {
        let (mut driver, mut rx) = test_driver(8192).await;
        for seq in [0u32, 2, 3] {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        assert_eq!(driver.link.loss_list_len(), 1, "seq 1 is NAKed");

        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        assert_eq!(
            drain_deliveries(&mut rx).len(),
            3,
            "0, 2, 3 delivered once the gap is skipped"
        );
        // The "fake ACK" of Too-Late Packet Drop: the receiver's ack point moves
        // past the dropped sequence number, so it is never NAKed forever.
        assert_eq!(
            driver.link.ack_point(),
            4,
            "the ack point must move past the packet TSBPD dropped"
        );
        assert_eq!(
            driver.link.loss_list_len(),
            0,
            "a dropped packet must not stay in the loss list"
        );
    }

    /// A delivered payload is exactly the received datagram's body (its fixed
    /// header dropped), never the header or a re-parsed frame.
    #[tokio::test(start_paused = true)]
    async fn delivery_hands_over_the_received_datagrams_body() {
        let (mut driver, mut rx) = test_driver(8192).await;
        let datagram = data_bytes(0, 0, b"the payload body");
        let body = match SrtPacket::parse(&datagram).expect("parse") {
            SrtPacket::Data(d) => d.data.to_vec(),
            other => panic!("expected DATA, got {other:?}"),
        };
        ingress(&mut driver, datagram);
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        let delivered = drain_deliveries(&mut rx);
        assert_eq!(delivered.len(), 1);
        assert_eq!(&delivered[0][..], body.as_slice());
    }

    /// A delivered packet's payload is a view into the received datagram's own
    /// allocation (header sliced off the front) — one copy from the socket
    /// buffer, not a second `to_vec` per packet (r08-SRT-O4). Pointer identity
    /// is the deterministic evidence: a copy would live at a different address.
    #[tokio::test(start_paused = true)]
    async fn delivery_reuses_the_received_datagrams_allocation() {
        let (mut driver, mut rx) = test_driver(8192).await;
        let datagram = bytes::Bytes::from(data_bytes(0, 0, b"zero-copy payload"));
        let allocation = datagram.as_ptr() as usize;
        driver.ingress(datagram);
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        let mut delivered = drain_deliveries(&mut rx);
        assert_eq!(delivered.len(), 1);
        let payload = delivered.remove(0);
        assert_eq!(&payload[..], b"zero-copy payload");
        assert_eq!(
            payload.as_ptr() as usize,
            allocation + SRT_HEADER_LEN,
            "the payload must be a view into the received datagram, not a copy"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn dropreq_unblocks_delivery_immediately() {
        let (mut driver, mut rx) = test_driver(8192).await;
        let ts0 = 0u32;

        for seq in [0u32, 2, 3] {
            ingress(
                &mut driver,
                data_bytes(seq, ts0, &[u8::try_from(seq).unwrap()]),
            );
        }
        assert!(
            drain_deliveries(&mut rx).is_empty(),
            "play time not yet due"
        );

        // The peer announces it will never send seq 1.
        ingress(&mut driver, dropreq_bytes(1, 1));

        tokio::time::advance(Duration::from_millis(140)).await;
        tick(&mut driver).await;

        let delivered = drain_deliveries(&mut rx);
        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
        assert_eq!(seqs, vec![0, 2, 3], "DROPREQ must unblock the gap");
    }

    #[tokio::test(start_paused = true)]
    async fn dropreq_ahead_of_the_ack_point_does_not_stall_the_flow_window() {
        const WINDOW: u32 = 64;
        let (mut driver, mut rx) = test_driver(WINDOW).await;
        for seq in [0u32, 5] {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        ingress(&mut driver, dropreq_bytes(3, 4));
        for seq in [1u32, 2] {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        let first: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
        assert_eq!(first, vec![0, 1, 2, 5]);

        let far = 3 + WINDOW + 1;
        for seq in 6..=far {
            ingress(
                &mut driver,
                data_bytes(seq, 130_000, &[u8::try_from(seq).unwrap()]),
            );
        }
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        let second: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
        let expected: Vec<u8> = (6..=far).map(|s| u8::try_from(s).unwrap()).collect();
        assert_eq!(
            second, expected,
            "the ARQ receiver stalled at its ack point and never released the later run"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn a_dropreq_wider_than_the_flow_window_is_ignored_by_the_driver() {
        const WINDOW: u32 = 64;
        let (mut driver, mut rx) = test_driver(WINDOW).await;
        ingress(&mut driver, data_bytes(0, 0, &[0]));
        ingress(&mut driver, dropreq_bytes(1, 0x3FFF_FFFF));
        ingress(&mut driver, data_bytes(1, 0, &[1]));
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        let delivered: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
        assert_eq!(delivered, vec![0, 1]);
        let sent = pending(&mut driver);
        let acks: Vec<u32> = sent
            .iter()
            .filter_map(|d| match control_of(d) {
                ControlPacket::Ack(a) => Some(a.ack_number.value()),
                _ => None,
            })
            .collect();
        assert!(
            acks.iter().all(|&n| n <= 2),
            "a DROPREQ wider than the flow window must be ignored: {acks:?}"
        );
    }

    #[cfg(feature = "crypto")]
    #[tokio::test]
    async fn km_refresh_with_both_keys_installs_both_parities() {
        let (mut driver, _rx) = test_driver(8192).await;
        driver.link.set_passphrase(b"audit-d-passphrase".to_vec());
        let salt = [0x5Au8; crate::crypto::SALT_LEN];
        let (even, odd) = ([0x11u8; 16], [0x22u8; 16]);
        let kek = crate::crypto::derive_kek(b"audit-d-passphrase", &salt, 16).unwrap();
        let mut both = even.to_vec();
        both.extend_from_slice(&odd);
        let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &both).unwrap();
        let km = crate::packet::KeyMaterial {
            kk: crate::packet::KmKeyFlag::Both,
            keki: 0,
            cipher: crate::packet::Cipher::AesCtr,
            auth: crate::packet::KmAuth::None,
            se: crate::packet::StreamEncapsulation::MpegTsSrt,
            salt: &salt,
            icv,
            x_sek: &wrapped[..16],
            o_sek: Some(&wrapped[16..]),
        };
        let mut km_buf = vec![0u8; km.serialized_len()];
        km.serialize_into(&mut km_buf).unwrap();
        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
            control_type: crate::packet::ControlType::UserDefined.to_bits(),
            subtype: crate::packet::handshake::EXT_TYPE_KMREQ,
            type_specific_info: 0,
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            cif: &km_buf,
        });
        let mut out = vec![0u8; ud.serialized_len()];
        ud.serialize_into(&mut out).unwrap();
        ingress(&mut driver, out);
        let installed = driver.link.rx_keys_installed();
        assert!(
            installed,
            "KK=Both carries both SEKs: even installed = {installed}, odd installed = {installed}"
        );
    }

    #[cfg(feature = "crypto")]
    fn refresh_test_thresholds() -> crate::km_refresh::KmRefreshThresholds {
        crate::km_refresh::KmRefreshThresholds::new(20, 5).unwrap()
    }

    /// #2840: a peer re-sending the same Key Material message back to back
    /// gets one answer, not one PBKDF2 run per datagram; a repeat after the
    /// interval is answered from the KEK cache instead of deriving again.
    #[cfg(feature = "crypto")]
    #[tokio::test(start_paused = true)]
    async fn repeat_kmreq_is_rate_limited_and_reuses_the_kek() {
        let (mut driver, _rx) = test_driver(8192).await;
        driver
            .link
            .set_passphrase(b"rate-limit-passphrase".to_vec());
        let salt = [0x6Bu8; crate::crypto::SALT_LEN];
        let sek = [0x5Au8; 16];
        let kek = crate::crypto::derive_kek(b"rate-limit-passphrase", &salt, sek.len()).unwrap();
        let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &sek).unwrap();
        let km = crate::packet::KeyMaterial {
            kk: crate::packet::KmKeyFlag::Even,
            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 mut km_buf = vec![0u8; km.serialized_len()];
        km.serialize_into(&mut km_buf).unwrap();
        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
            control_type: crate::packet::ControlType::UserDefined.to_bits(),
            subtype: crate::packet::handshake::EXT_TYPE_KMREQ,
            type_specific_info: 0,
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            cif: &km_buf,
        });
        let mut request = vec![0u8; ud.serialized_len()];
        ud.serialize_into(&mut request).unwrap();

        ingress(&mut driver, request.clone());
        assert_eq!(kmrsp_sent(&pending(&mut driver)), 1, "first KMREQ answered");
        assert_eq!(driver.link.kek_derivations(), 1);

        ingress(&mut driver, request.clone());
        assert_eq!(
            kmrsp_sent(&pending(&mut driver)),
            0,
            "a repeat inside KMREQ_MIN_INTERVAL must be dropped"
        );
        assert_eq!(driver.link.kek_derivations(), 1, "no derivation on a drop");

        tokio::time::advance(crate::test_support::DEFAULT_CADENCE.kmreq_min_interval).await;
        ingress(&mut driver, request);
        assert_eq!(
            kmrsp_sent(&pending(&mut driver)),
            1,
            "after the interval: answered"
        );
        assert_eq!(
            driver.link.kek_derivations(),
            1,
            "the same Salt and KLen must reuse the derived KEK"
        );
    }

    /// How many Key Material responses (`KMRSP`) a link queued.
    #[cfg(feature = "crypto")]
    fn kmrsp_sent(sent: &[Vec<u8>]) -> usize {
        sent.iter()
            .filter(|d| {
                matches!(
                    control_of(d),
                    ControlPacket::UserDefined(u)
                        if u.subtype == crate::packet::handshake::EXT_TYPE_KMRSP
                )
            })
            .count()
    }

    #[cfg(feature = "crypto")]
    async fn encrypted_pair() -> (
        Driver,
        mpsc::Receiver<Delivered>,
        Driver,
        mpsc::Receiver<Delivered>,
    ) {
        let (mut a, a_rx) = test_driver(8192).await;
        let (mut b, b_rx) = test_driver(8192).await;
        let salt = [0x3Cu8; crate::crypto::SALT_LEN];
        let sek = vec![0x42u8; 16];
        for d in [&mut a, &mut b] {
            d.link.install_refresh_test_keys(
                b"refresh-passphrase",
                &sek,
                salt,
                refresh_test_thresholds(),
            );
        }
        (a, a_rx, b, b_rx)
    }

    #[cfg(feature = "crypto")]
    fn is_kmreq(datagram: &[u8]) -> bool {
        matches!(
            SrtPacket::parse(datagram),
            Ok(SrtPacket::Control(ControlPacket::UserDefined(u)))
                if u.subtype == crate::packet::handshake::EXT_TYPE_KMREQ
        )
    }

    #[cfg(feature = "crypto")]
    fn pump(from: &mut Driver, to: &mut Driver, kmreqs_to_drop: &mut usize) {
        for datagram in pending(from) {
            if is_kmreq(&datagram) && *kmreqs_to_drop > 0 {
                *kmreqs_to_drop -= 1;
                continue;
            }
            ingress(to, datagram);
        }
    }

    #[cfg(feature = "crypto")]
    const REFRESH_TEST_PACKETS: u8 = 100;
    #[cfg(feature = "crypto")]
    const DRAIN_STEPS: u8 = 10;
    #[cfg(feature = "crypto")]
    const REFRESH_TEST_STEP: Duration = Duration::from_millis(20);

    #[cfg(feature = "crypto")]
    fn payloads(rx: &mut mpsc::Receiver<Delivered>) -> Vec<u8> {
        drain_deliveries(rx).iter().map(|p| p[0]).collect()
    }

    #[cfg(feature = "crypto")]
    #[tokio::test(start_paused = true)]
    async fn a_lost_refresh_kmreq_is_resent_and_no_data_is_lost_across_the_switchover() {
        let (mut a, _a_rx, mut b, mut b_rx) = encrypted_pair().await;
        let mut kmreqs_to_drop = 1;
        let mut no_drop = 0;
        let mut delivered = Vec::new();
        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
            if i < REFRESH_TEST_PACKETS {
                send_one(&mut a, &[i]);
            }
            pump(&mut a, &mut b, &mut kmreqs_to_drop);
            pump(&mut b, &mut a, &mut no_drop);
            tokio::time::advance(REFRESH_TEST_STEP).await;
            tick(&mut a).await;
            tick(&mut b).await;
            delivered.extend(payloads(&mut b_rx));
        }
        assert_eq!(kmreqs_to_drop, 0, "the first KMREQ was dropped");
        assert_eq!(
            delivered,
            (0..REFRESH_TEST_PACKETS).collect::<Vec<u8>>(),
            "every packet across the refresh is delivered and decrypted"
        );
        assert_eq!(a.link.tx_parity_name(), "odd", "the switchover happened");
        assert!(!a.link.refresh_pending(), "the KMRSP confirmed the refresh");
    }

    #[cfg(feature = "crypto")]
    #[tokio::test(start_paused = true)]
    async fn the_sender_keeps_the_old_key_while_the_refresh_is_unconfirmed() {
        let (mut a, _a_rx, mut b, mut b_rx) = encrypted_pair().await;
        let mut kmreqs_to_drop = usize::MAX;
        let mut no_drop = 0;
        let mut delivered = Vec::new();
        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
            if i < REFRESH_TEST_PACKETS {
                send_one(&mut a, &[i]);
            }
            pump(&mut a, &mut b, &mut kmreqs_to_drop);
            pump(&mut b, &mut a, &mut no_drop);
            tokio::time::advance(REFRESH_TEST_STEP).await;
            tick(&mut a).await;
            tick(&mut b).await;
            delivered.extend(payloads(&mut b_rx));
        }
        assert_eq!(a.link.tx_parity_name(), "even", "no KMRSP, no switch");
        assert!(a.link.refresh_pending());
        assert_eq!(
            delivered,
            (0..REFRESH_TEST_PACKETS).collect::<Vec<u8>>(),
            "traffic under the old key keeps flowing while the refresh is unconfirmed"
        );
    }

    #[cfg(feature = "crypto")]
    #[tokio::test(start_paused = true)]
    async fn both_directions_refreshing_together_keep_decrypting() {
        let (mut a, mut a_rx, mut b, mut b_rx) = encrypted_pair().await;
        let mut no_drop = 0;
        let mut from_a = Vec::new();
        let mut from_b = Vec::new();
        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
            if i < REFRESH_TEST_PACKETS {
                send_one(&mut a, &[i]);
                send_one(&mut b, &[i]);
            }
            pump(&mut a, &mut b, &mut no_drop);
            pump(&mut b, &mut a, &mut no_drop);
            tokio::time::advance(REFRESH_TEST_STEP).await;
            tick(&mut a).await;
            tick(&mut b).await;
            from_a.extend(payloads(&mut b_rx));
            from_b.extend(payloads(&mut a_rx));
        }
        let expected: Vec<u8> = (0..REFRESH_TEST_PACKETS).collect();
        assert_eq!(from_a, expected, "A to B survives both sides refreshing");
        assert_eq!(from_b, expected, "B to A survives both sides refreshing");
        assert_eq!(a.link.tx_parity_name(), "odd");
        assert_eq!(b.link.tx_parity_name(), "odd");
    }

    #[tokio::test]
    async fn staged_never_exceeds_the_flow_window() {
        const WINDOW: u32 = 64;
        let (mut driver, mut rx) = test_driver(WINDOW).await;
        let ts = 0u32;

        // seq 0 is the delivery cursor and never arrives; feed window+100
        // packets past the gap.
        for seq in 1..=(WINDOW + 100) {
            ingress(
                &mut driver,
                data_bytes(seq, ts, &[u8::try_from(seq).unwrap()]),
            );
            assert!(
                driver.link.staged_len() <= usize::try_from(WINDOW).unwrap(),
                "staged grew to {} past a gap (window {WINDOW})",
                driver.link.staged_len()
            );
        }
        drain_deliveries(&mut rx);
    }

    // -----------------------------------------------------------------------
    // Item 3 — bound listener pending state
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn listener_pending_is_capped_under_a_source_flood() {
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;

        for i in 0..5000u32 {
            let src = std::net::SocketAddr::from(([198, 18, (i >> 8) as u8, i as u8], 40_000));
            let _ = listener.handle_datagram(src, &induction_bytes(i));
        }

        assert!(
            listener.pending.len() <= 1024,
            "pending grew to {} — must be capped at the listener's max_pending",
            listener.pending.len()
        );
        assert_eq!(
            listener.pending.len(),
            0,
            "a spoofed INDUCTION flood must allocate no handshake state (#2820)"
        );
    }

    #[tokio::test]
    async fn stray_conclusions_do_not_hold_listener_handshake_slots() {
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        // Cookie 0 is never issued (`derive_cookie` forces the low bit), so a
        // CONCLUSION carrying it must allocate nothing.
        let stray = conclusion_bytes(5, 0);
        for i in 0..2000u32 {
            let src = std::net::SocketAddr::from(([198, 18, (i >> 8) as u8, i as u8], 40_000));
            let _ = listener.handle_datagram(src, &stray);
        }
        for _ in 0..1000 {
            listener.tick_pending();
        }
        assert_eq!(
            listener.pending.len(),
            0,
            "stray CONCLUSIONs left {} handshake slots allocated for good",
            listener.pending.len()
        );
        let honest = std::net::SocketAddr::from(([203, 0, 113, 9], 4000));
        let conclusion = listener_conclusion(&mut listener, honest, 7);
        listener
            .handle_datagram(honest, &conclusion)
            .expect("an honest caller");
        assert!(listener.pending.contains_key(&honest));
    }

    #[tokio::test(start_paused = true)]
    async fn pending_entries_expire_while_other_sources_keep_sending() {
        let config = HandshakeConfig {
            retransmit_after: Duration::from_millis(1),
            max_retries: 2,
            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
        };
        let mut listener = test_core(config).await;

        // A handshake left awaiting its CONCLUSION — the same state a
        // validated CONCLUSION's allocation passes through — stalled by
        // inserting it directly (no public path leaves it there).
        let stalling_src = std::net::SocketAddr::from(([203, 0, 113, 1], 1234));
        let bucket = unix_time_bucket();
        let secret = listener.cookie_keys.current();
        let cookie = derive_cookie(&stalling_src, 0, bucket, secret);
        let (own_socket_id, our_initial_seq) =
            listener.connection_ids(&stalling_src, 0, bucket, secret);
        let mut stalled_config = listener.config.clone();
        stalled_config.initial_seq_number = our_initial_seq;
        listener.pending.insert(
            stalling_src,
            PendingListener {
                handshake: ListenerHandshake::awaiting_conclusion(
                    own_socket_id,
                    cookie,
                    stalled_config,
                ),
                params: None,
                peer_initial_seq: 0,
                peer_timestamp_us: 0,
                concluded_at: None,
                created_at: Instant::now(),
                last_response: None,
                our_initial_seq,
            },
        );

        // Continuous traffic from *other* sources must not keep the stalling
        // entry alive: the timer-driven tick expires it.
        for i in 0..10u32 {
            let src = std::net::SocketAddr::from(([198, 51, (i >> 8) as u8, i as u8], 40_000));
            let _ = listener.handle_datagram(src, &induction_bytes(100 + i));
            tokio::time::advance(Duration::from_millis(10)).await;
            listener.tick_pending();
        }

        assert!(
            !listener.pending.contains_key(&stalling_src),
            "a stalled handshake must expire even under continuous traffic"
        );
    }

    // -----------------------------------------------------------------------
    // Item 2 (BLOCKER) — dropping an accepted socket must not leak its route
    // -----------------------------------------------------------------------

    /// Pre-fix, `Driver::run`'s route-table cleanup sat at the tail of its
    /// `loop`, reached only on a *normal* exit — `SrtSocket::Drop` instead
    /// calls `handle.abort()`, which cancels the task at its next await point
    /// and drops its future (the `Driver` included) without ever running
    /// that inline code. The entry then sat in `routes` forever: a harmless
    /// no-op for the new ID-keyed demux's correctness (a stale entry's key is
    /// a dead Socket ID no live peer packet names), but an unbounded
    /// per-listener memory leak across repeated accept/drop cycles.
    /// `RouteCleanup`'s `Drop` impl runs on both an abort and a normal
    /// return, since it fires whenever the guard itself — owned by the
    /// `Driver`, and so by the task's future — is dropped.
    #[tokio::test]
    async fn dropping_an_accepted_socket_removes_its_route_entry() {
        let mut listener = SrtListener::bind(
            "127.0.0.1:0",
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                crate::test_support::io_config(),
                UdpOptions::new(),
            ),
        )
        .await
        .expect("bind");
        let listener_addr = listener.local_addr().expect("local addr");

        let accept_jh = tokio::spawn(async move {
            let s = listener.accept().await.expect("accept");
            (listener, s)
        });
        let caller = SrtSocket::connect(
            listener_addr,
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
                crate::test_support::io_config(),
                UdpOptions::new(),
            ),
        )
        .await
        .expect("connect");
        let (listener, accepted) = accept_jh.await.expect("join accept");

        assert_eq!(
            lock(&listener.routes).len(),
            1,
            "the freshly accepted connection must have registered exactly one route"
        );

        drop(accepted); // SrtSocket::Drop aborts the driver task.
        drop(caller);

        // The abort is not synchronous with `drop` — the aborted task's
        // `Drop` impls (including `RouteCleanup`) run at the task's own next
        // poll. Yield to the (current-thread) runtime until it has had that
        // poll; no wall-clock sleep, bounded by an iteration count.
        let mut cleaned = false;
        for _ in 0..1_000 {
            tokio::task::yield_now().await;
            if lock(&listener.routes).is_empty() {
                cleaned = true;
                break;
            }
        }
        assert!(
            cleaned,
            "route table still has {} entries after the accepted socket was \
             dropped — the route leaked (pre-fix: `Driver::run`'s cleanup only \
             ran on a normal loop exit, never on `SrtSocket::Drop`'s task abort)",
            lock(&listener.routes).len()
        );
    }

    /// The data timestamps and the TSBPD time base the peer derives from the handshake count
    /// from one origin, the instant the handshake began. A connection whose data timestamps
    /// restarted from zero once the handshake was over, or whose time base lost its sign, was
    /// released early by the length of the handshake or twice it (390 ms against a 2000 ms latency
    /// in one loaded run).
    #[tokio::test(start_paused = true)]
    async fn a_payload_waits_the_latency_after_a_slow_handshake() {
        const LATENCY: Duration = Duration::from_millis(200);
        const HANDSHAKE_DELAY: Duration = Duration::from_millis(500);
        const DELIVERY_BOUND: Duration = Duration::from_secs(10);
        let config = || {
            SrtSocketConfig::new(
                HandshakeConfig::for_profile(broadcast_core::Profile::Server).with_latency(LATENCY),
                crate::test_support::io_config(),
                UdpOptions::new(),
            )
        };
        let reserved = std::net::UdpSocket::bind("127.0.0.1:0").expect("reserve a port");
        let listener_addr = reserved.local_addr().expect("local addr");
        let connect =
            tokio::spawn(async move { SrtSocket::connect(listener_addr, config()).await });
        tokio::time::sleep(HANDSHAKE_DELAY).await;
        drop(reserved);
        let mut listener = SrtListener::bind(listener_addr, config())
            .await
            .expect("bind");
        let mut accepted = listener.accept().await.expect("accept");
        let mut caller = connect.await.expect("join connect").expect("connect");

        let sent_at = Instant::now();
        caller.send(b"payload").await.expect("send");
        let got = tokio::time::timeout(DELIVERY_BOUND, accepted.recv())
            .await
            .expect("never delivered")
            .expect("recv")
            .expect("delivered");
        assert_eq!(got.as_ref(), b"payload");
        assert!(
            sent_at.elapsed() >= LATENCY,
            "the listener role delivered {:?} after it was sent, under a latency of {LATENCY:?}",
            sent_at.elapsed()
        );

        let sent_at = Instant::now();
        accepted.send(b"payload").await.expect("send");
        let got = tokio::time::timeout(DELIVERY_BOUND, caller.recv())
            .await
            .expect("never delivered")
            .expect("recv")
            .expect("delivered");
        assert_eq!(got.as_ref(), b"payload");
        assert!(
            sent_at.elapsed() >= LATENCY,
            "the caller role delivered {:?} after it was sent, under a latency of {LATENCY:?}",
            sent_at.elapsed()
        );
    }

    const SLOW_HANDSHAKE: Duration = Duration::from_millis(500);
    const SHORT_IDLE: Duration = Duration::from_millis(300);

    fn short_idle_config() -> SrtSocketConfig {
        SrtSocketConfig::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
            crate::test_support::io_config()
                .with_timeouts(crate::test_support::SRT_TIMEOUTS.with_read_idle(SHORT_IDLE)),
            UdpOptions::new(),
        )
    }

    /// A connection made after a handshake longer than the idle bound is still up when it is made:
    /// the silence clock starts at the conclusion, not at the handshake's start.
    async fn assert_alive_after_slow_handshake(socket: &mut SrtSocket) {
        let concluded = Instant::now();
        let ended = tokio::time::timeout(SHORT_IDLE / 2, socket.recv()).await;
        assert!(
            ended.is_err(),
            "the caller ended {:?} after its handshake concluded: {ended:?}",
            concluded.elapsed()
        );
    }

    /// A handshake longer than `read_idle` must not end the connection the moment it is made.
    /// Only the caller's handshake is slow here, so the caller is the side asserted: the listener
    /// and rendezvous roles build their driver through the same constructor, and a handshake they
    /// see as slow needs a peer that withholds its conclusion, which the sans-IO
    /// `the_idle_clock_starts_at_the_conclusion` pins at the link.
    #[tokio::test(start_paused = true)]
    async fn a_handshake_longer_than_read_idle_does_not_end_the_connection() {
        let reserved = std::net::UdpSocket::bind("127.0.0.1:0").expect("reserve a port");
        let listener_addr = reserved.local_addr().expect("local addr");
        let connect =
            tokio::spawn(
                async move { SrtSocket::connect(listener_addr, short_idle_config()).await },
            );
        tokio::time::sleep(SLOW_HANDSHAKE).await;
        drop(reserved);
        let mut listener = SrtListener::bind(listener_addr, short_idle_config())
            .await
            .expect("bind");
        let _accepted = listener.accept().await.expect("accept");
        let mut caller = connect.await.expect("join connect").expect("connect");
        assert_alive_after_slow_handshake(&mut caller).await;
    }

    // -----------------------------------------------------------------------
    // r08-SRT-W6 — liveness: keep-alive, idle timeout, bounded send buffer
    // -----------------------------------------------------------------------

    fn control_kind(datagram: &[u8]) -> &'static str {
        match control_of(datagram) {
            ControlPacket::KeepAlive(_) => "keepalive",
            ControlPacket::Ack(_) => "ack",
            ControlPacket::Nak(_) => "nak",
            ControlPacket::AckAck(_) => "ackack",
            _ => "other",
        }
    }

    /// The control packets a link hands over, named.
    fn control_kinds(sent: &[Vec<u8>]) -> Vec<&'static str> {
        sent.iter()
            .filter(|d| matches!(SrtPacket::parse(d), Ok(SrtPacket::Control(_))))
            .map(|d| control_kind(d))
            .collect()
    }

    fn keepalive_bytes() -> Vec<u8> {
        let ka = ControlPacket::KeepAlive(crate::packet::KeepAlivePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            libsrt_pad: true,
        });
        let mut buf = alloc::vec![0u8; ka.serialized_len()];
        ka.serialize_into(&mut buf).expect("serialize keepalive");
        buf
    }

    /// A connection that has sent nothing for the cadence's keep-alive (§3.2.3:
    /// one second) queues a Keep-Alive — not a millisecond earlier — and the
    /// timer restarts from the last packet actually sent.
    #[tokio::test(start_paused = true)]
    async fn an_idle_connection_sends_a_keepalive_after_one_second() {
        let (mut driver, _rx) = test_driver(8192).await;
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();

        tokio::time::advance(
            crate::test_support::DEFAULT_CADENCE.keepalive - Duration::from_millis(1),
        )
        .await;
        tick(&mut driver).await;
        let early = pending(&mut driver);
        assert!(
            !control_kinds(&early).contains(&"keepalive"),
            "no Keep-Alive before a full idle second: {:?}",
            control_kinds(&early)
        );

        tokio::time::advance(Duration::from_millis(1)).await;
        tick(&mut driver).await;
        let sent = pending(&mut driver);
        assert_eq!(
            control_kinds(&sent)
                .iter()
                .filter(|k| **k == "keepalive")
                .count(),
            1,
            "exactly one Keep-Alive once the second has elapsed: {:?}",
            control_kinds(&sent)
        );
        let ka = sent
            .iter()
            .find_map(|b| match control_of(b) {
                ControlPacket::KeepAlive(ka) => Some(ka),
                _ => None,
            })
            .expect("keepalive");
        assert_eq!(
            ka.dest_socket_id,
            crate::packet::SocketId::from_wire(1),
            "addressed to the peer's socket id"
        );

        // Sending it (this is the host's write, and the last packet that went
        // out) restarts the idle clock: half a second later, no more.
        let now = driver.link_now(Instant::now());
        let mut written = Vec::new();
        driver.link.flush(now, &mut written);
        let clock = driver
            .link_now(Instant::now())
            .saturating_add(crate::test_support::DEFAULT_CADENCE.keepalive / 2);
        let half = clock;
        let before = driver.link.next_deadline(half);
        tick(&mut driver).await;
        let after = driver.link.next_deadline(half);
        assert!(
            after >= before,
            "a keep-alive sent half a second ago does not move the next one earlier \
             ({before:?} -> {after:?})"
        );
    }

    /// Traffic in *either* direction counts: a connection that is sending data
    /// is not idle, so no Keep-Alive is added on top.
    #[tokio::test(start_paused = true)]
    async fn queued_data_suppresses_the_keepalive() {
        let (mut driver, _rx) = test_driver(8192).await;
        tokio::time::advance(crate::test_support::DEFAULT_CADENCE.keepalive).await;
        send_one(&mut driver, b"payload");
        tick(&mut driver).await;
        assert!(!control_kinds(&pending(&mut driver)).contains(&"keepalive"));
    }

    /// A received Keep-Alive only proves the peer is alive: it is not
    /// answered. (It used to be echoed; with each side now sending its own
    /// Keep-Alives, two adapters would bounce one back and forth forever.)
    #[tokio::test(start_paused = true)]
    async fn a_received_keepalive_is_not_answered() {
        let (mut driver, _rx) = test_driver(8192).await;
        ingress(&mut driver, keepalive_bytes());
        let sent = pending(&mut driver);
        assert!(
            control_kinds(&sent).is_empty(),
            "a Keep-Alive must not be echoed: {:?}",
            control_kinds(&sent)
        );
        assert!(!driver.link.is_ended());
    }

    /// Five silent seconds (any packet resets it) end the connection.
    #[tokio::test(start_paused = true)]
    async fn the_peer_idle_timeout_is_five_silent_seconds() {
        let (mut driver, _rx) = test_driver(8192).await;
        assert_eq!(
            crate::test_support::io_config().timeouts.read_idle,
            PEER_IDLE_TIMEOUT
        );
        let anchor = driver.last_rx_at;
        // A bound short of the whole timeout is not a silent peer yet.
        assert!(!driver.peer_idle(anchor + PEER_IDLE_TIMEOUT - Duration::from_millis(1)));
        assert!(driver.peer_idle(anchor + PEER_IDLE_TIMEOUT));

        // Any datagram from the peer — even a Keep-Alive — resets the anchor.
        ingress(&mut driver, keepalive_bytes());
        let reset = driver.last_rx_at;
        assert!(!driver.peer_idle(reset));
        assert!(!driver.peer_idle(reset + PEER_IDLE_TIMEOUT / 2));
        assert!(driver.peer_idle(reset + PEER_IDLE_TIMEOUT));
    }

    /// The sender never holds more than a flow window of unacknowledged
    /// packets: the window closes when full and reopens when an ACK frees it.
    #[tokio::test]
    async fn the_send_window_closes_when_a_full_window_is_unacknowledged() {
        const WINDOW: u32 = 8;
        let (mut driver, _rx) = test_driver(WINDOW).await;
        for sent in 0..WINDOW {
            assert!(driver.link.send_window_open(), "open after {sent} sends");
            send_one(&mut driver, b"x");
        }
        assert!(!driver.link.send_window_open(), "a full window closes it");

        let ack = ControlPacket::Ack(AckPacket {
            ack_number: crate::packet::AckNumber::ZERO,
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            cif: AckCif::Light {
                last_ack_seq: crate::packet::SeqNo::from_wire_masked(driver.link.next_send_seq()),
            },
        });
        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
        ingress(&mut driver, ack_bytes);
        assert!(driver.link.send_window_open(), "the ACK freed the window");
    }

    /// `Driver::run` honours the window: with a peer that never acknowledges
    /// anything, only one flow window of the application's payloads is ever
    /// taken off the hand-off channel; the rest wait in it (where
    /// `SrtSocket::send` would block) instead of growing the send buffer.
    #[tokio::test(start_paused = true)]
    async fn run_stops_taking_app_payloads_once_the_window_is_full() {
        const WINDOW: u32 = 8;
        const QUEUED: usize = 24;
        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(WINDOW).await;
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        let (app_tx, app_rx) =
            mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
        for _ in 0..QUEUED {
            app_tx
                .try_send(Outgoing {
                    payload: Bytes::from(alloc::vec![0u8; 100]),
                    handed_over_at: Instant::now(),
                })
                .expect("queue payload");
        }
        let handle = tokio::spawn(driver.run(app_rx));
        // Well inside the idle timeout, step the driver's clock a while.
        for _ in 0..50 {
            tokio::time::advance(Duration::from_millis(10)).await;
            tokio::task::yield_now().await;
        }
        let still_queued = app_tx.max_capacity() - app_tx.capacity();
        assert_eq!(
            still_queued,
            QUEUED - usize::try_from(WINDOW).unwrap(),
            "the driver must stop draining at one flow window"
        );
        handle.abort();
    }

    fn light_ack(last_ack: u32) -> Vec<u8> {
        let ack = ControlPacket::Ack(AckPacket {
            ack_number: crate::packet::AckNumber::ZERO,
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            cif: AckCif::Light {
                last_ack_seq: crate::packet::SeqNo::from_wire_masked(last_ack),
            },
        });
        let mut bytes = alloc::vec![0u8; ack.serialized_len()];
        ack.serialize_into(&mut bytes).expect("serialize ack");
        bytes
    }

    fn nak_for(seq: u32) -> Vec<u8> {
        use crate::packet::number::SeqNo;
        use crate::packet::{LossListEntry, NakPacket};
        let nak = ControlPacket::Nak(NakPacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            entries: alloc::vec![LossListEntry::Single(
                SeqNo::try_new(seq).expect("fits 31 bits")
            )],
        });
        let mut bytes = alloc::vec![0u8; nak.serialized_len()];
        nak.serialize_into(&mut bytes).expect("serialize nak");
        bytes
    }

    async fn recv_one(sink: &UdpSocket, buf: &mut [u8], deadline: tokio::time::Instant) -> Vec<u8> {
        const RECV_STEP: Duration = Duration::from_millis(10);
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(!remaining.is_zero(), "timed out waiting for a datagram");
            let wait = remaining.min(RECV_STEP);
            match tokio::time::timeout(wait, sink.recv(buf)).await {
                Ok(result) => {
                    let n = result.expect("UDP receive");
                    return buf[..n].to_vec();
                }
                Err(_) if remaining > wait => tokio::time::advance(wait).await,
                Err(_) => panic!("timed out waiting for a datagram"),
            }
        }
    }

    async fn data_seqs(sink: &UdpSocket, buf: &mut [u8], expected: usize) -> Vec<u32> {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
        let mut seqs = Vec::new();
        while seqs.len() < expected {
            let bytes = recv_one(sink, buf, deadline).await;
            if let Ok(SrtPacket::Data(data)) = SrtPacket::parse(&bytes)
                && !data.retransmitted
            {
                seqs.push(data.seq_number);
            }
        }
        seqs
    }

    async fn recv_until(
        sink: &UdpSocket,
        buf: &mut [u8],
        mut found: impl FnMut(&[u8]) -> bool,
    ) -> Vec<Vec<u8>> {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
        let mut packets = Vec::new();
        loop {
            let bytes = recv_one(sink, buf, deadline).await;
            let done = found(&bytes);
            packets.push(bytes);
            if done {
                return packets;
            }
        }
    }

    /// `send` returns once a payload is in the hand-off queue: a close request must not overtake
    /// payloads the caller was told were sent.
    #[tokio::test(start_paused = true)]
    async fn a_close_sends_every_payload_already_queued() {
        const PAYLOADS: u32 = 6;
        const ROUNDS: u32 = 50;
        for round in 0..ROUNDS {
            let (mut driver, _rx, datagrams) = test_driver_with_ingress(8192).await;
            let sink = UdpSocket::bind("127.0.0.1:0").await.expect("sink bind");
            driver.peer_addr = sink.local_addr().expect("sink addr");
            let (close_tx, close_rx) = mpsc::channel(1);
            driver.close_rx = close_rx;
            let (app_tx, app_rx) =
                mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
            for _ in 0..PAYLOADS {
                app_tx
                    .try_send(Outgoing {
                        payload: Bytes::from_static(b"tail"),
                        handed_over_at: Instant::now(),
                    })
                    .expect("queue payload");
            }
            close_tx.send(()).await.expect("close request");
            let handle = tokio::spawn(driver.run(app_rx));
            for _ in 0..20 {
                tokio::time::advance(Duration::from_millis(10)).await;
                tokio::task::yield_now().await;
            }
            let mut buf = [0u8; 2048];
            let seqs = data_seqs(
                &sink,
                &mut buf,
                usize::try_from(PAYLOADS).expect("payload count"),
            )
            .await;
            assert_eq!(
                seqs,
                (0..PAYLOADS).collect::<Vec<_>>(),
                "round {round}: every payload handed to `send` before the close must reach the link"
            );
            datagrams
                .send(Bytes::copy_from_slice(&light_ack(PAYLOADS)))
                .await
                .expect("ACK for every queued payload");
            for _ in 0..5 {
                tokio::time::advance(Duration::from_millis(10)).await;
                tokio::task::yield_now().await;
            }
            tokio::time::timeout(Duration::from_secs(1), handle)
                .await
                .expect("close must finish")
                .expect("driver task");
        }
    }

    /// A tail DATA packet is dropped, then NAKed twice inside the retransmit rate-limit window.
    /// No further ingress arrives: the drain must wake on the link's own keepalive/retransmit
    /// deadline, recover the packet, and only then send SHUTDOWN.
    #[tokio::test(start_paused = true)]
    async fn a_close_keeps_the_link_deadlines_while_draining_a_dropped_tail() {
        let (mut driver, _rx, datagrams) = test_driver_with_ingress(8192).await;
        let sink = UdpSocket::bind("127.0.0.1:0").await.expect("sink bind");
        driver.peer_addr = sink.local_addr().expect("sink addr");
        driver.close_linger = CloseTimings::new(Duration::from_secs(5));
        let (close_tx, close_rx) = mpsc::channel(1);
        driver.close_rx = close_rx;
        let (app_tx, app_rx) =
            mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
        for payload in [b"first".as_slice(), b"tail".as_slice()] {
            app_tx
                .try_send(Outgoing {
                    payload: Bytes::copy_from_slice(payload),
                    handed_over_at: Instant::now(),
                })
                .expect("queue payload");
        }
        let handle = tokio::spawn(driver.run(app_rx));
        for _ in 0..20 {
            tokio::time::advance(Duration::from_millis(10)).await;
            tokio::task::yield_now().await;
        }
        let mut buf = [0u8; 2048];
        let first = data_seqs(&sink, &mut buf, 2).await;
        assert_eq!(first, vec![0, 1], "the tail DATA was sent once");

        datagrams
            .send(Bytes::copy_from_slice(&light_ack(1)))
            .await
            .expect("ACK for first packet");
        for _ in 0..5 {
            tokio::task::yield_now().await;
        }
        for _ in 0..2 {
            datagrams
                .send(Bytes::from(nak_for(1)))
                .await
                .expect("NAK for dropped tail");
            tokio::task::yield_now().await;
        }
        close_tx.send(()).await.expect("close request");
        for _ in 0..20 {
            tokio::time::advance(Duration::from_millis(10)).await;
            tokio::task::yield_now().await;
        }
        recv_until(&sink, &mut buf, |bytes| {
            matches!(
                SrtPacket::parse(bytes),
                Ok(SrtPacket::Data(data)) if data.retransmitted && data.seq_number == 1
            )
        })
        .await;

        for _ in 0..150 {
            tokio::time::advance(Duration::from_millis(10)).await;
            tokio::task::yield_now().await;
        }
        let mut recovered = false;
        let mut shutdown = false;
        let packets = recv_until(&sink, &mut buf, |bytes| {
            match SrtPacket::parse(bytes) {
                Ok(SrtPacket::Data(data)) if data.retransmitted && data.seq_number == 1 => {
                    recovered = true;
                }
                Ok(SrtPacket::Control(ControlPacket::Shutdown(_))) => shutdown = true,
                _ => {}
            }
            recovered || shutdown
        })
        .await;
        assert!(
            packets.iter().any(|bytes| matches!(
                SrtPacket::parse(bytes),
                Ok(SrtPacket::Data(data)) if data.retransmitted && data.seq_number == 1
            )),
            "the dropped tail must be retransmitted during the drain"
        );
        assert!(!shutdown, "SHUTDOWN must wait for the recovered tail's ACK");

        datagrams
            .send(Bytes::copy_from_slice(&light_ack(2)))
            .await
            .expect("ACK for recovered tail");
        tokio::time::advance(Duration::from_millis(10)).await;
        tokio::time::timeout(Duration::from_secs(1), handle)
            .await
            .expect("close must finish after the recovered tail is ACKed")
            .expect("driver task");
        recv_until(&sink, &mut buf, |bytes| {
            matches!(
                SrtPacket::parse(bytes),
                Ok(SrtPacket::Control(ControlPacket::Shutdown(_)))
            )
        })
        .await;
    }

    /// An exit during a drain is damage, not a silent truncation.
    #[tokio::test(start_paused = true)]
    async fn a_close_that_loses_ingress_reports_the_unacknowledged_tail() {
        let (mut driver, _rx, datagrams) = test_driver_with_ingress(8192).await;
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        driver.close_linger = CloseTimings::new(Duration::from_secs(5));
        let damage = Arc::clone(&driver.close_damage);
        let (close_tx, close_rx) = mpsc::channel(1);
        driver.close_rx = close_rx;
        let (app_tx, app_rx) =
            mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
        app_tx
            .try_send(Outgoing {
                payload: Bytes::from_static(b"tail"),
                handed_over_at: Instant::now(),
            })
            .expect("queue payload");
        let handle = tokio::spawn(driver.run(app_rx));
        for _ in 0..5 {
            tokio::task::yield_now().await;
        }
        close_tx.send(()).await.expect("close request");
        drop(datagrams);
        tokio::time::advance(Duration::from_millis(10)).await;
        tokio::time::timeout(Duration::from_secs(1), handle)
            .await
            .expect("lost ingress must end the close")
            .expect("driver task");
        let report = damage
            .lock()
            .expect("damage slot")
            .take()
            .expect("lost ingress during a close is reported as damage");
        assert!(report.what().contains("unacknowledged"), "{report:?}");
    }

    /// The caller's linger bound is final: after it expires the close sends SHUTDOWN and reports
    /// the unacknowledged packets as damage instead of losing them silently.
    #[tokio::test(start_paused = true)]
    async fn a_close_that_expires_reports_damage() {
        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(8192).await;
        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
        let linger = Duration::from_millis(100);
        driver.close_linger = CloseTimings::new(linger);
        let damage = Arc::clone(&driver.close_damage);
        let (close_tx, close_rx) = mpsc::channel(1);
        driver.close_rx = close_rx;
        let (app_tx, app_rx) =
            mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
        app_tx
            .try_send(Outgoing {
                payload: Bytes::from_static(b"tail"),
                handed_over_at: Instant::now(),
            })
            .expect("queue payload");
        let handle = tokio::spawn(driver.run(app_rx));
        for _ in 0..5 {
            tokio::task::yield_now().await;
        }
        close_tx.send(()).await.expect("close request");

        tokio::time::advance(linger / 2).await;
        tokio::task::yield_now().await;
        assert!(!handle.is_finished(), "the bound has not expired yet");

        tokio::time::advance(linger).await;
        tokio::task::yield_now().await;
        assert!(handle.is_finished(), "the linger bound must end the close");
        tokio::time::timeout(Duration::from_secs(1), handle)
            .await
            .expect("expiry must end the close")
            .expect("driver task");
        let report = damage
            .lock()
            .expect("damage slot")
            .take()
            .expect("expiry is reported as damage");
        assert_eq!(
            report.kind(),
            broadcast_core::damage::DamageKind::MediaUnitDropped
        );
        assert!(report.what().contains("unacknowledged"), "{report:?}");
    }

    /// A close request pending when the peer-idle exit is chosen must still arm the drain: the
    /// unacknowledged tail is reported and the peer receives SHUTDOWN.
    #[tokio::test(start_paused = true)]
    async fn a_close_pending_at_peer_idle_reports_damage_and_shuts_down() {
        const IDLE: Duration = Duration::from_millis(10);
        const ROUNDS: u32 = 20;
        for round in 0..ROUNDS {
            let (mut driver, _rx, _datagrams) = test_driver_with_flags(8192, true, 0, IDLE).await;
            let sink = UdpSocket::bind("127.0.0.1:0").await.expect("sink bind");
            driver.peer_addr = sink.local_addr().expect("sink addr");
            driver.close_linger = CloseTimings::new(Duration::from_secs(5));
            let report_slot = Arc::clone(&driver.close_damage);
            let (close_tx, close_rx) = mpsc::channel(1);
            driver.close_rx = close_rx;
            let (app_tx, app_rx) =
                mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
            app_tx
                .try_send(Outgoing {
                    payload: Bytes::from_static(b"tail"),
                    handed_over_at: Instant::now(),
                })
                .expect("queue payload");
            close_tx.send(()).await.expect("close request");
            let handle = tokio::spawn(driver.run(app_rx));
            tokio::time::advance(IDLE * 2).await;
            tokio::time::timeout(Duration::from_secs(1), handle)
                .await
                .expect("close must finish")
                .expect("driver task");
            assert!(
                report_slot.lock().expect("damage slot").is_some(),
                "round {round}: pending close lost the unacknowledged tail"
            );
            let mut buf = [0u8; 2048];
            recv_until(&sink, &mut buf, |bytes| {
                matches!(
                    SrtPacket::parse(bytes),
                    Ok(SrtPacket::Control(ControlPacket::Shutdown(_)))
                )
            })
            .await;
        }
    }

    // -----------------------------------------------------------------------
    // r08-SRT-W12 — typed errors
    // -----------------------------------------------------------------------

    /// A datagram that is not an SRT packet is reported with its stage and
    /// the underlying codec error, not flattened to a generic invalid field.
    #[tokio::test]
    async fn listener_parse_failure_keeps_its_stage_and_cause() {
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let err = listener
            .handle_datagram(peer_addr(), &[0u8; 4])
            .expect_err("a 4-byte datagram is not an SRT packet");
        let Error::Handshake { stage, source } = err else {
            panic!("expected Error::Handshake, got {err:?}");
        };
        assert_eq!(stage, "parse");
        assert!(
            matches!(
                *source,
                Error::BufferTooShort(BufferTooShort { have: 4, .. })
            ),
            "the cause must be preserved, got {source:?}"
        );
    }

    /// A rejection the engine produces surfaces as `Error::Rejected` with the
    /// reason — a feed after the handshake already finished is the engine's
    /// own out-of-sequence error, wrapped with its stage.
    #[tokio::test]
    async fn listener_feed_failure_is_wrapped_with_the_engine_error() {
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let conclusion = listener_conclusion(&mut listener, src, 7);
        listener
            .handle_datagram(src, &conclusion)
            .expect("a cookie-validated conclusion completes the handshake");
        // A CONCLUSION from a different Caller Socket ID after this one
        // connected is out of sequence for the engine.
        let err = listener
            .handle_datagram(src, &conclusion_bytes(9, 0))
            .expect_err("a stray CONCLUSION on a connected entry");
        let Error::Handshake { stage, source } = err else {
            panic!("expected Error::Handshake, got {err:?}");
        };
        assert_eq!(stage, "listener feed");
        assert!(matches!(*source, Error::HandshakeOutOfSequence { .. }));
    }

    // -----------------------------------------------------------------------
    // #1134 — a poisoned lock must not cascade
    // -----------------------------------------------------------------------

    /// A connection task that panics while holding the route table's lock
    /// poisons it. Dropping a `RouteCleanup` (it runs in `Drop`, including
    /// while unwinding) and the routing pump's lookups must keep working, not
    /// panic a second time.
    #[test]
    fn a_poisoned_route_table_does_not_panic_the_cleanup_guard() {
        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
        {
            let routes = Arc::clone(&routes);
            let panicked = std::thread::spawn(move || {
                let _held = routes.lock().expect("lock");
                panic!("a connection task panicked holding the route table lock");
            })
            .join();
            assert!(panicked.is_err());
        }
        assert!(routes.is_poisoned(), "the lock must really be poisoned");

        let (tx, _rx) = mpsc::channel(1);
        lock(&routes).insert(
            7,
            RouteEntry {
                addr: peer_addr(),
                tx,
                stats: Arc::new(Counters::default()),
            },
        );
        assert_eq!(lock(&routes).len(), 1);
        drop(RouteCleanup(Some((7, Arc::clone(&routes)))));
        assert!(
            lock(&routes).is_empty(),
            "the guard must still remove its entry"
        );
    }

    // -----------------------------------------------------------------------
    // r08-SRT-W9 — the time base is seeded from the handshake
    // -----------------------------------------------------------------------

    /// `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP` with `T_NOW = 0` at the
    /// epoch is minus the peer's handshake timestamp (rule 12).
    #[test]
    fn the_time_base_is_minus_the_peer_handshake_timestamp() {
        assert_eq!(tsbpd_time_base_from(0), 0);
        assert_eq!(tsbpd_time_base_from(3_000_000), -3_000_000);
        assert_eq!(tsbpd_time_base_from(u32::MAX), -i64::from(u32::MAX));
    }

    /// A peer whose clock already reads 30 s when the handshake completes
    /// (its first data packet carries `Timestamp` ~30 s) is delivered one
    /// latency after arrival — not 30 s later, which is what a hard-coded
    /// zero base did (the packet's play time was `0 + 30 s + latency`).
    #[tokio::test(start_paused = true)]
    async fn a_peer_far_into_its_own_clock_is_not_delayed_by_its_timestamp() {
        const PEER_CLOCK_US: u32 = 30_000_000;
        let (mut driver, mut rx, _datagrams) =
            test_driver_with_flags(8192, true, PEER_CLOCK_US, PEER_IDLE_TIMEOUT).await;
        ingress(&mut driver, data_bytes(0, PEER_CLOCK_US, b"first"));
        assert!(drain_deliveries(&mut rx).is_empty(), "not due on arrival");
        tokio::time::advance(Duration::from_millis(LATENCY_MS)).await;
        tick(&mut driver).await;
        assert_eq!(
            drain_deliveries(&mut rx),
            vec![bytes::Bytes::from_static(b"first")],
            "delivered one latency after arrival"
        );
    }

    // -----------------------------------------------------------------------
    // Pacing schedule (issue #1061), deterministically
    // -----------------------------------------------------------------------

    /// Under a paused clock the token-bucket schedule is exact: the first DATA
    /// packet goes at once, the next not a nanosecond before one pacing period
    /// later, and a burst after an idle gap is not penalized (it sends
    /// immediately, then resumes the period).
    #[tokio::test(start_paused = true)]
    async fn data_leaves_one_packet_per_pacing_period() {
        let (mut driver, _rx) = test_driver(8192).await;
        const BACKLOG: usize = crate::test_support::ARQ_BOUNDS.sender.pacing_burst_packets * 3;
        for _ in 0..BACKLOG {
            send_one(&mut driver, &[0u8; 1316]);
        }
        let mut clock = driver.link_now(Instant::now());
        let send = |driver: &mut Driver, clock: LinkInstant| {
            let mut sent = Vec::new();
            driver.link.flush(clock, &mut sent);
            data_count(&sent)
        };
        let burst = send(&mut driver, clock);
        assert!(burst > 0, "the first DATA packet leaves at once");
        let mut sent_total = burst;
        while sent_total < BACKLOG {
            // Every wake is now one pacing period after the previous send, so each
            // releases one packet (a late wake would claim the burst it is allowed).
            clock = clock.saturating_add(driver.link.pacing_period());
            let due = send(&mut driver, clock);
            assert!(due > 0, "the pacing slot at {clock:?} releases packets");
            sent_total += due;
        }
        assert!(sent_total >= BACKLOG, "the whole backlog leaves, paced");
    }

    /// r08-SRT-O2: a retransmission feeds LiveCC the packet's *payload* length
    /// (the datagram less its fixed header), exactly as a first transmission
    /// does — read from the length instead of re-parsing the packet.
    #[tokio::test(start_paused = true)]
    async fn a_retransmission_is_accounted_by_its_payload_length() {
        use crate::packet::number::SeqNo;
        use crate::packet::{LossListEntry, NakPacket};
        let (mut driver, _rx) = test_driver(8192).await;
        send_one(&mut driver, &[0u8; 1000]); // seq 0
        let nak = ControlPacket::Nak(NakPacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            entries: alloc::vec![LossListEntry::Single(
                SeqNo::try_new(0).expect("fits 31 bits")
            )],
        });
        let mut bytes = alloc::vec![0u8; nak.serialized_len()];
        nak.serialize_into(&mut bytes).expect("serialize nak");
        ingress(&mut driver, bytes);
        tick(&mut driver).await;
        assert_eq!(
            data_sent(&pending(&mut driver)).len(),
            2,
            "the packet and its retransmit"
        );
        // The live congestion controller's own mean, after the same two samples.
        let mut reference = crate::livecc::LiveCC::default();
        reference.on_data_packet(1000);
        reference.on_data_packet(1000);
        assert_eq!(
            driver.link.average_payload_size(),
            reference.avg_payload_size(),
            "the retransmit is accounted by its payload length, not the header"
        );
    }

    /// #2819: one NAK naming the whole send buffer cannot queue more
    /// retransmissions than the negotiated flow window, and a second NAK
    /// before the queue drains adds no duplicates.
    #[tokio::test(start_paused = true)]
    async fn a_nak_naming_the_whole_buffer_is_capped_at_the_flow_window() {
        use crate::packet::number::SeqNo;
        use crate::packet::{LossListEntry, NakPacket};
        const WINDOW: u32 = 4;
        const BUFFERED: u32 = 8;
        let (mut driver, _rx) = test_driver(WINDOW).await;
        let nak = || {
            let nak = ControlPacket::Nak(NakPacket {
                timestamp: crate::packet::SrtTimestamp::ZERO,
                dest_socket_id: crate::packet::SocketId::from_wire(1),
                entries: alloc::vec![LossListEntry::Range(
                    SeqNo::try_new(0).expect("fits 31 bits"),
                    SeqNo::try_new(BUFFERED - 1).expect("fits 31 bits"),
                )],
            });
            let mut bytes = alloc::vec![0u8; nak.serialized_len()];
            nak.serialize_into(&mut bytes).expect("serialize nak");
            bytes
        };
        let offered = |driver: &mut Driver| {
            let mut sent = Vec::new();
            let now = driver.link_now(Instant::now());
            driver.link.flush(now, &mut sent);
            data_sent(&sent)
                .iter()
                .map(|d| data_of(d).retransmitted)
                .collect::<Vec<_>>()
        };

        for _ in 0..BUFFERED {
            send_one(&mut driver, &[0u8; 100]);
        }
        // The first transmissions are counting down their pacing slots.
        let first = pending(&mut driver);
        assert_eq!(data_sent(&first).len(), BUFFERED as usize);
        // Let their pacing slots pass, so a retransmission is the only DATA left queued.
        let epoch = driver.link_now(Instant::now());
        for step in 1..=BUFFERED {
            let mut sent = Vec::new();
            driver.link.flush(
                epoch.saturating_add(Duration::from_micros(u64::from(step))),
                &mut sent,
            );
        }
        assert!(data_sent(&pending(&mut driver)).is_empty());

        // A NAK naming the whole send buffer makes the sender offer every packet.
        ingress(&mut driver, nak());
        tick(&mut driver).await;

        // A second NAK before the queue drains adds no duplicate: every sequence
        // number it names is already marked queued, so the outbound queue holds at
        // most one full flow window of packets (it holds one burst of the paced
        // first transmissions here), and never two copies of any retransmission.
        ingress(&mut driver, nak());
        tick(&mut driver).await;
        let sent = offered(&mut driver);
        assert!(
            sent.len() <= usize::try_from(WINDOW).expect("fits"),
            "a repeated NAK must not queue a second copy: at most one flow \
             window of retransmissions leaves, got {}",
            sent.len()
        );
        assert!(
            sent.iter().all(|&retransmitted| retransmitted),
            "everything queued is a retransmission: {sent:?}"
        );
    }

    /// When the application handle is gone and the driver ends cooperatively
    /// (not by abort), it still tells the peer it is leaving (§3.2.7). (Real
    /// clock, bounded real waits: a paused clock would auto-advance past the
    /// `recv` timeout before the loopback datagram is delivered.)
    #[tokio::test]
    async fn a_driver_ending_because_its_handle_is_gone_sends_shutdown() {
        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(8192).await;
        driver.peer_addr = peer.local_addr().unwrap();
        let (app_tx, app_rx) =
            mpsc::channel::<Outgoing>(crate::test_support::SEND_CHANNEL_CAPACITY.get());
        let handle = tokio::spawn(driver.run(app_rx));
        drop(app_tx);
        tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("the driver must end once its handle is gone")
            .expect("join");

        let mut buf = [0u8; 2048];
        let shutdown = loop {
            let n = tokio::time::timeout(Duration::from_secs(5), peer.recv(&mut buf))
                .await
                .expect("no SHUTDOWN reached the peer")
                .expect("recv");
            if let Ok(SrtPacket::Control(ControlPacket::Shutdown(s))) = SrtPacket::parse(&buf[..n])
            {
                break s;
            }
        };
        assert_eq!(
            shutdown.dest_socket_id,
            crate::packet::SocketId::from_wire(1),
            "addressed to the peer's socket id"
        );
    }

    /// A hostile `retransmit_after` must not make the handshake timer's
    /// period zero (which would panic the connect).
    #[tokio::test]
    async fn an_absurd_retransmit_period_does_not_panic_the_connect() {
        let silent = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        for step in [Duration::ZERO, Duration::from_micros(1), Duration::MAX] {
            let config = HandshakeConfig {
                retransmit_after: step,
                ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
            };
            // Nobody answers; the point is only that it neither panics nor
            // fails immediately.
            let outcome = tokio::time::timeout(
                Duration::from_millis(150),
                SrtSocket::connect(
                    silent.local_addr().unwrap(),
                    SrtSocketConfig::new(
                        config,
                        crate::test_support::io_config(),
                        UdpOptions::new(),
                    ),
                ),
            )
            .await;
            assert!(
                outcome.is_err(),
                "step={step:?}: still waiting for the peer"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Stale sequence numbers, and the negotiated TLPKTDROP flag
    // -----------------------------------------------------------------------

    /// Packets behind the delivery cursor are never staged: with the cursor at
    /// 3, a hundred thousand distinct stale sequence numbers (each stamped
    /// with a far-future timestamp, so TSBPD would hold them) leave `staged`
    /// empty and are counted as late. They used to be staged, ignored by
    /// TSBPD and never removed.
    #[tokio::test(start_paused = true)]
    async fn stale_sequence_numbers_are_never_staged() {
        let (mut driver, mut rx) = test_driver(8192).await;
        for seq in 0..3u32 {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        tokio::time::advance(Duration::from_millis(130)).await;
        tick(&mut driver).await;
        assert_eq!(drain_deliveries(&mut rx).len(), 3);

        const STALE: u32 = 100_000;
        for back in 1..=STALE {
            // 2^31 - back is `back` behind the cursor at 0..3 in circular order.
            let seq = (1u32 << 31) - back;
            ingress(&mut driver, data_bytes(seq, u32::MAX, b"x"));
        }
        assert_eq!(driver.link.staged_len(), 0, "no stale packet may be staged");
        // A duplicate of something already delivered is late too.
        ingress(&mut driver, data_bytes(1, 0, b"dup"));
        assert_eq!(driver.link.staged_len(), 0);
    }

    /// Without a negotiated TLPKTDROP the receiver never skips a gap: it waits
    /// for the retransmission, delivers nothing past the hole however long it
    /// takes, and never moves its ack point past it (which would tell the
    /// sender a packet that never arrived was received).
    #[tokio::test(start_paused = true)]
    async fn without_negotiated_tlpktdrop_a_gap_is_waited_out_not_skipped() {
        let (mut driver, mut rx, _datagrams) =
            test_driver_with_flags(8192, false, 0, PEER_IDLE_TIMEOUT).await;
        for seq in [0u32, 2, 3] {
            ingress(
                &mut driver,
                data_bytes(seq, 0, &[u8::try_from(seq).unwrap()]),
            );
        }
        // Far beyond the latency (and the too-late threshold).
        for _ in 0..50 {
            tokio::time::advance(Duration::from_millis(100)).await;
            tick(&mut driver).await;
        }
        let delivered = drain_deliveries(&mut rx);
        assert_eq!(
            delivered.iter().map(|p| p[0]).collect::<Vec<_>>(),
            vec![0],
            "nothing may pass the hole"
        );
        // Never ACK past a gap: the cumulative ack point stays at the missing packet.
        assert_eq!(
            driver.link.ack_point(),
            1,
            "never ACK past a gap (its ACK carries the delta, so no packet past it is ACKed)"
        );
        assert_eq!(driver.link.loss_list_len(), 1, "still asking for seq 1");

        // The retransmission arrives, carrying its own (late) timestamp, so the
        // scheduler releases it at once — together with the packet it unblocked.
        // The third packet followed the successful first two, so they share a
        // play time.
        ingress(&mut driver, data_bytes(1, 0, &[1]));
        let staged = driver.link.staged_len();
        let ack = driver.link.ack_point();
        assert!(
            staged > 0 || ack > 1,
            "the retransmission must close the gap (staged {staged}, ack point {ack})"
        );
    }

    /// The negotiated flag, not a constant, decides: a connection negotiated
    /// with TLPKTDROP skips (the live-mode tests above), one without does not —
    /// pinned through the link's own configuration.
    #[tokio::test]
    async fn the_driver_honours_the_negotiated_tlpktdrop_flag() {
        for negotiated in [true, false] {
            let (driver, _rx, _datagrams) =
                test_driver_with_flags(8192, negotiated, 0, PEER_IDLE_TIMEOUT).await;
            assert_eq!(driver.link.tlpktdrop_enabled(), negotiated);
        }
    }

    // -----------------------------------------------------------------------
    // #1142 / O5 — the cookie key is secret, 128 bits, and rotates
    // -----------------------------------------------------------------------

    /// `{:?}` of a listener (and of its key holder) never prints the cookie
    /// key, in decimal or hex.
    #[tokio::test]
    async fn listener_debug_never_prints_the_cookie_key() {
        let listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let key = listener.cookie_keys.current();
        assert!(
            key > u128::from(u64::MAX),
            "a 128-bit key, not a 64-bit one"
        );
        for dump in [
            alloc::format!("{listener:?}"),
            alloc::format!("{listener:#?}"),
            alloc::format!("{listener:x?}"),
        ] {
            for needle in [
                alloc::format!("{key}"),
                alloc::format!("{key:x}"),
                alloc::format!("{:x}", key >> 64),
            ] {
                assert!(!dump.contains(&needle), "key leaked as {needle:?}: {dump}");
            }
            assert!(dump.contains("redacted"), "{dump}");
        }
    }

    fn induction_cookie(listener: &mut ListenerCore, src: std::net::SocketAddr) -> u32 {
        listener
            .handle_datagram(src, &induction_bytes(7))
            .expect("induction");
        let response = listener
            .outbound_queue
            .get_mut(&src)
            .and_then(VecDeque::pop_back)
            .expect("an INDUCTION response");
        match SrtPacket::parse(&response).expect("parse") {
            SrtPacket::Control(ControlPacket::Handshake(hp)) => hp.syn_cookie,
            other => panic!("expected a handshake, got {other:?}"),
        }
    }

    /// The key is replaced exactly once a minute is up; cookies issued after
    /// differ from those before for the same peer.
    #[tokio::test]
    async fn the_cookie_key_rotates_every_minute() {
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let t0 = listener.cookie_keys.drawn_at;
        let first = listener.cookie_keys.current();

        assert!(!listener.cookie_keys.rotate_if_due(
            t0 + crate::test_support::DEFAULT_COOKIE_KEY_ROTATION - Duration::from_millis(1)
        ));
        assert_eq!(listener.cookie_keys.current(), first, "not yet due");

        let src = peer_addr();
        let before = induction_cookie(&mut listener, src);
        listener.pending.clear();
        assert!(
            listener
                .cookie_keys
                .rotate_if_due(t0 + crate::test_support::DEFAULT_COOKIE_KEY_ROTATION)
        );
        assert_ne!(
            listener.cookie_keys.current(),
            first,
            "a fresh key was drawn"
        );
        assert_eq!(
            listener.cookie_keys.drawn_at,
            t0 + crate::test_support::DEFAULT_COOKIE_KEY_ROTATION,
            "the next rotation is measured from this one"
        );
        let after = induction_cookie(&mut listener, src);
        assert_ne!(
            before, after,
            "the same peer gets a different cookie after rotation"
        );
    }

    /// A handshake begun under the previous key still completes after the key
    /// rotates: its pending entry keeps the cookie it was issued.
    #[tokio::test]
    async fn a_handshake_begun_before_a_rotation_still_completes() {
        use crate::caller::CallerHandshake;
        let mut listener = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let mut caller = CallerHandshake::new(
            0x0000_0777,
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
        );
        let induction = caller.start().expect("start");
        listener
            .handle_datagram(src, &induction)
            .expect("induction");
        let response = listener
            .outbound_queue
            .get_mut(&src)
            .and_then(VecDeque::pop_back)
            .expect("response");

        let t0 = listener.cookie_keys.drawn_at;
        assert!(
            listener
                .cookie_keys
                .rotate_if_due(t0 + crate::test_support::DEFAULT_COOKIE_KEY_ROTATION)
        );

        let conclusion = caller
            .feed_bytes(&response)
            .expect("feed")
            .into_iter()
            .find_map(|o| match o {
                HandshakeOutput::Send(b) => Some(b),
                _ => None,
            })
            .expect("CONCLUSION");
        listener
            .handle_datagram(src, &conclusion)
            .expect("the CONCLUSION must be accepted across the rotation");
        assert!(
            listener.pending[&src].params.is_some(),
            "the handshake must have completed"
        );
        // The connection epoch is when the CONCLUSION arrived, and a repeat
        // does not move it.
        let concluded = listener.pending[&src].concluded_at.expect("recorded");
        listener
            .handle_datagram(src, &conclusion)
            .expect("a repeated CONCLUSION");
        assert_eq!(listener.pending[&src].concluded_at, Some(concluded));
    }

    fn test_life() -> Arc<ListenerLife> {
        Arc::new(ListenerLife {
            cancel: CancellationToken::new(),
            tasks: TaskTracker::new(),
        })
    }

    fn conclusion_with_encryption(socket_id: u32, encryption_field: EncryptionField) -> Vec<u8> {
        let hp = HandshakePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
            encryption_field,
            extension_field: HandshakeExtensionFlags::new(0),
            initial_seq_number: 0,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: crate::packet::HandshakeType::Conclusion,
            srt_socket_id: socket_id,
            syn_cookie: 0,
            peer_ip: [0; 4],
            extensions: HandshakeExtensions(Vec::new()),
        };
        let pkt = ControlPacket::Handshake(hp);
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        pkt.serialize_into(&mut buf).expect("serialize conclusion");
        buf
    }

    fn conclusion_with_extension_flags(
        socket_id: u32,
        extension_field: HandshakeExtensionFlags,
    ) -> Vec<u8> {
        let hp = HandshakePacket {
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
            encryption_field: EncryptionField::NoEncryption,
            extension_field,
            initial_seq_number: 0,
            mtu: 1500,
            max_flow_window_size: 8192,
            handshake_type: crate::packet::HandshakeType::Conclusion,
            srt_socket_id: socket_id,
            syn_cookie: 0,
            peer_ip: [0; 4],
            extensions: HandshakeExtensions(Vec::new()),
        };
        let pkt = ControlPacket::Handshake(hp);
        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
        pkt.serialize_into(&mut buf).expect("serialize conclusion");
        buf
    }

    /// §4.3.1.1: an INDUCTION reply cookie is bound to the source address —
    /// a CONCLUSION replayed from another port validates nothing.
    #[tokio::test]
    async fn cookie_replay_from_another_source_is_not_accepted() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src_a: std::net::SocketAddr = "127.0.0.1:40001".parse().unwrap();
        let src_b: std::net::SocketAddr = "127.0.0.1:40002".parse().unwrap();
        let conclusion = listener_conclusion(&mut core, src_a, 7);
        core.outbound_queue.clear();

        core.handle_datagram(src_b, &conclusion)
            .expect("a replayed conclusion is ignored");
        assert!(
            core.pending.is_empty(),
            "a cookie issued to another source must allocate no state"
        );
        assert!(
            core.outbound_queue.get(&src_b).is_none_or(|q| q.is_empty()),
            "no response may go to the replayer"
        );

        core.handle_datagram(src_a, &conclusion)
            .expect("the genuine source connects");
        assert_eq!(
            core.pending[&src_a].handshake.state(),
            ListenerHandshakeState::Connected
        );
    }

    /// A Listener without crypto refuses an encrypted INDUCTION with a
    /// well-formed REJ_UNSECURE handshake packet.
    #[tokio::test]
    async fn listener_refuses_an_encrypted_request_with_a_rejection_packet() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let caller_id = 0x0000_0777;
        core.handle_datagram(
            src,
            &conclusion_with_encryption(caller_id, EncryptionField::Aes128),
        )
        .expect("encrypted conclusion");
        let answer = core
            .outbound_queue
            .get(&src)
            .and_then(|queue| queue.back())
            .cloned()
            .expect("a rejection answer");
        let ControlPacket::Handshake(hp) = ControlPacket::parse(&answer).expect("parse") else {
            panic!("expected handshake");
        };
        assert_eq!(
            hp.handshake_type,
            RejectionReason::Unsecure.to_handshake_type()
        );
        assert_eq!(hp.srt_socket_id, 0);
        assert_eq!(
            hp.dest_socket_id,
            crate::packet::SocketId::from_wire(caller_id)
        );
        assert_eq!(answer.len(), 64, "SRT header (16) + fixed CIF (48)");
        assert!(core.pending.is_empty());
    }

    /// A CONCLUSION carrying the KMREQ extension bit is refused even when its
    /// Encryption Field is zero.
    #[tokio::test]
    async fn listener_refuses_a_kmreq_flag_on_a_conclusion() {
        use crate::packet::handshake::HS_EXT_FLAG_KMREQ;
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let caller_id = 0x0000_0778;
        core.handle_datagram(
            src,
            &conclusion_with_extension_flags(
                caller_id,
                HandshakeExtensionFlags::new(HS_EXT_FLAG_KMREQ),
            ),
        )
        .expect("conclusion");
        let answer = core
            .outbound_queue
            .get(&src)
            .and_then(|queue| queue.back())
            .cloned()
            .expect("a rejection answer");
        let ControlPacket::Handshake(hp) = ControlPacket::parse(&answer).expect("parse") else {
            panic!("expected handshake");
        };
        assert_eq!(
            hp.handshake_type,
            RejectionReason::Unsecure.to_handshake_type()
        );
        assert_eq!(
            hp.dest_socket_id,
            crate::packet::SocketId::from_wire(caller_id)
        );
    }

    /// The remembered CONCLUSION answer is answered while fresh and dropped at
    /// exactly the recent-accept TTL.
    #[tokio::test(start_paused = true)]
    async fn remembered_conclusion_answer_expires_at_the_ttl() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let src = peer_addr();
        let response = alloc::vec![1u8, 2, 3, 4];
        core.remember_accept(
            src,
            RecentAccept {
                peer_socket_id: 7,
                response: response.clone(),
                accepted_at: Instant::now(),
            },
        );
        core.handle_datagram(src, &conclusion_bytes(7, 123))
            .expect("repeat");
        assert_eq!(
            core.outbound_queue.get(&src).and_then(|q| q.back()),
            Some(&response)
        );
        core.outbound_queue.clear();

        core.recent_accepts
            .get_mut(&src)
            .expect("entry")
            .accepted_at = Instant::now() - crate::test_support::DEFAULT_RECENT_ACCEPT_TTL;
        core.handle_datagram(src, &conclusion_bytes(7, 123))
            .expect("expired repeat");
        assert!(
            core.outbound_queue.get(&src).is_none_or(|q| q.is_empty()),
            "a cached answer must not outlive its TTL"
        );
    }

    /// The pending-handshake tick re-sends an unanswered INDUCTION response.
    #[tokio::test]
    async fn tick_pending_retransmits_a_pending_handshake() {
        let config = HandshakeConfig {
            retransmit_after: Duration::from_millis(10),
            max_retries: 5,
            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
        };
        let mut core = test_core(config.clone()).await;
        let src = peer_addr();
        let mut handshake = ListenerHandshake::new(0x1234, 0xCAFE, config);
        let outputs = handshake
            .feed_bytes(&induction_bytes(7))
            .expect("induction");
        let expected = outputs
            .into_iter()
            .find_map(|o| match o {
                HandshakeOutput::Send(bytes) => Some(bytes),
                _ => None,
            })
            .expect("an INDUCTION response");
        core.pending.insert(
            src,
            PendingListener {
                handshake,
                params: None,
                peer_initial_seq: 0,
                peer_timestamp_us: 0,
                concluded_at: None,
                created_at: Instant::now(),
                last_response: None,
                our_initial_seq: 0,
            },
        );
        core.outbound_queue.clear();
        core.tick_pending();
        assert_eq!(
            core.outbound_queue.get(&src).and_then(|q| q.back()),
            Some(&expected),
            "the tick must queue the retransmit"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn tick_pending_reaps_expired_recent_accepts() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let stale = peer_addr();
        let fresh: std::net::SocketAddr = "10.0.0.2:9999".parse().unwrap();
        core.recent_accepts.insert(
            stale,
            RecentAccept {
                peer_socket_id: 1,
                response: alloc::vec![1],
                accepted_at: Instant::now() - crate::test_support::DEFAULT_RECENT_ACCEPT_TTL,
            },
        );
        core.recent_accepts.insert(
            fresh,
            RecentAccept {
                peer_socket_id: 2,
                response: alloc::vec![2],
                accepted_at: Instant::now(),
            },
        );
        core.tick_pending();
        assert!(!core.recent_accepts.contains_key(&stale));
        assert!(core.recent_accepts.contains_key(&fresh));
    }

    #[tokio::test(start_paused = true)]
    async fn remember_accept_reaps_expired_entries() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let stale = peer_addr();
        core.recent_accepts.insert(
            stale,
            RecentAccept {
                peer_socket_id: 1,
                response: alloc::vec![1],
                accepted_at: Instant::now() - crate::test_support::DEFAULT_RECENT_ACCEPT_TTL,
            },
        );
        let fresh: std::net::SocketAddr = "10.0.0.2:9999".parse().unwrap();
        core.remember_accept(
            fresh,
            RecentAccept {
                peer_socket_id: 2,
                response: alloc::vec![2],
                accepted_at: Instant::now(),
            },
        );
        assert!(!core.recent_accepts.contains_key(&stale));
        assert!(core.recent_accepts.contains_key(&fresh));
    }

    /// `flush_all` actually drains every queued per-peer datagram.
    #[tokio::test]
    async fn flush_all_sends_every_queued_datagram() {
        let (mut core, _tx, _accepted) = test_core_with_channels(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let peer_addr = peer.local_addr().unwrap();
        core.outbound_queue
            .entry(peer_addr)
            .or_default()
            .push_back(alloc::vec![1u8, 2, 3]);
        core.flush_all().await.expect("flush");
        assert!(core.outbound_queue.values().all(|q| q.is_empty()));
        let mut buf = [0u8; 8];
        let (n, _) = tokio::time::timeout(Duration::from_secs(2), peer.recv_from(&mut buf))
            .await
            .expect("no datagram")
            .expect("recv_from");
        assert_eq!(&buf[..n], &[1, 2, 3]);
    }

    /// `drain_completed` skips an entry whose negotiated parameters were never
    /// recorded (the defensive branch), rather than handing it over.
    #[tokio::test]
    async fn drain_completed_skips_an_entry_without_parameters() {
        let life = test_life();
        let (mut core, _tx, _accepted) = test_core_with_channels(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        core.life = Arc::downgrade(&life);
        let src = peer_addr();
        let conclusion = listener_conclusion(&mut core, src, 7);
        core.handle_datagram(src, &conclusion)
            .expect("cookie-validated conclusion");
        assert!(core.pending.contains_key(&src));
        core.pending.get_mut(&src).expect("pending").params = None;
        assert!(core.drain_completed().is_none());
    }

    /// The listener counters read the shared atomics, and `Debug` names the
    /// listener and its address.
    #[tokio::test]
    async fn listener_accessors_and_debug_report_the_live_values() {
        let (_accepted_tx, accepted) = mpsc::channel::<Result<SrtSocket>>(1);
        let listener = SrtListener {
            _life: test_life(),
            local: "127.0.0.1:1234".parse().unwrap(),
            udp: Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()),
            accepted,
            routes: Arc::new(Mutex::new(std::collections::HashMap::new())),
            unrouted_dropped: Arc::new(AtomicU64::new(7)),
            overflow_dropped: Arc::new(AtomicU64::new(8)),
            send_errors: Arc::new(AtomicU64::new(9)),
        };
        assert_eq!(listener.unrouted_dropped(), 7);
        assert_eq!(listener.accept_overflow_dropped(), 8);
        assert_eq!(listener.send_errors(), 9);
        let rendered = alloc::format!("{listener:?}");
        assert!(rendered.contains("SrtListener"), "{rendered}");
        assert!(rendered.contains("1234"), "{rendered}");
    }

    #[tokio::test]
    async fn local_crypto_enabled_reflects_the_configuration() {
        let mut core = test_core(HandshakeConfig::for_profile(
            broadcast_core::Profile::Server,
        ))
        .await;
        assert!(!core.local_crypto_enabled());
        #[cfg(feature = "crypto")]
        {
            core.config.crypto = Some(crate::handshake_sm::CryptoConfig::new(
                b"pw".to_vec(),
                [0u8; 16],
                vec![0u8; 16],
            ));
            assert!(core.local_crypto_enabled());
        }
    }

    #[test]
    fn with_handshake_stores_the_config() {
        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server)
            .with_srt_version(0x0105_0001)
            .with_max_retries(4);
        let socket_config = SrtSocketConfig::new(
            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
            crate::test_support::io_config(),
            UdpOptions::new(),
        )
        .with_handshake(config.clone());
        assert_eq!(socket_config.handshake, config);
    }

    /// The Retransmit-free helper `with_handshake` above also leaves the I/O
    /// config untouched; `SrtSocketConfig::new` is its equivalent.
    #[test]
    fn socket_config_new_keeps_the_callers_io() {
        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server).with_mtu(1400);
        let socket_config = SrtSocketConfig::new(
            config.clone(),
            crate::test_support::io_config(),
            UdpOptions::new(),
        );
        assert_eq!(socket_config.handshake, config);
        assert_eq!(socket_config.io, crate::test_support::io_config());
    }

    /// A dedicated-socket forwarder only passes datagrams from the peer.
    #[tokio::test]
    async fn forwarder_rejects_datagrams_from_another_source() {
        let local = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let stats = Arc::new(Counters::default());
        let (mut rx, _guard) = spawn_dedicated_socket_forwarder(
            Arc::clone(&local),
            peer.local_addr().unwrap(),
            stats,
            1500,
            crate::test_support::RX_CHANNEL_CAPACITY,
        );
        let local_addr = local.local_addr().unwrap();
        intruder.send_to(b"injected", local_addr).await.unwrap();
        peer.send_to(b"genuine", local_addr).await.unwrap();
        let got = tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("no genuine datagram")
            .expect("recv");
        assert_eq!(&got[..], b"genuine");
        assert!(
            tokio::time::timeout(Duration::from_millis(200), rx.recv())
                .await
                .is_err(),
            "a datagram from a third source must never be forwarded"
        );
    }

    /// An ACKACK measures the RTT from the matching ACK's send time.
    #[tokio::test(start_paused = true)]
    async fn ackack_updates_the_receiver_rtt() {
        let (mut driver, _rx) = test_driver(8192).await;
        assert_eq!(driver.link.rtt(), crate::arq::rtt::INITIAL_RTT);
        ingress(&mut driver, data_bytes(0, 0, b"x"));
        tokio::time::advance(Duration::from_millis(10)).await;
        tick(&mut driver).await;
        let sent = pending(&mut driver);
        let ack = sent
            .iter()
            .find_map(|bytes| match control_of(bytes) {
                ControlPacket::Ack(a) => Some(a),
                _ => None,
            })
            .expect("a full ACK");
        let ackack = crate::packet::misc::AckAckPacket {
            ack_number: ack.ack_number,
            timestamp: crate::packet::SrtTimestamp::ZERO,
            dest_socket_id: crate::packet::SocketId::from_wire(1),
            libsrt_pad: false,
        };
        let mut bytes = alloc::vec![0u8; ControlPacket::AckAck(ackack).serialized_len()];
        ControlPacket::AckAck(ackack)
            .serialize_into(&mut bytes)
            .expect("serialize ackack");
        tokio::time::advance(Duration::from_millis(20)).await;
        ingress(&mut driver, bytes);
        assert!(
            driver.link.rtt() < crate::arq::rtt::INITIAL_RTT,
            "the RTT sample must lower the estimate, got {:?}",
            driver.link.rtt()
        );
        assert!(driver.link.rtt() > Duration::from_millis(10));
    }

    /// A single-sequence DROPREQ is well-formed and must stop the NAK.
    #[tokio::test(start_paused = true)]
    async fn single_sequence_dropreq_stops_the_nak() {
        let (mut driver, _rx) = test_driver(8192).await;
        ingress(&mut driver, data_bytes(0, 1_000_000_000, b"a"));
        ingress(&mut driver, data_bytes(2, 1_000_000_000, b"c"));
        tokio::time::advance(Duration::from_millis(10)).await;
        tick(&mut driver).await;
        assert!(driver.link.loss_list_len() > 0, "seq 1 is missing");
        ingress(&mut driver, dropreq_bytes(1, 1));
        assert_eq!(
            driver.link.loss_list_len(),
            0,
            "a single-sequence DROPREQ must clear the loss list"
        );
    }

    /// The Keep-Alive carries the connection clock, not a zero timestamp.
    #[tokio::test(start_paused = true)]
    async fn keepalive_carries_the_connection_clock() {
        let (mut driver, _rx) = test_driver(8192).await;
        tokio::time::advance(Duration::from_secs(3)).await;
        tick(&mut driver).await;
        let sent = pending(&mut driver);
        let keepalive = sent
            .iter()
            .find_map(|bytes| match control_of(bytes) {
                ControlPacket::KeepAlive(ka) => Some(ka),
                _ => None,
            })
            .expect("a keep-alive");
        assert!(
            keepalive.timestamp.value() >= 3_000_000,
            "keep-alive timestamp {} ~= 0",
            keepalive.timestamp.value()
        );
    }

    /// An expired pacing slot is dropped, not replayed as credit.
    #[tokio::test(start_paused = true)]
    async fn idle_pacing_credit_expires_at_the_exact_deadline() {
        let (mut driver, _rx) = test_driver(8192).await;
        assert!(pending(&mut driver).is_empty());
        flush(&mut driver).await;
        assert!(pending(&mut driver).is_empty());
    }

    #[tokio::test]
    async fn task_guard_aborts_its_task_on_drop() {
        use core::sync::atomic::AtomicBool;
        struct MarkOnDrop(Arc<AtomicBool>);
        impl Drop for MarkOnDrop {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let dropped = Arc::new(AtomicBool::new(false));
        let marker = MarkOnDrop(Arc::clone(&dropped));
        let guard = TaskGuard(Some(tokio::spawn(async move {
            let _marker = marker;
            std::future::pending::<()>().await;
        })));
        drop(guard);
        let mut aborted = false;
        for _ in 0..1_000 {
            tokio::task::yield_now().await;
            if dropped.load(Ordering::SeqCst) {
                aborted = true;
                break;
            }
        }
        assert!(aborted, "dropping a TaskGuard must abort its task");
    }
}

#[cfg(test)]
mod listener_flood_tests;

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

    #[test]
    fn unix_time_bucket_tracks_the_current_minute() {
        let before = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("after the epoch")
            .as_secs()
            / 60;
        let bucket = u64::from(unix_time_bucket());
        assert!(
            bucket.abs_diff(before) <= 1,
            "bucket {bucket} is not the current minute ({before})"
        );
    }
}