librtmp2 0.8.0

librtmp2 — RTMP/RTMPS protocol library
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
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::buffer::Buffer;
use crate::chunk::reader::{ChunkMessage, chunk_read_owned};
use crate::chunk::state::{
    ChunkRegistry, DEFAULT_CHUNK_SIZE, DEFAULT_MAX_MSG_LENGTH, RTMP_WIRE_MAX_MSG_LENGTH,
};
use crate::chunk::writer::chunk_write;
use crate::ertmp::connect_amf::{negotiate_caps, write_negotiated_caps};
use crate::ertmp::multitrack_media::{first_track_fourcc, foreach_track, is_multitrack_container};
use crate::handshake::{self, Handshake, HandshakeState};
use crate::media::{
    is_on_metadata_payload, normalize_modex_payload, parse_video_metadata_hdr, populate_av_frame,
    populate_multitrack_frame, ERTMP_PACKET_TYPE_MODEX,
};
use crate::message::command;
use crate::message::control::{
    self, UCTRL_PING_REQUEST, UCTRL_PING_RESPONSE, UCTRL_SET_BUFFER_LENGTH, UCTRL_STREAM_BEGIN,
    UCTRL_STREAM_EOF,
};
use crate::message::message as msg_dispatch;
use crate::message::shared_object::{self, SharedObjectMessage};
use crate::session::publish_route::PublishRouteRegistry;
use crate::session::state_machine;
use crate::session::stream::Stream;
use crate::transport::Transport;
use crate::types::*;

pub const MAX_STREAMS_PER_CONN: u32 = 16;
pub const MAX_PENDING_RELAY_FRAMES: usize = 1024;
pub const MAX_PENDING_RELAY_BYTES: usize = 8 * 1024 * 1024;
/// Cap complete messages handled per `read_messages` call so one TCP recv batch
/// cannot drain thousands of tiny control messages in a single state-machine step.
const MAX_MESSAGES_PER_READ: usize = 256;
/// Hard cap on complete messages handled across all `read_messages` passes in a
/// single `recv` call. Without this, the outer `recv` loop (256 iterations)
/// multiplies the per-pass cap into 65,536 message parses per recv batch.
const MAX_MESSAGES_PER_RECV: usize = 256;
/// Maximum bytes retained in the per-connection inbound staging buffer. When
/// the per-call message budget stops draining faster than the peer sends,
/// complete wire data can otherwise accumulate here up to `BUFFER_MAX_SIZE`
/// (64 MiB) per connection. Sized to comfortably hold one in-flight
/// `DEFAULT_MAX_MSG_LENGTH` message even when reassembled from many small
/// chunks (e.g. a peer that never raises chunk size above the 128-byte
/// default) plus normal per-poll staging, while staying well below the
/// original unbounded-growth risk this cap replaces.
const MAX_RECV_BUFFER_BYTES: usize = 2 * DEFAULT_MAX_MSG_LENGTH as usize;

const SERVER_WINDOW_ACK_SIZE: u32 = 2_500_000;
const SERVER_PEER_BANDWIDTH: u32 = 2_500_000;
const PEER_BANDWIDTH_DYNAMIC: u8 = 2;
const PING_INTERVAL: Duration = Duration::from_secs(5);
const PING_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_PENDING_PINGS: usize = 4;

#[derive(Debug, Clone)]
struct QueuedPing {
    token: u32,
    queued_at: Instant,
    /// Bytes that must drain from the front of `send_buffer` before this ping
    /// is considered fully on the wire (bytes queued ahead of the ping at
    /// queue time plus the ping itself, but not data appended afterward).
    bytes_until_flushed: usize,
}
/// Cap inbound Ping-Request reflections per connection to prevent trivial
/// outbound bandwidth/CPU amplification from unauthenticated peers.
const MAX_INBOUND_PING_RESPONSES: usize = 8;
/// Minimum wall-clock gap between init-frame replay requests caused by
/// switching play routes. This prevents a client from alternating stream
/// names to force cached headers and keyframes to be resent every poll batch.
const INIT_REPLAY_COOLDOWN: Duration = Duration::from_secs(1);
/// Close publishers that claimed a route but never sent media. Shorter than
/// [`RTMP_SESSION_SETUP_TIMEOUT`] so squatters cannot block legitimate
/// publishers for the full post-connect grace window.
const PUBLISH_MEDIA_REQUIRED_TIMEOUT: Duration = Duration::from_secs(2);
const INBOUND_PING_WINDOW: Duration = Duration::from_secs(1);
/// Close inbound sessions that never complete the AMF `connect` exchange or
/// never start publishing/playing. Matches the RTMPS accept deadline so a
/// peer cannot hold a connection slot indefinitely with a partial legacy
/// handshake, an idle post-handshake TCP session, or ping responses alone
/// after `connect`.
pub(crate) const RTMP_SESSION_SETUP_TIMEOUT: Duration = Duration::from_secs(10);
/// Cap sub-tags unpacked from a single Aggregate message (mirrors
/// `message::message::MAX_AGGREGATE_SUBTAGS`).
const MAX_AGGREGATE_SUBTAGS: usize = 4096;

/// One media/script frame queued for local relay, stream-cache update, and
/// optional export to integrators.
///
/// Constructed by publishers (via the session media path), by
/// [`Conn::inject_relay_frame`], or by [`crate::server::Server::inject_relay_frame`].
/// Integrators that drain export buffers receive clones of these frames.
#[derive(Clone)]
pub struct RelayFrame {
    /// Audio, video, script (`onMetaData`), or metadata classification.
    pub frame_type: FrameType,
    /// RTMP message timestamp (milliseconds).
    pub timestamp: u32,
    /// Wire payload as received or injected (relayed to players unchanged).
    pub payload: Vec<u8>,
    /// ModEx-normalized bytes used only for codec parsing and cache classification.
    /// `None` means the normalized bytes are identical to `payload`.
    pub cache_payload: Option<Vec<u8>>,
    /// Application name used as the first half of the relay route key.
    pub app: String,
    /// Stream / relay-route key used to match publishers to players.
    pub stream_name: String,
    /// Owning publisher connection id. Socket-less injects use a high-bit
    /// external id ([`crate::server::is_external_publisher_id`]); the sentinel
    /// [`crate::server::EXTERNAL_RELAY_PUBLISHER_ID`] remains `u64::MAX`.
    pub publisher_conn_id: u64,
}

impl RelayFrame {
    /// Bytes used for codec parsing and cache classification.
    pub fn cache_payload(&self) -> &[u8] {
        self.cache_payload.as_deref().unwrap_or(&self.payload)
    }

    pub(crate) fn retained_bytes(&self) -> usize {
        self.payload
            .len()
            .saturating_add(
                self.cache_payload
                    .as_ref()
                    .map(|payload| payload.len())
                    .unwrap_or(0),
            )
            .saturating_add(self.app.len())
            .saturating_add(self.stream_name.len())
    }
}
pub struct Conn {
    pub state: ConnState,
    pub handshake: Handshake,
    pub recv_buffer: Buffer,
    pub send_buffer: Buffer,
    pub chunk_reg: ChunkRegistry,
    /// Target chunk size announced to the peer (from server config).
    pub chunk_size: u32,
    /// Active outbound chunk size; stays at the RTMP default until SetChunkSize
    /// is negotiated on the wire.
    active_chunk_size: u32,
    pub window_ack_size: u32,
    pub bytes_received: u64,
    pub bytes_at_last_ack: u64,
    /// Audio/video payload bytes received (excludes handshake/control overhead).
    pub media_bytes_received: u64,
    /// Bytes accepted via [`Conn::inject_relay_frame`] (AV + script/metadata;
    /// socket telemetry stays in `media_bytes_received`). Counts trusted
    /// injects toward publisher liveness and deferred-relay drain so route
    /// squatters still time out and metadata is not stuck while relay is deferred.
    pub injected_media_bytes: u64,
    /// Audio/video payload bytes sent to this peer.
    pub media_bytes_sent: u64,
    /// Snapshot of `media_bytes_sent` consumed by the last pause-grace reset.
    /// A later pause may refresh setup grace only after additional relay bytes
    /// have been sent, so historical activity cannot keep a slot alive forever.
    pause_grace_media_bytes_sent: u64,
    pub client_fd: i32,
    /// Stable per-connection id (monotonic, never reused while the server runs).
    pub conn_id: u64,
    /// Peer socket address for logging (not persisted).
    pub remote_addr: String,
    pub transport: Option<Transport>,
    pub app: String,
    /// Canonical relay route key. When set, publisher/player media is matched
    /// on this value instead of the RTMP stream name (e.g. separate publish/play keys).
    pub relay_key: String,
    pub next_stream_id: u32,
    pub current_stream: Option<Box<Stream>>,
    pub connect_cb_fired: bool,
    pub send_mutex: Mutex<()>,
    pub pending_relay: Vec<RelayFrame>,
    pub needs_init_frames: bool,
    /// Last play-route change that requested cached init frames.
    last_init_replay_request: Option<Instant>,
    pub detected_video_codec: Option<String>,
    pub detected_audio_codec: Option<String>,
    pub detected_video_width: Option<u32>,
    pub detected_video_height: Option<u32>,
    pub detected_video_framerate: Option<f64>,
    pub detected_audio_sample_rate: Option<u32>,
    pub detected_audio_channels: Option<u32>,
    /// HDR `colorInfo` parsed from the publisher's most recent enhanced video
    /// Metadata packet (`ERTMP_PACKET_TYPE_METADATA`), if any. Rust-only --
    /// not part of `Frame`'s ABI-stable `#[repr(C)]` layout (see
    /// `docs/abi-policy.md`).
    pub detected_hdr_info: Option<HdrInfo>,
    pub relay_enabled: bool,
    /// When true, media relay stays off until the integrator sets `relay_enabled`
    /// after its own post-auth bookkeeping (used by librtmp2-server).
    pub defer_media_relay: bool,
    /// Cap on queued relay payload bytes for this connection.
    pub max_pending_relay_bytes: usize,
    pub on_frame_cb: Option<fn(&Frame)>,
    /// When set, must return true before audio/video is queued for relay.
    /// For a multitrack (`ManyTracks`/`ManyTracksManyCodecs`) container, this
    /// is called once per track with that track's codec, not once per frame —
    /// any single denial rejects the whole frame.
    pub on_media_cb: Option<fn(u64, FrameType, Option<&str>) -> bool>,
    pub on_connect_cb: Option<fn()>,
    pub on_publish_cb: Option<fn(conn_id: u64, app: &str, stream_name: &str) -> bool>,
    pub on_play_cb: Option<fn(conn_id: u64, app: &str, stream_name: &str) -> bool>,
    /// Must return true before a parsed AMF3 Shared Object message is delivered
    /// to [`Self::on_shared_object_cb`]. When unset while `on_publish_cb` or
    /// `on_play_cb` is configured, inbound shared objects are dropped so a
    /// peer authorized only for publish/play cannot inject shared-object events.
    pub on_shared_object_auth_cb: Option<fn(conn_id: u64, so: &SharedObjectMessage) -> bool>,
    /// Fired for every parsed AMF3 Shared Object message (RTMP message type
    /// `0x10`) received on this connection. The library only delivers the
    /// parsed envelope -- multi-client attribute sync/persistence is left to
    /// the host application, consistent with this crate's "deliver the
    /// event, not the policy" design.
    pub on_shared_object_cb: Option<fn(conn_id: u64, so: &SharedObjectMessage)>,
    /// Must return true to allow `releaseStream` to force-evict *another*
    /// connection's publish-route claim for `stream_name` (e.g. reclaiming a
    /// route after a reconnecting encoder's old TCP session went stale but
    /// hasn't timed out yet). Unset (the default) makes `releaseStream` a
    /// no-op: unlike `on_media_cb`/`on_publish_cb`, this has no permissive
    /// default, since evicting a still-live publisher would otherwise let
    /// any authenticated peer hijack another connection's stream by name.
    pub on_release_stream_cb: Option<fn(conn_id: u64, app: &str, stream_name: &str) -> bool>,
    /// When set by the built-in server, enforces single-publisher-per-route.
    pub(crate) publish_routes: Option<PublishRouteRegistry>,
    /// Exact stream-name key currently held in `publish_routes` for this conn.
    /// Must be released on teardown even when `relay_key` later diverges from
    /// the RTMP publish name (librtmp2-server pins `relay_key` to the DB id).
    claimed_publish_route: Option<String>,
    /// Cache keys to evict after the publisher renames its stream.
    pub pending_cache_evictions: Vec<(String, String)>,
    /// Last measured client↔server RTT in milliseconds (RTMP UserControl ping).
    pub rtt_ms: f64,
    pending_pings: HashMap<u32, Instant>,
    /// Ping queued in `send_buffer` but not yet fully flushed.
    queued_ping: Option<QueuedPing>,
    last_ping_sent: Option<Instant>,
    next_ping_token: u32,
    inbound_ping_responses: usize,
    inbound_ping_window_start: Option<Instant>,
    /// Retains the last frame payload delivered through `on_frame_cb` so
    /// `Frame.data` stays valid until the next callback on this connection.
    frame_cb_scratch: Vec<u8>,
    /// Set when `read_messages` stops because `MAX_MESSAGES_PER_READ` or
    /// `MAX_MESSAGES_PER_RECV` was hit while `recv_buffer` still holds
    /// complete, unprocessed messages -- as opposed to stopping because the
    /// buffer ran out of data. Callers must keep draining (e.g. via another
    /// `recv(&[])`) until this clears, or a batch that exceeds the budget can
    /// sit unprocessed until the peer happens to send more bytes.
    budget_exhausted: bool,
    /// Start of the current "must become active" grace window: set when
    /// this inbound TCP session was accepted, and reset every time the
    /// session goes idle after publishing/playing (`FCUnpublish`,
    /// `deleteStream`, `closeStream`) so a legitimate client that stops and
    /// later republishes on the same connection gets a fresh window instead
    /// of being reaped for the unpublished gap. Used by
    /// [`Conn::session_setup_timed_out`].
    session_setup_started: Instant,
    /// E-RTMP caps agreed during connect (empty when legacy connect).
    pub negotiated_caps: NegotiatedCaps,
    /// Player-side buffer length from SetBufferLength user control (ms).
    pub buffer_length_ms: u32,
}

impl Conn {
    pub fn new() -> Self {
        let mut chunk_reg = ChunkRegistry::new();
        chunk_reg.init();
        Self {
            state: ConnState::TcpAccepted,
            handshake: Handshake::default(),
            recv_buffer: Buffer::new(),
            send_buffer: Buffer::new(),
            chunk_reg,
            chunk_size: DEFAULT_CHUNK_SIZE,
            active_chunk_size: DEFAULT_CHUNK_SIZE,
            window_ack_size: 0,
            bytes_received: 0,
            bytes_at_last_ack: 0,
            media_bytes_received: 0,
            injected_media_bytes: 0,
            media_bytes_sent: 0,
            pause_grace_media_bytes_sent: 0,
            client_fd: -1,
            conn_id: 0,
            remote_addr: String::new(),
            transport: None,
            app: String::new(),
            relay_key: String::new(),
            next_stream_id: 0,
            current_stream: None,
            connect_cb_fired: false,
            send_mutex: Mutex::new(()),
            pending_relay: Vec::new(),
            needs_init_frames: false,
            last_init_replay_request: None,
            detected_video_codec: None,
            detected_audio_codec: None,
            detected_video_width: None,
            detected_video_height: None,
            detected_video_framerate: None,
            detected_audio_sample_rate: None,
            detected_audio_channels: None,
            detected_hdr_info: None,
            relay_enabled: false,
            defer_media_relay: false,
            max_pending_relay_bytes: MAX_PENDING_RELAY_BYTES,
            on_frame_cb: None,
            on_media_cb: None,
            on_connect_cb: None,
            on_publish_cb: None,
            on_play_cb: None,
            on_shared_object_auth_cb: None,
            on_shared_object_cb: None,
            on_release_stream_cb: None,
            publish_routes: None,
            claimed_publish_route: None,
            pending_cache_evictions: Vec::new(),
            rtt_ms: 0.0,
            pending_pings: HashMap::new(),
            queued_ping: None,
            last_ping_sent: None,
            next_ping_token: 1,
            inbound_ping_responses: 0,
            inbound_ping_window_start: None,
            frame_cb_scratch: Vec::new(),
            budget_exhausted: false,
            session_setup_started: Instant::now(),
            negotiated_caps: NegotiatedCaps::default(),
            buffer_length_ms: 3000,
        }
    }

    /// True when an inbound peer has held a connection slot without being an
    /// active publisher or player for longer than
    /// [`RTMP_SESSION_SETUP_TIMEOUT`]. Covers incomplete handshakes, post-
    /// `connect` idle sessions that only answer server pings, and sessions
    /// that stopped publishing/playing and haven't resumed within a fresh
    /// grace window (`session_setup_started` is reset on every such
    /// transition -- see `FCUnpublish`/`deleteStream`/`closeStream` in
    /// `handle_command`).
    pub fn session_setup_timed_out(&self) -> bool {
        // `ConnState` only moves forward, so a peer that briefly published
        // (or played) and then unpublished before the deadline would stay
        // "exempt" forever if this checked `self.state`. Check the current
        // stream's active flags instead -- they're cleared on unpublish.
        let Some(stream) = self.current_stream.as_ref() else {
            // Inject-held claims can exist without `current_stream` (socket-less
            // inject path). Sustain while media has flowed; otherwise apply the
            // publish-media squat timer instead of the longer setup timeout.
            if self.claimed_publish_route.is_some() {
                if self.injected_media_bytes > 0 || self.media_bytes_received > 0 {
                    return false;
                }
                return self.session_setup_started.elapsed() >= PUBLISH_MEDIA_REQUIRED_TIMEOUT;
            }
            return self.session_setup_started.elapsed() >= RTMP_SESSION_SETUP_TIMEOUT;
        };
        // Publish role *or* an inject-held route claim must obey the media
        // squat timer. Otherwise an idle/inject Conn (or a player that somehow
        // held a claim) blocks socket publishers until TCP disconnect.
        let holding_inject_claim = self.claimed_publish_route.is_some();
        if stream.is_publishing || holding_inject_claim {
            // A peer that claims a publish route but never sends media can
            // otherwise squat the route indefinitely by keeping TCP alive.
            // Trusted injects count toward liveness without polluting socket
            // receive telemetry (`media_bytes_received`).
            if self.media_bytes_received == 0 && self.injected_media_bytes == 0 {
                return self.session_setup_started.elapsed() >= PUBLISH_MEDIA_REQUIRED_TIMEOUT;
            }
            return false;
        }
        // Inject-only squatters (no publish role) must not hold a route
        // longer than a real publisher would without sending media.
        if self.claimed_publish_route.is_some()
            && self.media_bytes_received == 0
            && self.injected_media_bytes == 0
        {
            return self.session_setup_started.elapsed() >= PUBLISH_MEDIA_REQUIRED_TIMEOUT;
        }
        if self.session_setup_started.elapsed() < RTMP_SESSION_SETUP_TIMEOUT {
            return false;
        }
        if stream.is_playing {
            // Paused players opt out of relay delivery, so they never hit the
            // slow-reader disconnect path. Unpaused viewers who have received
            // outbound relay are protected; squatters who issued play against a
            // dead route with zero relay must not hold slots forever.
            if !stream.paused && self.media_bytes_sent > 0 {
                return false;
            }
            return true;
        }
        true
    }

    #[cfg(test)]
    pub(crate) fn set_session_setup_started_for_test(&mut self, started: Instant) {
        self.session_setup_started = started;
    }

    #[cfg(test)]
    fn handle_message_for_test(
        &mut self,
        msg: &ChunkMessage,
        payload: &[u8],
    ) -> Result<()> {
        let mut messages_budget = usize::MAX;
        self.handle_message(msg, payload, &mut messages_budget)
    }

    #[cfg(test)]
    fn handle_aggregate_for_test(
        &mut self,
        msg_stream_id: u32,
        base_timestamp: u32,
        payload: &[u8],
    ) -> Result<()> {
        let mut messages_budget = usize::MAX;
        self.handle_aggregate(msg_stream_id, base_timestamp, payload, &mut messages_budget)
    }

    /// True if the last `recv`/`process` pass stopped early because the
    /// per-call message budget was exhausted while complete messages were
    /// still buffered. Callers (e.g. the server poll loop) should keep
    /// calling `recv(&[])` until this returns false so a batch larger than
    /// the budget doesn't stall waiting on the peer to send more bytes.
    pub fn has_buffered_messages(&self) -> bool {
        self.budget_exhausted
    }

    fn pending_relay_bytes(&self) -> usize {
        self.pending_relay
            .iter()
            .map(RelayFrame::retained_bytes)
            .sum()
    }

    /// Key used to route relayed media between publishers and players.
    pub fn relay_route_key(&self) -> String {
        if !self.relay_key.is_empty() {
            return self.relay_key.clone();
        }
        self.current_stream
            .as_ref()
            .map(|s| s.name.clone())
            .unwrap_or_default()
    }

    pub fn accepts_multitrack(&self) -> bool {
        !self.negotiated_caps.has_caps_ex || self.negotiated_caps.multitrack_enabled
    }

    /// Queue eviction of the current publish route's cache key when
    /// `current_stream` is about to be repurposed or replaced while still
    /// marked as actively publishing (a fresh `createStream`, or switching
    /// to `play`, both abandon whatever was being published). Unlike a
    /// `publish` rename there is no new route to keep serving, so this
    /// always evicts when the connection was publishing. No-op otherwise.
    fn evict_active_publish_route(&mut self) {
        let was_publishing = self
            .current_stream
            .as_ref()
            .map(|s| s.is_publishing)
            .unwrap_or(false);
        if !was_publishing {
            // Idle/prior-epoch inject must not survive createStream / play /
            // FCUnpublish into a later empty publish's media deadline. A
            // connection-level inject can claim a route without ever
            // transitioning to Publishing, so release that claim here too or
            // the route stays unavailable to socket publishers until close.
            // Also evict any cache this idle inject wrote — a later publisher
            // on the same route must not inherit stale codec headers.
            let claimed_route = self.claimed_publish_route.clone();
            self.release_claimed_publish_route();
            if let Some(route_key) = claimed_route
                && !route_key.is_empty()
            {
                self.pending_cache_evictions
                    .push((self.app.clone(), route_key));
            }
            self.injected_media_bytes = 0;
            return;
        }
        let claimed_route = self.claimed_publish_route.clone();
        self.release_claimed_publish_route();
        // Cached frames are keyed by whatever relay_route_key() was live at
        // the moment each frame was queued (see RelayFrame::stream_name), so
        // if an integrator pins relay_key after the route was claimed, cache
        // entries can exist under both the originally claimed key and the
        // current one. Evict both to avoid leaving either behind.
        let live_route_key = self.relay_route_key();
        let mut evicted = std::collections::HashSet::new();
        for route_key in [claimed_route, Some(live_route_key)].into_iter().flatten() {
            if !route_key.is_empty() && evicted.insert(route_key.clone()) {
                self.pending_cache_evictions
                    .push((self.app.clone(), route_key));
            }
        }
        self.clear_detected_stream_metadata();
        self.injected_media_bytes = 0;
    }

    fn release_claimed_publish_route(&mut self) {
        if let Some(claimed) = self.claimed_publish_route.take() {
            if let Some(routes) = self.publish_routes.as_ref() {
                routes.release(self.conn_id, &self.app, &claimed);
            }
        }
    }

    fn claim_publish_route(&mut self, stream: &str) -> bool {
        let Some(routes) = self.publish_routes.as_ref() else {
            self.claimed_publish_route = Some(stream.to_string());
            return true;
        };
        if !routes.claim(self.conn_id, &self.app, stream) {
            return false;
        }
        match self.claimed_publish_route.take() {
            Some(prev) if prev == stream => self.claimed_publish_route = Some(prev),
            Some(prev) => {
                routes.release(self.conn_id, &self.app, &prev);
                // Mirror the publish-rename path: free the old route's init
                // cache so a later publisher on `prev` cannot inherit stale
                // codec headers from this connection.
                if !prev.is_empty() {
                    self.pending_cache_evictions.push((self.app.clone(), prev));
                }
                self.claimed_publish_route = Some(stream.to_string());
            }
            None => self.claimed_publish_route = Some(stream.to_string()),
        }
        true
    }

    fn clear_detected_stream_metadata(&mut self) {
        self.detected_video_codec = None;
        self.detected_audio_codec = None;
        self.detected_video_width = None;
        self.detected_video_height = None;
        self.detected_video_framerate = None;
        self.detected_audio_sample_rate = None;
        self.detected_audio_channels = None;
        self.detected_hdr_info = None;
    }

    fn publishing_metadata_allowed(&self, msg_stream_id: u32) -> bool {
        let expected_stream_id = self
            .current_stream
            .as_ref()
            .filter(|s| s.is_publishing)
            .map(|s| s.stream_id)
            .unwrap_or(0);
        msg_stream_id == expected_stream_id && expected_stream_id != 0
    }

    fn handle_publisher_data_message(
        &mut self,
        msg_stream_id: u32,
        timestamp: u32,
        payload: &[u8],
    ) -> Result<()> {
        if !self.publishing_metadata_allowed(msg_stream_id) {
            return Ok(());
        }
        let relay_metadata = is_on_metadata_payload(payload)
            && self.relay_enabled
            && self
                .current_stream
                .as_ref()
                .map(|s| s.is_publishing)
                .unwrap_or(false);
        if relay_metadata && !self.media_allowed(FrameType::Script, None) {
            return Err(ErrorCode::Auth);
        }
        self.handle_data_message(payload)?;
        if relay_metadata {
            if let Some(cb) = self.on_frame_cb {
                self.frame_cb_scratch.clear();
                self.frame_cb_scratch.extend_from_slice(payload);
                let frame = Frame {
                    frame_type: FrameType::Script,
                    timestamp,
                    size: self.frame_cb_scratch.len() as u32,
                    data: self.frame_cb_scratch.as_ptr(),
                    is_metadata: 1,
                    ..Default::default()
                };
                cb(&frame);
            }
            self.queue_relay_frame(FrameType::Script, timestamp, payload, payload)?;
        }
        Ok(())
    }

    /// Inject media into this connection's pending relay queue as if it were
    /// published locally.
    ///
    /// Uses the same ModEx-normalize + `queue_relay_frame` path as inbound
    /// publisher media, but skips `on_media_cb` / `on_frame_cb` (integrator-
    /// trusted). Does not require `relay_enabled`. Rejects playing-only
    /// connections so inject cannot squat publish routes from a player session.
    pub fn inject_relay_frame(
        &mut self,
        frame_type: FrameType,
        timestamp: u32,
        payload: &[u8],
    ) -> Result<()> {
        let max_len = self.chunk_reg.max_msg_length.min(RTMP_WIRE_MAX_MSG_LENGTH) as usize;
        if payload.len() > max_len {
            return Err(ErrorCode::Internal);
        }
        if let Some(stream) = self.current_stream.as_ref() {
            if stream.is_playing && !stream.is_publishing {
                return Err(ErrorCode::Internal);
            }
        }
        let stream_name = self.relay_route_key();
        if self.app.is_empty() || stream_name.is_empty() {
            return Err(ErrorCode::Internal);
        }
        if self.app.len() > 1024 || stream_name.len() > 1024 {
            return Err(ErrorCode::Internal);
        }
        let previous_claim = self.claimed_publish_route.clone();
        let eviction_len_before = self.pending_cache_evictions.len();
        let already_owned_route =
            self.claimed_publish_route.as_deref() == Some(stream_name.as_str());
        if !self.claim_publish_route(&stream_name) {
            // `relay_route_key()` prefers `relay_key`. If an integrator pointed
            // it at a contended route, restore it to the still-held claim so
            // later socket media cannot snapshot an unclaimed key.
            if let Some(ref claimed) = self.claimed_publish_route {
                self.relay_key = claimed.clone();
            }
            return Err(ErrorCode::Internal);
        }
        let normalized = normalize_modex_payload(payload, self.negotiated_caps.caps_ex_mask);
        if let Err(e) = self.queue_relay_frame(frame_type, timestamp, payload, normalized.as_ref())
        {
            // Don't let a rejected frame (e.g. over the pending-byte budget)
            // leave a route claimed that this connection never actually
            // delivered anything on — that would block a real publisher.
            // Only roll back a claim/switch we just took; a claim already held
            // from an earlier successful inject on the same route stays intact.
            // On a failed route switch, restore the previous claim and undo the
            // cache-eviction marker so the active feed is not abandoned.
            if !already_owned_route {
                self.release_claimed_publish_route();
                self.pending_cache_evictions.truncate(eviction_len_before);
                if let Some(prev) = previous_claim {
                    if let Some(routes) = self.publish_routes.as_ref() {
                        let _ = routes.claim(self.conn_id, &self.app, &prev);
                    }
                    self.claimed_publish_route = Some(prev.clone());
                    // Keep relay_route_key() aligned with the restored claim so
                    // socket media cannot queue under the rejected key B.
                    self.relay_key = prev;
                }
            }
            return Err(e);
        }
        // Count all successful injects (AV + script/metadata) as publisher
        // activity for squat timeout and deferred-relay drain/export. Script
        // and metadata never touch socket receive telemetry, but they must
        // still wake `Server::process_connections` when `defer_media_relay`
        // holds `relay_enabled` off.
        self.injected_media_bytes = self
            .injected_media_bytes
            .saturating_add((payload.len() as u64).max(1));
        Ok(())
    }

    fn queue_relay_frame(
        &mut self,
        frame_type: FrameType,
        timestamp: u32,
        payload: &[u8],
        cache_payload: &[u8],
    ) -> Result<()> {
        let max_len = self.chunk_reg.max_msg_length.min(RTMP_WIRE_MAX_MSG_LENGTH) as usize;
        if payload.len() > max_len {
            return Err(ErrorCode::Internal);
        }
        let cache_payload = if cache_payload.len() == payload.len()
            && std::ptr::eq(cache_payload.as_ptr(), payload.as_ptr())
        {
            None
        } else {
            Some(cache_payload.to_vec())
        };
        let app = self.app.clone();
        let stream_name = self.relay_route_key();
        let retained_bytes = payload
            .len()
            .saturating_add(
                cache_payload
                    .as_ref()
                    .map(|payload| payload.len())
                    .unwrap_or(0),
            )
            .saturating_add(app.len())
            .saturating_add(stream_name.len());
        if self.pending_relay.len() >= MAX_PENDING_RELAY_FRAMES
            || self.pending_relay_bytes().saturating_add(retained_bytes)
                > self.max_pending_relay_bytes
        {
            return Err(ErrorCode::Internal);
        }
        self.pending_relay.push(RelayFrame {
            frame_type,
            timestamp,
            payload: payload.to_vec(),
            cache_payload,
            app,
            stream_name,
            publisher_conn_id: self.conn_id,
        });
        Ok(())
    }

    fn media_allowed(&self, frame_type: FrameType, codec: Option<&str>) -> bool {
        let Some(cb) = self.on_media_cb else {
            return true;
        };
        // Unknown codec identity must not bypass deny-list policies by appearing
        // as `None` when the frame is otherwise valid publisher media.
        if matches!(frame_type, FrameType::Video | FrameType::Audio) && codec.is_none() {
            return false;
        }
        cb(self.conn_id, frame_type, codec)
    }

    /// Request a one-shot init-frame replay for a playing client,
    /// rate-limited so rapid play-route changes cannot amplify cached data.
    fn request_init_replay(&mut self) {
        let now = Instant::now();
        if self
            .last_init_replay_request
            .is_some_and(|last| now.duration_since(last) < INIT_REPLAY_COOLDOWN)
        {
            return;
        }
        self.last_init_replay_request = Some(now);
        self.needs_init_frames = true;
    }

    fn handle_media_frame(
        &mut self,
        msg_stream_id: u32,
        frame_type: FrameType,
        timestamp: u32,
        payload: &[u8],
    ) -> Result<()> {
        if !self.relay_enabled
            || !self
                .current_stream
                .as_ref()
                .map(|s| s.is_publishing)
                .unwrap_or(false)
        {
            return Ok(());
        }

        let expected_stream_id = self
            .current_stream
            .as_ref()
            .map(|s| s.stream_id)
            .unwrap_or(0);
        if msg_stream_id != expected_stream_id {
            return Ok(());
        }

        // Always peel ModEx wrappers for codec authorization and callbacks.
        // Gating on negotiated `caps_ex_mask` let publishers craft ModEx
        // frames whose extension bytes spell an allowed FourCC while relaying
        // a different inner codec to players.
        let normalized_payload = normalize_modex_payload(payload, CAPS_EX_MASK_MODEX);
        let parse_payload = normalized_payload.as_ref();

        let current_codec = match frame_type {
            FrameType::Video => detect_video_codec(parse_payload),
            FrameType::Audio => detect_audio_codec(parse_payload),
            _ => None,
        };

        let is_multitrack = is_multitrack_container(frame_type, parse_payload);

        if is_multitrack {
            // A `ManyTracksManyCodecs` container can carry a different codec
            // per track; `current_codec` only reflects the first one. Check
            // every track's codec so a publisher can't smuggle a disallowed
            // codec past authorization by pairing it with an allowed first
            // track.
            let mut auth_denied = false;
            let tracks_valid = foreach_track(frame_type, parse_payload, |track| {
                if auth_denied {
                    return;
                }
                let track_codec = media_fourcc_auth_label(&track.fourcc);
                if !self.media_allowed(frame_type, track_codec.as_deref()) {
                    auth_denied = true;
                }
            });
            if !tracks_valid {
                return Err(ErrorCode::Protocol);
            }
            if auth_denied {
                return Err(ErrorCode::Auth);
            }
        } else if !self.media_allowed(frame_type, current_codec.as_deref()) {
            return Err(ErrorCode::Auth);
        }

        // Only pin the detected codec once the frame has cleared
        // authorization, so a rejected frame's codec never lingers in
        // `detected_video_codec`/`detected_audio_codec` for telemetry readers.
        match frame_type {
            FrameType::Video if self.detected_video_codec.is_none() => {
                self.detected_video_codec = current_codec.clone();
            }
            FrameType::Audio if self.detected_audio_codec.is_none() => {
                self.detected_audio_codec = current_codec.clone();
            }
            _ => {}
        }

        if frame_type == FrameType::Video && !is_multitrack {
            if let Some(color_info) = parse_video_metadata_hdr(parse_payload) {
                self.detected_hdr_info = Some(color_info);
            }
        }

        self.media_bytes_received = self
            .media_bytes_received
            .saturating_add(payload.len() as u64);

        let cb = self.on_frame_cb;
        let parsed_multitrack = foreach_track(frame_type, parse_payload, |track| {
            if let Some(cb) = cb {
                self.invoke_multitrack_on_frame_cb(
                    cb,
                    frame_type,
                    timestamp,
                    track.track_id,
                    track.fourcc,
                    track.packet_type,
                    track.video_frame_type,
                    track.payload,
                );
            }
        });
        if is_multitrack && !parsed_multitrack {
            return Err(ErrorCode::Protocol);
        }
        if !is_multitrack {
            if let Some(cb) = cb {
                self.invoke_on_frame_cb(cb, frame_type, timestamp, u8::MAX, parse_payload);
            }
        }
        if self
            .queue_relay_frame(frame_type, timestamp, payload, parse_payload)
            .is_err()
        {
            return Err(ErrorCode::Internal);
        }
        Ok(())
    }

    /// Unpack an RTMP Aggregate message (type 0x16) into its constituent FLV
    /// sub-tags and route each audio/video sub-tag through the same relay path
    /// as a standalone `RTMP_MSG_AUDIO`/`RTMP_MSG_VIDEO` message.
    ///
    /// Each sub-tag is `tag_type(1) + data_size(3) + timestamp(3) + timestamp_ext(1)
    /// + stream_id(3) + data(data_size) + prev_tag_size(4)`. Sub-tag timestamps are
    /// relative to the first sub-tag's timestamp; that delta is added to the
    /// aggregate message's own chunk timestamp per the FLV/RTMP aggregate spec.
    fn handle_aggregate(
        &mut self,
        msg_stream_id: u32,
        base_timestamp: u32,
        payload: &[u8],
        messages_budget: &mut usize,
    ) -> Result<()> {
        let mut pos = 0;
        let mut have_base = false;
        let mut sub_base_ts: u32 = 0;
        let mut subtags = 0usize;

        while pos + 11 <= payload.len() {
            if subtags >= MAX_AGGREGATE_SUBTAGS {
                return Err(ErrorCode::Protocol);
            }
            subtags += 1;

            let tag_type = payload[pos];
            let data_size = ((payload[pos + 1] as u32) << 16)
                | ((payload[pos + 2] as u32) << 8)
                | (payload[pos + 3] as u32);
            let ts = ((payload[pos + 4] as u32) << 16)
                | ((payload[pos + 5] as u32) << 8)
                | (payload[pos + 6] as u32)
                | ((payload[pos + 7] as u32) << 24);

            let body = pos + 11;
            let data_size = data_size as usize;
            if body + data_size > payload.len() {
                return Err(ErrorCode::Protocol);
            }

            if !have_base {
                sub_base_ts = ts;
                have_base = true;
            }
            // Use wrapping arithmetic: a sub-tag ts less than the first sub-tag's
            // ts (malformed but possible) must not panic in debug or silently
            // wrap in an unexpected direction in release.
            let out_ts = base_timestamp.wrapping_add(ts.wrapping_sub(sub_base_ts));
            let tag_payload = &payload[body..body + data_size];

            match tag_type {
                msg_dispatch::RTMP_MSG_AUDIO
                | msg_dispatch::RTMP_MSG_VIDEO
                | msg_dispatch::RTMP_MSG_AMF0_DATA => {
                    if *messages_budget == 0 {
                        return Ok(());
                    }
                    *messages_budget = messages_budget.saturating_sub(1);
                }
                _ => {
                    pos = body + data_size + 4;
                    continue;
                }
            }

            match tag_type {
                msg_dispatch::RTMP_MSG_AUDIO => {
                    self.handle_media_frame(msg_stream_id, FrameType::Audio, out_ts, tag_payload)?;
                }
                msg_dispatch::RTMP_MSG_VIDEO => {
                    self.handle_media_frame(msg_stream_id, FrameType::Video, out_ts, tag_payload)?;
                }
                msg_dispatch::RTMP_MSG_AMF0_DATA => {
                    self.handle_publisher_data_message(msg_stream_id, out_ts, tag_payload)?;
                }
                _ => {}
            }

            pos = body + data_size + 4;
        }

        Ok(())
    }

    pub fn get_fd(&self) -> i32 {
        self.client_fd
    }

    pub fn recv(&mut self, data: &[u8]) -> Result<()> {
        if !data.is_empty()
            && self.recv_buffer.available().saturating_add(data.len()) > MAX_RECV_BUFFER_BYTES
        {
            return Err(ErrorCode::Protocol);
        }
        self.recv_buffer
            .write(data)
            .map_err(|_| ErrorCode::Internal)?;
        self.bytes_received = self.bytes_received.saturating_add(data.len() as u64);
        self.budget_exhausted = false;
        let mut max_iter = 256;
        let mut no_progress = 0;
        let mut messages_budget = MAX_MESSAGES_PER_RECV;
        while max_iter > 0 {
            if messages_budget == 0 {
                self.budget_exhausted = true;
                break;
            }
            max_iter -= 1;
            let avail = self.recv_buffer.available();
            if avail == 0 && self.state != ConnState::Handshake {
                break;
            }
            let before = avail;
            let rc = self.process(&mut messages_budget);
            if rc < 0 {
                return Err(match rc {
                    -1 => ErrorCode::Io,
                    -2 => ErrorCode::Timeout,
                    -3 => ErrorCode::Protocol,
                    -4 => ErrorCode::Handshake,
                    -5 => ErrorCode::Chunk,
                    -6 => ErrorCode::Amf,
                    -7 => ErrorCode::Unsupported,
                    -8 => ErrorCode::Auth,
                    -9 => ErrorCode::Internal,
                    _ => ErrorCode::Internal,
                });
            }
            if rc == 0 {
                let after = self.recv_buffer.available();
                if after == before {
                    no_progress += 1;
                    if no_progress > 3 {
                        break;
                    }
                } else {
                    no_progress = 0;
                }
                if after == 0 && self.state < ConnState::Closing {
                    break;
                }
            } else {
                no_progress = 0;
            }
        }
        if self.window_ack_size > 0
            && self.bytes_received.saturating_sub(self.bytes_at_last_ack)
                >= self.window_ack_size as u64
        {
            self.send_acknowledgement(self.bytes_received as u32)?;
            self.bytes_at_last_ack = self.bytes_received;
        }
        Ok(())
    }

    pub fn process(&mut self, messages_budget: &mut usize) -> i32 {
        match self.state {
            ConnState::TcpAccepted | ConnState::Handshake => self.do_handshake(),
            ConnState::Connected
            | ConnState::AppConnected
            | ConnState::StreamCreated
            | ConnState::Publishing
            | ConnState::Playing
            | ConnState::CapsNegotiated => self.read_messages(messages_budget),
            ConnState::Closing | ConnState::Closed => 0,
        }
    }

    pub fn do_handshake(&mut self) -> i32 {
        match self.handshake.state {
            HandshakeState::ServerWaitC0 => {
                handshake::server_init(&mut self.handshake);
                match handshake::server_read_c0(&mut self.handshake, &mut self.recv_buffer) {
                    Ok(()) => {
                        self.state = ConnState::Handshake;
                        self.do_handshake_recurse()
                    }
                    Err(ErrorCode::Io) => 0,
                    Err(e) => e as i32,
                }
            }
            HandshakeState::ServerWaitC1 => self.do_handshake_recurse(),
            HandshakeState::ServerWaitC2 => {
                match handshake::server_read_c2(&mut self.handshake, &mut self.recv_buffer) {
                    Ok(()) => {
                        self.state = ConnState::Connected;
                        1
                    }
                    Err(ErrorCode::Io) => 0,
                    Err(e) => e as i32,
                }
            }
            HandshakeState::Done => {
                self.state = ConnState::Connected;
                1
            }
            _ => -1,
        }
    }

    fn do_handshake_recurse(&mut self) -> i32 {
        match handshake::server_read_c1(&mut self.handshake, &mut self.recv_buffer) {
            Ok(()) => {
                if self.client_fd >= 0 {
                    let s0 = [0x03u8];
                    if self.send_buffer.write(&s0).is_err() {
                        return ErrorCode::Internal as i32;
                    }
                    let out_data = self.handshake.out.peek();
                    if self.send_buffer.write(out_data).is_err() {
                        return ErrorCode::Internal as i32;
                    }
                }
                self.handshake.out.reset();
                1
            }
            Err(ErrorCode::Io) => 0,
            Err(e) => e as i32,
        }
    }

    pub fn read_messages(&mut self, messages_budget: &mut usize) -> i32 {
        let mut processed = 0usize;
        loop {
            if processed >= MAX_MESSAGES_PER_READ || *messages_budget == 0 {
                // Stopped because the budget ran out, not because the buffer
                // is empty -- there may still be complete messages sitting in
                // `recv_buffer` that the caller needs to keep draining.
                self.budget_exhausted = true;
                break;
            }
            let mut msg = ChunkMessage::default();
            match chunk_read_owned(&mut self.recv_buffer, &mut self.chunk_reg, &mut msg) {
                Ok((0, _)) => break,
                Ok((1, payload_owned)) => {
                    if msg.is_complete {
                        processed += 1;
                        if let Err(e) = self.handle_message(&msg, &payload_owned, messages_budget) {
                            return match e {
                                ErrorCode::Auth => -8,
                                _ => -3,
                            };
                        }
                        let _ = self.flush();
                    }
                }
                Ok(_) => break,
                Err(ErrorCode::Chunk) => return -5,
                Err(_) => return -1,
            }
        }
        1
    }

    fn handle_message(
        &mut self,
        msg: &ChunkMessage,
        payload: &[u8],
        messages_budget: &mut usize,
    ) -> Result<()> {
        match msg.msg_type_id {
            msg_dispatch::RTMP_MSG_AGGREGATE => {
                return self.handle_aggregate(
                    msg.msg_stream_id,
                    msg.timestamp,
                    payload,
                    messages_budget,
                );
            }
            _ => {
                if *messages_budget == 0 {
                    return Ok(());
                }
                *messages_budget = messages_budget.saturating_sub(1);
            }
        }

        match msg.msg_type_id {
            msg_dispatch::RTMP_MSG_SET_CHUNK_SIZE
            | msg_dispatch::RTMP_MSG_ABORT_MESSAGE
            | msg_dispatch::RTMP_MSG_ACKNOWLEDGEMENT
            | msg_dispatch::RTMP_MSG_WINDOW_ACK_SIZE
            | msg_dispatch::RTMP_MSG_SET_PEER_BANDWIDTH => {
                self.handle_control(msg.msg_type_id, payload)
            }
            msg_dispatch::RTMP_MSG_USER_CONTROL => self.handle_user_control(payload),
            msg_dispatch::RTMP_MSG_AMF0_COMMAND => self.handle_command(payload),
            msg_dispatch::RTMP_MSG_AMF3_COMMAND => {
                if !payload.is_empty() && payload[0] == 0x00 {
                    self.handle_command(&payload[1..])
                } else {
                    self.handle_command(payload)
                }
            }
            msg_dispatch::RTMP_MSG_AUDIO => {
                self.handle_media_frame(msg.msg_stream_id, FrameType::Audio, msg.timestamp, payload)
            }
            msg_dispatch::RTMP_MSG_VIDEO => {
                self.handle_media_frame(msg.msg_stream_id, FrameType::Video, msg.timestamp, payload)
            }
            msg_dispatch::RTMP_MSG_AMF0_DATA => {
                self.handle_publisher_data_message(msg.msg_stream_id, msg.timestamp, payload)
            }
            msg_dispatch::RTMP_MSG_AMF3_DATA => {
                if !payload.is_empty() && payload[0] == 0x00 {
                    self.handle_publisher_data_message(
                        msg.msg_stream_id,
                        msg.timestamp,
                        &payload[1..],
                    )
                } else {
                    self.handle_publisher_data_message(msg.msg_stream_id, msg.timestamp, payload)
                }
            }
            msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT => {
                let data = if !payload.is_empty() && payload[0] == 0x00 {
                    &payload[1..]
                } else {
                    payload
                };
                self.handle_amf3_shared_object(data)
            }
            msg_dispatch::RTMP_MSG_AGGREGATE => Ok(()),
            _ => Ok(()),
        }
    }

    fn handle_amf3_shared_object(&mut self, payload: &[u8]) -> Result<()> {
        // Shared objects are an application-scoped feature: reject them
        // before `connect` completes, when `self.app` is still empty and no
        // connect-time authorization has run, so the host callback is never
        // handed a message it cannot attribute to an application.
        if self.state < ConnState::AppConnected {
            return Ok(());
        }
        // Malformed shared-object messages are dropped, not fatal to the
        // connection -- mirrors how other opportunistic-parse paths (e.g.
        // onMetaData) degrade on bad input rather than closing the session.
        let Ok(so) = shared_object::parse(payload) else {
            return Ok(());
        };
        if self.on_shared_object_cb.is_none() {
            return Ok(());
        }
        match self.on_shared_object_auth_cb {
            Some(auth_cb) if !auth_cb(self.conn_id, &so) => return Ok(()),
            None if self.on_publish_cb.is_some()
                || self.on_play_cb.is_some()
                || self.on_media_cb.is_some()
                || self.on_frame_cb.is_some() =>
            {
                return Ok(());
            }
            _ => {}
        }
        if let Some(cb) = self.on_shared_object_cb {
            cb(self.conn_id, &so);
        }
        Ok(())
    }

    /// Send an AMF3 Shared Object message (RTMP message type `0x10`) on this
    /// connection.
    pub fn send_shared_object(&mut self, so: &SharedObjectMessage) -> Result<()> {
        let mut amf_buf = Buffer::with_capacity(256);
        shared_object::write(so, &mut amf_buf)?;
        // AMF3 command/data/shared-object messages carry a leading 0x00
        // marker byte ahead of the AMF3 payload (mirrors how this module's
        // AMF3 command/data paths are unwrapped on read).
        let mut wire = Vec::with_capacity(amf_buf.available() + 1);
        wire.push(0x00);
        wire.extend_from_slice(amf_buf.as_slice());

        let mut cmsg = ChunkMessage::default();
        cmsg.msg_length = wire.len() as u32;
        cmsg.msg_stream_id = 0;
        cmsg.fmt = 0;
        cmsg.csid = 3;
        cmsg.msg_type_id = msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT;
        chunk_write(
            &mut self.send_buffer,
            &cmsg,
            &wire,
            wire.len(),
            self.active_chunk_size as usize,
        )
    }

    fn handle_data_message(&mut self, payload: &[u8]) -> Result<()> {
        let mut buf = Buffer::from_slice(payload);
        let first_byte = match buf.peek().first().copied() {
            Some(b) => b,
            None => return Ok(()),
        };
        if first_byte != crate::amf::amf0::Amf0Type::String as u8
            && first_byte != crate::amf::amf0::Amf0Type::LongString as u8
        {
            return Ok(());
        }

        let mut name = [0u8; 64];
        let Some(name_len) = read_data_event_name(
            &mut buf,
            first_byte == crate::amf::amf0::Amf0Type::String as u8,
            &mut name,
        ) else {
            return Ok(());
        };
        let name_str = std::str::from_utf8(&name[..name_len]).unwrap_or("");

        if name_str == "@setDataFrame" {
            let next_byte = match buf.peek().first().copied() {
                Some(b) => b,
                None => return Ok(()),
            };
            if next_byte != crate::amf::amf0::Amf0Type::String as u8
                && next_byte != crate::amf::amf0::Amf0Type::LongString as u8
            {
                return Ok(());
            }
            let mut inner = [0u8; 64];
            let Some(inner_len) = read_data_event_name(
                &mut buf,
                next_byte == crate::amf::amf0::Amf0Type::String as u8,
                &mut inner,
            ) else {
                return Ok(());
            };
            let inner_str = std::str::from_utf8(&inner[..inner_len]).unwrap_or("");
            if inner_str != "onMetaData" {
                return Ok(());
            }
        } else if name_str != "onMetaData" {
            return Ok(());
        }

        self.clear_detected_stream_metadata();
        self.parse_on_metadata_object(&mut buf)
    }

    fn parse_on_metadata_object(&mut self, buf: &mut Buffer) -> Result<()> {
        let ty = match crate::amf::amf0::read_type(buf) {
            Ok(t) => t,
            Err(_) => return Ok(()),
        };
        if ty != crate::amf::amf0::Amf0Type::Object && ty != crate::amf::amf0::Amf0Type::EcmaArray {
            return Ok(());
        }
        if ty == crate::amf::amf0::Amf0Type::EcmaArray {
            let mut count_bytes = [0u8; 4];
            if buf.read(&mut count_bytes).is_err() {
                return Ok(());
            }
        }

        let mut keys = 0usize;
        while !crate::amf::amf0::is_object_end(buf) {
            keys += 1;
            if keys > crate::amf::amf0::MAX_OBJECT_KEYS {
                return Ok(());
            }
            let mut key = [0u8; 256];
            if crate::amf::amf0::read_object_key(buf, &mut key).is_err() {
                return Ok(());
            }
            let key_len = key.iter().position(|&b| b == 0).unwrap_or(key.len());
            let key_str = std::str::from_utf8(&key[..key_len]).unwrap_or("");
            if !self.apply_metadata_key(key_str, buf) {
                return Ok(());
            }
        }
        let mut end = [0u8; 3];
        if buf.read(&mut end).is_err() {
            return Ok(());
        }
        Ok(())
    }

    fn apply_metadata_key(&mut self, key: &str, buf: &mut Buffer) -> bool {
        let ty = match crate::amf::amf0::read_type(buf) {
            Ok(t) => t,
            Err(_) => return false,
        };
        match key {
            "width" => {
                if ty == crate::amf::amf0::Amf0Type::Number {
                    let v = match crate::amf::amf0::read_number(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    if let Some(w) = positive_f64_to_u32(v) {
                        self.detected_video_width = Some(w);
                    }
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            "height" => {
                if ty == crate::amf::amf0::Amf0Type::Number {
                    let v = match crate::amf::amf0::read_number(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    if let Some(h) = positive_f64_to_u32(v) {
                        self.detected_video_height = Some(h);
                    }
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            "framerate" | "videoframerate" => {
                if ty == crate::amf::amf0::Amf0Type::Number {
                    let v = match crate::amf::amf0::read_number(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    if sane_framerate(v) {
                        self.detected_video_framerate = Some(v);
                    }
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            "audiosamplerate" => {
                if ty == crate::amf::amf0::Amf0Type::Number {
                    let v = match crate::amf::amf0::read_number(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    if let Some(sr) = positive_f64_to_u32(v) {
                        self.detected_audio_sample_rate = Some(sr);
                    }
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            "audiochannels" => {
                if ty == crate::amf::amf0::Amf0Type::Number {
                    let v = match crate::amf::amf0::read_number(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    if let Some(ch) = positive_f64_to_u32(v) {
                        if ch > 0 && ch <= 32 {
                            self.detected_audio_channels = Some(ch);
                        }
                    }
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            "stereo" => {
                if ty == crate::amf::amf0::Amf0Type::Boolean {
                    let stereo = match crate::amf::amf0::read_boolean(buf) {
                        Ok(v) => v,
                        Err(_) => return false,
                    };
                    self.detected_audio_channels = Some(if stereo { 2 } else { 1 });
                } else {
                    return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok();
                }
            }
            _ => return crate::amf::amf0::skip_value_after_type(buf, ty).is_ok(),
        }
        true
    }

    fn handle_control(&mut self, msg_type_id: u8, payload: &[u8]) -> Result<()> {
        match msg_type_id {
            msg_dispatch::RTMP_MSG_SET_CHUNK_SIZE => {
                if payload.len() >= 4 {
                    if let Ok(cs) = control::read_set_chunk_size(payload) {
                        self.chunk_reg.set_all_chunk_size(cs);
                    }
                }
            }
            msg_dispatch::RTMP_MSG_ABORT_MESSAGE => {
                if payload.len() >= 4 {
                    if let Ok(csid) = control::read_abort_message(payload) {
                        self.chunk_reg.reset_stream(csid);
                    }
                }
            }
            msg_dispatch::RTMP_MSG_WINDOW_ACK_SIZE => {
                if payload.len() >= 4 {
                    if let Ok(win) = control::read_window_ack_size(payload) {
                        self.window_ack_size = win;
                    }
                }
            }
            msg_dispatch::RTMP_MSG_ACKNOWLEDGEMENT => {
                if payload.len() >= 4 {
                    let _ = control::read_acknowledgement_size(payload);
                }
            }
            msg_dispatch::RTMP_MSG_SET_PEER_BANDWIDTH => {
                if payload.len() >= 5 {
                    let _ = control::read_set_peer_bandwidth(payload);
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Apply a chunk size to outbound writes and inbound reassembly.
    pub fn apply_chunk_size(&mut self, chunk_size: u32) {
        self.chunk_size = chunk_size;
        self.active_chunk_size = chunk_size;
        self.chunk_reg.set_all_chunk_size(chunk_size);
    }

    fn activate_announced_chunk_size(&mut self) {
        self.active_chunk_size = self.chunk_size;
        self.chunk_reg.set_all_chunk_size(self.chunk_size);
    }

    fn handle_user_control(&mut self, payload: &[u8]) -> Result<()> {
        if payload.len() < 6 {
            return Ok(());
        }
        let event_type = ((payload[0] as u16) << 8) | (payload[1] as u16);
        let (event_type, param1, param2) = if event_type == UCTRL_SET_BUFFER_LENGTH {
            control::read_user_control(payload, true)?
        } else {
            let (ty, p1, _) = control::read_user_control(payload, false)?;
            (ty, p1, None)
        };
        match event_type {
            UCTRL_PING_RESPONSE => {
                if let Some(sent_at) = self.pending_pings.remove(&param1) {
                    self.rtt_ms = sent_at.elapsed().as_secs_f64() * 1000.0;
                }
            }
            UCTRL_PING_REQUEST => {
                let now = Instant::now();
                if let Some(start) = self.inbound_ping_window_start {
                    if now.duration_since(start) >= INBOUND_PING_WINDOW {
                        self.inbound_ping_window_start = Some(now);
                        self.inbound_ping_responses = 0;
                    }
                } else {
                    self.inbound_ping_window_start = Some(now);
                }
                if self.inbound_ping_responses >= MAX_INBOUND_PING_RESPONSES {
                    return Err(ErrorCode::Protocol);
                }
                self.inbound_ping_responses += 1;
                self.send_user_control_ping_response(param1)?;
            }
            UCTRL_STREAM_BEGIN => {
                let _ = param1;
            }
            UCTRL_STREAM_EOF => {
                let _ = param1;
            }
            UCTRL_SET_BUFFER_LENGTH => {
                if let Some(ms) = param2 {
                    self.buffer_length_ms = ms;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Send an RTMP ping when due and measure RTT from the client's response.
    pub fn maybe_send_ping(&mut self) -> Result<()> {
        if self.state < ConnState::AppConnected {
            return Ok(());
        }
        let now = Instant::now();
        if self
            .last_ping_sent
            .is_some_and(|t| now.duration_since(t) < PING_INTERVAL)
        {
            return Ok(());
        }
        if let Some(queued) = &self.queued_ping {
            if now.duration_since(queued.queued_at) >= PING_TIMEOUT {
                return Err(ErrorCode::Protocol);
            }
            return Ok(());
        }

        let had_stale_ping = self
            .pending_pings
            .values()
            .any(|sent| now.duration_since(*sent) >= PING_TIMEOUT);
        self.pending_pings
            .retain(|_, sent| now.duration_since(*sent) < PING_TIMEOUT);
        if had_stale_ping {
            return Err(ErrorCode::Protocol);
        }
        if self.pending_pings.len() + usize::from(self.queued_ping.is_some()) >= MAX_PENDING_PINGS {
            return Err(ErrorCode::Protocol);
        }

        let token = self.next_ping_token;
        self.next_ping_token = self.next_ping_token.wrapping_add(1);
        self.send_user_control_ping_request(token)?;
        self.queued_ping = Some(QueuedPing {
            token,
            queued_at: now,
            bytes_until_flushed: self.send_buffer.available(),
        });
        Ok(())
    }

    pub fn handle_command(&mut self, payload: &[u8]) -> Result<()> {
        let mut buf = Buffer::from_slice(payload);
        let mut name_buf = [0u8; 64];
        if command::peek_name(&mut buf, &mut name_buf).is_err() {
            return Ok(());
        }
        let name = std::str::from_utf8(&name_buf)
            .unwrap_or("")
            .trim_end_matches('\0');
        match name {
            "connect" => {
                // A connection may only negotiate its app namespace once. Without
                // this guard a peer that's already publishing/playing under an
                // authorized app could send a second `connect` with a different
                // app, silently repointing `self.app` (and therefore relay/cache
                // routing) to a namespace `on_publish_cb`/`on_play_cb` never
                // authorized -- cache poisoning / cross-app playback.
                if self.state >= ConnState::AppConnected {
                    return Ok(());
                }
                let mut info = ConnectInfo::default();
                if command::read_connect(&mut buf, &mut info).is_err() {
                    self.send_command_error(
                        info.transaction_id,
                        "NetConnection.Connect.Rejected",
                        "Invalid connect command or capability negotiation.",
                    )?;
                    return Ok(());
                }
                self.app = match command::decode_route_amf_string(&info.app) {
                    Ok(app) => app,
                    Err(_) => {
                        self.send_command_error(
                            info.transaction_id,
                            "NetConnection.Connect.Rejected",
                            "Invalid connect app name.",
                        )?;
                        return Ok(());
                    }
                };
                if self.app.is_empty() {
                    self.send_command_error(
                        info.transaction_id,
                        "NetConnection.Connect.Rejected",
                        "Empty connect app name.",
                    )?;
                    return Ok(());
                }
                let needs_caps = info.has_four_cc_list
                    || info.has_caps_ex
                    || info.has_video_four_cc_info_map
                    || info.has_reconnect;
                if needs_caps {
                    let _ =
                        state_machine::conn_transition(&mut self.state, ConnState::CapsNegotiated);
                }
                let negotiated = if needs_caps {
                    let caps = negotiate_caps(&info);
                    self.negotiated_caps = caps.clone();
                    Some(caps)
                } else {
                    None
                };
                let _ = state_machine::conn_transition(&mut self.state, ConnState::AppConnected);
                self.send_connect_response(info.transaction_id, negotiated.as_ref())?;
                if !self.connect_cb_fired {
                    self.connect_cb_fired = true;
                    if let Some(cb) = self.on_connect_cb {
                        cb();
                    }
                }
            }
            "createStream" => {
                if self.state < ConnState::AppConnected {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Failed",
                        "connect required before createStream",
                    );
                }
                let txn = command::read_create_stream(&mut buf)?;
                if self.next_stream_id >= MAX_STREAMS_PER_CONN {
                    self.send_onstatus(0, "error", "NetStream.Failed", "Too many streams")?;
                } else {
                    // A fresh createStream replaces current_stream outright;
                    // if the stream it's replacing was actively publishing,
                    // that route is being abandoned and must be evicted now
                    // rather than left as a dangling cache-key tracking
                    // entry until this connection eventually disconnects.
                    self.evict_active_publish_route();
                    self.next_stream_id += 1;
                    let stream_id = self.next_stream_id;
                    self.current_stream = Some(Box::new(Stream::new(stream_id)));
                    let _ =
                        state_machine::conn_transition(&mut self.state, ConnState::StreamCreated);
                    self.send_create_stream_response(txn, stream_id)?;
                }
            }
            "publish" => {
                let mut stream_name = [0u8; 256];
                let mut publish_type = [0u8; 64];
                command::read_publish(&mut buf, &mut stream_name, &mut publish_type)?;
                let name_str = match command::decode_route_amf_string(&stream_name) {
                    Ok(name) => name,
                    Err(_) => {
                        return self.send_onstatus(
                            0,
                            "error",
                            "NetStream.Publish.BadName",
                            "Invalid stream name",
                        );
                    }
                };
                if name_str.is_empty() {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Publish.BadName",
                        "Empty stream name",
                    );
                }
                if self.current_stream.is_none() {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Publish.BadConnection",
                        "No stream created",
                    );
                }
                if self.on_publish_cb.is_none()
                    && (self.on_play_cb.is_some()
                        || self.on_media_cb.is_some()
                        || self.on_frame_cb.is_some())
                {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Publish.BadName",
                        "Publish not authorized",
                    );
                }
                if let Some(cb) = self.on_publish_cb {
                    if !cb(self.conn_id, &self.app, &name_str) {
                        return self.send_onstatus(
                            0,
                            "error",
                            "NetStream.Publish.BadName",
                            "Publish not authorized",
                        );
                    }
                }
                // Use current_stream.is_publishing rather than self.state
                // here: conn_transition() only allows forward moves through
                // ConnState, so a play-then-publish sequence leaves
                // self.state stuck at Playing (Publishing < Playing) even
                // though this stream is genuinely publishing again. `play`
                // explicitly clears is_publishing when it takes over a
                // stream, so the flag accurately reflects whether this
                // specific current_stream is the one actively publishing.
                let was_publishing = self
                    .current_stream
                    .as_ref()
                    .map(|s| s.is_publishing)
                    .unwrap_or(false);
                let prev_route_key = self.relay_route_key();
                let next_route_key = if !self.relay_key.is_empty() {
                    self.relay_key.clone()
                } else {
                    name_str.clone()
                };
                let renaming_route = was_publishing
                    && !prev_route_key.is_empty()
                    && prev_route_key != next_route_key;
                if !self.claim_publish_route(&next_route_key) {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Publish.BadName",
                        "Route already publishing",
                    );
                }
                // Start a publish-media deadline only for a genuinely new
                // publish session or route. Repeating `publish` for the route
                // already owned by this connection must not refresh the timer.
                if !was_publishing || renaming_route {
                    self.session_setup_started = Instant::now();
                    // Injected activity from a prior publish/idle epoch must
                    // not exempt a new empty publish from the media deadline.
                    self.injected_media_bytes = 0;
                }
                if renaming_route {
                    self.pending_cache_evictions
                        .push((self.app.clone(), prev_route_key));
                }
                if !self.defer_media_relay {
                    self.relay_enabled = true;
                }
                {
                    if let Some(ref mut stream) = self.current_stream {
                        stream.is_publishing = true;
                        stream.is_playing = false;
                        stream.name = name_str;
                    }
                    self.clear_detected_stream_metadata();
                    let _ = state_machine::conn_transition(&mut self.state, ConnState::Publishing);
                    let sid = self
                        .current_stream
                        .as_ref()
                        .map(|s| s.stream_id)
                        .unwrap_or(0);
                    self.send_onstatus(sid, "status", "NetStream.Publish.Start", "Publishing")?;
                }
            }
            "play" => {
                let mut stream_name = [0u8; 256];
                command::read_play(&mut buf, &mut stream_name)?;
                let name_str = match command::decode_route_amf_string(&stream_name) {
                    Ok(name) => name,
                    Err(_) => {
                        return self.send_onstatus(
                            0,
                            "error",
                            "NetStream.Play.Failed",
                            "Invalid stream name",
                        );
                    }
                };
                if name_str.is_empty() {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Play.Failed",
                        "Empty stream name",
                    );
                }
                if self.current_stream.is_none() {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Play.BadConnection",
                        "No stream created",
                    );
                }
                if self.on_play_cb.is_none()
                    && (self.on_publish_cb.is_some()
                        || self.on_media_cb.is_some()
                        || self.on_frame_cb.is_some())
                {
                    return self.send_onstatus(
                        0,
                        "error",
                        "NetStream.Play.Failed",
                        "Play not authorized",
                    );
                }
                if let Some(cb) = self.on_play_cb {
                    if !cb(self.conn_id, &self.app, &name_str) {
                        return self.send_onstatus(
                            0,
                            "error",
                            "NetStream.Play.Failed",
                            "Play not authorized",
                        );
                    }
                }
                if !self.defer_media_relay {
                    self.relay_enabled = true;
                }
                {
                    // `play` supersedes any publish role this current_stream
                    // held: evict the abandoned publish route's cache key
                    // now (there's no "next" publish route to preserve it
                    // for), and clear is_publishing so it can't be
                    // mistaken for an active publish by a later command.
                    self.evict_active_publish_route();
                    let already_playing_same = self
                        .current_stream
                        .as_ref()
                        .map(|s| s.is_playing && s.name == name_str)
                        .unwrap_or(false);
                    if let Some(ref mut stream) = self.current_stream {
                        stream.is_playing = true;
                        stream.is_publishing = false;
                        stream.name = name_str;
                    }
                    if !already_playing_same {
                        // Relay bytes from a previous play route are historical
                        // for pause-grace purposes. A new route must deliver
                        // fresh bytes before it can earn another grace reset.
                        self.pause_grace_media_bytes_sent = self.media_bytes_sent;
                        self.request_init_replay();
                    }
                    let _ = state_machine::conn_transition(&mut self.state, ConnState::Playing);
                    let sid = self
                        .current_stream
                        .as_ref()
                        .map(|s| s.stream_id)
                        .unwrap_or(0);
                    self.send_onstatus(sid, "status", "NetStream.Play.Start", "Playing")?;
                    self.send_stream_lifecycle_begin(sid)?;
                }
            }
            "FCUnpublish" | "deleteStream" => {
                // The client is explicitly tearing down its publish or play
                // role -- deleteStream is sent by both publishers and
                // players, not just publishers, so this must clear
                // is_playing too or a player using deleteStream would never
                // be considered idle (see `session_setup_timed_out`).
                // Release the claimed publish route now rather than holding
                // it until the TCP connection eventually closes, so a
                // different connection can immediately republish the same
                // (app, stream) route.
                let was_active = self
                    .current_stream
                    .as_ref()
                    .is_some_and(|s| s.is_publishing || s.is_playing);
                self.evict_active_publish_route();
                if let Some(ref mut stream) = self.current_stream {
                    stream.is_publishing = false;
                    stream.is_playing = false;
                    // Matches closeStream: play() never resets `paused`, so
                    // a stale true here would leave a later play on this
                    // connection silently receiving no relayed frames
                    // (relay delivery is gated on !paused).
                    stream.paused = false;
                }
                // Give this connection a fresh setup-timeout window now that
                // it's gone idle, rather than treating the moment it stops
                // publishing/playing as an immediate setup failure --
                // otherwise a client that has been legitimately active for a
                // long time gets reaped the instant it tears down if it
                // doesn't restart within whatever's left of the original 10s
                // window (see `session_setup_timed_out`). Only reset when
                // this was a genuine active->idle transition: a peer that
                // was never active gets no reset here, so it can't use
                // repeated FCUnpublish/deleteStream calls to keep dodging
                // the reaper forever.
                if was_active {
                    self.session_setup_started = Instant::now();
                }
                // Clear relay_enabled along with the publish role: with
                // `defer_media_relay`, the publish handler leaves it
                // untouched on the next `publish` (the integrator must
                // explicitly re-authorize it via on_publish_cb), so a stale
                // `true` here would let a new publish on this connection
                // relay before it's actually re-authorized.
                self.relay_enabled = false;
                if let Some(sid) = self.current_stream.as_ref().map(|s| s.stream_id) {
                    let _ = self.send_stream_lifecycle_eof(sid);
                }
            }
            "FCPublish" => {}
            "releaseStream" => {
                let mut stream_name = [0u8; 256];
                if command::read_release_stream(&mut buf, &mut stream_name).is_ok() {
                    if let Ok(name_str) = command::decode_route_amf_string(&stream_name) {
                        if !name_str.is_empty() {
                            // Force-releasing a route can evict a *different*,
                            // still-live connection's active publish claim, so
                            // this stays a safe no-op unless the host
                            // explicitly authorizes it -- unlike
                            // on_media_cb/on_publish_cb, there is no
                            // permissive default here.
                            let authorized = self
                                .on_release_stream_cb
                                .is_some_and(|cb| cb(self.conn_id, &self.app, &name_str));
                            if authorized {
                                if let Some(ref routes) = self.publish_routes {
                                    routes.force_release(&self.app, &name_str);
                                }
                            }
                        }
                    }
                }
            }
            "pause" => {
                if let Ok(pause_flag) = command::read_pause(&mut buf) {
                    if let Some(ref mut stream) = self.current_stream {
                        if pause_flag && stream.is_playing && !stream.paused {
                            // Give paused players the same setup-timeout grace
                            // window as FCUnpublish/deleteStream so a brief pause
                            // during playback is not reaped immediately. Require
                            // relay activity since the previous grace reset; the
                            // lifetime `media_bytes_sent` counter alone would let
                            // historical bytes power unlimited pause cycling.
                            if self.media_bytes_sent > self.pause_grace_media_bytes_sent {
                                self.session_setup_started = Instant::now();
                                self.pause_grace_media_bytes_sent = self.media_bytes_sent;
                            }
                        }
                        stream.paused = pause_flag;
                    }
                    let sid = self
                        .current_stream
                        .as_ref()
                        .map(|s| s.stream_id)
                        .unwrap_or(0);
                    let (code, desc) = if pause_flag {
                        ("NetStream.Pause.Notify", "Paused")
                    } else {
                        ("NetStream.Unpause.Notify", "Unpaused")
                    };
                    self.send_onstatus(sid, "status", code, desc)?;
                }
            }
            "seek" => {
                let _millis = command::read_seek(&mut buf).unwrap_or(0.0);
                let sid = self
                    .current_stream
                    .as_ref()
                    .map(|s| s.stream_id)
                    .unwrap_or(0);
                self.send_onstatus(sid, "status", "NetStream.Seek.Notify", "Seeking")?;
            }
            "receiveAudio" => {
                if let Ok(flag) = command::read_bool_command(&mut buf) {
                    if let Some(ref mut stream) = self.current_stream {
                        stream.receive_audio = flag;
                    }
                }
            }
            "receiveVideo" => {
                if let Ok(flag) = command::read_bool_command(&mut buf) {
                    if let Some(ref mut stream) = self.current_stream {
                        stream.receive_video = flag;
                    }
                }
            }
            "closeStream" => {
                let target_id = command::read_close_stream(&mut buf)
                    .ok()
                    .flatten()
                    .or_else(|| self.current_stream.as_ref().map(|s| s.stream_id))
                    .unwrap_or(0);
                if self.current_stream.as_ref().map(|s| s.stream_id) == Some(target_id) {
                    let was_active = self
                        .current_stream
                        .as_ref()
                        .is_some_and(|s| s.is_publishing || s.is_playing);
                    self.evict_active_publish_route();
                    if let Some(ref mut stream) = self.current_stream {
                        stream.is_playing = false;
                        stream.is_publishing = false;
                        stream.paused = false;
                    }
                    // See the matching comment in the FCUnpublish/deleteStream
                    // arm: give this connection a fresh setup-timeout window
                    // now that it's gone idle, but only on a genuine
                    // active->idle transition -- a peer that was never
                    // publishing/playing gets no reset, so it can't use
                    // repeated closeStream calls to dodge the reaper forever.
                    if was_active {
                        self.session_setup_started = Instant::now();
                    }
                    self.relay_enabled = false;
                    let _ = self.send_stream_lifecycle_eof(target_id);
                }
            }
            _ => {}
        }
        Ok(())
    }

    pub fn send_connect_response(
        &mut self,
        transaction_id: f64,
        caps: Option<&NegotiatedCaps>,
    ) -> Result<()> {
        let win = SERVER_WINDOW_ACK_SIZE.to_be_bytes();
        self.send_control(0x05, &win)?;
        let mut bw = [0u8; 5];
        let bw_val = SERVER_PEER_BANDWIDTH.to_be_bytes();
        bw[..4].copy_from_slice(&bw_val);
        bw[4] = PEER_BANDWIDTH_DYNAMIC;
        self.send_control(0x06, &bw)?;
        let cs = self.chunk_size.to_be_bytes();
        self.send_control(0x01, &cs)?;
        // Negotiation complete: subsequent server chunks and client sends use
        // the announced size (connect AMF above was still at 128).
        self.activate_announced_chunk_size();
        let mut amf_buf = Buffer::with_capacity(512);
        crate::amf::amf0::write_string(&mut amf_buf, "_result")?;
        crate::amf::amf0::write_number(&mut amf_buf, transaction_id)?;
        crate::amf::amf0::write_null(&mut amf_buf)?;
        crate::amf::amf0::write_object_begin(&mut amf_buf)?;
        crate::amf::amf0::write_object_key(&mut amf_buf, "level")?;
        crate::amf::amf0::write_string(&mut amf_buf, "status")?;
        crate::amf::amf0::write_object_key(&mut amf_buf, "code")?;
        crate::amf::amf0::write_string(&mut amf_buf, "NetConnection.Connect.Success")?;
        crate::amf::amf0::write_object_key(&mut amf_buf, "description")?;
        crate::amf::amf0::write_string(&mut amf_buf, "Connection succeeded.")?;
        if let Some(caps) = caps {
            write_negotiated_caps(&mut amf_buf, caps)?;
        }
        crate::amf::amf0::write_object_end(&mut amf_buf)?;
        self.send_command(0, amf_buf.as_slice())
    }

    pub fn send_command_error(
        &mut self,
        transaction_id: f64,
        code: &str,
        description: &str,
    ) -> Result<()> {
        let mut amf_buf = Buffer::with_capacity(256);
        command::build_error(&mut amf_buf, transaction_id, code, description)?;
        self.send_command(0, amf_buf.as_slice())
    }

    pub fn send_create_stream_response(
        &mut self,
        transaction_id: f64,
        stream_id: u32,
    ) -> Result<()> {
        let mut amf_buf = Buffer::with_capacity(256);
        command::build_create_stream_result(&mut amf_buf, transaction_id, stream_id as f64)?;
        self.send_command(0, amf_buf.as_slice())
    }

    pub fn send_onstatus(
        &mut self,
        stream_id: u32,
        level: &str,
        code: &str,
        description: &str,
    ) -> Result<()> {
        let mut amf_buf = Buffer::with_capacity(512);
        command::build_onstatus(&mut amf_buf, level, code, description)?;
        self.send_command(stream_id, amf_buf.as_slice())
    }

    /// Ask the client to reconnect, per the E-RTMP v2 reconnect mechanism:
    /// sends `NetConnection.Connect.ReconnectRequest` on the connection
    /// (stream id 0). `tc_url` redirects the client to a different server;
    /// `None` tells it to reuse its current connection URL. The client is
    /// expected to keep streaming through the next media boundary, then
    /// establish a new connection and disconnect from this one -- this call
    /// only sends the request, it does not close the connection itself.
    pub fn send_reconnect_request(
        &mut self,
        tc_url: Option<&str>,
        description: Option<&str>,
    ) -> Result<()> {
        let mut amf_buf = Buffer::with_capacity(512);
        command::build_reconnect_request(&mut amf_buf, tc_url, description)?;
        self.send_command(0, amf_buf.as_slice())
    }

    pub fn flush(&mut self) -> Result<()> {
        if self.client_fd < 0 || self.send_buffer.available() == 0 {
            self.commit_flushed_ping();
            return Ok(());
        }
        let Some(ref mut transport) = self.transport else {
            self.commit_flushed_ping();
            return Ok(());
        };
        while self.send_buffer.available() > 0 {
            let pending = self.send_buffer.peek();
            let n = transport.try_send(pending, &mut 0i32)?;
            if n == 0 {
                break;
            }
            self.send_buffer.drain(n);
            if let Some(ref mut queued) = self.queued_ping {
                queued.bytes_until_flushed = queued.bytes_until_flushed.saturating_sub(n);
            }
        }
        self.commit_flushed_ping();
        Ok(())
    }

    /// Drop the transport and clear the embedder-visible fd copy.
    pub fn disconnect_transport(&mut self) {
        self.transport = None;
        self.client_fd = -1;
    }

    fn commit_flushed_ping(&mut self) {
        let Some(queued) = self.queued_ping.as_ref() else {
            return;
        };
        if queued.bytes_until_flushed > 0 {
            return;
        }
        let now = Instant::now();
        self.pending_pings.insert(queued.token, now);
        self.last_ping_sent = Some(now);
        self.queued_ping = None;
    }

    pub fn send_frame(
        &mut self,
        frame_type: FrameType,
        timestamp: u32,
        payload: &[u8],
    ) -> Result<()> {
        let stream_id = self
            .current_stream
            .as_ref()
            .map(|s| s.stream_id)
            .unwrap_or(1);
        let mut cmsg = ChunkMessage::default();
        cmsg.timestamp = timestamp;
        cmsg.msg_length = payload.len() as u32;
        cmsg.msg_stream_id = stream_id;
        cmsg.fmt = 0;
        if frame_type == FrameType::Audio {
            cmsg.csid = 4;
            cmsg.msg_type_id = 0x08;
        } else {
            cmsg.csid = 6;
            cmsg.msg_type_id = 0x09;
        }
        chunk_write(
            &mut self.send_buffer,
            &cmsg,
            payload,
            payload.len(),
            self.active_chunk_size as usize,
        )?;
        self.media_bytes_sent = self.media_bytes_sent.saturating_add(payload.len() as u64);
        Ok(())
    }

    /// Send an AMF0 data message (e.g. onMetaData) on the current stream.
    pub fn send_data_message(&mut self, timestamp: u32, payload: &[u8]) -> Result<()> {
        let stream_id = self
            .current_stream
            .as_ref()
            .map(|s| s.stream_id)
            .unwrap_or(1);
        let mut cmsg = ChunkMessage::default();
        cmsg.timestamp = timestamp;
        cmsg.msg_length = payload.len() as u32;
        cmsg.msg_stream_id = stream_id;
        cmsg.fmt = 0;
        cmsg.csid = 5;
        cmsg.msg_type_id = msg_dispatch::RTMP_MSG_AMF0_DATA;
        chunk_write(
            &mut self.send_buffer,
            &cmsg,
            payload,
            payload.len(),
            self.active_chunk_size as usize,
        )?;
        self.media_bytes_sent = self.media_bytes_sent.saturating_add(payload.len() as u64);
        Ok(())
    }

    fn send_control(&mut self, ty: u8, data: &[u8]) -> Result<()> {
        let mut msg = ChunkMessage::default();
        msg.csid = 2;
        msg.fmt = 0;
        msg.msg_length = data.len() as u32;
        msg.msg_type_id = ty;
        msg.msg_stream_id = 0;
        chunk_write(
            &mut self.send_buffer,
            &msg,
            data,
            data.len(),
            self.active_chunk_size as usize,
        )
    }

    fn send_command(&mut self, msg_stream_id: u32, amf_data: &[u8]) -> Result<()> {
        let mut cmd_msg = ChunkMessage::default();
        cmd_msg.csid = 3;
        cmd_msg.fmt = 0;
        cmd_msg.timestamp = 0;
        cmd_msg.msg_length = amf_data.len() as u32;
        cmd_msg.msg_type_id = 0x14;
        cmd_msg.msg_stream_id = msg_stream_id;
        chunk_write(
            &mut self.send_buffer,
            &cmd_msg,
            amf_data,
            amf_data.len(),
            self.active_chunk_size as usize,
        )
    }

    fn send_acknowledgement(&mut self, seq: u32) -> Result<()> {
        self.send_control(0x03, &seq.to_be_bytes())
    }

    fn send_user_control_ping_request(&mut self, timestamp: u32) -> Result<()> {
        let mut buf = Buffer::with_capacity(6);
        control::write_user_control_ping_request(&mut buf, timestamp)?;
        self.send_control(msg_dispatch::RTMP_MSG_USER_CONTROL, buf.as_slice())
    }

    fn send_user_control_ping_response(&mut self, timestamp: u32) -> Result<()> {
        let mut buf = Buffer::with_capacity(6);
        control::write_user_control_ping_response(&mut buf, timestamp)?;
        self.send_control(msg_dispatch::RTMP_MSG_USER_CONTROL, buf.as_slice())
    }

    fn send_stream_lifecycle_begin(&mut self, stream_id: u32) -> Result<()> {
        let mut buf = Buffer::with_capacity(14);
        control::write_user_control_stream_begin(&mut buf, stream_id)?;
        self.send_control(msg_dispatch::RTMP_MSG_USER_CONTROL, buf.as_slice())?;
        buf.reset();
        control::write_user_control_set_buffer_length(&mut buf, stream_id, self.buffer_length_ms)?;
        self.send_control(msg_dispatch::RTMP_MSG_USER_CONTROL, buf.as_slice())
    }

    fn send_stream_lifecycle_eof(&mut self, stream_id: u32) -> Result<()> {
        let mut buf = Buffer::with_capacity(6);
        control::write_user_control_stream_eof(&mut buf, stream_id)?;
        self.send_control(msg_dispatch::RTMP_MSG_USER_CONTROL, buf.as_slice())
    }

    fn invoke_multitrack_on_frame_cb(
        &mut self,
        cb: fn(&Frame),
        frame_type: FrameType,
        timestamp: u32,
        track_id: u8,
        fourcc: [u8; 4],
        packet_type: u8,
        video_frame_type: u8,
        payload: &[u8],
    ) {
        self.frame_cb_scratch.clear();
        self.frame_cb_scratch.extend_from_slice(payload);
        let mut frame = Frame {
            frame_type,
            timestamp,
            size: self.frame_cb_scratch.len() as u32,
            data: self.frame_cb_scratch.as_ptr(),
            track_id,
            ..Default::default()
        };
        populate_multitrack_frame(&mut frame, fourcc, packet_type, video_frame_type);
        cb(&frame);
    }
    fn invoke_on_frame_cb(
        &mut self,
        cb: fn(&Frame),
        frame_type: FrameType,
        timestamp: u32,
        track_id: u8,
        payload: &[u8],
    ) {
        self.frame_cb_scratch.clear();
        self.frame_cb_scratch.extend_from_slice(payload);
        let mut frame = Frame {
            frame_type,
            timestamp,
            size: self.frame_cb_scratch.len() as u32,
            data: self.frame_cb_scratch.as_ptr(),
            track_id,
            ..Default::default()
        };
        populate_av_frame(&mut frame, &self.frame_cb_scratch);
        cb(&frame);
    }
}

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

fn positive_f64_to_u32(v: f64) -> Option<u32> {
    if !v.is_finite() || v < 0.0 || v > u32::MAX as f64 {
        return None;
    }
    Some(v as u32)
}

fn sane_framerate(v: f64) -> bool {
    v.is_finite() && v > 0.0 && v <= 1000.0
}

fn read_data_event_name(buf: &mut Buffer, is_string: bool, out: &mut [u8; 64]) -> Option<usize> {
    match if is_string {
        crate::amf::amf0::read_string(buf, out)
    } else {
        crate::amf::amf0::read_long_string(buf, out)
    } {
        Ok(n) => Some(n),
        Err(_) => None,
    }
}

/// Wildcard FourCC (`*`) is valid in E-RTMP capability objects but must not
/// appear on publisher media tags — it carries no concrete codec identity and
/// would let codec-specific `on_media_cb` deny lists be bypassed.
fn is_wildcard_media_fourcc(fourcc: &[u8; 4]) -> bool {
    fourcc[0] == b'*'
}

/// Codec label for `on_media_cb`, or `None` when the wire FourCC cannot be
/// authorized (wildcard / unknown-enhanced identity).
fn media_fourcc_auth_label(fourcc: &[u8; 4]) -> Option<String> {
    if is_wildcard_media_fourcc(fourcc) {
        return None;
    }
    Some(fourcc_auth_label(fourcc))
}

/// Stable codec label for `on_media_cb` authorization. Valid UTF-8 FourCCs are
/// passed through; non-UTF-8 bytes are hex-encoded so deny-list policies can
/// still observe the identity instead of receiving `None`.
fn fourcc_auth_label(fourcc: &[u8; 4]) -> String {
    match std::str::from_utf8(fourcc) {
        Ok(label) if !label.is_empty() => label.to_string(),
        _ => format!(
            "fourcc:{:02x}{:02x}{:02x}{:02x}",
            fourcc[0], fourcc[1], fourcc[2], fourcc[3]
        ),
    }
}

fn detect_video_codec(payload: &[u8]) -> Option<String> {
    if let Some(cc) = first_track_fourcc(FrameType::Video, payload) {
        return media_fourcc_auth_label(&cc);
    }
    let mut hdr = VideoHeader::default();
    if crate::ertmp::exvideo::exvideo_parse(payload, &mut hdr).is_err() {
        return None;
    }
    if hdr.is_ex_header != 0 {
        // Unpeeled ModEx wrappers expose extension metadata at bytes 1..5,
        // not the inner codec FourCC — treat as unknown so deny lists apply.
        if hdr.packet_type == ERTMP_PACKET_TYPE_MODEX {
            return None;
        }
        let mut fourcc = [0u8; 4];
        fourcc.copy_from_slice(&hdr.fourcc[..4]);
        return media_fourcc_auth_label(&fourcc);
    } else {
        match payload[0] & 0x0F {
            7 => Some("avc1".to_string()),
            12 => Some("hvc1".to_string()),
            13 => Some("av01".to_string()),
            nibble => Some(format!("legacy:{nibble:x}")),
        }
    }
}

fn detect_audio_codec(payload: &[u8]) -> Option<String> {
    if let Some(cc) = first_track_fourcc(FrameType::Audio, payload) {
        return media_fourcc_auth_label(&cc);
    }
    let mut hdr = AudioHeader::default();
    if crate::ertmp::exaudio::exaudio_parse(payload, &mut hdr).is_err() {
        return None;
    }
    if hdr.is_ex_header != 0 {
        if hdr.packet_type == ERTMP_PACKET_TYPE_MODEX {
            return None;
        }
        let mut fourcc = [0u8; 4];
        fourcc.copy_from_slice(&hdr.fourcc[..4]);
        return media_fourcc_auth_label(&fourcc);
    } else {
        match hdr.audio_codec {
            AudioCodec::Aac => Some("mp4a".to_string()),
            AudioCodec::Mp3 => Some("mp3".to_string()),
            AudioCodec::Opus => Some("Opus".to_string()),
            other => Some(format!("legacy:{other:?}")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::amf::amf0;
    use crate::session::stream::Stream;

    #[test]
    fn relay_budget_counts_actual_retained_bytes() {
        let mut conn = Conn::new();
        conn.max_pending_relay_bytes = 6;

        assert!(
            conn.queue_relay_frame(FrameType::Video, 0, b"data", b"data")
                .is_ok()
        );
        assert_eq!(conn.pending_relay_bytes(), 4);
        assert!(conn.pending_relay[0].cache_payload.is_none());
        assert_eq!(conn.pending_relay[0].cache_payload(), b"data");

        assert!(
            conn.queue_relay_frame(FrameType::Video, 0, b"x", b"y")
                .is_ok()
        );
        assert_eq!(conn.pending_relay_bytes(), 6);
        assert!(
            conn.queue_relay_frame(FrameType::Video, 0, b"z", b"z")
                .is_err()
        );
    }
    #[test]
    fn relay_route_key_prefers_relay_key_over_rtmp_name() {
        let mut conn = Conn::new();
        conn.relay_key = "stream-db-id".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(ref mut stream) = conn.current_stream {
            stream.name = "pub_or_play_key".to_string();
        }
        assert_eq!(conn.relay_route_key(), "stream-db-id");
    }

    #[test]
    fn relay_route_key_falls_back_to_rtmp_stream_name() {
        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(ref mut stream) = conn.current_stream {
            stream.name = "legacy_name".to_string();
        }
        assert_eq!(conn.relay_route_key(), "legacy_name");
    }

    #[test]
    fn connect_with_caps_sets_negotiated_state_and_caps() {
        let mut conn = Conn::new();
        conn.state = ConnState::Connected;

        let mut buf = Buffer::new();
        amf0::write_string(&mut buf, "connect").unwrap();
        amf0::write_number(&mut buf, 1.0).unwrap();
        amf0::write_object_begin(&mut buf).unwrap();
        amf0::write_object_key(&mut buf, "app").unwrap();
        amf0::write_string(&mut buf, "live").unwrap();
        amf0::write_object_key(&mut buf, "fourCcList").unwrap();
        buf.write(&[0x0A, 0x00, 0x00, 0x00, 0x02]).unwrap();
        amf0::write_string(&mut buf, "av01").unwrap();
        amf0::write_string(&mut buf, "hvc1").unwrap();
        amf0::write_object_end(&mut buf).unwrap();

        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.state, ConnState::AppConnected);
        assert!(conn.negotiated_caps.has_four_cc_list);
        assert_eq!(conn.negotiated_caps.four_cc_list.count, 2);
    }

    #[test]
    fn connect_with_caps_ex_enables_multitrack() {
        let mut conn = Conn::new();
        conn.state = ConnState::Connected;

        let mut buf = Buffer::new();
        amf0::write_string(&mut buf, "connect").unwrap();
        amf0::write_number(&mut buf, 1.0).unwrap();
        amf0::write_object_begin(&mut buf).unwrap();
        amf0::write_object_key(&mut buf, "app").unwrap();
        amf0::write_string(&mut buf, "live").unwrap();
        amf0::write_object_key(&mut buf, "capsEx").unwrap();
        amf0::write_number(&mut buf, CAPS_EX_MASK_MULTITRACK as f64).unwrap();
        amf0::write_object_end(&mut buf).unwrap();

        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.state, ConnState::AppConnected);
        assert!(conn.negotiated_caps.has_caps_ex);
        assert!(conn.negotiated_caps.multitrack_enabled);
    }

    #[test]
    fn connect_parse_failure_sends_error_response() {
        let mut conn = Conn::new();
        let mut buf = Buffer::with_capacity(512);
        let long_app = "a".repeat(256);
        command::build_connect(
            &mut buf,
            &long_app,
            "rtmp://host/app",
            "",
            "",
            "FMLE/3.0",
            0,
            0,
            None,
        )
        .unwrap();
        assert_eq!(conn.handle_command(buf.as_slice()), Ok(()));
        assert!(conn.app.is_empty());
        assert_ne!(conn.state, ConnState::AppConnected);
        assert!(
            conn.send_buffer
                .peek()
                .windows(b"_error".len())
                .any(|window| window == b"_error")
        );
    }

    #[test]
    fn connect_after_app_connected_does_not_repoint_app_namespace() {
        let mut conn = Conn::new();

        let mut buf = Buffer::with_capacity(256);
        command::build_connect(
            &mut buf,
            "public",
            "rtmp://host/public",
            "",
            "",
            "FMLE/3.0",
            0,
            0,
            None,
        )
        .unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.app, "public");
        assert_eq!(conn.state, ConnState::AppConnected);

        // A second `connect` after the app namespace is already authorized
        // must be ignored -- it must not silently repoint `self.app` (and
        // therefore relay/cache routing) to a namespace that was never
        // passed through on_publish_cb/on_play_cb.
        let mut buf2 = Buffer::with_capacity(256);
        command::build_connect(
            &mut buf2,
            "private",
            "rtmp://host/private",
            "",
            "",
            "FMLE/3.0",
            0,
            0,
            None,
        )
        .unwrap();
        conn.handle_command(buf2.as_slice()).unwrap();
        assert_eq!(conn.app, "public");
        assert_eq!(conn.state, ConnState::AppConnected);
    }

    fn build_publish_with_raw_stream_name(stream_bytes: &[u8]) -> Buffer {
        let mut buf = Buffer::with_capacity(128);
        amf0::write_string(&mut buf, "publish").unwrap();
        amf0::write_number(&mut buf, 1.0).unwrap();
        amf0::write_null(&mut buf).unwrap();
        let len = stream_bytes.len();
        assert!(len <= u16::MAX as usize);
        buf.write(&[amf0::Amf0Type::String as u8, (len >> 8) as u8, len as u8])
            .unwrap();
        buf.write(stream_bytes).unwrap();
        amf0::write_string(&mut buf, "live").unwrap();
        buf
    }

    fn build_connect_with_raw_app(app_bytes: &[u8]) -> Buffer {
        let mut buf = Buffer::with_capacity(256);
        amf0::write_string(&mut buf, "connect").unwrap();
        amf0::write_number(&mut buf, 1.0).unwrap();
        amf0::write_object_begin(&mut buf).unwrap();
        amf0::write_object_key(&mut buf, "app").unwrap();
        let len = app_bytes.len();
        assert!(len <= u16::MAX as usize);
        buf.write(&[amf0::Amf0Type::String as u8, (len >> 8) as u8, len as u8])
            .unwrap();
        buf.write(app_bytes).unwrap();
        amf0::write_object_key(&mut buf, "tcUrl").unwrap();
        amf0::write_string(&mut buf, "rtmp://host/live").unwrap();
        amf0::write_object_end(&mut buf).unwrap();
        buf
    }

    #[test]
    fn connect_rejects_invalid_utf8_app_name() {
        let mut conn = Conn::new();
        let buf = build_connect_with_raw_app(&[0xFF, 0xFE]);
        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.app, "");
        assert_eq!(conn.state, ConnState::TcpAccepted);
    }

    #[test]
    fn publish_rejects_invalid_utf8_stream_name() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        let buf = build_publish_with_raw_stream_name(&[0x80, 0x81]);
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);
    }

    #[test]
    fn publish_rejects_play_only_connections_when_publish_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_play_cb = Some(|_, _, _| true);

        let mut play = Buffer::with_capacity(128);
        command::build_play(&mut play, "viewer").unwrap();
        conn.handle_command(play.as_slice()).unwrap();
        assert!(conn.current_stream.as_ref().unwrap().is_playing);

        let mut publish = Buffer::with_capacity(128);
        command::build_publish(&mut publish, "inject", "live").unwrap();
        conn.handle_command(publish.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_publishing,
            "play-authorized peers must not publish when on_publish_cb is unset"
        );
    }

    #[test]
    fn play_rejects_publish_only_connections_when_play_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_publish_cb = Some(|_, _, _| true);

        let mut play = Buffer::with_capacity(128);
        command::build_play(&mut play, "viewer").unwrap();
        conn.handle_command(play.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_playing,
            "publish-authorized peers must not play when on_play_cb is unset"
        );
        assert!(
            !conn.relay_enabled,
            "relay must stay disabled when play is rejected on a publish-only server"
        );
    }

    #[test]
    fn publish_rejects_media_only_connections_when_publish_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_media_cb = Some(|_, _, _| true);

        let mut publish = Buffer::with_capacity(128);
        command::build_publish(&mut publish, "inject", "live").unwrap();
        conn.handle_command(publish.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_publishing,
            "media-filtered servers must not accept publish without on_publish_cb"
        );
        assert!(
            !conn.relay_enabled,
            "relay must stay disabled when publish is rejected on a media-only server"
        );
    }

    #[test]
    fn play_rejects_media_only_connections_when_play_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_media_cb = Some(|_, _, _| true);

        let mut play = Buffer::with_capacity(128);
        command::build_play(&mut play, "viewer").unwrap();
        conn.handle_command(play.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_playing,
            "media-filtered servers must not accept play without on_play_cb"
        );
        assert!(
            !conn.relay_enabled,
            "relay must stay disabled when play is rejected on a media-only server"
        );
    }

    #[test]
    fn publish_rejects_frame_only_connections_when_publish_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_frame_cb = Some(|_| {});

        let mut publish = Buffer::with_capacity(128);
        command::build_publish(&mut publish, "inject", "live").unwrap();
        conn.handle_command(publish.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_publishing,
            "frame-observing servers must not accept publish without on_publish_cb"
        );
        assert!(
            !conn.relay_enabled,
            "relay must stay disabled when publish is rejected on a frame-only server"
        );
    }

    #[test]
    fn play_rejects_frame_only_connections_when_play_cb_missing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.on_frame_cb = Some(|_| {});

        let mut play = Buffer::with_capacity(128);
        command::build_play(&mut play, "viewer").unwrap();
        conn.handle_command(play.as_slice()).unwrap();
        assert!(
            !conn.current_stream.as_ref().unwrap().is_playing,
            "frame-observing servers must not accept play without on_play_cb"
        );
        assert!(
            !conn.relay_enabled,
            "relay must stay disabled when play is rejected on a frame-only server"
        );
    }

    #[test]
    fn defer_media_relay_keeps_relay_disabled_without_publish_cb() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.defer_media_relay = true;

        let mut publish = Buffer::with_capacity(128);
        command::build_publish(&mut publish, "stream", "live").unwrap();
        conn.handle_command(publish.as_slice()).unwrap();

        assert!(conn.current_stream.as_ref().unwrap().is_publishing);
        assert!(
            !conn.relay_enabled,
            "defer_media_relay must hold relay off until the integrator enables it"
        );
    }

    #[test]
    fn invalid_utf8_stream_names_do_not_collide_on_empty_relay_namespace() {
        let mut first = Conn::new();
        first.app = "live".to_string();
        first.current_stream = Some(Box::new(Stream::new(1)));
        let buf = build_publish_with_raw_stream_name(&[0x80]);
        first.handle_command(buf.as_slice()).unwrap();
        assert!(!first.current_stream.as_ref().unwrap().is_publishing);

        let mut second = Conn::new();
        second.app = "live".to_string();
        second.current_stream = Some(Box::new(Stream::new(1)));
        let buf = build_publish_with_raw_stream_name(&[0x81]);
        second.handle_command(buf.as_slice()).unwrap();
        assert!(!second.current_stream.as_ref().unwrap().is_publishing);
    }

    #[test]
    fn apply_chunk_size_updates_outbound_and_inbound() {
        let mut conn = Conn::new();
        conn.apply_chunk_size(4096);
        assert_eq!(conn.chunk_size, 4096);
        assert_eq!(conn.active_chunk_size, 4096);
        assert_eq!(conn.chunk_reg.default_chunk_size, 4096);
    }

    #[test]
    fn new_connection_starts_at_rtmp_default_chunk_size() {
        let conn = Conn::new();
        assert_eq!(conn.chunk_size, DEFAULT_CHUNK_SIZE);
        assert_eq!(conn.active_chunk_size, DEFAULT_CHUNK_SIZE);
        assert_eq!(conn.chunk_reg.default_chunk_size, DEFAULT_CHUNK_SIZE);
    }

    #[test]
    fn enhanced_av1_media_frames_accepted_while_publishing() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }

        let av1_seq = vec![0x90, b'a', b'v', b'0', b'1', 0x01, 0x02, 0x03];
        assert!(
            conn.handle_media_frame(1, FrameType::Video, 0, &av1_seq)
                .is_ok()
        );

        let aac_seq = vec![0xAF, 0x00, 0x12, 0x10];
        assert!(
            conn.handle_media_frame(1, FrameType::Audio, 0, &aac_seq)
                .is_ok()
        );

        let av1_frame = vec![0x91, b'a', b'v', b'0', b'1', 0xDE, 0xAD, 0xBE, 0xEF];
        assert!(
            conn.handle_media_frame(1, FrameType::Video, 40, &av1_frame)
                .is_ok()
        );
    }

    #[test]
    fn publish_rename_with_relay_key_does_not_evict_stale_rtmp_name() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.relay_key = "route-1".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.pending_cache_evictions.is_empty());
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "A");

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "B", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        // relay_route_key() is pinned to relay_key, so republishing under a new
        // RTMP stream name must NOT queue an eviction for the stale RTMP name
        // ("A") -- the real cache key ("route-1") never changed.
        assert!(conn.pending_cache_evictions.is_empty());
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "B");
    }

    #[test]
    fn publish_rename_without_relay_key_evicts_old_route_key() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.pending_cache_evictions.is_empty());

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "B", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert_eq!(
            conn.pending_cache_evictions,
            vec![("live".to_string(), "A".to_string())]
        );
    }

    #[test]
    fn play_then_publish_does_not_evict_foreign_cache_key() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_play(&mut buf, "victim").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "victim");
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "other", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        // This connection only ever played "victim" -- it never published it
        // -- so publishing "other" afterwards must not queue an eviction for
        // a cache key this connection never created.
        assert!(conn.pending_cache_evictions.is_empty());
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "other");
        assert!(!conn.current_stream.as_ref().unwrap().is_playing);
    }

    #[test]
    fn evict_active_publish_route_evicts_both_claimed_and_pinned_relay_key() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        // Publish claims the route under the RTMP name (no relay_key set
        // yet), so frames get cached under "A".
        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.pending_cache_evictions.is_empty());

        // Integrator pins relay_key mid-publish, after the route was
        // already claimed under "A". New frames from this point on are
        // cached under "route-pinned" (relay_route_key() is live at
        // frame-queue time), diverging from the claimed route key.
        conn.relay_key = "route-pinned".to_string();

        // `play` supersedes the active publish, evicting whatever was
        // being served. Both the originally claimed key ("A") and the
        // now-current relay route key ("route-pinned") must be evicted,
        // since cached frames may exist under either.
        let mut buf = Buffer::with_capacity(128);
        command::build_play(&mut buf, "victim").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert_eq!(
            conn.pending_cache_evictions,
            vec![
                ("live".to_string(), "A".to_string()),
                ("live".to_string(), "route-pinned".to_string()),
            ]
        );
    }

    #[test]
    fn publish_then_play_then_publish_does_not_evict_played_stream_key() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.pending_cache_evictions.is_empty());

        // `play` supersedes the active publish of "A" on this stream, so it
        // must evict "A" itself right away (there's no future publish
        // rename to hang that eviction off of, and is_publishing is cleared
        // so this stream can no longer be mistaken for an active publisher
        // of "A").
        let mut buf = Buffer::with_capacity(128);
        command::build_play(&mut buf, "victim").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "victim");
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);
        assert_eq!(
            conn.pending_cache_evictions,
            vec![("live".to_string(), "A".to_string())]
        );
        conn.pending_cache_evictions.clear();

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "other", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        // This connection was never actively publishing "victim" -- it was
        // only playing it -- so publishing "other" must not queue a second
        // eviction for a cache key it never owned.
        assert!(conn.pending_cache_evictions.is_empty());
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "other");
    }

    #[test]
    fn create_stream_evicts_active_publish_route() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.state = ConnState::AppConnected;
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.pending_cache_evictions.is_empty());
        assert!(conn.current_stream.as_ref().unwrap().is_publishing);

        // A fresh createStream replaces current_stream outright, abandoning
        // the active publish of "A" with no future rename to hang an
        // eviction off of -- it must be evicted immediately here, not left
        // as a dangling publisher_cache_keys tracking entry until this
        // connection eventually disconnects.
        let mut buf = Buffer::with_capacity(128);
        command::build_create_stream(&mut buf, 4.0).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert_eq!(
            conn.pending_cache_evictions,
            vec![("live".to_string(), "A".to_string())]
        );
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);
        assert_eq!(conn.current_stream.as_ref().unwrap().name, "");
    }

    #[test]
    fn handle_control_peer_set_chunk_size_updates_inbound_only() {
        let mut conn = Conn::new();
        conn.chunk_size = 4096;
        conn.handle_control(
            msg_dispatch::RTMP_MSG_SET_CHUNK_SIZE,
            &8192u32.to_be_bytes(),
        )
        .unwrap();
        assert_eq!(conn.chunk_size, 4096);
        assert_eq!(conn.active_chunk_size, DEFAULT_CHUNK_SIZE);
        assert_eq!(conn.chunk_reg.default_chunk_size, 8192);
    }

    #[test]
    fn inbound_ping_requests_are_rate_limited() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.transport = None;
        let mut ping = |token: u32| {
            let mut buf = Buffer::with_capacity(6);
            control::write_user_control_ping_request(&mut buf, token).unwrap();
            conn.handle_user_control(buf.as_slice())
        };
        for token in 0..8 {
            assert!(ping(token).is_ok(), "token {token} should be accepted");
        }
        assert!(
            matches!(ping(99), Err(ErrorCode::Protocol)),
            "9th ping in one second must be rejected"
        );
    }

    #[test]
    fn post_connect_idle_without_publish_or_play_times_out() {
        use std::time::{Duration, Instant};

        let mut conn = Conn::new();
        conn.state = ConnState::AppConnected;
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            conn.session_setup_timed_out(),
            "AppConnected peers that never publish/play must be reaped"
        );

        let mut publishing = Conn::new();
        publishing.state = ConnState::Publishing;
        publishing.current_stream = Some(Box::new(Stream {
            is_publishing: true,
            ..Stream::new(1)
        }));
        publishing.media_bytes_received = 1;
        publishing.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            !publishing.session_setup_timed_out(),
            "publishers that have sent media must not be reaped by the setup timer"
        );

        let mut injected_only = Conn::new();
        injected_only.state = ConnState::Publishing;
        injected_only.app = "live".to_string();
        injected_only.current_stream = Some(Box::new(Stream {
            is_publishing: true,
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        injected_only
            .inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
            .unwrap();
        injected_only.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert_eq!(injected_only.media_bytes_received, 0);
        assert!(injected_only.injected_media_bytes > 0);
        assert!(
            !injected_only.session_setup_timed_out(),
            "trusted inject must count toward publisher liveness"
        );

        let mut script_only = Conn::new();
        script_only.state = ConnState::Publishing;
        script_only.app = "live".to_string();
        script_only.defer_media_relay = true;
        script_only.relay_enabled = false;
        script_only.current_stream = Some(Box::new(Stream {
            is_publishing: true,
            name: "meta".to_string(),
            ..Stream::new(1)
        }));
        let script = b"@setDataFrame";
        script_only
            .inject_relay_frame(FrameType::Script, 0, script)
            .unwrap();
        assert_eq!(
            script_only.injected_media_bytes,
            script.len() as u64,
            "script inject must count toward deferred-relay drain liveness"
        );
        assert_eq!(script_only.pending_relay.len(), 1);

        // Injected bytes from a prior epoch must not exempt a later empty publish.
        injected_only.evict_active_publish_route();
        injected_only.current_stream = Some(Box::new(Stream {
            is_publishing: true,
            ..Stream::new(2)
        }));
        injected_only.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(3));
        assert_eq!(injected_only.injected_media_bytes, 0);
        assert!(
            injected_only.session_setup_timed_out(),
            "new publish epoch without media must still time out"
        );

        // Idle inject (no publish role) must also clear on createStream/unpublish
        // paths that call evict while !was_publishing.
        let mut idle_inject = Conn::new();
        idle_inject.state = ConnState::StreamCreated;
        idle_inject.app = "live".to_string();
        idle_inject.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        idle_inject
            .inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
            .unwrap();
        assert!(idle_inject.injected_media_bytes > 0);
        idle_inject.evict_active_publish_route();
        assert!(
            idle_inject.injected_media_bytes == 0,
            "idle inject must not carry into a later publish epoch"
        );

        // Active players must not claim a publish route via Conn inject.
        let mut playing = Conn::new();
        playing.app = "live".to_string();
        playing.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            is_playing: true,
            ..Stream::new(1)
        }));
        assert!(
            playing
                .inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
                .is_err(),
            "playing connections must not squat publish routes via inject"
        );

        let mut squatting = Conn::new();
        squatting.state = ConnState::Publishing;
        squatting.current_stream = Some(Box::new(Stream {
            is_publishing: true,
            ..Stream::new(1)
        }));
        squatting.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(3));
        assert!(
            squatting.session_setup_timed_out(),
            "publishers that never send media must be reaped so they cannot squat routes"
        );

        // A peer that published and then unpublished before the deadline
        // must not be exempted forever just because `ConnState` only moves
        // forward -- the exemption must track the *current* is_publishing
        // flag, not the monotonic state.
        let mut unpublished = Conn::new();
        unpublished.state = ConnState::Publishing;
        unpublished.current_stream = Some(Box::new(Stream::new(1)));
        unpublished.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            unpublished.session_setup_timed_out(),
            "peers that unpublished before the deadline must be reaped"
        );

        let mut paused_player = Conn::new();
        paused_player.state = ConnState::Playing;
        paused_player.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: true,
            ..Stream::new(1)
        }));
        paused_player.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            paused_player.session_setup_timed_out(),
            "paused players must be reaped after the setup grace window"
        );

        let mut active_player = Conn::new();
        active_player.state = ConnState::Playing;
        active_player.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: false,
            ..Stream::new(1)
        }));
        active_player.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            active_player.session_setup_timed_out(),
            "unpaused players with no outbound relay must be reaped after the setup grace window"
        );

        let mut receiving_player = Conn::new();
        receiving_player.state = ConnState::Playing;
        receiving_player.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: false,
            ..Stream::new(1)
        }));
        receiving_player.media_bytes_sent = 1;
        receiving_player
            .set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        assert!(
            !receiving_player.session_setup_timed_out(),
            "unpaused players receiving relay must not be reaped by the setup timer"
        );
    }

    #[test]
    fn pause_unpause_cycling_cannot_reset_setup_timer_without_relay() {
        use std::time::{Duration, Instant};

        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.state = ConnState::Playing;
        conn.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: false,
            ..Stream::new(1)
        }));
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut pause = Buffer::with_capacity(64);
        command::build_pause(&mut pause, true).unwrap();
        conn.handle_command(pause.as_slice()).unwrap();
        assert!(
            conn.session_setup_timed_out(),
            "pausing a viewer that never received relay must not refresh the setup timer"
        );

        let mut receiving = Conn::new();
        receiving.app = "live".to_string();
        receiving.state = ConnState::Playing;
        receiving.media_bytes_sent = 1;
        receiving.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: false,
            ..Stream::new(1)
        }));
        receiving.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut pause = Buffer::with_capacity(64);
        command::build_pause(&mut pause, true).unwrap();
        receiving.handle_command(pause.as_slice()).unwrap();
        assert!(
            !receiving.session_setup_timed_out(),
            "pausing a viewer that is receiving relay must still refresh the setup timer"
        );

        let mut unpause = Buffer::with_capacity(64);
        command::build_pause(&mut unpause, false).unwrap();
        receiving.handle_command(unpause.as_slice()).unwrap();
        receiving.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut stale_pause = Buffer::with_capacity(64);
        command::build_pause(&mut stale_pause, true).unwrap();
        receiving.handle_command(stale_pause.as_slice()).unwrap();
        assert!(
            receiving.session_setup_timed_out(),
            "historical relay bytes must not refresh pause grace more than once"
        );

        let mut unpause = Buffer::with_capacity(64);
        command::build_pause(&mut unpause, false).unwrap();
        receiving.handle_command(unpause.as_slice()).unwrap();
        receiving.media_bytes_sent = 2;
        receiving.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut fresh_pause = Buffer::with_capacity(64);
        command::build_pause(&mut fresh_pause, true).unwrap();
        receiving.handle_command(fresh_pause.as_slice()).unwrap();
        assert!(
            !receiving.session_setup_timed_out(),
            "fresh relay activity must allow another pause grace window"
        );
    }

    #[test]
    fn play_route_change_does_not_reuse_historical_relay_for_pause_grace() {
        use std::time::{Duration, Instant};

        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.state = ConnState::Playing;
        conn.media_bytes_sent = 1;
        conn.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: false,
            name: "live-route".to_string(),
            ..Stream::new(1)
        }));

        let mut play = Buffer::with_capacity(128);
        command::build_play(&mut play, "dead-route").unwrap();
        conn.handle_command(play.as_slice()).unwrap();
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut pause = Buffer::with_capacity(64);
        command::build_pause(&mut pause, true).unwrap();
        conn.handle_command(pause.as_slice()).unwrap();
        assert!(
            conn.session_setup_timed_out(),
            "relay bytes from a previous play route must not qualify a dead route for pause grace"
        );
    }

    #[test]
    fn repeated_publish_same_route_does_not_refresh_media_deadline() {
        use std::time::{Duration, Instant};

        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "room", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.current_stream.as_ref().unwrap().is_publishing);

        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(3));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "room", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(
            conn.session_setup_timed_out(),
            "repeating publish for the already-owned route must not refresh the media deadline"
        );
    }

    #[test]
    fn unpublish_grants_a_fresh_setup_timeout_window() {
        use std::time::{Duration, Instant};

        // Regression test: a client that has been legitimately publishing
        // for a long time (well past RTMP_SESSION_SETUP_TIMEOUT) must not
        // be reaped the instant it unpublishes -- it should get a fresh
        // grace window to republish on the same connection, not be judged
        // against however little time is left of its original setup
        // window (which may already be long gone).
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "A", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.current_stream.as_ref().unwrap().is_publishing);
        conn.media_bytes_received = 1;

        // Simulate having been connected/publishing for a long time already.
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(3600));
        assert!(
            !conn.session_setup_timed_out(),
            "an active publisher must not be reaped regardless of connection age"
        );

        let mut buf = Buffer::with_capacity(128);
        command::build_fcunpublish(&mut buf, "A").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);

        assert!(
            !conn.session_setup_timed_out(),
            "unpublishing must grant a fresh setup-timeout window, not reap \
             immediately using up whatever remained of the original window"
        );
    }

    #[test]
    fn teardown_commands_do_not_refresh_timer_for_a_never_active_peer() {
        use std::time::{Duration, Instant};

        // Regression test: a peer that never published/played must not be
        // able to keep dodging the setup-timeout reaper forever by
        // repeatedly sending FCUnpublish/deleteStream/closeStream --
        // resetting session_setup_started must be conditioned on a genuine
        // active->idle transition, not fire on every teardown command.
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));

        let mut buf = Buffer::with_capacity(128);
        command::build_fcunpublish(&mut buf, "A").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(
            conn.session_setup_timed_out(),
            "FCUnpublish on a stream that was never publishing must not reset the timer"
        );

        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        let mut buf = Buffer::with_capacity(128);
        command::build_deletestream(&mut buf, 2.0, 1).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(
            conn.session_setup_timed_out(),
            "deleteStream on a stream that was never active must not reset the timer"
        );

        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(11));
        let mut buf = Buffer::with_capacity(128);
        crate::amf::amf0::write_string(&mut buf, "closeStream").unwrap();
        crate::amf::amf0::write_number(&mut buf, 2.0).unwrap();
        crate::amf::amf0::write_null(&mut buf).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(
            conn.session_setup_timed_out(),
            "closeStream on a stream that was never active must not reset the timer"
        );
    }

    #[test]
    fn delete_stream_clears_is_playing_and_grants_a_fresh_window() {
        use std::time::{Duration, Instant};

        // Regression test: deleteStream is sent by players, not just
        // publishers. The FCUnpublish/deleteStream arm must clear
        // is_playing too (not just is_publishing), otherwise a player that
        // tears down via deleteStream would never be considered idle and
        // could hold its slot forever.
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        // Model a viewer that has actually received relay; squatters with
        // zero outbound relay are reaped separately (see
        // `session_setup_timed_out`).
        conn.media_bytes_sent = 1;
        conn.current_stream = Some(Box::new(Stream {
            is_playing: true,
            ..Stream::new(1)
        }));
        conn.set_session_setup_started_for_test(Instant::now() - Duration::from_secs(3600));
        assert!(
            !conn.session_setup_timed_out(),
            "an active player must not be reaped regardless of connection age"
        );

        let mut buf = Buffer::with_capacity(128);
        command::build_deletestream(&mut buf, 2.0, 1).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(
            !conn.current_stream.as_ref().unwrap().is_playing,
            "deleteStream must clear is_playing"
        );
        assert!(
            !conn.session_setup_timed_out(),
            "tearing down an active player via deleteStream must grant a fresh setup-timeout \
             window, not reap immediately"
        );
    }

    #[test]
    fn delete_stream_clears_paused_flag() {
        // Regression test: deleteStream must reset `paused` like
        // closeStream does. play() never resets `paused` on its own, and
        // relay delivery is gated on !paused, so a pause -> deleteStream ->
        // play sequence on the same connection would otherwise leave
        // playback silently stuck with no relayed frames.
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            is_playing: true,
            paused: true,
            ..Stream::new(1)
        }));

        let mut buf = Buffer::with_capacity(128);
        command::build_deletestream(&mut buf, 2.0, 1).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(
            !conn.current_stream.as_ref().unwrap().paused,
            "deleteStream must clear paused"
        );
    }

    #[test]
    fn unanswered_ping_timeouts_close_connection() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.transport = None;
        conn.state = ConnState::AppConnected;
        conn.last_ping_sent = Some(Instant::now() - PING_TIMEOUT - Duration::from_secs(1));
        conn.pending_pings
            .insert(42, Instant::now() - PING_TIMEOUT - Duration::from_secs(1));

        assert!(
            matches!(conn.maybe_send_ping(), Err(ErrorCode::Protocol)),
            "stale unanswered pings must fail the connection"
        );
    }

    #[test]
    fn excessive_pending_pings_close_connection() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.transport = None;
        conn.state = ConnState::AppConnected;
        conn.last_ping_sent = Some(Instant::now() - PING_INTERVAL - Duration::from_millis(1));
        for token in 1..=MAX_PENDING_PINGS as u32 {
            conn.pending_pings
                .insert(token, Instant::now() - Duration::from_millis(100));
        }

        assert!(
            matches!(conn.maybe_send_ping(), Err(ErrorCode::Protocol)),
            "too many unanswered pings must fail the connection"
        );
    }

    #[test]
    fn ping_timeout_starts_after_flush_not_queue() {
        use std::os::unix::io::IntoRawFd;
        use std::os::unix::net::UnixStream;

        let (client_end, _peer) = UnixStream::pair().unwrap();
        client_end.set_nonblocking(true).unwrap();

        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.state = ConnState::AppConnected;
        conn.transport = Some(Transport::new_plain(client_end.into_raw_fd()));
        conn.send_buffer.write(b"backlog").unwrap();

        conn.maybe_send_ping().unwrap();
        assert!(
            conn.pending_pings.is_empty(),
            "unflushed ping must not start the RTT timeout"
        );
        assert!(conn.queued_ping.is_some());
        assert!(
            conn.last_ping_sent.is_none(),
            "ping interval must not advance until the ping is flushed"
        );

        conn.flush().unwrap();
        assert_eq!(conn.pending_pings.len(), 1);
        assert!(conn.queued_ping.is_none());
        assert!(conn.last_ping_sent.is_some());
    }

    #[test]
    fn commit_flushed_ping_waits_for_ping_bytes_not_later_media() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.state = ConnState::AppConnected;
        conn.transport = None;
        conn.send_buffer.write(b"still queued").unwrap();
        conn.queued_ping = Some(QueuedPing {
            token: 1,
            queued_at: Instant::now(),
            bytes_until_flushed: conn.send_buffer.available(),
        });

        conn.flush().unwrap();
        assert!(
            conn.pending_pings.is_empty(),
            "ping must not be timed until its own queued bytes are flushed"
        );
        assert!(conn.queued_ping.is_some());

        if let Some(ref mut queued) = conn.queued_ping {
            queued.bytes_until_flushed = 0;
        }
        conn.flush().unwrap();
        assert_eq!(conn.pending_pings.len(), 1);
        assert!(conn.queued_ping.is_none());
    }

    #[test]
    fn commit_flushed_ping_does_not_wait_for_post_ping_media() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.state = ConnState::AppConnected;
        conn.transport = None;
        conn.send_buffer.write(b"backlog").unwrap();

        conn.maybe_send_ping().unwrap();
        let bytes_through_ping = conn.queued_ping.as_ref().unwrap().bytes_until_flushed;
        conn.send_buffer.write(b"after-ping").unwrap();
        assert_eq!(
            bytes_through_ping,
            conn.send_buffer.available() - b"after-ping".len(),
            "flush target must exclude post-ping media appended afterward"
        );

        conn.send_buffer.drain(bytes_through_ping);
        if let Some(ref mut queued) = conn.queued_ping {
            queued.bytes_until_flushed = 0;
        }
        conn.flush().unwrap();

        assert_eq!(
            conn.pending_pings.len(),
            1,
            "ping RTT must start once the ping leaves the buffer, not after post-ping media"
        );
        assert!(conn.queued_ping.is_none());
        assert_eq!(conn.send_buffer.available(), b"after-ping".len());
        assert_eq!(conn.send_buffer.peek(), b"after-ping");
    }

    #[test]
    fn stale_queued_ping_closes_connection() {
        let mut conn = Conn::new();
        conn.client_fd = 0;
        conn.transport = None;
        conn.state = ConnState::AppConnected;
        conn.queued_ping = Some(QueuedPing {
            token: 7,
            queued_at: Instant::now() - PING_TIMEOUT - Duration::from_secs(1),
            bytes_until_flushed: 1,
        });

        assert!(
            matches!(conn.maybe_send_ping(), Err(ErrorCode::Protocol)),
            "unflushed ping stuck longer than PING_TIMEOUT must close the connection"
        );
    }

    #[test]
    fn media_frames_on_wrong_msg_stream_id_are_ignored() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }

        let payload = vec![0x17, 0x01, 0x00, 0x00, 0x00];
        conn.handle_media_frame(99, FrameType::Video, 0, &payload)
            .unwrap();
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn read_messages_respects_recv_level_message_budget() {
        use crate::chunk::writer::chunk_write;

        let mut conn = Conn::new();
        conn.state = ConnState::Connected;

        let mut wire = Buffer::new();
        for i in 0..300usize {
            let payload = [i as u8];
            let msg = ChunkMessage {
                csid: 2,
                fmt: 0,
                timestamp: 0,
                msg_length: 1,
                msg_type_id: 0x03,
                msg_stream_id: 0,
                is_complete: false,
            };
            chunk_write(&mut wire, &msg, &payload, 1, 128).unwrap();
        }
        conn.recv_buffer = wire;

        let mut budget = MAX_MESSAGES_PER_RECV;
        let _ = conn.read_messages(&mut budget);
        assert_eq!(budget, 0);
        assert!(conn.recv_buffer.available() > 0);
    }

    #[test]
    fn recv_rejects_recv_buffer_growth_past_cap() {
        let mut conn = Conn::new();
        conn.recv_buffer
            .write(&vec![0u8; MAX_RECV_BUFFER_BYTES])
            .unwrap();
        assert!(matches!(conn.recv(&[1]), Err(ErrorCode::Protocol)));
    }

    #[test]
    fn multitrack_invokes_on_frame_cb_per_track() {
        use std::sync::{LazyLock, Mutex};

        static SEEN_TRACK_IDS: LazyLock<Mutex<Vec<u8>>> = LazyLock::new(|| Mutex::new(Vec::new()));

        fn record_track_id(frame: &Frame) {
            SEEN_TRACK_IDS.lock().unwrap().push(frame.track_id);
        }

        SEEN_TRACK_IDS.lock().unwrap().clear();
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }
        conn.on_frame_cb = Some(record_track_id);

        let payload = vec![
            0x86, 0x10, b'a', b'v', b'c', b'1', 0x00, 0x00, 0x00, 0x03, 0xAA, 0xBB, 0xCC, 0x01,
            0x00, 0x00, 0x02, 0xDD, 0xEE,
        ];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();

        assert_eq!(*SEEN_TRACK_IDS.lock().unwrap(), vec![0, 1]);
        assert_eq!(conn.pending_relay.len(), 1);
        assert_eq!(conn.pending_relay[0].payload, payload);
    }

    #[test]
    fn multitrack_codec_is_detected_before_authorization() {
        use std::sync::{LazyLock, Mutex};

        static SEEN_CODEC: LazyLock<Mutex<Option<String>>> = LazyLock::new(|| Mutex::new(None));
        fn allow_media(_: u64, _: FrameType, codec: Option<&str>) -> bool {
            *SEEN_CODEC.lock().unwrap() = codec.map(str::to_owned);
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_media);
        let payload = vec![0x86, 0x10, b'a', b'v', b'c', b'1', 0, 0, 0, 1, 0xAA];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();
        assert_eq!(SEEN_CODEC.lock().unwrap().as_deref(), Some("avc1"));
    }

    #[test]
    fn on_media_cb_authorizes_each_frame_codec_not_first_frame_pin() {
        fn allow_avc1_only(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return codec == Some("avc1");
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_avc1_only);

        let avc1_multitrack = vec![0x86, 0x10, b'a', b'v', b'c', b'1', 0, 0, 0, 1, 0xAA];
        conn.handle_media_frame(1, FrameType::Video, 0, &avc1_multitrack)
            .unwrap();
        assert_eq!(conn.pending_relay.len(), 1);

        let vp09 = vec![0x90, b'v', b'p', b'0', b'9'];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 1, &vp09),
            Err(ErrorCode::Auth)
        );
        assert_eq!(conn.pending_relay.len(), 1);
    }

    #[test]
    fn on_media_cb_authorizes_every_track_in_many_codecs_container() {
        fn allow_avc1_only(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return codec == Some("avc1");
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_avc1_only);

        // ManyTracksManyCodecs container: first track is the allowed "avc1",
        // second track is the disallowed "vp09". Authorization must inspect
        // every track, not just the first, or a publisher could smuggle the
        // disallowed codec past `on_media_cb` by pairing it with an allowed
        // first track.
        let mixed_codec_frame = vec![
            0x86, 0x20, // multitrack video, type=ManyTracksManyCodecs
            b'a', b'v', b'c', b'1', 0x00, 0x00, 0x00, 0x01, 0xAA, // track 0: avc1
            b'v', b'p', b'0', b'9', 0x01, 0x00, 0x00, 0x01, 0xBB, // track 1: vp09
        ];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &mixed_codec_frame),
            Err(ErrorCode::Auth)
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn on_media_cb_authorizes_shared_codec_in_many_tracks_container() {
        fn allow_avc1_only(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return codec == Some("avc1");
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_avc1_only);

        // ManyTracks container: both tracks share the disallowed "vp09"
        // codec. Even though every track carries the same codec here, this
        // container type still runs `foreach_track`/`media_allowed` rather
        // than the single-codec fast path, and must reject the frame.
        let shared_disallowed_codec_frame = vec![
            0x86, 0x10, // multitrack video, type=ManyTracks
            b'v', b'p', b'0', b'9', // shared fourcc: vp09
            0x00, 0x00, 0x00, 0x01, 0xAA, // track 0
            0x01, 0x00, 0x00, 0x01, 0xBB, // track 1
        ];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &shared_disallowed_codec_frame),
            Err(ErrorCode::Auth)
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn on_media_cb_receives_hex_label_for_non_utf8_fourcc() {
        use std::sync::{LazyLock, Mutex};

        static SEEN_CODEC: LazyLock<Mutex<Option<String>>> = LazyLock::new(|| Mutex::new(None));
        fn record_codec(_: u64, _: FrameType, codec: Option<&str>) -> bool {
            *SEEN_CODEC.lock().unwrap() = codec.map(str::to_owned);
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(record_codec);

        let non_utf8_fourcc = vec![
            0x90, 0x80, 0x80, 0x80, 0x80,
            0x00, 0x00, 0x00, 0x01, 0xAA,
        ];
        conn.handle_media_frame(1, FrameType::Video, 0, &non_utf8_fourcc)
            .unwrap();
        assert_eq!(
            SEEN_CODEC.lock().unwrap().as_deref(),
            Some("fourcc:80808080")
        );
    }

    #[test]
    fn on_media_cb_deny_list_can_block_hex_fourcc_labels() {
        fn deny_hex_fourcc(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return !codec.is_some_and(|c| c.starts_with("fourcc:"));
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(deny_hex_fourcc);

        let non_utf8_fourcc = vec![
            0x90, 0x80, 0x80, 0x80, 0x80,
            0x00, 0x00, 0x00, 0x01, 0xAA,
        ];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &non_utf8_fourcc),
            Err(ErrorCode::Auth)
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn on_media_cb_deny_list_observes_unknown_legacy_codec_nibble() {
        fn deny_legacy_vp6(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return codec != Some("legacy:4");
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(deny_legacy_vp6);

        // Legacy FLV video with codec nibble 4 (VP6) must surface a stable
        // identity to `on_media_cb`, not `None`.
        let legacy_vp6 = vec![0x14, 0x01, 0xAA];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &legacy_vp6),
            Err(ErrorCode::Auth)
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn modex_wrapper_cannot_bypass_codec_deny_list_without_caps_ex() {
        fn allow_avc1_only(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            frame_type == FrameType::Video && codec == Some("avc1")
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        // Legacy connect: negotiated_caps.caps_ex_mask stays 0.
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_avc1_only);

        // Naive exvideo_parse reads bytes 1..5 as the FourCC on ModEx packets.
        // Craft those bytes as "avc1" while the peeled inner packet is vp09.
        let payload = vec![
            0x97, b'a', b'v', b'c', b'1', 0x02, 0, 1, 2, 0x01, 0x90, b'v', b'p', b'0', b'9', 0,
            0, 0, 0xBB,
        ];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &payload),
            Err(ErrorCode::Auth),
            "ModEx wrapper must not let publishers smuggle a disallowed inner codec \
             past on_media_cb when capsEx was not negotiated"
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn excessive_modex_chain_cannot_bypass_codec_deny_list() {
        fn allow_avc1_only(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            frame_type == FrameType::Video && codec == Some("avc1")
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.negotiated_caps.has_caps_ex = true;
        conn.negotiated_caps.caps_ex_mask = CAPS_EX_MASK_MODEX;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(allow_avc1_only);

        let mut payload = vec![0x97, b'a', b'v', b'c', b'1'];
        for _ in 0..40 {
            payload.extend_from_slice(&[0x00, 0x00, 0x07]);
        }
        payload.extend_from_slice(&[0x90, b'v', b'p', b'0', b'9', 0, 0, 0, 0xBB]);
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &payload),
            Err(ErrorCode::Auth),
            "unpeelable ModEx chains must not bypass codec-specific deny lists"
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn on_media_cb_deny_list_blocks_wildcard_enhanced_fourcc() {
        fn deny_hevc_and_av1(_: u64, frame_type: FrameType, codec: Option<&str>) -> bool {
            if frame_type == FrameType::Video {
                return !matches!(codec, Some("hvc1") | Some("av01"));
            }
            true
        }

        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_media_cb = Some(deny_hevc_and_av1);

        let hvc1 = vec![0x90, b'h', b'v', b'c', b'1', 0, 0, 0, 1, 0xAA];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &hvc1),
            Err(ErrorCode::Auth)
        );

        let wildcard = vec![0x90, b'*', b' ', b' ', b' ', 0, 0, 0, 1, 0xAA];
        assert_eq!(
            conn.handle_media_frame(1, FrameType::Video, 0, &wildcard),
            Err(ErrorCode::Auth),
            "wildcard media FourCC must not bypass codec-specific deny lists"
        );
        assert!(conn.pending_relay.is_empty());
    }

    #[test]
    fn evict_active_publish_route_clears_detected_codecs() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        let payload = vec![0x86, 0x10, b'a', b'v', b'c', b'1', 0, 0, 0, 1, 0xAA];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();
        assert_eq!(conn.detected_video_codec.as_deref(), Some("avc1"));

        conn.evict_active_publish_route();
        assert!(conn.detected_video_codec.is_none());
        assert!(conn.detected_audio_codec.is_none());
    }

    #[test]
    fn enhanced_video_metadata_frame_populates_detected_hdr_info() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;

        assert!(conn.detected_hdr_info.is_none());

        let mut amf = Buffer::new();
        crate::amf::amf0::write_object_begin(&mut amf).unwrap();
        crate::amf::amf0::write_object_key(&mut amf, "colorPrimaries").unwrap();
        crate::amf::amf0::write_number(&mut amf, 1.0).unwrap();
        crate::amf::amf0::write_object_key(&mut amf, "transferCharacteristics").unwrap();
        crate::amf::amf0::write_number(&mut amf, 2.0).unwrap();
        crate::amf::amf0::write_object_key(&mut amf, "matrixCoefficients").unwrap();
        crate::amf::amf0::write_number(&mut amf, 3.0).unwrap();
        crate::amf::amf0::write_object_end(&mut amf).unwrap();

        let mut payload = vec![0x94, b'h', b'v', b'c', b'1']; // ex-header, frame_type=1, packet_type=4 (Metadata)
        payload.extend_from_slice(amf.as_slice());
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();

        let hdr = conn.detected_hdr_info.expect("colorInfo must be captured");
        assert_eq!(hdr.color_primaries, 1);
        assert_eq!(hdr.transfer_chars, 2);
        assert_eq!(hdr.matrix_coeffs, 3);

        conn.evict_active_publish_route();
        assert!(
            conn.detected_hdr_info.is_none(),
            "detected_hdr_info must be cleared alongside the other detected-* fields"
        );
    }

    #[test]
    fn inject_relay_frame_rejects_playing_only_connection() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            stream_id: 1,
            name: "cam".to_string(),
            is_publishing: false,
            is_playing: true,
            paused: false,
            receive_audio: true,
            receive_video: true,
        }));
        assert!(
            conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
                .is_err(),
            "playing-only connections must not inject publisher media"
        );
    }

    #[test]
    fn evict_active_publish_route_releases_idle_inject_claim() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let registry = PublishRouteRegistry::new(Arc::clone(&routes));
        let key = ("live".to_string(), "cam".to_string());

        let mut conn = Conn::new();
        conn.conn_id = 7;
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        conn.publish_routes = Some(registry);

        conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
            .unwrap();
        assert_eq!(routes.lock().unwrap().get(&key), Some(&7));

        // No publish/play command ever ran (current_stream.is_publishing is
        // still false), but a later createStream/play/teardown still calls
        // evict_active_publish_route(); the claim from the idle inject must
        // not survive it, or the route stays unavailable to a real publisher
        // until this connection closes.
        conn.evict_active_publish_route();
        assert!(
            routes.lock().unwrap().get(&key).is_none(),
            "route claimed by an idle inject must be released on stream replacement"
        );
    }

    #[test]
    fn inject_relay_frame_releases_fresh_claim_when_queueing_fails() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let registry = PublishRouteRegistry::new(Arc::clone(&routes));
        let key = ("live".to_string(), "cam".to_string());

        let mut conn = Conn::new();
        conn.conn_id = 7;
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        conn.publish_routes = Some(registry);
        conn.max_pending_relay_bytes = 0;

        assert!(
            conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
                .is_err(),
            "queueing must fail once the pending-relay byte budget is exhausted"
        );
        assert!(
            routes.lock().unwrap().get(&key).is_none(),
            "a claim taken only to service a rejected frame must not be left behind"
        );

        // A different connection must now be able to claim the route.
        let mut other = Conn::new();
        other.conn_id = 9;
        other.app = "live".to_string();
        other.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        other.publish_routes = Some(PublishRouteRegistry::new(Arc::clone(&routes)));
        assert!(
            other
                .inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
                .is_ok(),
            "a rolled-back claim must not block a subsequent legitimate claim"
        );
    }

    fn allow_release_stream(_conn_id: u64, _app: &str, _stream_name: &str) -> bool {
        true
    }

    #[test]
    fn release_stream_force_releases_a_route_owned_by_another_connection_when_authorized() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let key = ("live".to_string(), "cam1".to_string());
        PublishRouteRegistry::new(Arc::clone(&routes)).claim(7, "live", "cam1");
        assert_eq!(routes.lock().unwrap().get(&key), Some(&7));

        let mut conn = Conn::new();
        conn.conn_id = 9;
        conn.app = "live".to_string();
        conn.publish_routes = Some(PublishRouteRegistry::new(Arc::clone(&routes)));
        conn.on_release_stream_cb = Some(allow_release_stream);

        let mut buf = Buffer::new();
        command::build_release_stream(&mut buf, "cam1").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(
            routes.lock().unwrap().get(&key).is_none(),
            "releaseStream must force-clear a stale claim once the host authorizes it, so a \
             reconnecting encoder can republish"
        );
    }

    #[test]
    fn release_stream_without_a_callback_does_not_evict_another_connections_live_claim() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let key = ("live".to_string(), "cam1".to_string());
        PublishRouteRegistry::new(Arc::clone(&routes)).claim(7, "live", "cam1");

        let mut conn = Conn::new();
        conn.conn_id = 9;
        conn.app = "live".to_string();
        conn.publish_routes = Some(PublishRouteRegistry::new(Arc::clone(&routes)));
        // No on_release_stream_cb set -- must be a safe no-op by default.

        let mut buf = Buffer::new();
        command::build_release_stream(&mut buf, "cam1").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert_eq!(
            routes.lock().unwrap().get(&key),
            Some(&7),
            "releaseStream must not evict another connection's active claim unless the host \
             explicitly authorizes it -- otherwise any peer could hijack another stream by name"
        );
    }

    #[test]
    fn release_stream_callback_denial_does_not_evict() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        fn deny_release_stream(_conn_id: u64, _app: &str, _stream_name: &str) -> bool {
            false
        }

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let key = ("live".to_string(), "cam1".to_string());
        PublishRouteRegistry::new(Arc::clone(&routes)).claim(7, "live", "cam1");

        let mut conn = Conn::new();
        conn.conn_id = 9;
        conn.app = "live".to_string();
        conn.publish_routes = Some(PublishRouteRegistry::new(Arc::clone(&routes)));
        conn.on_release_stream_cb = Some(deny_release_stream);

        let mut buf = Buffer::new();
        command::build_release_stream(&mut buf, "cam1").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert_eq!(routes.lock().unwrap().get(&key), Some(&7));
    }

    #[test]
    fn release_stream_on_an_unclaimed_route_is_a_no_op() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));

        let mut conn = Conn::new();
        conn.conn_id = 9;
        conn.app = "live".to_string();
        conn.publish_routes = Some(PublishRouteRegistry::new(Arc::clone(&routes)));

        let mut buf = Buffer::new();
        command::build_release_stream(&mut buf, "cam1").unwrap();
        assert!(conn.handle_command(buf.as_slice()).is_ok());
    }

    #[test]
    fn inject_relay_frame_keeps_prior_claim_when_a_later_frame_is_rejected() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let registry = PublishRouteRegistry::new(Arc::clone(&routes));
        let key = ("live".to_string(), "cam".to_string());

        let mut conn = Conn::new();
        conn.conn_id = 7;
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            name: "cam".to_string(),
            ..Stream::new(1)
        }));
        conn.publish_routes = Some(registry);

        conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
            .unwrap();
        assert_eq!(routes.lock().unwrap().get(&key), Some(&7));

        // Starve the budget so the next frame is rejected.
        conn.max_pending_relay_bytes = 0;
        assert!(
            conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
                .is_err()
        );

        // The connection already legitimately owned this route from the
        // first successful inject; a later rejected frame must not evict it.
        assert_eq!(
            routes.lock().unwrap().get(&key),
            Some(&7),
            "an already-owned route must survive a subsequent rejected frame"
        );
    }

    #[test]
    fn inject_relay_frame_restores_prior_claim_when_route_switch_queueing_fails() {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};

        let routes = Arc::new(Mutex::new(HashMap::new()));
        let registry = PublishRouteRegistry::new(Arc::clone(&routes));
        let key_a = ("live".to_string(), "A".to_string());
        let key_b = ("live".to_string(), "B".to_string());

        let mut conn = Conn::new();
        conn.conn_id = 7;
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream {
            name: "A".to_string(),
            ..Stream::new(1)
        }));
        conn.publish_routes = Some(registry);

        conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xAA])
            .unwrap();
        assert_eq!(routes.lock().unwrap().get(&key_a), Some(&7));
        assert!(conn.pending_cache_evictions.is_empty());

        // Switch the public relay key, then reject the inject by exhausting
        // the pending budget. Claim/eviction for B must roll back to A.
        conn.relay_key = "B".to_string();
        conn.max_pending_relay_bytes = 0;
        assert!(
            conn.inject_relay_frame(FrameType::Video, 0, &[0x17, 0x01, 0xBB])
                .is_err()
        );
        assert_eq!(
            routes.lock().unwrap().get(&key_a),
            Some(&7),
            "failed route-switch inject must restore the previous claim"
        );
        assert!(
            routes.lock().unwrap().get(&key_b).is_none(),
            "rejected switch must not leave the new route claimed"
        );
        assert!(
            conn.pending_cache_evictions.is_empty(),
            "failed switch must not queue eviction of the restored route"
        );
        assert_eq!(conn.claimed_publish_route.as_deref(), Some("A"));
    }

    #[test]
    fn multitrack_on_frame_cb_scratch_retains_last_track_payload() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }
        conn.on_frame_cb = Some(|_| {});

        let payload = vec![
            0x86, 0x10, b'a', b'v', b'c', b'1', 0x00, 0x00, 0x00, 0x03, 0xAA, 0xBB, 0xCC, 0x01,
            0x00, 0x00, 0x02, 0xDD, 0xEE,
        ];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();

        assert_eq!(conn.frame_cb_scratch.as_slice(), &[0xDD, 0xEE]);
    }

    #[test]
    fn modex_is_normalized_for_callbacks_and_cache_but_relayed_opaque() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.negotiated_caps.has_caps_ex = true;
        conn.negotiated_caps.caps_ex_mask = CAPS_EX_MASK_MODEX;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        conn.current_stream.as_mut().unwrap().is_publishing = true;
        conn.on_frame_cb = Some(|_| {});

        let payload = vec![
            0x97, 0x02, 0, 1, 2, 0x01, b'a', b'v', b'c', b'1', 0, 0, 0, 0xAA,
        ];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();

        assert_eq!(conn.pending_relay[0].payload, payload);
        assert_eq!(
            conn.pending_relay[0].cache_payload(),
            &[0x91, b'a', b'v', b'c', b'1', 0, 0, 0, 0xAA]
        );
        assert_eq!(
            conn.frame_cb_scratch,
            vec![0x91, b'a', b'v', b'c', b'1', 0, 0, 0, 0xAA]
        );
    }

    #[test]
    fn on_frame_cb_scratch_retains_payload_after_delivery() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }
        conn.on_frame_cb = Some(|_| {});

        let payload = vec![0x17, 0x42];
        conn.handle_media_frame(1, FrameType::Video, 0, &payload)
            .unwrap();
        assert_eq!(conn.frame_cb_scratch.as_slice(), payload.as_slice());
    }

    fn flv_subtag(tag_type: u8, timestamp: u32, data: &[u8]) -> Vec<u8> {
        let mut v = Vec::new();
        v.push(tag_type);
        let len = data.len() as u32;
        v.extend_from_slice(&[(len >> 16) as u8, (len >> 8) as u8, len as u8]);
        v.extend_from_slice(&[
            (timestamp >> 16) as u8,
            (timestamp >> 8) as u8,
            timestamp as u8,
            (timestamp >> 24) as u8,
        ]);
        v.extend_from_slice(&[0, 0, 0]); // stream id (always 0 on the wire)
        v.extend_from_slice(data);
        let prev_tag_size = (11 + data.len()) as u32;
        v.extend_from_slice(&prev_tag_size.to_be_bytes());
        v
    }

    #[test]
    fn aggregate_message_unpacks_audio_and_video_subtags_into_relay() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }

        let audio_payload = vec![0xAF, 0x01, 0x11, 0x22];
        let video_payload = vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xAA];
        let mut aggregate = Vec::new();
        aggregate.extend(flv_subtag(0x08, 100, &audio_payload));
        aggregate.extend(flv_subtag(0x09, 140, &video_payload));

        conn.handle_aggregate_for_test(1, 1000, &aggregate).unwrap();

        assert_eq!(conn.pending_relay.len(), 2);
        assert_eq!(conn.pending_relay[0].frame_type, FrameType::Audio);
        assert_eq!(conn.pending_relay[0].timestamp, 1000);
        assert_eq!(conn.pending_relay[0].payload, audio_payload);
        assert_eq!(conn.pending_relay[1].frame_type, FrameType::Video);
        // Second sub-tag's ts (140) is 40 past the first sub-tag's ts (100),
        // so its relayed timestamp is the aggregate's own timestamp (1000) + 40.
        assert_eq!(conn.pending_relay[1].timestamp, 1040);
        assert_eq!(conn.pending_relay[1].payload, video_payload);
    }

    #[test]
    fn aggregate_subtag_dispatches_consume_message_budget() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }
        conn.max_pending_relay_bytes = usize::MAX;

        let audio_payload = vec![0xAF, 0x01];
        let mut aggregate = Vec::new();
        for i in 0..10 {
            aggregate.extend(flv_subtag(0x08, i, &audio_payload));
        }

        let mut messages_budget = 3;
        conn.handle_aggregate(1, 0, &aggregate, &mut messages_budget)
            .unwrap();

        assert_eq!(messages_budget, 0);
        assert_eq!(conn.pending_relay.len(), 3);
    }

    #[test]
    fn aggregate_message_rejects_subtag_size_overrunning_payload() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }

        // Claims a data_size far larger than the bytes actually present.
        let mut aggregate = vec![0x08, 0xFF, 0xFF, 0xFF];
        aggregate.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0]);
        aggregate.extend_from_slice(b"short");

        assert_eq!(
            conn.handle_aggregate_for_test(1, 0, &aggregate),
            Err(ErrorCode::Protocol)
        );
    }

    #[test]
    fn aggregate_dispatch_reaches_handle_aggregate_via_handle_message() {
        let mut conn = Conn::new();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }

        let video_payload = vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xBB];
        let aggregate = flv_subtag(0x09, 0, &video_payload);
        let msg = ChunkMessage {
            csid: 6,
            fmt: 0,
            timestamp: 500,
            msg_length: aggregate.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AGGREGATE,
            msg_stream_id: 1,
            is_complete: true,
        };

        conn.handle_message_for_test(&msg, &aggregate).unwrap();

        assert_eq!(conn.pending_relay.len(), 1);
        assert_eq!(conn.pending_relay[0].frame_type, FrameType::Video);
        assert_eq!(conn.pending_relay[0].timestamp, 500);
        assert_eq!(conn.pending_relay[0].payload, video_payload);
    }

    #[test]
    fn amf3_shared_object_dispatch_reaches_callback() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<Option<(u64, String, usize)>>> =
            LazyLock::new(|| Mutex::new(None));

        fn record_so(conn_id: u64, so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = Some((conn_id, so.name.clone(), so.events.len()));
        }

        *SEEN.lock().unwrap() = None;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.state = ConnState::AppConnected;
        conn.on_shared_object_cb = Some(record_so);

        let so = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Use,
                data: Vec::new(),
            }],
        };
        let mut amf_buf = Buffer::with_capacity(64);
        shared_object::write(&so, &mut amf_buf).unwrap();
        let mut payload = vec![0x00];
        payload.extend_from_slice(amf_buf.as_slice());

        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();

        assert_eq!(
            *SEEN.lock().unwrap(),
            Some((42, "chat".to_string(), 1)),
            "on_shared_object_cb must fire with the parsed envelope"
        );
    }

    #[test]
    fn amf3_shared_object_dropped_when_publish_auth_configured_without_so_auth() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(false));

        fn record_so(_conn_id: u64, _so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = true;
        }

        *SEEN.lock().unwrap() = false;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.state = ConnState::AppConnected;
        conn.on_publish_cb = Some(|_, _, _| true);
        conn.on_shared_object_cb = Some(record_so);

        let so = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Change,
                data: b"evil".to_vec(),
            }],
        };
        let mut amf_buf = Buffer::with_capacity(64);
        shared_object::write(&so, &mut amf_buf).unwrap();
        let mut payload = vec![0x00];
        payload.extend_from_slice(amf_buf.as_slice());
        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert!(
            !*SEEN.lock().unwrap(),
            "shared objects must not bypass publish/play auth hooks"
        );
    }

    #[test]
    fn amf3_shared_object_dropped_when_only_on_media_cb_configured() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(false));

        fn record_so(_conn_id: u64, _so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = true;
        }

        *SEEN.lock().unwrap() = false;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.state = ConnState::AppConnected;
        conn.on_media_cb = Some(|_, _, _| true);
        conn.on_shared_object_cb = Some(record_so);

        let so = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Change,
                data: b"evil".to_vec(),
            }],
        };
        let mut amf_buf = Buffer::with_capacity(64);
        shared_object::write(&so, &mut amf_buf).unwrap();
        let mut payload = vec![0x00];
        payload.extend_from_slice(amf_buf.as_slice());
        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert!(
            !*SEEN.lock().unwrap(),
            "shared objects must not bypass media-only auth configuration"
        );
    }

    #[test]
    fn amf3_shared_object_dropped_when_only_on_frame_cb_configured() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(false));

        fn record_so(_conn_id: u64, _so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = true;
        }

        *SEEN.lock().unwrap() = false;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.state = ConnState::AppConnected;
        conn.on_frame_cb = Some(|_| {});
        conn.on_shared_object_cb = Some(record_so);

        let so = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Change,
                data: b"evil".to_vec(),
            }],
        };
        let mut amf_buf = Buffer::with_capacity(64);
        shared_object::write(&so, &mut amf_buf).unwrap();
        let mut payload = vec![0x00];
        payload.extend_from_slice(amf_buf.as_slice());
        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert!(
            !*SEEN.lock().unwrap(),
            "shared objects must not bypass frame-only auth configuration"
        );
    }

    #[test]
    fn amf3_shared_object_honors_on_shared_object_auth_cb() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(false));

        fn record_so(_conn_id: u64, _so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = true;
        }

        fn allow_chat(_conn_id: u64, so: &SharedObjectMessage) -> bool {
            so.name == "chat"
        }

        *SEEN.lock().unwrap() = false;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.state = ConnState::AppConnected;
        conn.on_shared_object_auth_cb = Some(allow_chat);
        conn.on_shared_object_cb = Some(record_so);

        let denied = SharedObjectMessage {
            name: "admin".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Change,
                data: b"nope".to_vec(),
            }],
        };
        let mut denied_buf = Buffer::with_capacity(64);
        shared_object::write(&denied, &mut denied_buf).unwrap();
        let mut denied_payload = vec![0x00];
        denied_payload.extend_from_slice(denied_buf.as_slice());
        let denied_msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: denied_payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&denied_msg, &denied_payload).unwrap();
        assert!(!*SEEN.lock().unwrap(), "denied shared object must not fire callback");

        let allowed = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Use,
                data: Vec::new(),
            }],
        };
        let mut allowed_buf = Buffer::with_capacity(64);
        shared_object::write(&allowed, &mut allowed_buf).unwrap();
        let mut allowed_payload = vec![0x00];
        allowed_payload.extend_from_slice(allowed_buf.as_slice());
        let allowed_msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: allowed_payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&allowed_msg, &allowed_payload).unwrap();
        assert!(
            *SEEN.lock().unwrap(),
            "authorized shared object must reach on_shared_object_cb"
        );
    }

    #[test]
    fn malformed_amf3_shared_object_is_dropped_without_error() {
        let mut conn = Conn::new();
        conn.state = ConnState::AppConnected;
        let payload = vec![0x00, 0xFF, 0xFF]; // truncated name length, no body
        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        assert!(conn.handle_message_for_test(&msg, &payload).is_ok());
    }

    #[test]
    fn amf3_shared_object_before_connect_does_not_reach_callback() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};
        use std::sync::{LazyLock, Mutex};

        static SEEN: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(false));

        fn record_so(_conn_id: u64, _so: &SharedObjectMessage) {
            *SEEN.lock().unwrap() = true;
        }

        *SEEN.lock().unwrap() = false;
        let mut conn = Conn::new();
        conn.conn_id = 42;
        conn.on_shared_object_cb = Some(record_so);
        // conn.state defaults to a pre-connect state (e.g. TcpAccepted or
        // Handshake) -- self.app is still empty here.

        let so = SharedObjectMessage {
            name: "chat".to_string(),
            version: 1,
            flags: 0,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Use,
                data: Vec::new(),
            }],
        };
        let mut amf_buf = Buffer::with_capacity(64);
        shared_object::write(&so, &mut amf_buf).unwrap();
        let mut payload = vec![0x00];
        payload.extend_from_slice(amf_buf.as_slice());

        let msg = ChunkMessage {
            csid: 3,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT,
            msg_stream_id: 0,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();

        assert!(
            !*SEEN.lock().unwrap(),
            "shared objects must be rejected before connect completes"
        );
    }

    #[test]
    fn send_shared_object_round_trips_through_parse() {
        use crate::message::shared_object::{SharedObjectEvent, SharedObjectEventType};

        let mut conn = Conn::new();
        let so = SharedObjectMessage {
            name: "scoreboard".to_string(),
            version: 2,
            flags: 0x01,
            events: vec![SharedObjectEvent {
                event_type: SharedObjectEventType::Change,
                data: vec![1, 2, 3],
            }],
        };
        conn.send_shared_object(&so).unwrap();

        let mut reg = ChunkRegistry::new();
        let mut out_msg = ChunkMessage::default();
        let (status, payload) = chunk_read_owned(&mut conn.send_buffer, &mut reg, &mut out_msg)
            .expect("wire bytes from send_shared_object must decode as a valid chunk message");
        assert_eq!(status, 1);
        assert!(out_msg.is_complete);
        assert_eq!(
            out_msg.msg_type_id,
            msg_dispatch::RTMP_MSG_AMF3_SHARED_OBJECT
        );
        assert_eq!(payload[0], 0x00);
        let parsed = shared_object::parse(&payload[1..]).unwrap();
        assert_eq!(parsed.name, "scoreboard");
        assert_eq!(parsed.version, 2);
        assert!(parsed.is_persistent());
        assert_eq!(parsed.events.len(), 1);
    }

    fn amf0_string(s: &str) -> Vec<u8> {
        let mut buf = Buffer::with_capacity(64);
        crate::amf::amf0::write_string(&mut buf, s).unwrap();
        buf.as_slice().to_vec()
    }

    fn amf0_object_end() -> [u8; 3] {
        [0, 0, 0x09]
    }

    fn publishing_conn(stream_id: u32) -> Conn {
        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(stream_id)));
        if let Some(s) = conn.current_stream.as_mut() {
            s.is_publishing = true;
        }
        conn
    }

    fn build_on_metadata_payload(
        with_set_data_frame: bool,
        entries: &[(&str, f64)],
        extra: &[(&str, bool)],
    ) -> Vec<u8> {
        let mut payload = Vec::new();
        if with_set_data_frame {
            payload.extend(amf0_string("@setDataFrame"));
        }
        payload.extend(amf0_string("onMetaData"));
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        for (key, value) in entries {
            let mut buf = Buffer::with_capacity(32);
            crate::amf::amf0::write_object_key(&mut buf, key).unwrap();
            crate::amf::amf0::write_number(&mut buf, *value).unwrap();
            payload.extend_from_slice(buf.as_slice());
        }
        for (key, value) in extra {
            let mut buf = Buffer::with_capacity(32);
            crate::amf::amf0::write_object_key(&mut buf, key).unwrap();
            crate::amf::amf0::write_boolean(&mut buf, *value).unwrap();
            payload.extend_from_slice(buf.as_slice());
        }
        payload.extend_from_slice(&amf0_object_end());
        payload
    }

    #[test]
    fn on_metadata_is_queued_for_relay_while_publishing() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.relay_enabled = true;
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(ref mut stream) = conn.current_stream {
            stream.is_publishing = true;
            stream.name = "stream".to_string();
        }
        let payload = build_on_metadata_payload(false, &[("width", 1920.0)], &[]);
        conn.handle_publisher_data_message(1, 9000, &payload)
            .unwrap();
        assert_eq!(conn.pending_relay.len(), 1);
        assert_eq!(conn.pending_relay[0].frame_type, FrameType::Script);
        assert_eq!(conn.pending_relay[0].timestamp, 9000);
        assert_eq!(conn.pending_relay[0].payload, payload);
    }

    #[test]
    fn on_metadata_relay_honors_on_media_cb() {
        fn deny_all(_: u64, _: FrameType, _: Option<&str>) -> bool {
            false
        }

        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.relay_enabled = true;
        conn.on_media_cb = Some(deny_all);
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(ref mut stream) = conn.current_stream {
            stream.is_publishing = true;
            stream.name = "stream".to_string();
        }
        let payload = build_on_metadata_payload(false, &[("width", 1920.0)], &[]);
        assert_eq!(
            conn.handle_publisher_data_message(1, 9000, &payload),
            Err(ErrorCode::Auth)
        );
        assert!(conn.pending_relay.is_empty());
        assert_eq!(conn.detected_video_width, None);
    }

    #[test]
    fn connect_rejects_empty_app_name() {
        let mut conn = Conn::new();
        let mut buf = Buffer::with_capacity(256);
        command::build_connect(
            &mut buf,
            "",
            "rtmp://host/live",
            "",
            "",
            "FMLE/3.0",
            0,
            0,
            None,
        )
        .unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(conn.app.is_empty());
        assert_eq!(conn.state, ConnState::TcpAccepted);
        assert!(
            conn.send_buffer
                .peek()
                .windows(b"_error".len())
                .any(|window| window == b"_error")
        );
    }

    #[test]
    fn publish_rejects_empty_stream_name() {
        let mut conn = Conn::new();
        conn.app = "live".to_string();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        let mut buf = Buffer::with_capacity(128);
        command::build_publish(&mut buf, "", "live").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();
        assert!(!conn.current_stream.as_ref().unwrap().is_publishing);
        assert!(
            conn.send_buffer
                .peek()
                .windows(b"BadName".len())
                .any(|window| window == b"BadName")
        );
    }

    #[test]
    fn bytes_received_ack_uses_u64_after_u32_wrap() {
        let mut conn = Conn::new();
        conn.state = ConnState::Connected;
        conn.window_ack_size = 1024;
        conn.bytes_received = u32::MAX as u64;
        conn.bytes_at_last_ack = u32::MAX as u64;
        conn.recv(&[0u8; 2048]).unwrap();
        assert_eq!(conn.bytes_received, u32::MAX as u64 + 2048);
        assert_eq!(conn.bytes_at_last_ack, conn.bytes_received);
    }

    #[test]
    fn play_route_changes_are_init_replay_rate_limited() {
        use std::time::{Duration, Instant};

        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(1)));

        let play = |conn: &mut Conn, stream_name: &str| {
            let mut buf = Buffer::new();
            crate::amf::amf0::write_string(&mut buf, "play").unwrap();
            crate::amf::amf0::write_number(&mut buf, 1.0).unwrap();
            crate::amf::amf0::write_null(&mut buf).unwrap();
            crate::amf::amf0::write_string(&mut buf, stream_name).unwrap();
            conn.handle_command(buf.as_slice()).unwrap();
        };

        play(&mut conn, "room-a");
        assert!(conn.needs_init_frames);
        conn.needs_init_frames = false;

        play(&mut conn, "room-b");
        assert!(
            !conn.needs_init_frames,
            "rapid play-route changes must not request another cached replay"
        );

        conn.last_init_replay_request =
            Some(Instant::now() - INIT_REPLAY_COOLDOWN - Duration::from_millis(1));
        play(&mut conn, "room-c");
        assert!(
            conn.needs_init_frames,
            "a route change after the cooldown should request cached init frames"
        );
    }

    #[test]
    fn repeated_play_on_same_stream_does_not_request_init_replay() {
        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        {
            let stream = conn.current_stream.as_mut().unwrap();
            stream.is_playing = true;
            stream.name = "room".to_string();
        }
        conn.needs_init_frames = false;

        let mut buf = Buffer::new();
        crate::amf::amf0::write_string(&mut buf, "play").unwrap();
        crate::amf::amf0::write_number(&mut buf, 1.0).unwrap();
        crate::amf::amf0::write_null(&mut buf).unwrap();
        crate::amf::amf0::write_string(&mut buf, "room").unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(!conn.needs_init_frames);
    }

    #[test]
    fn receive_video_reenable_does_not_request_cached_replay() {
        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        {
            let stream = conn.current_stream.as_mut().unwrap();
            stream.is_playing = true;
            stream.receive_video = false;
        }
        conn.needs_init_frames = false;

        let mut buf = Buffer::new();
        crate::amf::amf0::write_string(&mut buf, "receiveVideo").unwrap();
        crate::amf::amf0::write_number(&mut buf, 1.0).unwrap();
        crate::amf::amf0::write_null(&mut buf).unwrap();
        crate::amf::amf0::write_boolean(&mut buf, true).unwrap();
        conn.handle_command(buf.as_slice()).unwrap();

        assert!(conn.current_stream.as_ref().unwrap().receive_video);
        assert!(
            !conn.needs_init_frames,
            "receiveAudio/receiveVideo toggles must not schedule init-cache replay"
        );
    }

    #[test]
    fn malformed_pause_command_leaves_stream_unpaused() {
        let mut conn = Conn::new();
        conn.current_stream = Some(Box::new(Stream::new(1)));
        if let Some(ref mut stream) = conn.current_stream {
            stream.is_playing = true;
            stream.paused = false;
        }

        let mut buf = Buffer::new();
        crate::amf::amf0::write_string(&mut buf, "pause").unwrap();
        crate::amf::amf0::write_number(&mut buf, 1.0).unwrap();
        // Missing null + boolean: parse must fail without forcing paused=true.
        assert!(conn.handle_command(buf.as_slice()).is_ok());
        assert!(!conn.current_stream.as_ref().unwrap().paused);
    }

    #[test]
    fn on_metadata_populates_conn_fields() {
        let mut conn = Conn::new();
        let payload = build_on_metadata_payload(
            false,
            &[
                ("width", 1920.0),
                ("height", 1080.0),
                ("framerate", 30.0),
                ("audiosamplerate", 48000.0),
                ("audiochannels", 2.0),
            ],
            &[],
        );
        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(1920));
        assert_eq!(conn.detected_video_height, Some(1080));
        assert_eq!(conn.detected_video_framerate, Some(30.0));
        assert_eq!(conn.detected_audio_sample_rate, Some(48000));
        assert_eq!(conn.detected_audio_channels, Some(2));
    }

    #[test]
    fn on_metadata_with_set_data_frame_prefix() {
        let mut conn = Conn::new();
        let payload = build_on_metadata_payload(
            true,
            &[
                ("width", 1280.0),
                ("height", 720.0),
                ("videoframerate", 60.0),
            ],
            &[("stereo", true)],
        );
        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(1280));
        assert_eq!(conn.detected_video_height, Some(720));
        assert_eq!(conn.detected_video_framerate, Some(60.0));
        assert_eq!(conn.detected_audio_channels, Some(2));
        assert_eq!(conn.detected_audio_sample_rate, None);
    }

    #[test]
    fn on_metadata_missing_keys_leave_fields_none() {
        let mut conn = Conn::new();
        let payload = build_on_metadata_payload(false, &[("width", 640.0)], &[]);
        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(640));
        assert_eq!(conn.detected_video_height, None);
        assert_eq!(conn.detected_video_framerate, None);
        assert_eq!(conn.detected_audio_sample_rate, None);
        assert_eq!(conn.detected_audio_channels, None);
    }

    #[test]
    fn on_metadata_skips_unknown_extra_keys() {
        let mut conn = Conn::new();
        let mut payload = amf0_string("onMetaData");
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        let mut width = Buffer::with_capacity(32);
        crate::amf::amf0::write_object_key(&mut width, "width").unwrap();
        crate::amf::amf0::write_number(&mut width, 800.0).unwrap();
        payload.extend_from_slice(width.as_slice());
        let mut unknown = Buffer::with_capacity(64);
        crate::amf::amf0::write_object_key(&mut unknown, "customTag").unwrap();
        crate::amf::amf0::write_string(&mut unknown, "ignored").unwrap();
        payload.extend_from_slice(unknown.as_slice());
        payload.extend_from_slice(&amf0_object_end());

        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(800));
    }

    #[test]
    fn on_metadata_rejects_out_of_range_dimensions() {
        let mut conn = Conn::new();
        let payload = build_on_metadata_payload(
            false,
            &[("width", -1.0), ("height", (u32::MAX as f64) + 1.0)],
            &[],
        );
        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, None);
        assert_eq!(conn.detected_video_height, None);
    }

    #[test]
    fn amf3_data_message_strips_leading_zero_byte() {
        let mut conn = publishing_conn(1);
        let mut body =
            build_on_metadata_payload(false, &[("width", 1024.0), ("height", 576.0)], &[]);
        let mut payload = vec![0x00];
        payload.append(&mut body);
        let msg = ChunkMessage {
            csid: 4,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF3_DATA,
            msg_stream_id: 1,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(1024));
        assert_eq!(conn.detected_video_height, Some(576));
    }

    #[test]
    fn on_metadata_ignores_oversized_leading_event_name() {
        let mut conn = Conn::new();
        let long_name = "x".repeat(65);
        let mut payload = amf0_string(&long_name);
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        payload.extend_from_slice(&amf0_object_end());

        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, None);
    }

    #[test]
    fn on_metadata_ignores_oversized_set_data_frame_inner_name() {
        let mut conn = Conn::new();
        let long_name = "y".repeat(65);
        let mut payload = amf0_string("@setDataFrame");
        payload.extend(amf0_string(&long_name));
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        payload.extend_from_slice(&amf0_object_end());

        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, None);
    }

    #[test]
    fn on_metadata_keeps_partial_fields_when_unknown_value_cannot_be_skipped() {
        let mut conn = Conn::new();
        let mut payload = amf0_string("onMetaData");
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        let mut width = Buffer::with_capacity(32);
        crate::amf::amf0::write_object_key(&mut width, "width").unwrap();
        crate::amf::amf0::write_number(&mut width, 1280.0).unwrap();
        payload.extend_from_slice(width.as_slice());
        let mut unknown = Buffer::with_capacity(8);
        crate::amf::amf0::write_object_key(&mut unknown, "vendor").unwrap();
        unknown
            .write(&[crate::amf::amf0::Amf0Type::Recordset as u8])
            .unwrap();
        payload.extend_from_slice(unknown.as_slice());
        payload.extend_from_slice(&amf0_object_end());

        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(1280));
    }

    #[test]
    fn on_metadata_ignored_while_not_publishing() {
        let mut conn = Conn::new();
        let payload = build_on_metadata_payload(false, &[("width", 1920.0)], &[]);
        let msg = ChunkMessage {
            csid: 4,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF0_DATA,
            msg_stream_id: 1,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert_eq!(conn.detected_video_width, None);
    }

    #[test]
    fn on_metadata_ignored_on_wrong_stream_id() {
        let mut conn = publishing_conn(1);
        let payload = build_on_metadata_payload(false, &[("width", 1920.0)], &[]);
        let msg = ChunkMessage {
            csid: 4,
            fmt: 0,
            timestamp: 0,
            msg_length: payload.len() as u32,
            msg_type_id: msg_dispatch::RTMP_MSG_AMF0_DATA,
            msg_stream_id: 99,
            is_complete: true,
        };
        conn.handle_message_for_test(&msg, &payload).unwrap();
        assert_eq!(conn.detected_video_width, None);
    }

    #[test]
    fn later_on_metadata_replaces_stale_values() {
        let mut conn = publishing_conn(1);
        let first = build_on_metadata_payload(false, &[("width", 1920.0), ("height", 1080.0)], &[]);
        let second = build_on_metadata_payload(false, &[("width", 1280.0), ("height", 720.0)], &[]);
        conn.handle_data_message(&first).unwrap();
        conn.handle_data_message(&second).unwrap();
        assert_eq!(conn.detected_video_width, Some(1280));
        assert_eq!(conn.detected_video_height, Some(720));
    }

    #[test]
    fn aggregate_script_subtag_populates_metadata() {
        let mut conn = publishing_conn(1);
        let metadata =
            build_on_metadata_payload(false, &[("width", 720.0), ("height", 480.0)], &[]);
        let aggregate = flv_subtag(msg_dispatch::RTMP_MSG_AMF0_DATA, 0, &metadata);
        conn.handle_aggregate_for_test(1, 0, &aggregate).unwrap();
        assert_eq!(conn.detected_video_width, Some(720));
        assert_eq!(conn.detected_video_height, Some(480));
    }

    #[test]
    fn on_metadata_tolerates_excess_keys() {
        let mut conn = publishing_conn(1);
        let mut payload = amf0_string("onMetaData");
        payload.push(crate::amf::amf0::Amf0Type::Object as u8);
        let mut width = Buffer::with_capacity(32);
        crate::amf::amf0::write_object_key(&mut width, "width").unwrap();
        crate::amf::amf0::write_number(&mut width, 800.0).unwrap();
        payload.extend_from_slice(width.as_slice());
        for i in 0..crate::amf::amf0::MAX_OBJECT_KEYS {
            let mut entry = Buffer::with_capacity(32);
            crate::amf::amf0::write_object_key(&mut entry, &format!("k{i}")).unwrap();
            crate::amf::amf0::write_null(&mut entry).unwrap();
            payload.extend_from_slice(entry.as_slice());
        }
        payload.extend_from_slice(&amf0_object_end());

        conn.handle_data_message(&payload).unwrap();
        assert_eq!(conn.detected_video_width, Some(800));
    }
}