rtmp-runtime 0.7.2

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) ingest session engine — a driveable server-side publish state machine over the handshake, chunk stream, AMF0, and message layers; optional tokio socket adapter.
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
//! RTMP chunk stream — basic header, message header, extended timestamp
//! (Adobe RTMP 1.0 §5.3).
//!
//! See [`docs/rtmp.md`](../docs/rtmp.md) §3 (RTMP Chunk Stream) for the wire
//! layout: chunk format (§5.3.1), basic header (§5.3.1.1), the four message
//! header `fmt` variants (§5.3.1.2), and extended timestamp (§5.3.1.3).
//!
//! This module implements the chunk **header** wire types (`BasicHeader`,
//! `MessageHeader`) and the stateful reassembly engine built on top of them:
//! [`ChunkAssembler`] (inbound, tracks prior-chunk state per csid so `fmt`
//! 1/2/3 headers can inherit the fields they omit, and reassembles chunked
//! payload back into whole [`Message`]s) and [`ChunkWriter`] (outbound,
//! splits a [`Message`] into `fmt` 0 + 3 chunks at the configured chunk
//! size).

use std::collections::HashMap;

use broadcast_common::{Parse, Serialize};

use crate::RtmpError;

type Result<T> = core::result::Result<T, RtmpError>;

/// Default maximum chunk size (§5.3, §5.4.1): 128 bytes, in effect until a
/// Set Chunk Size protocol control message changes it.
pub const DEFAULT_CHUNK_SIZE: u32 = 128;

/// Largest chunk size [`ChunkAssembler::set_chunk_size`]/[`ChunkWriter::set_chunk_size`]
/// will adopt from a Set Chunk Size protocol control message (§5.4.1): 16
/// MiB. The wire field is a 31-bit value (up to ~2 GiB), but no real
/// publisher/player needs a chunk size anywhere near that — a single chunk
/// this large would already hold many seconds of encoded audio/video — so
/// this is a defensive ceiling, not a spec limit: values above it are
/// clamped down rather than rejected, matching the existing floor-of-1
/// behaviour for values below it.
pub const MAX_CHUNK_SIZE: u32 = 16 * 1024 * 1024;

/// Largest total `message_length` (§5.3.1.2) [`ChunkAssembler`] will begin
/// buffering for a single reassembled message: 8 MiB. `message_length` is a
/// fully peer-supplied 24-bit wire field (max ~16 MiB); real RTMP
/// audio/video/command messages are always far smaller than this (a single
/// compressed video frame, even a keyframe, is normally well under 1 MiB),
/// so this is a generous ceiling that still bounds worst-case allocation
/// per in-progress message. A Type 0/1 header declaring a larger
/// `message_length` is rejected by [`ChunkAssembler`] before any buffer for
/// it is allocated.
pub const MAX_MESSAGE_LEN: u32 = 8 * 1024 * 1024;

/// Largest number of distinct chunk stream ids [`ChunkAssembler`] will track
/// reassembly state for concurrently. A well-behaved publisher uses only a
/// handful of chunk streams (2/3 for control/command traffic, plus a few
/// more for audio/video) — this bound is generous headroom above that, not
/// a spec limit — so a flood of chunks opening many distinct (and mostly
/// bogus) csids is rejected rather than growing the per-csid state map
/// without bound.
pub const MAX_CSIDS: usize = 64;

/// Default aggregate ceiling on the total payload bytes [`ChunkAssembler`]
/// will buffer across **all** in-progress messages on one connection
/// (#1108/RTMP-W1). Per-message [`MAX_MESSAGE_LEN`] (8 MiB) and per-
/// connection [`MAX_CSIDS`] (64) each bound their own dimension, but their
/// product — 512 MiB per TCP connection, reachable before `connect` even
/// completes by opening one partially-filled maximum-size message on each
/// csid — is not a bound anyone intended. This is a generous figure far
/// above any real publisher's interleaved in-flight media (a few concurrent
/// audio/video frames is a few hundred KB), so it does not threaten
/// interoperability, while capping a hostile peer's buffered-but-never-
/// completed bytes at a predictable number.
pub const DEFAULT_MAX_IN_PROGRESS_BYTES: usize = 16 * 1024 * 1024;

/// The 24-bit sentinel value that, in a Type 0/1/2 message header's
/// `timestamp`/`timestamp delta` field, signals that the field does not carry
/// the real value: the full 32-bit value instead follows in a 4-byte
/// Extended Timestamp (§5.3.1.3). Per §5.3.1.2.1, any real timestamp/delta
/// `>= EXTENDED_TIMESTAMP_MARKER` is encoded this way.
pub const EXTENDED_TIMESTAMP_MARKER: u32 = 0x00FF_FFFF;

/// Byte width of a 24-bit (`u24`) wire field (`timestamp`, `timestamp delta`,
/// `message length`).
const U24_LEN: usize = 3;
/// Byte width of the Extended Timestamp field (§5.3.1.3).
const EXTENDED_TIMESTAMP_LEN: usize = 4;

/// Byte width of a Type 0 message header (§5.3.1.2.1), excluding any
/// Extended Timestamp.
const TYPE0_LEN: usize = 11;
/// Byte width of a Type 1 message header (§5.3.1.2.2), excluding any
/// Extended Timestamp.
const TYPE1_LEN: usize = 7;
/// Byte width of a Type 2 message header (§5.3.1.2.3), excluding any
/// Extended Timestamp.
const TYPE2_LEN: usize = 3;
/// Byte width of a Type 3 message header (§5.3.1.2.4): always empty.
const TYPE3_LEN: usize = 0;

/// Chunk stream id (csid) offset added back on the 2-/3-byte basic header
/// forms (§5.3.1.1): both forms carry `csid - 64`.
const BASIC_HEADER_CSID_OFFSET: u32 = 64;
/// The 2-byte basic header form's marker value in byte 0's low 6 bits.
const BASIC_HEADER_2BYTE_MARKER: u8 = 0;
/// The 3-byte basic header form's marker value in byte 0's low 6 bits.
const BASIC_HEADER_3BYTE_MARKER: u8 = 1;
/// Bit shift of the 2-bit `fmt` field within basic header byte 0.
const BASIC_HEADER_FMT_SHIFT: u8 = 6;
/// Mask for the low 6 bits of basic header byte 0 (the 1-byte csid, or the
/// 2-/3-byte form marker).
const BASIC_HEADER_MARKER_MASK: u8 = 0x3F;

/// Smallest csid encodable in the basic header's 1-byte form (§5.3.1.1).
/// Csid values 0 and 1 are reserved as the 2-/3-byte form markers and so can
/// never appear as a literal 1-byte-form csid; csid 2 is additionally
/// reserved by the spec for low-level protocol control messages/commands but
/// remains structurally encodable.
const BASIC_HEADER_1BYTE_MIN_CSID: u32 = 2;
/// Largest csid encodable in the basic header's 1-byte form.
const BASIC_HEADER_1BYTE_MAX_CSID: u32 = 63;
/// Smallest csid encodable in the basic header's 2-byte form.
const BASIC_HEADER_2BYTE_MIN_CSID: u32 = 64;
/// Largest csid encodable in the basic header's 2-byte form (csids 64-319
/// are also representable in the 3-byte form; 2-byte is the minimal one).
const BASIC_HEADER_2BYTE_MAX_CSID: u32 = 319;
/// Smallest csid that requires the basic header's 3-byte form.
const BASIC_HEADER_3BYTE_MIN_CSID: u32 = 320;
/// Largest csid the protocol supports at all (§5.3.1.1: "up to 65597 chunk
/// streams, IDs 3-65599" — the 3-byte form's 16-bit `csid - 64` field tops
/// out here).
const BASIC_HEADER_3BYTE_MAX_CSID: u32 = 65599;

// ── u24 helpers ─────────────────────────────────────────────────────────

/// Read a 3-byte big-endian unsigned integer. `b` must have at least
/// [`U24_LEN`] bytes (caller-checked).
fn read_u24_be(b: &[u8]) -> u32 {
    (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2])
}

/// Write `v`'s low 24 bits as big-endian into `buf`. `buf` must have at
/// least [`U24_LEN`] bytes (caller-checked). Bits above the low 24 are
/// silently dropped — every wire user of this helper (`message length`, and
/// `timestamp`/`timestamp delta` after the extended-timestamp check) is
/// only ever asked to write a value already known to fit.
fn write_u24_be(v: u32, buf: &mut [u8]) {
    buf[0] = (v >> 16) as u8;
    buf[1] = (v >> 8) as u8;
    buf[2] = v as u8;
}

// ── fmt (chunk type) ────────────────────────────────────────────────────

/// The 2-bit `fmt` field selecting one of the 4 Chunk Message Header formats
/// (§5.3.1.1, §5.3.1.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fmt {
    /// Type 0 (§5.3.1.2.1): the full 11-byte header.
    Type0,
    /// Type 1 (§5.3.1.2.2): 7-byte header, inherits `message stream id`.
    Type1,
    /// Type 2 (§5.3.1.2.3): 3-byte header, inherits length/type/stream id.
    Type2,
    /// Type 3 (§5.3.1.2.4): no header, inherits everything.
    Type3,
}

impl Fmt {
    /// The spec token for this `fmt` value.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Fmt::Type0 => "type 0",
            Fmt::Type1 => "type 1",
            Fmt::Type2 => "type 2",
            Fmt::Type3 => "type 3",
        }
    }

    /// Decode the 2-bit wire value (0..=3) into a [`Fmt`].
    ///
    /// # Errors
    /// [`RtmpError::Malformed`] if `bits` is not in `0..=3`.
    pub const fn from_bits(bits: u8) -> core::result::Result<Self, RtmpError> {
        match bits {
            0 => Ok(Fmt::Type0),
            1 => Ok(Fmt::Type1),
            2 => Ok(Fmt::Type2),
            3 => Ok(Fmt::Type3),
            _ => Err(RtmpError::Malformed {
                what: "chunk fmt (must be 0..=3)",
            }),
        }
    }

    /// Encode this `fmt` back to its 2-bit wire value (0..=3).
    #[must_use]
    pub const fn to_bits(self) -> u8 {
        match self {
            Fmt::Type0 => 0,
            Fmt::Type1 => 1,
            Fmt::Type2 => 2,
            Fmt::Type3 => 3,
        }
    }
}

broadcast_common::impl_spec_display!(Fmt);

// ── Basic Header (§5.3.1.1) ─────────────────────────────────────────────

/// One of the three basic header forms, chosen purely by csid range
/// (§5.3.1.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BasicHeaderForm {
    One,
    Two,
    Three,
}

/// The minimal basic-header form that can encode `csid`.
fn basic_header_form(csid: u32) -> Result<BasicHeaderForm> {
    match csid {
        BASIC_HEADER_1BYTE_MIN_CSID..=BASIC_HEADER_1BYTE_MAX_CSID => Ok(BasicHeaderForm::One),
        BASIC_HEADER_2BYTE_MIN_CSID..=BASIC_HEADER_2BYTE_MAX_CSID => Ok(BasicHeaderForm::Two),
        BASIC_HEADER_3BYTE_MIN_CSID..=BASIC_HEADER_3BYTE_MAX_CSID => Ok(BasicHeaderForm::Three),
        _ => Err(RtmpError::Malformed {
            what: "chunk stream id (must be 2..=65599)",
        }),
    }
}

/// Chunk Basic Header (§5.3.1.1): 1 to 3 bytes encoding the 2-bit `fmt` and
/// the chunk stream id (csid). Length depends only on the csid value; the
/// implementation SHOULD (and this [`Serialize`] impl does) use the smallest
/// form that holds the id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BasicHeader {
    /// Selects which of the 4 Chunk Message Header formats follows.
    pub fmt: Fmt,
    /// Chunk stream id. Valid range 2..=65599 on the wire (0/1 are the
    /// 2-/3-byte form markers, not real ids; 2 is further reserved by the
    /// spec for low-level protocol control messages/commands but is still a
    /// structurally valid basic-header value).
    pub chunk_stream_id: u32,
}

impl<'a> Parse<'a> for BasicHeader {
    type Error = RtmpError;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.is_empty() {
            return Err(RtmpError::BufferTooShort {
                need: 1,
                have: 0,
                what: "chunk basic header",
            });
        }
        let byte0 = bytes[0];
        let fmt = Fmt::from_bits((byte0 >> BASIC_HEADER_FMT_SHIFT) & 0x03)?;
        let marker = byte0 & BASIC_HEADER_MARKER_MASK;

        let chunk_stream_id = match marker {
            BASIC_HEADER_2BYTE_MARKER => {
                if bytes.len() < 2 {
                    return Err(RtmpError::BufferTooShort {
                        need: 2,
                        have: bytes.len(),
                        what: "chunk basic header (2-byte form)",
                    });
                }
                u32::from(bytes[1]) + BASIC_HEADER_CSID_OFFSET
            }
            BASIC_HEADER_3BYTE_MARKER => {
                if bytes.len() < 3 {
                    return Err(RtmpError::BufferTooShort {
                        need: 3,
                        have: bytes.len(),
                        what: "chunk basic header (3-byte form)",
                    });
                }
                // §5.3.1.1: csid = (byte2 * 256) + byte1 + 64 — byte 1 is
                // the low byte, byte 2 the high byte (little-endian).
                u32::from(bytes[1]) + u32::from(bytes[2]) * 256 + BASIC_HEADER_CSID_OFFSET
            }
            literal => u32::from(literal),
        };

        Ok(BasicHeader {
            fmt,
            chunk_stream_id,
        })
    }
}

impl Serialize for BasicHeader {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        match basic_header_form(self.chunk_stream_id) {
            Ok(BasicHeaderForm::One) => 1,
            Ok(BasicHeaderForm::Two) => 2,
            Ok(BasicHeaderForm::Three) => 3,
            // Out-of-range csid: nominal upper bound. `serialize_into`
            // performs the real validation and returns the error.
            Err(_) => 3,
        }
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let form = basic_header_form(self.chunk_stream_id)?;
        let fmt_bits = self.fmt.to_bits() << BASIC_HEADER_FMT_SHIFT;

        match form {
            BasicHeaderForm::One => {
                if buf.is_empty() {
                    return Err(RtmpError::BufferTooShort {
                        need: 1,
                        have: 0,
                        what: "chunk basic header output (1-byte form)",
                    });
                }
                buf[0] = fmt_bits | (self.chunk_stream_id as u8);
                Ok(1)
            }
            BasicHeaderForm::Two => {
                if buf.len() < 2 {
                    return Err(RtmpError::BufferTooShort {
                        need: 2,
                        have: buf.len(),
                        what: "chunk basic header output (2-byte form)",
                    });
                }
                buf[0] = fmt_bits | BASIC_HEADER_2BYTE_MARKER;
                buf[1] = (self.chunk_stream_id - BASIC_HEADER_CSID_OFFSET) as u8;
                Ok(2)
            }
            BasicHeaderForm::Three => {
                if buf.len() < 3 {
                    return Err(RtmpError::BufferTooShort {
                        need: 3,
                        have: buf.len(),
                        what: "chunk basic header output (3-byte form)",
                    });
                }
                buf[0] = fmt_bits | BASIC_HEADER_3BYTE_MARKER;
                let rel = self.chunk_stream_id - BASIC_HEADER_CSID_OFFSET;
                buf[1] = rel as u8;
                buf[2] = (rel >> 8) as u8;
                Ok(3)
            }
        }
    }
}

// ── Message Header (§5.3.1.2) ───────────────────────────────────────────

/// Whether `field` (a 24-bit `timestamp`/`timestamp delta`) needs the 4-byte
/// Extended Timestamp (§5.3.1.3): any value `>= EXTENDED_TIMESTAMP_MARKER`.
fn needs_extended_timestamp(field: u32) -> bool {
    field >= EXTENDED_TIMESTAMP_MARKER
}

/// Chunk Message Header: one of 4 formats selected by [`Fmt`] (§5.3.1.2),
/// carrying decreasing field sets — each format after Type 0 inherits the
/// fields it omits from the preceding chunk on the same chunk stream.
///
/// Reassembling that "preceding chunk" state (so Type 1/2/3 headers can be
/// resolved to absolute values) is a stateful job for the chunk-stream
/// reassembler (#738 Task 4), not this header type. In particular, a Type 3
/// header carrying zero bytes here does *not* by itself tell you whether an
/// Extended Timestamp follows it on the wire: per §5.3.1.3, a Type 3 chunk
/// carries the 4-byte Extended Timestamp when — and only when — the most
/// recent Type 0/1/2 chunk on the same csid itself used one. Deciding that
/// requires exactly that per-csid state, so [`MessageHeader::parse`] never
/// consumes an Extended Timestamp for `Fmt::Type3`; the reassembler must
/// apply this rule itself once it is tracking that state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MessageHeader {
    /// Type 0 (§5.3.1.2.1, 11 bytes on the wire before any Extended
    /// Timestamp). MUST be used at the start of a chunk stream and whenever
    /// the stream timestamp goes backward.
    Type0 {
        /// Absolute timestamp of the message (already resolved from any
        /// Extended Timestamp).
        timestamp: u32,
        /// Length in bytes of the whole message (not the chunk payload).
        message_length: u32,
        /// Message type id (§6/§7.1).
        message_type_id: u8,
        /// Message stream id. The wire encoding of this field alone is
        /// little-endian (§5.3.1.2.1).
        message_stream_id: u32,
    },
    /// Type 1 (§5.3.1.2.2, 7 bytes before any Extended Timestamp). No
    /// message stream id — inherits the preceding chunk's.
    Type1 {
        /// Delta from the previous chunk's timestamp on this csid (already
        /// resolved from any Extended Timestamp).
        timestamp_delta: u32,
        /// Length in bytes of the whole message.
        message_length: u32,
        /// Message type id (§6/§7.1).
        message_type_id: u8,
    },
    /// Type 2 (§5.3.1.2.3, 3 bytes before any Extended Timestamp). Neither
    /// stream id nor message length included — both inherited.
    Type2 {
        /// Delta from the previous chunk's timestamp on this csid (already
        /// resolved from any Extended Timestamp).
        timestamp_delta: u32,
    },
    /// Type 3 (§5.3.1.2.4, 0 bytes). Stream id, message length, message type
    /// id, and timestamp delta are all inherited from the preceding chunk on
    /// the same csid.
    Type3,
}

impl MessageHeader {
    /// Parse the message header that follows a [`BasicHeader`] carrying
    /// `fmt`. Returns the parsed variant and the number of bytes consumed
    /// from `bytes` — the fixed per-`fmt` header length, plus 4 more if a
    /// Type 0/1/2 field's 24-bit value read exactly [`EXTENDED_TIMESTAMP_MARKER`]
    /// (in which case the real, unresolved value is read from the following
    /// 4-byte big-endian Extended Timestamp — see §5.3.1.3).
    ///
    /// # Errors
    /// [`RtmpError::BufferTooShort`] if `bytes` does not hold the full fixed
    /// header (and, when signalled, the Extended Timestamp).
    pub fn parse(fmt: Fmt, bytes: &[u8]) -> Result<(Self, usize)> {
        match fmt {
            Fmt::Type0 => {
                if bytes.len() < TYPE0_LEN {
                    return Err(RtmpError::BufferTooShort {
                        need: TYPE0_LEN,
                        have: bytes.len(),
                        what: "type 0 message header",
                    });
                }
                let raw_timestamp = read_u24_be(&bytes[0..U24_LEN]);
                let message_length = read_u24_be(&bytes[U24_LEN..2 * U24_LEN]);
                let message_type_id = bytes[2 * U24_LEN];
                let message_stream_id =
                    u32::from_le_bytes([bytes[7], bytes[8], bytes[9], bytes[10]]);

                let (timestamp, consumed) = resolve_extended(raw_timestamp, bytes, TYPE0_LEN)?;

                Ok((
                    MessageHeader::Type0 {
                        timestamp,
                        message_length,
                        message_type_id,
                        message_stream_id,
                    },
                    consumed,
                ))
            }
            Fmt::Type1 => {
                if bytes.len() < TYPE1_LEN {
                    return Err(RtmpError::BufferTooShort {
                        need: TYPE1_LEN,
                        have: bytes.len(),
                        what: "type 1 message header",
                    });
                }
                let raw_delta = read_u24_be(&bytes[0..U24_LEN]);
                let message_length = read_u24_be(&bytes[U24_LEN..2 * U24_LEN]);
                let message_type_id = bytes[2 * U24_LEN];

                let (timestamp_delta, consumed) = resolve_extended(raw_delta, bytes, TYPE1_LEN)?;

                Ok((
                    MessageHeader::Type1 {
                        timestamp_delta,
                        message_length,
                        message_type_id,
                    },
                    consumed,
                ))
            }
            Fmt::Type2 => {
                if bytes.len() < TYPE2_LEN {
                    return Err(RtmpError::BufferTooShort {
                        need: TYPE2_LEN,
                        have: bytes.len(),
                        what: "type 2 message header",
                    });
                }
                let raw_delta = read_u24_be(&bytes[0..U24_LEN]);
                let (timestamp_delta, consumed) = resolve_extended(raw_delta, bytes, TYPE2_LEN)?;

                Ok((MessageHeader::Type2 { timestamp_delta }, consumed))
            }
            Fmt::Type3 => Ok((MessageHeader::Type3, TYPE3_LEN)),
        }
    }
}

/// Shared tail of Type 0/1/2 parsing: given the 24-bit field already read at
/// `bytes[..3]`, resolve it to its real value (reading the trailing 4-byte
/// Extended Timestamp if the field read the sentinel), and return
/// `(value, total_consumed)` where `total_consumed = fixed_len (+4)`.
fn resolve_extended(raw: u32, bytes: &[u8], fixed_len: usize) -> Result<(u32, usize)> {
    if raw == EXTENDED_TIMESTAMP_MARKER {
        let need = fixed_len + EXTENDED_TIMESTAMP_LEN;
        if bytes.len() < need {
            return Err(RtmpError::BufferTooShort {
                need,
                have: bytes.len(),
                what: "extended timestamp",
            });
        }
        let ext = u32::from_be_bytes([
            bytes[fixed_len],
            bytes[fixed_len + 1],
            bytes[fixed_len + 2],
            bytes[fixed_len + 3],
        ]);
        Ok((ext, need))
    } else {
        Ok((raw, fixed_len))
    }
}

impl Serialize for MessageHeader {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        match self {
            MessageHeader::Type0 { timestamp, .. } => TYPE0_LEN + extended_len(*timestamp),
            MessageHeader::Type1 {
                timestamp_delta, ..
            } => TYPE1_LEN + extended_len(*timestamp_delta),
            MessageHeader::Type2 { timestamp_delta } => TYPE2_LEN + extended_len(*timestamp_delta),
            MessageHeader::Type3 => TYPE3_LEN,
        }
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        match *self {
            MessageHeader::Type0 {
                timestamp,
                message_length,
                message_type_id,
                message_stream_id,
            } => {
                let extended = needs_extended_timestamp(timestamp);
                let written = TYPE0_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
                if buf.len() < written {
                    return Err(RtmpError::BufferTooShort {
                        need: written,
                        have: buf.len(),
                        what: "type 0 message header output",
                    });
                }
                let field = if extended {
                    EXTENDED_TIMESTAMP_MARKER
                } else {
                    timestamp
                };
                write_u24_be(field, &mut buf[0..U24_LEN]);
                write_u24_be(message_length, &mut buf[U24_LEN..2 * U24_LEN]);
                buf[2 * U24_LEN] = message_type_id;
                buf[7..11].copy_from_slice(&message_stream_id.to_le_bytes());
                if extended {
                    buf[11..15].copy_from_slice(&timestamp.to_be_bytes());
                }
                Ok(written)
            }
            MessageHeader::Type1 {
                timestamp_delta,
                message_length,
                message_type_id,
            } => {
                let extended = needs_extended_timestamp(timestamp_delta);
                let written = TYPE1_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
                if buf.len() < written {
                    return Err(RtmpError::BufferTooShort {
                        need: written,
                        have: buf.len(),
                        what: "type 1 message header output",
                    });
                }
                let field = if extended {
                    EXTENDED_TIMESTAMP_MARKER
                } else {
                    timestamp_delta
                };
                write_u24_be(field, &mut buf[0..U24_LEN]);
                write_u24_be(message_length, &mut buf[U24_LEN..2 * U24_LEN]);
                buf[2 * U24_LEN] = message_type_id;
                if extended {
                    buf[7..11].copy_from_slice(&timestamp_delta.to_be_bytes());
                }
                Ok(written)
            }
            MessageHeader::Type2 { timestamp_delta } => {
                let extended = needs_extended_timestamp(timestamp_delta);
                let written = TYPE2_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
                if buf.len() < written {
                    return Err(RtmpError::BufferTooShort {
                        need: written,
                        have: buf.len(),
                        what: "type 2 message header output",
                    });
                }
                let field = if extended {
                    EXTENDED_TIMESTAMP_MARKER
                } else {
                    timestamp_delta
                };
                write_u24_be(field, &mut buf[0..U24_LEN]);
                if extended {
                    buf[3..7].copy_from_slice(&timestamp_delta.to_be_bytes());
                }
                Ok(written)
            }
            MessageHeader::Type3 => Ok(0),
        }
    }
}

/// Extra bytes (0 or 4) [`Serialize`] will write for a 24-bit
/// `timestamp`/`timestamp delta` value.
fn extended_len(field: u32) -> usize {
    if needs_extended_timestamp(field) {
        EXTENDED_TIMESTAMP_LEN
    } else {
        0
    }
}

// ── Message (the assembled unit) ────────────────────────────────────────

/// One fully reassembled RTMP message: the payload of a single message
/// stream at a single (resolved, absolute) timestamp (§6.1). Produced by
/// [`ChunkAssembler::push`] and consumed by [`ChunkWriter::write`].
///
/// Task 5 (`message.rs`) adds typed interpretation of `payload`/
/// `message_type_id`; this carrier stays stable underneath that.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    /// Chunk stream id this message was carried on.
    pub chunk_stream_id: u32,
    /// Absolute timestamp (already resolved from any timestamp delta /
    /// Extended Timestamp — never a delta).
    pub timestamp: u32,
    /// Message type id (§6/§7.1).
    pub message_type_id: u8,
    /// Message stream id.
    pub message_stream_id: u32,
    /// The whole message payload (reassembled across every chunk it was
    /// split into).
    pub payload: Vec<u8>,
}

// ── ChunkAssembler (stateful inbound reassembly, §5.3) ──────────────────

/// Per-csid reassembly state: the most recently resolved header fields (used
/// by `fmt` 1/2/3 to inherit the fields they omit) plus the payload
/// accumulated so far for the message currently in progress on this csid.
#[derive(Debug, Clone, Default)]
struct CsidState {
    /// Absolute timestamp of the current/most recent message on this csid.
    timestamp: u32,
    /// Delta most recently applied to reach `timestamp` — re-applied
    /// unchanged when a Type 3 chunk begins a new message (inherits the
    /// prior delta). Per §3.1.2 Type 3: when a Type 3 chunk immediately
    /// follows a Type 0 chunk with no intervening Type 1/2, its implied
    /// delta equals the Type 0 chunk's own absolute timestamp — so a Type 0
    /// chunk seeds this field with its `timestamp`, not `0`.
    timestamp_delta: u32,
    /// Total length in bytes of the current/most recent message.
    message_length: u32,
    /// Message type id of the current/most recent message.
    message_type_id: u8,
    /// Message stream id of the current/most recent message.
    message_stream_id: u32,
    /// Whether the most recent Type 0/1/2 header on this csid used the
    /// Extended Timestamp (§5.3.1.3) — a Type 3 chunk then also carries (and
    /// must consume) that 4-byte field, per csid, until the next Type 0/1/2
    /// changes the flag.
    extended: bool,
    /// Whether a Type 0/1/2 header has ever been seen on this csid (Type
    /// 1/2/3 headers inherit from it; nothing to inherit before the first
    /// Type 0).
    initialized: bool,
    /// Whether a message is currently mid-accumulation on this csid (a
    /// prior chunk started it but its `message_length` bytes are not all
    /// in yet). Distinguishes, for a Type 3 chunk, a **continuation** of
    /// that in-progress message (`true`) from the **start of a new**
    /// message reusing the prior header (`false`, at a message boundary) —
    /// `payload.len()` alone can't tell them apart once a message has
    /// completed and `payload` was reset to empty for the next one.
    in_progress: bool,
    /// Payload bytes accumulated so far for the message in progress
    /// (`message_length` total once complete). Reset to empty once a
    /// message completes.
    payload: Vec<u8>,
    /// The #1108/RTMP-W1 aggregate-budget reservation currently held by
    /// this csid's in-progress message (its full declared
    /// `message_length`, charged when the message opened — see
    /// [`ChunkAssembler::in_progress_bytes`]). `None` when no message is
    /// in progress on this csid (the reservation was released when the
    /// message completed, or there never was one). The authoritative copy
    /// of the amount to credit back on completion, overwrite, or abort.
    reserved: Option<u32>,
}

/// Stateful inbound chunk reassembler (§5.3): feed inbound bytes, get back
/// each complete [`Message`] as soon as its last chunk arrives.
///
/// Maintains per-`chunk_stream_id` state, so multiple chunk streams may be
/// interleaved on the same connection (as the wire format requires) and are
/// each reassembled independently.
#[derive(Debug)]
pub struct ChunkAssembler {
    chunk_size: u32,
    csids: HashMap<u32, CsidState>,
    /// Bytes carried over from a previous `push` call that did not yet form
    /// a complete chunk (partial basic header, message header, extended
    /// timestamp, or payload slice).
    pending: Vec<u8>,
    /// How many bytes at the front of `pending` have already been consumed
    /// by chunks parsed earlier in the current [`Self::next_message`] call,
    /// but not yet physically dropped. Dropping them is deferred to one
    /// [`Self::compact`] per `next_message` return rather than done per
    /// chunk — see `compact`'s doc for why that matters.
    cursor: usize,
    /// Total payload bytes currently reserved across all in-progress
    /// (incomplete) messages — #1108/RTMP-W1. A new message reserves its
    /// full declared `message_length` the moment its header validates, so
    /// the ceiling bounds what a peer can *hold open*, not just what it
    /// has paid for in bytes sent (a header alone can declare 8 MiB).
    /// Maintained incrementally (updated in [`Self::try_parse_one`]
    /// wherever a message opens, completes, or aborts) rather than
    /// recomputed per chunk, and checked against `max_in_progress_bytes`
    /// before any reservation is made.
    in_progress_bytes: usize,
    /// Ceiling for `in_progress_bytes` — see
    /// [`DEFAULT_MAX_IN_PROGRESS_BYTES`].
    max_in_progress_bytes: usize,
}

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

impl ChunkAssembler {
    /// New assembler, chunk size at the §5.3 default (128 bytes).
    #[must_use]
    pub fn new() -> Self {
        Self {
            chunk_size: DEFAULT_CHUNK_SIZE,
            csids: HashMap::new(),
            pending: Vec::new(),
            cursor: 0,
            in_progress_bytes: 0,
            max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
        }
    }

    /// Set the ceiling on total payload bytes buffered across all
    /// in-progress messages (#1108/RTMP-W1); see
    /// [`DEFAULT_MAX_IN_PROGRESS_BYTES`] for the default and its rationale.
    #[must_use]
    pub fn with_max_in_progress_bytes(mut self, max_in_progress_bytes: usize) -> Self {
        self.max_in_progress_bytes = max_in_progress_bytes;
        self
    }

    /// Builder form of [`Self::set_chunk_size`] (same clamping rules).
    #[must_use]
    pub fn with_chunk_size(mut self, n: u32) -> Self {
        self.set_chunk_size(n);
        self
    }

    /// Update the chunk size in effect for subsequent chunks (called on
    /// receipt of a Set Chunk Size protocol control message, §5.4.1). Per
    /// `docs/rtmp.md` §3's transcription of §5.4.1 ("Default max chunk size
    /// is 128; SHOULD be ≥ 128, MUST be ≥ 1"), 128 is only a `SHOULD` for a
    /// *sender* choosing what to announce — a peer that announces (and
    /// then frames its own chunks at) a smaller value is still wire-legal,
    /// and this side must parse at whatever size the peer actually
    /// announced or every later chunk boundary is misparsed. So this only
    /// enforces the hard `MUST >= 1` floor (a chunk size of 0 would never
    /// make progress splitting payload) and caps at [`MAX_CHUNK_SIZE`] (a
    /// defensive ceiling, not a spec limit — see its own doc). The wire's
    /// reserved top bit and the `== 0` case are already rejected earlier, at
    /// [`crate::message::ProtocolControl::from_payload`]'s parse of the Set
    /// Chunk Size message itself, before a value ever reaches here; the
    /// floor below is this method's own defensive backstop for any other
    /// caller.
    pub fn set_chunk_size(&mut self, n: u32) {
        self.chunk_size = n.clamp(1, MAX_CHUNK_SIZE);
    }

    /// Discard any partially-received message on `csid` (§5.4.2 Abort
    /// Message). A no-op if `csid` has no in-progress message.
    ///
    /// #1108/RTMP-W2: without this, `Abort` was accepted and silently
    /// ignored, so `in_progress` stayed `true` and the next Type 3 chunk
    /// that actually starts a *new* message on that csid was instead
    /// appended to the aborted payload as a continuation — `message_length`
    /// bytes later, a corrupted merged message came out.
    pub fn abort(&mut self, csid: u32) {
        if let Some(state) = self.csids.get_mut(&csid) {
            if state.in_progress {
                let released = state.reserved.take().unwrap_or(0) as usize;
                self.in_progress_bytes = self.in_progress_bytes.saturating_sub(released);
            }
            state.payload.clear();
            state.in_progress = false;
        }
    }

    /// Feed inbound bytes; returns each complete [`Message`] decoded from
    /// the buffer (in arrival order), leaving any trailing partial chunk or
    /// partial message buffered internally for the next call.
    ///
    /// Callers that need to react to a message's side effects (e.g. a Set
    /// Chunk Size protocol control message, §5.4.1) **before** parsing the
    /// bytes that follow it in the same input — because the sender may
    /// switch to the new chunk size for its very next chunk — should use the
    /// crate-internal incremental `feed`/`next_message` pair instead,
    /// dispatching each message immediately. `push` collects every message
    /// from `input` under a single, unchanging `chunk_size`, which
    /// misparses a buffer that itself contains a Set Chunk Size followed by
    /// chunks already framed at the new size (see
    /// [`ServerSession`](crate::server::ServerSession), which uses the
    /// incremental form for exactly this reason).
    ///
    /// # Errors
    /// [`RtmpError::Malformed`] on structurally invalid input (e.g. a Type
    /// 1/2/3 chunk on a csid that has never seen a Type 0). Never errors
    /// merely because the input ends mid-chunk — that is buffered, not an
    /// error.
    pub fn push(&mut self, input: &[u8]) -> Result<Vec<Message>> {
        self.feed(input);
        let mut out = Vec::new();
        while let Some(msg) = match self.next_message() {
            Ok(Some(msg)) => Some(msg),
            Ok(None) => return Ok(out),
            Err(e) => return Err(e),
        } {
            out.push(msg);
        }
        Ok(out)
    }

    /// Buffer inbound bytes without parsing them yet. Pair with repeated
    /// calls to [`next_message`](Self::next_message) to parse and dispatch
    /// one message at a time (see [`push`](Self::push)'s docs for why this
    /// matters for Set Chunk Size).
    pub(crate) fn feed(&mut self, input: &[u8]) {
        self.pending.extend_from_slice(input);
    }

    /// Parse and return the next complete [`Message`] out of the
    /// previously-[`feed`](Self::feed) bytes, or `Ok(None)` if what remains
    /// buffered isn't (yet) a complete message. Internally keeps parsing
    /// individual chunks — which may belong to other interleaved csids, or
    /// be a non-final chunk of the same in-progress message — until either a
    /// full message is assembled or the buffered bytes run out.
    ///
    /// Each chunk's payload bytes are appended in place to that csid's own
    /// persistent [`CsidState::payload`] buffer (never cloned), and the
    /// consumed prefix of `pending` is only physically dropped once, when
    /// this call returns (see [`Self::compact`]) — not once per chunk. A
    /// message split across many small chunks (e.g. an 8 MiB message at a
    /// 1-byte chunk size) used to cost O(`message_length`^2 /
    /// `chunk_size`) — clone the whole accumulated payload on every
    /// continuation chunk, and shift the rest of `pending` down on every
    /// chunk's drain — and now costs O(`message_length`).
    ///
    /// # Errors
    /// Same as [`push`](Self::push).
    pub(crate) fn next_message(&mut self) -> Result<Option<Message>> {
        let max_in_progress_bytes = self.max_in_progress_bytes;
        // #1108/RTMP-W1 defence-in-depth: cap the not-yet-parsed `pending`
        // receive buffer at twice the in-progress budget. The primary
        // bound is the declared-length reservation enforced in
        // `try_parse_one` below (which holds whether or not the message's
        // bytes have committed); this backstop covers the residual slack
        // of bytes that belong to no reserved message (a caller that keeps
        // feeding unparsed input despite errors) plus at most one
        // unreserved in-flight header's worth.
        if self.pending.len() - self.cursor > max_in_progress_bytes * 2 {
            return Err(RtmpError::Malformed {
                what: "pending input buffer exceeds the per-connection budget",
            });
        }
        {
            // Disjoint field borrows: the parse input is a slice of
            // `pending` while the commit target is `csids`, so `pending`
            // is briefly moved out to satisfy the borrow checker. Every
            // return path below restores it (with the consumed prefix
            // still in place — compaction happens in `compact`, once per
            // return, not per chunk).
            let pending = core::mem::take(&mut self.pending);
            let mut cursor = self.cursor;
            let outcome = loop {
                let rest = &pending[cursor..];
                match Self::try_parse_one(
                    rest,
                    &mut self.csids,
                    self.chunk_size,
                    &mut self.in_progress_bytes,
                    max_in_progress_bytes,
                ) {
                    Ok(Some(parsed)) => {
                        cursor += parsed.consumed;
                        // Safe to unwrap: `try_parse_one` always commits
                        // (inserts or updates) `parsed.csid`'s entry before
                        // returning `Ok(Some(_))`.
                        let state = self.csids.get(&parsed.csid).expect("just committed above");
                        if state.payload.len() as u32 != state.message_length {
                            // This chunk only partially filled its message
                            // (or belongs to a different, interleaved csid)
                            // — keep looping to try the next chunk already
                            // in `pending`.
                            continue;
                        }
                        let state = self
                            .csids
                            .get_mut(&parsed.csid)
                            .expect("checked just above");
                        state.in_progress = false;
                        // #1108/RTMP-W1: a completed message's reservation
                        // (its declared length, charged when it opened)
                        // leaves the budget the moment it is handed over.
                        let released = state.reserved.take().unwrap_or(0) as usize;
                        self.in_progress_bytes = self.in_progress_bytes.saturating_sub(released);
                        let msg = Message {
                            chunk_stream_id: parsed.csid,
                            timestamp: state.timestamp,
                            message_type_id: state.message_type_id,
                            message_stream_id: state.message_stream_id,
                            payload: core::mem::take(&mut state.payload),
                        };
                        break Ok(Some((msg, cursor)));
                    }
                    Ok(None) => break Ok(None),
                    Err(e) => break Err(e),
                }
            };
            self.pending = pending;
            self.cursor = cursor;
            match outcome {
                Ok(Some((msg, cursor))) => {
                    self.cursor = 0;
                    self.pending.drain(..cursor);
                    Ok(Some(msg))
                }
                Ok(None) => {
                    self.compact();
                    Ok(None)
                }
                Err(e) => {
                    // A budget error was produced by a header that
                    // validated but whose chunk did not commit: re-parsing
                    // the same bytes would count the declaration again, so
                    // never resume consuming after one — the caller must
                    // treat it as terminal (the error is unrecoverable for
                    // this connection anyway).
                    self.compact();
                    Err(e)
                }
            }
        }
    }

    /// Physically drop the front `self.cursor` bytes of `pending` (the
    /// prefix already consumed by chunks parsed earlier in this call) and
    /// reset the cursor to 0. Called once per [`Self::next_message`]
    /// return, never per chunk inside its loop: a `Vec::drain` from the
    /// front is O(remaining length), so doing it once per *chunk* while a
    /// single message was still being reassembled out of many small chunks
    /// was, independently of the payload-clone cost, itself enough to make
    /// reassembly quadratic in the chunk count.
    fn compact(&mut self) {
        if self.cursor > 0 {
            self.pending.drain(..self.cursor);
            self.cursor = 0;
        }
    }

    /// Attempt to parse exactly one chunk (basic header + message header +
    /// any extended timestamp + its payload slice) from the front of `buf`,
    /// committing its resolved header fields and payload bytes directly into
    /// the owning csid's entry in `states`. Returns:
    /// - `Ok(Some(_))` — a full chunk was parsed and committed; `consumed`
    ///   bytes should be dropped from the front of the caller's buffer
    ///   (batched — see [`Self::compact`] — not per chunk).
    /// - `Ok(None)` — not enough bytes yet for a full chunk (structurally
    ///   plausible so far); caller should wait for more input. `states` is
    ///   left untouched.
    /// - `Err(_)` — structurally invalid input. `states` is left untouched.
    fn try_parse_one(
        buf: &[u8],
        states: &mut HashMap<u32, CsidState>,
        chunk_size: u32,
        in_progress_bytes: &mut usize,
        max_in_progress_bytes: usize,
    ) -> Result<Option<ParsedChunk>> {
        let bh = match BasicHeader::parse(buf) {
            Ok(bh) => bh,
            Err(RtmpError::BufferTooShort { .. }) => return Ok(None),
            Err(e) => return Err(e),
        };
        // `BasicHeader::parse` having succeeded means `buf` holds at least
        // as many bytes as this form needs; re-derive that count from the
        // marker bits actually on the wire (not from `basic_header_form`,
        // which reflects the *minimal* form for the csid and may disagree
        // with a wire that legally used a longer form for a csid in the
        // 64..=319 overlap range).
        let marker = buf[0] & BASIC_HEADER_MARKER_MASK;
        let header_len = match marker {
            BASIC_HEADER_2BYTE_MARKER => 2,
            BASIC_HEADER_3BYTE_MARKER => 3,
            _ => 1,
        };

        // Extract just the small, `Copy` header-inheritance fields (never
        // the payload itself — that would clone the whole accumulated
        // buffer just to *read* it) so this immutable peek at `states` ends
        // before the mutable commit further down needs it.
        let existing = states.get(&bh.chunk_stream_id).map(|s| ExistingHeader {
            timestamp: s.timestamp,
            timestamp_delta: s.timestamp_delta,
            message_length: s.message_length,
            message_type_id: s.message_type_id,
            message_stream_id: s.message_stream_id,
            extended: s.extended,
            in_progress: s.in_progress,
            accumulated_len: s.payload.len(),
        });

        // Remote-DoS guard: a flood of chunks opening distinct, previously
        // unseen csids would otherwise grow `states` without bound (one
        // `CsidState`, each with its own payload buffer, per bogus csid).
        // Reject before the caller ever inserts a new entry for this csid.
        if existing.is_none() && states.len() >= MAX_CSIDS {
            return Err(RtmpError::Malformed {
                what: "too many concurrent chunk stream ids (csid flood)",
            });
        }

        let rest = &buf[header_len..];
        let (mh, mh_consumed) = match MessageHeader::parse(bh.fmt, rest) {
            Ok(v) => v,
            Err(RtmpError::BufferTooShort { .. }) => return Ok(None),
            Err(e) => return Err(e),
        };
        let mut consumed = header_len + mh_consumed;

        // Resolve this chunk's header fields (timestamp/length/type/stream
        // id/extended-flag) and whether it begins a new message or
        // continues the one already in progress on this csid.
        let (resolved, starts_new) = match (bh.fmt, mh) {
            (
                Fmt::Type0,
                MessageHeader::Type0 {
                    timestamp,
                    message_length,
                    message_type_id,
                    message_stream_id,
                },
            ) => {
                let used_extended = mh_consumed > TYPE0_LEN;
                (
                    ResolvedHeader {
                        // §3.1.2: a Type 3 immediately following this Type 0
                        // (no intervening Type 1/2) implies a delta equal to
                        // this Type 0's own absolute timestamp.
                        timestamp_delta: timestamp,
                        timestamp,
                        message_length,
                        message_type_id,
                        message_stream_id,
                        extended: used_extended,
                    },
                    true,
                )
            }
            // #1108/RTMP-W3 (was TODO #738 follow-up): a Type 1/2 header
            // arriving while a message is already `in_progress` on this
            // csid (a header interleaved mid-message, rather than at a
            // message boundary) used to go undetected here — it silently
            // reset `payload`/state and dropped the in-flight bytes rather
            // than erroring. Real streams shouldn't do this, but a
            // malformed/desynced one could, and (combined with RTMP-W2's
            // Abort bug) the two resync paths disagreed with each other.
            (
                Fmt::Type1,
                MessageHeader::Type1 {
                    timestamp_delta,
                    message_length,
                    message_type_id,
                },
            ) => {
                let existing = existing.ok_or(RtmpError::Malformed {
                    what: "type 1 chunk header on a csid with no prior chunk to inherit from",
                })?;
                if existing.in_progress {
                    return Err(RtmpError::Malformed {
                        what: "type 1 chunk header mid-message (prior message on this csid not yet complete)",
                    });
                }
                let used_extended = mh_consumed > TYPE1_LEN;
                (
                    ResolvedHeader {
                        timestamp: existing.timestamp.wrapping_add(timestamp_delta),
                        timestamp_delta,
                        message_length,
                        message_type_id,
                        message_stream_id: existing.message_stream_id,
                        extended: used_extended,
                    },
                    true,
                )
            }
            (Fmt::Type2, MessageHeader::Type2 { timestamp_delta }) => {
                let existing = existing.ok_or(RtmpError::Malformed {
                    what: "type 2 chunk header on a csid with no prior chunk to inherit from",
                })?;
                if existing.in_progress {
                    return Err(RtmpError::Malformed {
                        what: "type 2 chunk header mid-message (prior message on this csid not yet complete)",
                    });
                }
                let used_extended = mh_consumed > TYPE2_LEN;
                (
                    ResolvedHeader {
                        timestamp: existing.timestamp.wrapping_add(timestamp_delta),
                        timestamp_delta,
                        message_length: existing.message_length,
                        message_type_id: existing.message_type_id,
                        message_stream_id: existing.message_stream_id,
                        extended: used_extended,
                    },
                    true,
                )
            }
            (Fmt::Type3, MessageHeader::Type3) => {
                let existing = existing.ok_or(RtmpError::Malformed {
                    what: "type 3 chunk header on a csid with no prior chunk to inherit from",
                })?;
                let continuation = existing.in_progress;
                if existing.extended {
                    if buf.len() < consumed + EXTENDED_TIMESTAMP_LEN {
                        return Ok(None);
                    }
                    // Present per §3.1.3 whenever the most recent Type 0/1/2
                    // on this csid used one. A continuation chunk's message
                    // timestamp is already fixed (ignore the value); a
                    // new-message Type 3 re-applies the inherited delta
                    // (also ignoring the value: Type 3 has nothing of its
                    // own to contribute, by definition it inherits).
                    consumed += EXTENDED_TIMESTAMP_LEN;
                }
                if continuation {
                    (
                        ResolvedHeader {
                            timestamp: existing.timestamp,
                            timestamp_delta: existing.timestamp_delta,
                            message_length: existing.message_length,
                            message_type_id: existing.message_type_id,
                            message_stream_id: existing.message_stream_id,
                            extended: existing.extended,
                        },
                        false,
                    )
                } else {
                    (
                        ResolvedHeader {
                            timestamp: existing.timestamp.wrapping_add(existing.timestamp_delta),
                            timestamp_delta: existing.timestamp_delta,
                            message_length: existing.message_length,
                            message_type_id: existing.message_type_id,
                            message_stream_id: existing.message_stream_id,
                            extended: existing.extended,
                        },
                        true,
                    )
                }
            }
            // `MessageHeader::parse` is always called with the `Fmt` that
            // selects its own variant, so every other pairing is
            // unreachable.
            _ => unreachable!("MessageHeader::parse always returns the variant for its Fmt"),
        };

        // Remote-DoS guard: `message_length` is a fully peer-supplied
        // 24-bit wire field (Type 0/1 headers set it directly; Type 2/3
        // inherit an already-checked value). Reject before any payload
        // buffer for this message is allocated — see `MAX_MESSAGE_LEN`'s
        // doc for why this bound is safe for real RTMP traffic.
        if resolved.message_length > MAX_MESSAGE_LEN {
            return Err(RtmpError::Malformed {
                what: "message length exceeds the maximum accepted message size",
            });
        }

        let already_accumulated = if starts_new {
            0
        } else {
            existing.map(|s| s.accumulated_len).unwrap_or(0)
        };
        let remaining_needed =
            (resolved.message_length as usize).saturating_sub(already_accumulated);
        let take = (chunk_size as usize).min(remaining_needed);

        // #1108/RTMP-W1 aggregate budget. A new message reserves its full
        // declared length when its header validates (before the payload
        // arrives: hoarding hides in bytes that never come); the
        // reservation is released on completion or abort. Continuation
        // chunks never re-reserve. Idempotent: a header re-parsed because
        // its payload was incomplete finds `reserved` equal to its own
        // declaration and nets zero. A rejected header records nothing.
        if starts_new {
            let prior = states
                .get(&bh.chunk_stream_id)
                .and_then(|s| s.reserved)
                .unwrap_or(0) as usize;
            let new_total = in_progress_bytes
                .saturating_sub(prior)
                .saturating_add(resolved.message_length as usize);
            if new_total > max_in_progress_bytes {
                return Err(RtmpError::Malformed {
                    what: "aggregate in-progress message bytes exceed the per-connection budget",
                });
            }
            *in_progress_bytes = new_total;
            states.entry(bh.chunk_stream_id).or_default().reserved = Some(resolved.message_length);
        }

        if buf.len() < consumed + take {
            return Ok(None);
        }

        // Commit: append this chunk's bytes directly into the owning
        // csid's own persistent payload buffer — no
        // `Vec::with_capacity(resolved.message_length)` (that would
        // pre-reserve up to `MAX_MESSAGE_LEN` bytes off a single peer-
        // supplied header field before a single payload byte has actually
        // arrived) and, critically, no clone of the bytes already
        // accumulated (the previous version built a brand-new Vec by
        // cloning the whole in-progress payload on every continuation
        // chunk, which is what made reassembly O(`message_length`^2 /
        // `chunk_size`)).
        let state = states.entry(bh.chunk_stream_id).or_default();
        state.timestamp = resolved.timestamp;
        state.timestamp_delta = resolved.timestamp_delta;
        state.message_length = resolved.message_length;
        state.message_type_id = resolved.message_type_id;
        state.message_stream_id = resolved.message_stream_id;
        state.extended = resolved.extended;
        state.initialized = true;
        if starts_new {
            state.payload.clear();
        }
        state
            .payload
            .extend_from_slice(&buf[consumed..consumed + take]);
        #[cfg(test)]
        record_payload_bytes_copied_for_test(take);
        state.in_progress = state.payload.len() as u32 != state.message_length;
        consumed += take;

        Ok(Some(ParsedChunk {
            csid: bh.chunk_stream_id,
            consumed,
        }))
    }
}

/// The small, `Copy` subset of [`CsidState`] a chunk's header-inheritance
/// resolution needs to read — deliberately excludes `payload` itself
/// (`accumulated_len` carries only its *length*) so reading it never clones
/// the accumulated buffer.
#[derive(Clone, Copy)]
struct ExistingHeader {
    timestamp: u32,
    timestamp_delta: u32,
    message_length: u32,
    message_type_id: u8,
    message_stream_id: u32,
    extended: bool,
    in_progress: bool,
    accumulated_len: usize,
}

/// Header fields resolved for one chunk, after applying `fmt`-specific
/// inheritance from the csid's prior state.
struct ResolvedHeader {
    timestamp: u32,
    timestamp_delta: u32,
    message_length: u32,
    message_type_id: u8,
    message_stream_id: u32,
    extended: bool,
}

/// Outcome of one [`ChunkAssembler::try_parse_one`] call: its header fields
/// and payload bytes have already been committed to the owning csid's
/// [`CsidState`] by the time this is returned — the caller only needs
/// `consumed` (to advance its read cursor) and `csid` (to look the state
/// back up and check for message completion).
struct ParsedChunk {
    csid: u32,
    consumed: usize,
}

// ── ChunkWriter (outbound, §5.3) ─────────────────────────────────────────

/// Stateless-per-message outbound chunk writer (§5.3): serializes a
/// [`Message`] into chunk bytes at the current chunk size.
///
/// Simple, always-correct strategy: the first chunk is always Type 0 (full
/// absolute-timestamp header) and every continuation chunk is Type 3
/// (0-byte header, inheriting everything). This is spec-valid — Type 1/2's
/// more compact delta-based headers are a size optimisation this writer
/// does not perform.
#[derive(Debug, Clone)]
pub struct ChunkWriter {
    chunk_size: u32,
}

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

impl ChunkWriter {
    /// New writer, chunk size at the §5.3 default (128 bytes).
    #[must_use]
    pub fn new() -> Self {
        Self {
            chunk_size: DEFAULT_CHUNK_SIZE,
        }
    }

    /// Update the chunk size used for subsequent [`ChunkWriter::write`]
    /// calls (called on sending a Set Chunk Size protocol control message,
    /// §5.4.1). Capped at [`MAX_CHUNK_SIZE`] (the floor-of-1 is applied in
    /// [`ChunkWriter::write`] itself).
    pub fn set_chunk_size(&mut self, n: u32) {
        self.chunk_size = n.min(MAX_CHUNK_SIZE);
    }

    /// Serialize `msg` into chunk bytes at the current chunk size: a Type 0
    /// first chunk carrying up to `chunk_size` payload bytes, then Type 3
    /// continuation chunks for the remainder.
    ///
    /// # Errors
    /// Returns [`RtmpError::FieldOverflow`] if `msg.payload` is 16 MiB
    /// (2^24) or larger — `message_length` is a UI24 field (§5.3.1.2) and
    /// cannot represent it (#1129: unfixed, `payload.len() as u32` then the
    /// UI24 writer silently kept only the low 24 bits, misframing every
    /// later message on the chunk stream).
    ///
    /// Returns [`RtmpError::InvalidChunkStreamId`] if `msg.chunk_stream_id`
    /// is outside the basic header's encodable range (2..=65599). Every
    /// `chunk_stream_id` produced by [`ChunkAssembler::push`] satisfies this
    /// (`BasicHeader::parse` never yields one outside the range); callers
    /// building a `Message` from scratch must respect it.
    pub fn write(&mut self, msg: &Message) -> Result<Vec<u8>> {
        if !(BASIC_HEADER_1BYTE_MIN_CSID..=BASIC_HEADER_3BYTE_MAX_CSID)
            .contains(&msg.chunk_stream_id)
        {
            return Err(RtmpError::InvalidChunkStreamId {
                chunk_stream_id: msg.chunk_stream_id,
            });
        }
        let chunk_size = (self.chunk_size as usize).max(1);
        let message_length = broadcast_common::len::fit_u24(msg.payload.len(), "message_length")?;
        let extended = needs_extended_timestamp(msg.timestamp);

        let mut out = Vec::with_capacity(TYPE0_LEN + msg.payload.len() + 16);

        let bh0 = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: msg.chunk_stream_id,
        };
        let mh0 = MessageHeader::Type0 {
            timestamp: msg.timestamp,
            message_length,
            message_type_id: msg.message_type_id,
            message_stream_id: msg.message_stream_id,
        };
        write_serialized(&mut out, &bh0)?;
        write_serialized(&mut out, &mh0)?;

        let mut offset = 0usize;
        let take0 = chunk_size.min(msg.payload.len());
        out.extend_from_slice(&msg.payload[offset..offset + take0]);
        offset += take0;

        while offset < msg.payload.len() {
            let bh = BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: msg.chunk_stream_id,
            };
            write_serialized(&mut out, &bh)?;
            if extended {
                out.extend_from_slice(&msg.timestamp.to_be_bytes());
            }
            let take = chunk_size.min(msg.payload.len() - offset);
            out.extend_from_slice(&msg.payload[offset..offset + take]);
            offset += take;
        }

        Ok(out)
    }
}

/// Serialize `item` and append the bytes to `out`.
///
/// # Errors
/// Propagates `item.serialize_into`'s error (for the [`BasicHeader`]s this is
/// used with, a `chunk_stream_id` outside the encodable range).
fn write_serialized<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) -> Result<()> {
    let len = item.serialized_len();
    let start = out.len();
    out.resize(start + len, 0);
    match item.serialize_into(&mut out[start..]) {
        Ok(n) => {
            out.truncate(start + n);
            Ok(())
        }
        Err(e) => {
            out.truncate(start);
            Err(e)
        }
    }
}

/// Test-only infallible wrapper over [`write_serialized`].
#[cfg(test)]
fn write_serialized_ok<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) {
    write_serialized(out, item).expect("valid chunk_stream_id in test fixture");
}

#[cfg(test)]
thread_local! {
    /// Total payload bytes [`ChunkAssembler::try_parse_one`] has appended
    /// via `extend_from_slice` on this thread since the last reset — a
    /// test-only instrumentation hook so a regression test can assert
    /// reassembly does O(message length) work directly, rather than
    /// inferring it from wall-clock time (see
    /// `reassembling_an_8mib_message_at_the_floor_chunk_size_is_linear_not_quadratic`).
    static PAYLOAD_BYTES_COPIED_FOR_TEST: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}

#[cfg(test)]
fn record_payload_bytes_copied_for_test(n: usize) {
    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(c.get() + n));
}

#[cfg(test)]
fn reset_payload_bytes_copied_for_test() {
    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(0));
}

#[cfg(test)]
fn payload_bytes_copied_for_test() -> usize {
    PAYLOAD_BYTES_COPIED_FOR_TEST.with(core::cell::Cell::get)
}

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

    // ── u24 helper ───────────────────────────────────────────────────────

    #[test]
    fn u24_round_trip_zero() {
        let mut buf = [0xFFu8; U24_LEN];
        write_u24_be(0, &mut buf);
        assert_eq!(buf, [0, 0, 0]);
        assert_eq!(read_u24_be(&buf), 0);
    }

    #[test]
    fn u24_round_trip_max() {
        let mut buf = [0u8; U24_LEN];
        write_u24_be(0x00FF_FFFF, &mut buf);
        assert_eq!(buf, [0xFF, 0xFF, 0xFF]);
        assert_eq!(read_u24_be(&buf), 0x00FF_FFFF);
    }

    #[test]
    fn u24_round_trip_mid_value() {
        let mut buf = [0u8; U24_LEN];
        write_u24_be(0x0012_3456, &mut buf);
        assert_eq!(buf, [0x12, 0x34, 0x56]);
        assert_eq!(read_u24_be(&buf), 0x0012_3456);
    }

    // ── Fmt ──────────────────────────────────────────────────────────────

    #[test]
    fn fmt_from_bits_round_trip() {
        for (bits, fmt) in [
            (0u8, Fmt::Type0),
            (1, Fmt::Type1),
            (2, Fmt::Type2),
            (3, Fmt::Type3),
        ] {
            let parsed = Fmt::from_bits(bits).unwrap();
            assert_eq!(parsed, fmt);
            assert_eq!(parsed.to_bits(), bits);
        }
    }

    #[test]
    fn fmt_from_bits_out_of_range_is_malformed() {
        assert!(matches!(
            Fmt::from_bits(4),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn fmt_display_matches_name() {
        assert_eq!(Fmt::Type0.to_string(), "type 0");
        assert_eq!(Fmt::Type3.to_string(), "type 3");
    }

    // ── BasicHeader: 1-byte form ─────────────────────────────────────────

    #[test]
    fn basic_header_one_byte_form_round_trip_build_serialize_parse() {
        for csid in [BASIC_HEADER_1BYTE_MIN_CSID, 5, BASIC_HEADER_1BYTE_MAX_CSID] {
            let bh = BasicHeader {
                fmt: Fmt::Type1,
                chunk_stream_id: csid,
            };
            let mut buf = [0u8; 1];
            let n = bh.serialize_into(&mut buf).unwrap();
            assert_eq!(n, 1, "csid {csid} must use the 1-byte form");
            let parsed = BasicHeader::parse(&buf).unwrap();
            assert_eq!(parsed, bh);
        }
    }

    #[test]
    fn basic_header_one_byte_form_parse_serialize_byte_identical() {
        // fmt=1 (bits 01), csid=5: byte0 = 0b01_000101 = 0x45.
        let bytes = [0x45u8];
        let bh = BasicHeader::parse(&bytes).unwrap();
        assert_eq!(bh.fmt, Fmt::Type1);
        assert_eq!(bh.chunk_stream_id, 5);
        let mut buf = [0u8; 1];
        bh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    // ── BasicHeader: 2-byte form ─────────────────────────────────────────

    #[test]
    fn basic_header_two_byte_form_round_trip_boundaries() {
        for csid in [
            BASIC_HEADER_2BYTE_MIN_CSID,
            200,
            BASIC_HEADER_2BYTE_MAX_CSID,
        ] {
            let bh = BasicHeader {
                fmt: Fmt::Type2,
                chunk_stream_id: csid,
            };
            let mut buf = [0u8; 2];
            let n = bh.serialize_into(&mut buf).unwrap();
            assert_eq!(n, 2, "csid {csid} must use the minimal 2-byte form");
            let parsed = BasicHeader::parse(&buf).unwrap();
            assert_eq!(parsed, bh);
        }
    }

    #[test]
    fn basic_header_two_byte_form_parse_serialize_byte_identical() {
        // fmt=2 (bits 10), marker 0, csid-64 = 0 => csid 64.
        let bytes = [0b10_000000u8, 0x00];
        let bh = BasicHeader::parse(&bytes).unwrap();
        assert_eq!(bh.fmt, Fmt::Type2);
        assert_eq!(bh.chunk_stream_id, 64);
        let mut buf = [0u8; 2];
        bh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    // ── BasicHeader: 3-byte form ─────────────────────────────────────────

    #[test]
    fn basic_header_three_byte_form_round_trip_boundaries() {
        for csid in [
            BASIC_HEADER_3BYTE_MIN_CSID,
            40000,
            BASIC_HEADER_3BYTE_MAX_CSID,
        ] {
            let bh = BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: csid,
            };
            let mut buf = [0u8; 3];
            let n = bh.serialize_into(&mut buf).unwrap();
            assert_eq!(n, 3, "csid {csid} must use the 3-byte form");
            let parsed = BasicHeader::parse(&buf).unwrap();
            assert_eq!(parsed, bh);
        }
    }

    #[test]
    fn basic_header_three_byte_form_parse_serialize_byte_identical() {
        // fmt=0, marker 1, csid-64 = 0xFFFF (LE: byte1=0xFF, byte2=0xFF) => csid 65599.
        let bytes = [0b00_000001u8, 0xFF, 0xFF];
        let bh = BasicHeader::parse(&bytes).unwrap();
        assert_eq!(bh.fmt, Fmt::Type0);
        assert_eq!(bh.chunk_stream_id, BASIC_HEADER_3BYTE_MAX_CSID);
        let mut buf = [0u8; 3];
        bh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    #[test]
    fn basic_header_2byte_and_3byte_csid_are_little_endian() {
        // csid = 64 + 0x0102 = 0x0142 = 322. 3-byte form: byte1=low=0x02, byte2=high=0x01.
        let bh = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: 64 + 0x0102,
        };
        let mut buf = [0u8; 3];
        bh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf[1], 0x02, "low byte of csid-64 must come first");
        assert_eq!(buf[2], 0x01, "high byte of csid-64 must come second");
        assert_eq!(BasicHeader::parse(&buf).unwrap(), bh);
    }

    // ── BasicHeader: errors ──────────────────────────────────────────────

    #[test]
    fn basic_header_csid_zero_is_malformed_on_serialize() {
        let bh = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: 0,
        };
        let mut buf = [0u8; 3];
        assert!(matches!(
            bh.serialize_into(&mut buf),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn basic_header_csid_one_is_malformed_on_serialize() {
        let bh = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: 1,
        };
        let mut buf = [0u8; 3];
        assert!(matches!(
            bh.serialize_into(&mut buf),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn basic_header_csid_above_max_is_malformed_on_serialize() {
        let bh = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: BASIC_HEADER_3BYTE_MAX_CSID + 1,
        };
        let mut buf = [0u8; 3];
        assert!(matches!(
            bh.serialize_into(&mut buf),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn basic_header_empty_input_is_buffer_too_short() {
        assert!(matches!(
            BasicHeader::parse(&[]),
            Err(RtmpError::BufferTooShort {
                need: 1,
                have: 0,
                ..
            })
        ));
    }

    #[test]
    fn basic_header_truncated_two_byte_form_is_buffer_too_short() {
        let bytes = [0b00_000000u8]; // marker=0 (2-byte form) but only 1 byte given.
        assert!(matches!(
            BasicHeader::parse(&bytes),
            Err(RtmpError::BufferTooShort {
                need: 2,
                have: 1,
                ..
            })
        ));
    }

    #[test]
    fn basic_header_truncated_three_byte_form_is_buffer_too_short() {
        let bytes = [0b00_000001u8, 0xAB]; // marker=1 (3-byte form) but only 2 bytes given.
        assert!(matches!(
            BasicHeader::parse(&bytes),
            Err(RtmpError::BufferTooShort {
                need: 3,
                have: 2,
                ..
            })
        ));
    }

    // ── MessageHeader: Type 0 ────────────────────────────────────────────

    #[test]
    fn type0_round_trip_build_serialize_parse_no_extended() {
        let mh = MessageHeader::Type0 {
            timestamp: 0x0011_2233,
            message_length: 0x0004_5566,
            message_type_id: 0x09,
            message_stream_id: 0xAABB_CCDD,
        };
        let mut buf = [0u8; TYPE0_LEN];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, TYPE0_LEN);
        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
        assert_eq!(consumed, TYPE0_LEN);
        assert_eq!(parsed, mh);
    }

    #[test]
    fn type0_parse_serialize_byte_identical_no_extended_and_le_stream_id() {
        // timestamp = 0x001122 (< marker, no extension).
        // message_length = 0x334455.
        // message_type_id = 0x09.
        // message_stream_id = 0xAABBCCDD, wire LE => DD CC BB AA.
        let bytes: [u8; TYPE0_LEN] = [
            0x00, 0x11, 0x22, // timestamp
            0x33, 0x44, 0x55, // message_length
            0x09, // message_type_id
            0xDD, 0xCC, 0xBB, 0xAA, // message_stream_id, little-endian
        ];
        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
        assert_eq!(consumed, TYPE0_LEN);
        assert_eq!(
            mh,
            MessageHeader::Type0 {
                timestamp: 0x0000_1122,
                message_length: 0x0033_4455,
                message_type_id: 0x09,
                message_stream_id: 0xAABB_CCDD,
            }
        );
        let mut buf = [0u8; TYPE0_LEN];
        mh.serialize_into(&mut buf).unwrap();
        assert_eq!(
            buf, bytes,
            "byte-identical round trip, LE stream id included"
        );
    }

    #[test]
    fn type0_extended_timestamp_parse_serialize_byte_identical() {
        // 24-bit timestamp field = sentinel 0xFFFFFF => extended 4-byte BE
        // timestamp follows, value 0x01020304 (chosen so BE != LE, catching
        // an endianness bug in the extended field).
        let bytes: [u8; TYPE0_LEN + 4] = [
            0xFF, 0xFF, 0xFF, // timestamp sentinel
            0x00, 0x00, 0x10, // message_length
            0x08, // message_type_id
            0x01, 0x00, 0x00, 0x00, // message_stream_id = 1, LE
            0x01, 0x02, 0x03, 0x04, // extended timestamp, big-endian
        ];
        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
        assert_eq!(consumed, TYPE0_LEN + 4);
        assert_eq!(
            mh,
            MessageHeader::Type0 {
                timestamp: 0x0102_0304,
                message_length: 0x0000_0010,
                message_type_id: 0x08,
                message_stream_id: 1,
            }
        );
        let mut buf = [0u8; TYPE0_LEN + 4];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, TYPE0_LEN + 4);
        assert_eq!(
            buf, bytes,
            "extended timestamp path must round-trip byte-identically"
        );
    }

    #[test]
    fn type0_timestamp_exactly_at_marker_boundary_uses_extended_path() {
        // timestamp == EXTENDED_TIMESTAMP_MARKER exactly: per spec this MUST
        // still go through the extended-timestamp path (">=", not ">").
        let mh = MessageHeader::Type0 {
            timestamp: EXTENDED_TIMESTAMP_MARKER,
            message_length: 10,
            message_type_id: 1,
            message_stream_id: 0,
        };
        assert_eq!(mh.serialized_len(), TYPE0_LEN + 4);
        let mut buf = [0u8; TYPE0_LEN + 4];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, TYPE0_LEN + 4);
        assert_eq!(
            &buf[0..3],
            [0xFF, 0xFF, 0xFF],
            "24-bit field must be the sentinel"
        );
        assert_eq!(
            &buf[11..15],
            &EXTENDED_TIMESTAMP_MARKER.to_be_bytes()[..],
            "extended field carries the real value"
        );
        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
        assert_eq!(consumed, TYPE0_LEN + 4);
        assert_eq!(parsed, mh);
    }

    // ── MessageHeader: Type 1 ────────────────────────────────────────────

    #[test]
    fn type1_round_trip_build_serialize_parse_no_extended() {
        let mh = MessageHeader::Type1 {
            timestamp_delta: 20,
            message_length: 32,
            message_type_id: 8,
        };
        let mut buf = [0u8; TYPE1_LEN];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, TYPE1_LEN);
        let (parsed, consumed) = MessageHeader::parse(Fmt::Type1, &buf).unwrap();
        assert_eq!(consumed, TYPE1_LEN);
        assert_eq!(parsed, mh);
    }

    #[test]
    fn type1_extended_timestamp_parse_serialize_byte_identical() {
        let bytes: [u8; TYPE1_LEN + 4] = [
            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
            0x00, 0x00, 0x20, // message_length
            0x09, // message_type_id
            0x0A, 0x0B, 0x0C, 0x0D, // extended timestamp delta, big-endian
        ];
        let (mh, consumed) = MessageHeader::parse(Fmt::Type1, &bytes).unwrap();
        assert_eq!(consumed, TYPE1_LEN + 4);
        assert_eq!(
            mh,
            MessageHeader::Type1 {
                timestamp_delta: 0x0A0B_0C0D,
                message_length: 0x0000_0020,
                message_type_id: 0x09,
            }
        );
        let mut buf = [0u8; TYPE1_LEN + 4];
        mh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    // ── MessageHeader: Type 2 ────────────────────────────────────────────

    #[test]
    fn type2_round_trip_build_serialize_parse_no_extended() {
        let mh = MessageHeader::Type2 {
            timestamp_delta: 20,
        };
        let mut buf = [0u8; TYPE2_LEN];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, TYPE2_LEN);
        let (parsed, consumed) = MessageHeader::parse(Fmt::Type2, &buf).unwrap();
        assert_eq!(consumed, TYPE2_LEN);
        assert_eq!(parsed, mh);
    }

    #[test]
    fn type2_extended_timestamp_parse_serialize_byte_identical() {
        let bytes: [u8; TYPE2_LEN + 4] = [
            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
            0x11, 0x22, 0x33, 0x44, // extended timestamp delta, big-endian
        ];
        let (mh, consumed) = MessageHeader::parse(Fmt::Type2, &bytes).unwrap();
        assert_eq!(consumed, TYPE2_LEN + 4);
        assert_eq!(
            mh,
            MessageHeader::Type2 {
                timestamp_delta: 0x1122_3344,
            }
        );
        let mut buf = [0u8; TYPE2_LEN + 4];
        mh.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    // ── MessageHeader: Type 3 ────────────────────────────────────────────

    #[test]
    fn type3_round_trip_is_zero_bytes() {
        let mh = MessageHeader::Type3;
        assert_eq!(mh.serialized_len(), 0);
        let mut buf: [u8; 0] = [];
        let n = mh.serialize_into(&mut buf).unwrap();
        assert_eq!(n, 0);
        let (parsed, consumed) = MessageHeader::parse(Fmt::Type3, &[]).unwrap();
        assert_eq!(consumed, 0);
        assert_eq!(parsed, MessageHeader::Type3);
    }

    // ── MessageHeader: errors ────────────────────────────────────────────

    #[test]
    fn type0_truncated_input_is_buffer_too_short() {
        let bytes = [0u8; TYPE0_LEN - 1];
        assert!(matches!(
            MessageHeader::parse(Fmt::Type0, &bytes),
            Err(RtmpError::BufferTooShort {
                need: TYPE0_LEN,
                ..
            })
        ));
    }

    #[test]
    fn type0_extended_marker_but_truncated_extended_field_is_buffer_too_short() {
        let mut bytes = [0u8; TYPE0_LEN + 2]; // only 2 of the 4 extended bytes.
        bytes[0] = 0xFF;
        bytes[1] = 0xFF;
        bytes[2] = 0xFF;
        assert!(matches!(
            MessageHeader::parse(Fmt::Type0, &bytes),
            Err(RtmpError::BufferTooShort {
                need,
                ..
            }) if need == TYPE0_LEN + 4
        ));
    }

    // ── Mutation-check sentinels ─────────────────────────────────────────
    // These pin exact wire-byte expectations (not just self-round-trip),
    // so a serializer that silently drops the extended-timestamp tail, or
    // mis-orders the little-endian message_stream_id, fails a test above:
    // `type0_parse_serialize_byte_identical_no_extended_and_le_stream_id`
    // hand-builds its expected bytes with the stream id reversed from host
    // order, and `type0_extended_timestamp_parse_serialize_byte_identical`
    // hand-builds a 15-byte fixture whose length alone (`TYPE0_LEN + 4`)
    // fails if the extended tail is ever omitted.

    #[test]
    fn message_stream_id_le_differs_from_be_for_asymmetric_value() {
        // Sanity check that our fixture value's LE and BE encodings differ,
        // so the byte-identical test above truly exercises endianness (a
        // palindromic value like 0x01010101 would pass either order).
        let v: u32 = 0xAABB_CCDD;
        assert_ne!(v.to_le_bytes(), v.to_be_bytes());
    }

    // ── ChunkAssembler / ChunkWriter ─────────────────────────────────────

    fn msg(csid: u32, timestamp: u32, type_id: u8, stream_id: u32, payload: Vec<u8>) -> Message {
        Message {
            chunk_stream_id: csid,
            timestamp,
            message_type_id: type_id,
            message_stream_id: stream_id,
            payload,
        }
    }

    #[test]
    fn writer_assembler_round_trip_small_message_single_chunk() {
        let original = msg(4, 1000, 9, 1, vec![0xAB; 50]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&bytes).unwrap();
        assert_eq!(out.len(), 1, "one message must come back out");
        assert_eq!(out[0], original);
    }

    /// A 16 MiB (2^24) payload cannot fit the 24-bit `message_length` field
    /// (#1129): unfixed, `payload.len() as u32` then the UI24 writer kept
    /// only the low 24 bits, silently misframing the chunk stream with `Ok`.
    #[test]
    fn write_oversized_payload_errors() {
        let original = msg(4, 0, 9, 1, vec![0xABu8; 1 << 24]);
        let err = ChunkWriter::new().write(&original).unwrap_err();
        assert!(
            matches!(
                err,
                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
                    field: "message_length",
                    ..
                })
            ),
            "expected FieldOverflow for message_length, got {err:?}"
        );
    }

    /// The boundary: exactly (2^24 - 1) bytes still writes and reassembles.
    #[test]
    fn write_max_payload_message_length_field_is_exact() {
        // ChunkAssembler has its own, separate 8 MiB reassembly cap
        // (MAX_MESSAGE_LEN) below this field's 16 MiB wire max, so this
        // checks the written header bytes directly rather than
        // round-tripping through the assembler.
        let payload = vec![0xCDu8; (1 << 24) - 1];
        let original = msg(4, 0, 9, 1, payload.clone());
        let bytes = ChunkWriter::new().write(&original).unwrap();

        // BasicHeader (1 byte, csid 4) + timestamp (3 bytes) precede
        // message_length (3 bytes, §5.3.1.2.1).
        let message_length = read_u24_be(&bytes[4..7]);
        assert_eq!(message_length, (1 << 24) - 1);
    }

    #[test]
    fn writer_assembler_round_trip_message_larger_than_chunk_size() {
        // 300-byte payload at the default 128-byte chunk size => 3 chunks
        // (128 + 128 + 44): Type 0 first chunk, two Type 3 continuations.
        let original = msg(6, 5000, 9, 42, (0u8..=255).cycle().take(300).collect());
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        // Sanity: verify the byte stream really contains 3 chunks (1 basic
        // header for csid 6 is 1 byte; Type 0 header is TYPE0_LEN; then 128
        // payload bytes; then two Type 3 (1-byte basic header, 0-byte
        // message header) + payload chunks of 128 and 44).
        let expected_len = 1 + TYPE0_LEN + 128 + (1 + 128) + (1 + 44);
        assert_eq!(bytes.len(), expected_len);

        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&bytes).unwrap();
        assert_eq!(
            out.len(),
            1,
            "the 3 chunks must reassemble into ONE message"
        );
        assert_eq!(out[0], original);
        assert_eq!(out[0].payload.len(), 300);
    }

    #[test]
    fn assembler_multi_chunk_payload_reassembled_in_order() {
        // Hand-built stream: Type 0 header (csid 3, len 10, type 8, stream
        // 0, timestamp 0) with 4 payload bytes, chunk size forced to 4, then
        // two Type 3 continuations of 4 and 2 bytes — assert the payload
        // comes back concatenated in the right order, not reordered.
        let mut assembler = ChunkAssembler::new();
        assembler.set_chunk_size(4);

        let bh0 = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: 3,
        };
        let mh0 = MessageHeader::Type0 {
            timestamp: 0,
            message_length: 10,
            message_type_id: 8,
            message_stream_id: 0,
        };
        let mut input = Vec::new();
        write_serialized_ok(&mut input, &bh0);
        write_serialized_ok(&mut input, &mh0);
        input.extend_from_slice(&[1, 2, 3, 4]);

        let bh3 = BasicHeader {
            fmt: Fmt::Type3,
            chunk_stream_id: 3,
        };
        write_serialized_ok(&mut input, &bh3);
        input.extend_from_slice(&[5, 6, 7, 8]);
        write_serialized_ok(&mut input, &bh3);
        input.extend_from_slice(&[9, 10]);

        let out = assembler.push(&input).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    #[test]
    fn assembler_header_inheritance_type0_type1_type2_type3() {
        // fmt0 (ts=1000, len=5, type=8, stream=7) -> fmt1 (delta=20) ->
        // fmt2 (delta=30) -> fmt3 (inherits fmt2's delta=30). Each chunk's
        // message completes in one go (message_length == chunk_size == 5)
        // so every header starts a fresh message on this csid.
        let mut assembler = ChunkAssembler::new();
        assembler.set_chunk_size(5);
        let csid = 5;

        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 1000,
                message_length: 5,
                message_type_id: 8,
                message_stream_id: 7,
            },
        );
        input.extend_from_slice(&[0; 5]);

        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type1,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type1 {
                timestamp_delta: 20,
                message_length: 5,
                message_type_id: 8,
            },
        );
        input.extend_from_slice(&[1; 5]);

        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type2,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type2 {
                timestamp_delta: 30,
            },
        );
        input.extend_from_slice(&[2; 5]);

        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: csid,
            },
        );
        input.extend_from_slice(&[3; 5]);

        let out = assembler.push(&input).unwrap();
        assert_eq!(out.len(), 4);

        assert_eq!(out[0].timestamp, 1000);
        assert_eq!(out[0].message_stream_id, 7);
        assert_eq!(out[0].message_type_id, 8);
        assert_eq!(out[0].payload, vec![0; 5]);

        assert_eq!(out[1].timestamp, 1020, "fmt1: 1000 + delta 20");
        assert_eq!(out[1].message_stream_id, 7, "fmt1 inherits stream id");
        assert_eq!(out[1].message_type_id, 8);
        assert_eq!(out[1].payload, vec![1; 5]);

        assert_eq!(out[2].timestamp, 1050, "fmt2: 1020 + delta 30");
        assert_eq!(out[2].message_stream_id, 7, "fmt2 inherits stream id");
        assert_eq!(out[2].message_type_id, 8, "fmt2 inherits type id");
        assert_eq!(out[2].payload, vec![2; 5], "fmt2 inherits message length");

        assert_eq!(
            out[3].timestamp, 1080,
            "fmt3 (new message) inherits fmt2's delta 30: 1050 + 30"
        );
        assert_eq!(out[3].message_stream_id, 7, "fmt3 inherits stream id");
        assert_eq!(out[3].message_type_id, 8, "fmt3 inherits type id");
        assert_eq!(out[3].payload, vec![3; 5], "fmt3 inherits message length");
    }

    #[test]
    fn assembler_mid_stream_set_chunk_size_changes_split_boundary() {
        // First message at chunk_size 128 (default): a 10-byte message on
        // csid 7 fits in one chunk. Then shrink chunk_size to 4 and send a
        // second 10-byte message on the same csid (fresh Type 0): it must
        // now arrive in 3 physical chunks (4 + 4 + 2), and pushing only the
        // first two must NOT complete the message yet.
        let mut assembler = ChunkAssembler::new();
        let csid = 7;

        let first = msg(csid, 100, 8, 1, vec![0xAA; 10]);
        let mut writer = ChunkWriter::new();
        let first_bytes = writer.write(&first).unwrap();
        let out = assembler.push(&first_bytes).unwrap();
        assert_eq!(out, vec![first]);

        assembler.set_chunk_size(4);
        let bh0 = BasicHeader {
            fmt: Fmt::Type0,
            chunk_stream_id: csid,
        };
        let mh0 = MessageHeader::Type0 {
            timestamp: 200,
            message_length: 10,
            message_type_id: 8,
            message_stream_id: 1,
        };
        let mut chunk1 = Vec::new();
        write_serialized_ok(&mut chunk1, &bh0);
        write_serialized_ok(&mut chunk1, &mh0);
        chunk1.extend_from_slice(&[1, 2, 3, 4]);
        let out = assembler.push(&chunk1).unwrap();
        assert!(
            out.is_empty(),
            "only 4 of 10 payload bytes arrived, message must not complete yet"
        );

        let bh3 = BasicHeader {
            fmt: Fmt::Type3,
            chunk_stream_id: csid,
        };
        let mut chunk2 = Vec::new();
        write_serialized_ok(&mut chunk2, &bh3);
        chunk2.extend_from_slice(&[5, 6, 7, 8]);
        let out = assembler.push(&chunk2).unwrap();
        assert!(out.is_empty(), "8 of 10 payload bytes, still incomplete");

        let mut chunk3 = Vec::new();
        write_serialized_ok(&mut chunk3, &bh3);
        chunk3.extend_from_slice(&[9, 10]);
        let out = assembler.push(&chunk3).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    #[test]
    fn writer_assembler_round_trip_extended_timestamp_split_across_chunks() {
        // timestamp >= EXTENDED_TIMESTAMP_MARKER forces the Type 0 header
        // (and every Type 3 continuation) to carry the 4-byte Extended
        // Timestamp (§3.1.3) — payload longer than chunk_size so at least
        // one Type 3 continuation chunk exercises the "fmt3 also carries
        // extended timestamp" edge.
        let original = msg(8, EXTENDED_TIMESTAMP_MARKER + 12345, 9, 2, vec![0x7E; 300]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        // Sanity: the first chunk's basic header + Type0 header must be
        // TYPE0_LEN + 4 (extended) bytes, and each Type 3 continuation
        // basic header must be immediately followed by 4 extended bytes
        // before its payload slice.
        let bh_len = 1; // csid 8 fits the 1-byte basic header form.
        let first_header_len = bh_len + TYPE0_LEN + EXTENDED_TIMESTAMP_LEN;
        assert_eq!(&bytes[bh_len..bh_len + 3], [0xFF, 0xFF, 0xFF]);
        let ext_offset = bh_len + TYPE0_LEN;
        assert_eq!(
            &bytes[ext_offset..ext_offset + 4],
            &original.timestamp.to_be_bytes()
        );
        let first_payload_take = 128usize;
        let second_chunk_start = first_header_len + first_payload_take;
        // second chunk: 1-byte Type 3 basic header + 4-byte extended ts.
        assert_eq!(bytes[second_chunk_start] >> 6, Fmt::Type3.to_bits());
        let second_ext_offset = second_chunk_start + 1;
        assert_eq!(
            &bytes[second_ext_offset..second_ext_offset + 4],
            &original.timestamp.to_be_bytes(),
            "fmt3 continuation must carry the same extended timestamp"
        );

        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&bytes).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], original);
        assert_eq!(out[0].timestamp, EXTENDED_TIMESTAMP_MARKER + 12345);
    }

    #[test]
    fn assembler_partial_feed_split_mid_header_no_drop_or_duplicate() {
        let original = msg(9, 42, 8, 3, vec![0x11; 200]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        // Split at an arbitrary offset that lands inside the Type 0 header
        // (byte 3 of 11), well before any payload.
        let split_at = 4;
        assert!(split_at < 1 + TYPE0_LEN);

        let mut assembler = ChunkAssembler::new();
        let out1 = assembler.push(&bytes[..split_at]).unwrap();
        assert!(out1.is_empty(), "partial header must not error or complete");
        let out2 = assembler.push(&bytes[split_at..]).unwrap();
        assert_eq!(out2.len(), 1, "message must complete exactly once");
        assert_eq!(out2[0], original);
    }

    #[test]
    fn assembler_partial_feed_split_mid_payload_no_drop_or_duplicate() {
        let original = msg(10, 42, 8, 3, vec![0x22; 300]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        // Split partway through the first (128-byte) payload chunk.
        let split_at = 1 + TYPE0_LEN + 60;
        let mut assembler = ChunkAssembler::new();
        let out1 = assembler.push(&bytes[..split_at]).unwrap();
        assert!(out1.is_empty());
        let out2 = assembler.push(&bytes[split_at..]).unwrap();
        assert_eq!(out2.len(), 1);
        assert_eq!(out2[0], original);
    }

    /// RTMP-W2 (#1108): `Abort` on a csid with an in-progress message must
    /// discard it, so the next Type 0 message on that csid parses cleanly
    /// instead of the following chunk being read as a continuation of the
    /// aborted (never-completed) payload.
    #[test]
    fn abort_discards_in_progress_message_on_csid() {
        let aborted = msg(12, 1, 8, 3, vec![0xAA; 300]); // spans 3 chunks at default 128
        let mut writer = ChunkWriter::new();
        let aborted_bytes = writer.write(&aborted).unwrap();

        // Feed only the first chunk (Type 0 header + 128 bytes) — the
        // message is left in-progress on csid 12.
        let split_at = 1 + TYPE0_LEN + 128;
        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
        assert!(out.is_empty(), "message must still be in progress");

        assembler.abort(12);

        // A brand-new, independent Type 0 message on the SAME csid must
        // now parse as itself.
        let fresh = msg(12, 2, 8, 3, vec![0xBB; 50]);
        let fresh_bytes = writer.write(&fresh).unwrap();
        let out2 = assembler.push(&fresh_bytes).unwrap();
        assert_eq!(out2.len(), 1);
        assert_eq!(out2[0], fresh);
    }

    /// RTMP-W2 (#1108): the precise corruption mechanism the finding
    /// describes — after `Abort`, a Type 3 chunk that the SENDER means as
    /// the start of a fresh message (inheriting the prior Type 0 header,
    /// same `message_length`) must NOT be read as a continuation of the
    /// aborted payload. Pre-fix, `in_progress` stayed `true` after Abort,
    /// so this Type 3 chunk's bytes were appended onto the old (partial,
    /// stale) payload instead of starting a clean new accumulation.
    #[test]
    fn abort_makes_next_type3_chunk_start_fresh_not_continue() {
        let aborted = msg(12, 1, 8, 3, vec![0xAA; 300]); // message_length=300, no extended ts
        let mut writer = ChunkWriter::new();
        let aborted_bytes = writer.write(&aborted).unwrap();

        let split_at = 1 + TYPE0_LEN + 128;
        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
        assert!(out.is_empty());

        assembler.abort(12);

        // Bare Type 3 chunks (fmt=3, csid=12 -> (3<<6)|12 = 0xCC), a
        // DIFFERENT fill value, completing a fresh 300-byte message that
        // inherits message_length/type/stream_id from the last Type 0
        // header on this csid (§3.1.2) — 128 + 128 + 44 = 300.
        let mut rest = Vec::new();
        for chunk_len in [128, 128, 44] {
            rest.push(0xCC);
            rest.extend(core::iter::repeat_n(0xEEu8, chunk_len));
        }
        let completed = assembler.push(&rest).unwrap();
        assert_eq!(
            completed.len(),
            1,
            "the 300-byte message must complete exactly once"
        );
        assert_eq!(
            completed[0].payload,
            vec![0xEE; 300],
            "must be entirely the fresh fill value, with none of the aborted 0xAA bytes leaked in"
        );
    }

    /// RTMP-W3 (#1108): a Type 1 chunk header arriving mid-message (the
    /// csid already has an in-progress, incomplete message) must be
    /// rejected, not silently reset the csid's state and discard the
    /// in-flight bytes.
    #[test]
    fn type1_header_mid_message_is_rejected() {
        let in_progress = msg(12, 1, 8, 3, vec![0xAA; 300]); // 3 chunks at default 128
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&in_progress).unwrap();

        // Feed only the first chunk — csid 12 is left in-progress.
        let split_at = 1 + TYPE0_LEN + 128;
        let mut assembler = ChunkAssembler::new();
        let out = assembler.push(&bytes[..split_at]).unwrap();
        assert!(out.is_empty());

        // A hand-built Type 1 chunk header on the SAME csid (fmt=1, csid=12
        // fits the 1-byte basic header form: (1 << 6) | 12 = 0x4C).
        let type1_chunk = [
            0x4C, // basic header: fmt=1, csid=12
            0x00, 0x00, 0x05, // timestamp_delta = 5
            0x00, 0x00, 0x32, // message_length = 50
            0x08, // message_type_id
        ];
        let err = assembler.push(&type1_chunk).unwrap_err();
        assert!(matches!(err, RtmpError::Malformed { .. }));
    }

    #[test]
    fn assembler_partial_feed_byte_at_a_time_never_drops_or_duplicates() {
        let original = msg(11, 7, 9, 4, vec![0x33; 260]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        let mut assembler = ChunkAssembler::new();
        let mut collected = Vec::new();
        for b in &bytes {
            collected.extend(assembler.push(std::slice::from_ref(b)).unwrap());
        }
        assert_eq!(collected.len(), 1);
        assert_eq!(collected[0], original);
    }

    #[test]
    fn assembler_type1_on_unseen_csid_is_malformed() {
        let mut assembler = ChunkAssembler::new();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type1,
                chunk_stream_id: 20,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type1 {
                timestamp_delta: 5,
                message_length: 3,
                message_type_id: 1,
            },
        );
        input.extend_from_slice(&[0, 0, 0]);
        assert!(matches!(
            assembler.push(&input),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn assembler_type3_on_unseen_csid_is_malformed() {
        let mut assembler = ChunkAssembler::new();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: 21,
            },
        );
        assert!(matches!(
            assembler.push(&input),
            Err(RtmpError::Malformed { .. })
        ));
    }

    #[test]
    fn assembler_truncated_input_never_panics_across_many_split_points() {
        let original = msg(12, 99, 8, 5, vec![0x44; 400]);
        let mut writer = ChunkWriter::new();
        let bytes = writer.write(&original).unwrap();

        // Feed every possible byte-prefix of the stream to a fresh
        // assembler each time: none may panic, and any that do parse fully
        // must reproduce the original message exactly.
        for split in 0..=bytes.len() {
            let mut assembler = ChunkAssembler::new();
            let first = assembler.push(&bytes[..split]);
            let Ok(first_msgs) = first else {
                continue;
            };
            let second = assembler.push(&bytes[split..]).unwrap();
            let mut all = first_msgs;
            all.extend(second);
            assert_eq!(all, vec![original.clone()]);
        }
    }

    #[test]
    fn writer_default_chunk_size_matches_assembler_default() {
        assert_eq!(ChunkWriter::new().chunk_size, DEFAULT_CHUNK_SIZE);
        assert_eq!(ChunkAssembler::new().chunk_size, DEFAULT_CHUNK_SIZE);
    }

    #[test]
    fn assembler_type3_immediately_after_type0_uses_type0_timestamp_as_implied_delta() {
        // §3.1.2: a Type 3 chunk that starts a NEW message immediately after
        // a Type 0 (nothing intervening) has an implied `timestamp_delta`
        // equal to that Type 0's own absolute timestamp — NOT 0. Every other
        // existing test intervenes a Type 1/2 before the fmt3, so this is
        // the only test that reaches this resolution path directly (bites a
        // mutation of `timestamp_delta: timestamp` -> `timestamp_delta: 0`
        // in the Type 0 arm).
        let mut assembler = ChunkAssembler::new();
        let csid = 40;

        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 1000,
                message_length: 5,
                message_type_id: 8,
                message_stream_id: 2,
            },
        );
        input.extend_from_slice(&[1, 2, 3, 4, 5]);

        // Immediately (same csid, nothing between) a fmt3 chunk starting a
        // new message, inheriting message_length 5 from the Type 0 above.
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: csid,
            },
        );
        input.extend_from_slice(&[9, 9, 9, 9, 9]);

        let out = assembler.push(&input).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].timestamp, 1000);
        assert_eq!(
            out[1].timestamp, 2000,
            "fmt3 immediately after fmt0 implies delta == the fmt0's own timestamp (1000), not 0: 1000 + 1000"
        );
    }

    #[test]
    fn assembler_type2_on_unseen_csid_is_malformed() {
        let mut assembler = ChunkAssembler::new();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type2,
                chunk_stream_id: 22,
            },
        );
        write_serialized_ok(&mut input, &MessageHeader::Type2 { timestamp_delta: 5 });
        assert!(matches!(
            assembler.push(&input),
            Err(RtmpError::Malformed { .. })
        ));
    }

    /// A peer that announces a chunk size below 128 (wire-legal — §5.4.1
    /// only recommends `SHOULD >= 128` for a *sender* choosing what to
    /// announce, the hard floor is `MUST >= 1`) must be parsed at exactly
    /// that size: this crate does not get to unilaterally decide the peer
    /// under-chunked and reinterpret its bytes at a larger boundary,
    /// because the peer already framed every subsequent chunk at the size
    /// it announced. Regression for a prior version of this fix that
    /// clamped an incoming announcement up to a 128-byte floor, which would
    /// have misparsed exactly this stream.
    #[test]
    fn assembler_honours_a_peer_announced_chunk_size_below_128() {
        let mut assembler = ChunkAssembler::new();
        assembler.set_chunk_size(64);
        assert_eq!(
            assembler.chunk_size, 64,
            "the announced size must not be clamped up"
        );

        let payload: Vec<u8> = (0u32..150).map(|i| (i % 251) as u8).collect();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: 12,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 0,
                message_length: payload.len() as u32,
                message_type_id: 8,
                message_stream_id: 0,
            },
        );
        input.extend_from_slice(&payload[0..64]);
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: 12,
            },
        );
        input.extend_from_slice(&payload[64..128]);
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: 12,
            },
        );
        input.extend_from_slice(&payload[128..]);

        let out = assembler.push(&input).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload, payload);
    }

    #[test]
    fn assembler_set_chunk_size_zero_is_floored_to_one() {
        let mut assembler = ChunkAssembler::new();
        assembler.set_chunk_size(0);
        assert_eq!(assembler.chunk_size, 1, "floored at 1, not stuck at 0");

        // A message chunked consistently with the floored size (1 payload
        // byte per physical chunk) still assembles correctly — the floor
        // makes progress possible rather than wedging on every push.
        let csid = 41;
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 1,
                message_length: 3,
                message_type_id: 8,
                message_stream_id: 0,
            },
        );
        input.push(0xAA);
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: csid,
            },
        );
        input.push(0xBB);
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: csid,
            },
        );
        input.push(0xCC);

        let out = assembler.push(&input).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload, vec![0xAA, 0xBB, 0xCC]);
    }

    // ── Remote-DoS caps (excessive-allocation guard) ────────────────────

    /// A complete, well-formed one-chunk message on `csid`: a Type 0 header
    /// declaring `message_length == payload.len()`, immediately followed by
    /// `payload` (so it fits in the default 128-byte chunk size and
    /// completes in a single chunk).
    fn single_chunk(csid: u32, payload: &[u8]) -> Vec<u8> {
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 0,
                message_length: payload.len() as u32,
                message_type_id: 9,
                message_stream_id: 1,
            },
        );
        input.extend_from_slice(payload);
        input
    }

    #[test]
    fn oversized_message_length_header_is_rejected_without_allocating() {
        // Mutation check: a Type 0 header claims a ~16 MiB message_length
        // (the max a 24-bit field can encode) but only ever supplies a
        // single default-chunk-size (128-byte) slice of payload after it —
        // exactly the shape of the excessive-allocation DoS (the peer never
        // has to send anywhere near the claimed length). Without the
        // MAX_MESSAGE_LEN cap this used to `Vec::with_capacity(message_length)`
        // (~16 MiB) right here and return `Ok(vec![])` (message merely
        // in-progress, no error) — this test would then fail, since it
        // asserts an `Err` instead.
        let mut assembler = ChunkAssembler::new();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: 4,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 0,
                message_length: 0x00FF_FFFF, // ~16 MiB: the largest 24-bit value.
                message_type_id: 9,
                message_stream_id: 1,
            },
        );
        input.extend(std::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE as usize));

        let err = assembler.push(&input).expect_err(
            "a message_length beyond MAX_MESSAGE_LEN must be rejected before any \
             message_length-sized buffer is allocated",
        );
        assert!(matches!(err, RtmpError::Malformed { .. }));
    }

    #[test]
    fn message_length_at_the_cap_is_accepted() {
        // Boundary check: exactly MAX_MESSAGE_LEN must still be accepted
        // (only values strictly above the cap are rejected).
        let mut assembler = ChunkAssembler::new();
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: 4,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 0,
                message_length: MAX_MESSAGE_LEN,
                message_type_id: 9,
                message_stream_id: 1,
            },
        );
        input.extend(std::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE as usize));

        // Not yet complete (only one chunk of a much larger message has
        // arrived) but must not be rejected outright.
        assert!(assembler.push(&input).is_ok());
    }

    #[test]
    fn csid_flood_beyond_max_csids_is_rejected() {
        // Mutation check: fill the bound with MAX_CSIDS distinct,
        // well-formed chunk streams first (none of these may error — the
        // cap must not reject legitimate, moderate csid usage), then assert
        // that one more previously-unseen csid is rejected rather than
        // silently growing the per-csid state map without bound. Without
        // the MAX_CSIDS cap this last `push` would also return `Ok(_)`,
        // failing this test's `Err` assertion.
        let mut assembler = ChunkAssembler::new();
        for i in 0..MAX_CSIDS {
            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i as u32;
            let out = assembler
                .push(&single_chunk(csid, &[0xAB]))
                .unwrap_or_else(|e| panic!("csid {csid} (#{i}, within the bound) rejected: {e}"));
            assert_eq!(out.len(), 1);
        }

        let flood_csid = BASIC_HEADER_1BYTE_MIN_CSID + MAX_CSIDS as u32;
        let err = assembler
            .push(&single_chunk(flood_csid, &[0xCD]))
            .expect_err("a new csid beyond MAX_CSIDS must be rejected, not silently accepted");
        assert!(matches!(err, RtmpError::Malformed { .. }));
    }

    #[test]
    fn csid_flood_cap_does_not_count_repeats_of_the_same_csid() {
        // A single csid reused for many messages must never itself trip the
        // MAX_CSIDS cap (the bound is on distinct concurrent csids, not on
        // total message count).
        let mut assembler = ChunkAssembler::new();
        for i in 0..(MAX_CSIDS * 4) {
            let out = assembler
                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8]))
                .expect("repeated use of a single already-known csid must never be rejected");
            assert_eq!(out.len(), 1);
        }
    }

    #[test]
    fn set_chunk_size_is_capped_at_max_chunk_size() {
        let mut assembler = ChunkAssembler::new();
        assembler.set_chunk_size(u32::MAX);
        assert_eq!(assembler.chunk_size, MAX_CHUNK_SIZE);

        let mut writer = ChunkWriter::new();
        writer.set_chunk_size(u32::MAX);
        assert_eq!(writer.chunk_size, MAX_CHUNK_SIZE);
    }

    /// #1108/RTMP-W1: a fresh message opened on `csid` declaring
    /// `declared_len` (> one chunk) payload bytes, with exactly its first
    /// full chunk delivered so it commits and stays in progress. The full
    /// declared length is reserved against the aggregate budget when the
    /// header validates.
    fn open_partial_chunk(csid: u32, declared_len: u32) -> Vec<u8> {
        let sent_len = DEFAULT_CHUNK_SIZE as usize;
        assert!(sent_len < declared_len as usize);
        let mut input = Vec::new();
        write_serialized_ok(
            &mut input,
            &BasicHeader {
                fmt: Fmt::Type0,
                chunk_stream_id: csid,
            },
        );
        write_serialized_ok(
            &mut input,
            &MessageHeader::Type0 {
                timestamp: 0,
                message_length: declared_len,
                message_type_id: 9,
                message_stream_id: 1,
            },
        );
        input.extend_from_slice(&vec![0x5Au8; sent_len]);
        input
    }

    #[test]
    fn aggregate_in_progress_bytes_across_csids_is_capped() {
        // Mutation check: MAX_MESSAGE_LEN bounds ONE message and MAX_CSIDS
        // bounds HOW MANY csids, but neither bounds the *product* — the
        // hoarder does not even have to send the bytes; N csids each with
        // a 24 KiB declaration cost one header each. Without the aggregate
        // budget every push below returns Ok and the assembler accepts
        // (MAX_MESSAGE_LEN x MAX_CSIDS) = 512 MiB of declarations per
        // connection.
        const BUDGET: usize = 64 * 1024;
        const DECL: u32 = 24 * 1024;
        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(BUDGET);
        // First prove the normal-traffic path: complete messages cycling
        // every legal csid must never trip the budget (reservations are
        // released on delivery), and the csid space really is reachable.
        for i in 0..MAX_CSIDS as u32 {
            let out = assembler
                .push(&single_chunk(
                    BASIC_HEADER_1BYTE_MIN_CSID + i,
                    &[0x5Au8; 100],
                ))
                .expect("complete messages must never trip the budget");
            assert_eq!(out.len(), 1);
            assert_eq!(assembler.in_progress_bytes, 0);
        }
        // Now the hoarding shape: one permanently-partial 24 KiB
        // declaration per csid, each costing the hoarder only a 16-byte
        // payload fragment. 64 KiB / 24 KiB = 2 fit, so the budget must
        // trip on the third push.
        let mut hoarded = 0;
        for i in 0..MAX_CSIDS as u32 {
            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i;
            match assembler.push(&open_partial_chunk(csid, DECL)) {
                Ok(msgs) => {
                    assert!(msgs.is_empty(), "a partial message must not complete");
                    assert_eq!(
                        assembler.in_progress_bytes,
                        (hoarded + 1) * DECL as usize,
                        "each accepted declaration must reserve its full length"
                    );
                    hoarded += 1;
                }
                Err(err) => {
                    assert!(
                        matches!(&err, RtmpError::Malformed { .. }),
                        "budget overrun must be Malformed (push #{hoarded}), got {err:?}"
                    );
                    break;
                }
            }
        }
        // 64 KiB / 24 KiB = 2 partials fit: the budget trips on the third
        // push — long before the MAX_CSIDS cap could (only 3 csids exist
        // on this connection, far below the 64-csid ceiling).
        assert_eq!(
            hoarded, 2,
            "the budget must be what stops the flood, not the csid cap"
        );
        assert!(
            assembler.in_progress_bytes <= BUDGET,
            "held bytes must never exceed the budget"
        );
    }

    #[test]
    fn aggregate_in_progress_budget_trips_mid_message_and_recovers_on_completion() {
        const DECL: u32 = 200;
        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
        assert!(
            assembler
                .push(&open_partial_chunk(3, DECL))
                .unwrap()
                .is_empty()
        );
        assert_eq!(assembler.in_progress_bytes, DECL as usize);
        // A second declaration would need 2x DECL: fatal, and the rejected
        // message leaves no reservation behind.
        assembler
            .push(&open_partial_chunk(4, DECL))
            .expect_err("a second declaration trips the cap");
        assert_eq!(assembler.in_progress_bytes, DECL as usize);
        // Recovery is checked on a fresh assembler (the error is fatal for
        // the connection): completing the message releases its reservation.
        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
        assembler.push(&open_partial_chunk(3, DECL)).unwrap();
        let mut tail = Vec::new();
        write_serialized_ok(
            &mut tail,
            &BasicHeader {
                fmt: Fmt::Type3,
                chunk_stream_id: 3,
            },
        );
        tail.extend_from_slice(&vec![0x11u8; DECL as usize - DEFAULT_CHUNK_SIZE as usize]);
        let out = assembler.push(&tail).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload.len(), DECL as usize);
        assert_eq!(assembler.in_progress_bytes, 0);
        assembler
            .push(&open_partial_chunk(5, DECL))
            .expect("freed budget must be reusable");
        assert_eq!(assembler.in_progress_bytes, DECL as usize);
    }

    #[test]
    fn aggregate_in_progress_budget_unchanged_by_completed_messages() {
        // Many complete messages through a tight budget must never trip
        // the cap (payload leaves the budget the moment it is delivered),
        // proving the cap bounds *stuck* bytes, not throughput.
        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(16);
        for i in 0..50u32 {
            let out = assembler
                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8; 15]))
                .expect("completed messages must not count toward the budget");
            assert_eq!(out.len(), 1);
        }
        assert_eq!(assembler.in_progress_bytes, 0);
    }

    /// r08-RTMP-C1 regression: reassembling a large message split into many
    /// small physical chunks (here, chunk size 1 — the wire's own hard
    /// floor, `MUST >= 1`, and the shape the original finding used) must do
    /// O(`message_length`) total payload-copying work, not
    /// O(`message_length`^2 / `chunk_size`). Measured directly via the
    /// `#[cfg(test)]` byte-copy hook rather than a wall-clock bound (a
    /// wall-clock bound is inherently flaky under load; this one instead
    /// asserts the exact quantity the fix changes).
    ///
    /// Pre-fix, at `MAX_MESSAGE_LEN` (8 MiB) split into 1-byte chunks
    /// (~8.4 million of them), the old "clone the whole accumulated payload
    /// on every continuation chunk" code would have copied on the order of
    /// `sum(1, 2, ..., 8 MiB) ~= 8MiB^2 / 2` bytes — many terabytes, not
    /// safely runnable here (would allocate far beyond a reasonable test
    /// budget). A *smaller*-scale version of this same shape was run
    /// directly against the pre-fix code (64 KiB / 256 KiB at chunk size 1)
    /// and confirmed the quadratic blowup (wall-clock time scaled ~11x for
    /// a 4x size increase) before this fix landed; see brief/PR notes.
    #[test]
    fn reassembling_an_8mib_message_at_chunk_size_one_is_linear_not_quadratic() {
        let payload: Vec<u8> = (0..MAX_MESSAGE_LEN).map(|i| (i % 251) as u8).collect();
        let original = msg(10, 0, 9, 1, payload.clone());

        let mut writer = ChunkWriter::new();
        writer.set_chunk_size(1);
        let bytes = writer.write(&original).unwrap();

        let mut assembler = ChunkAssembler::new().with_chunk_size(1);

        reset_payload_bytes_copied_for_test();
        let out = assembler.push(&bytes).unwrap();
        let copied = payload_bytes_copied_for_test();

        assert_eq!(out.len(), 1);
        assert_eq!(out[0].payload, payload);

        // Generous (4x message length) but already far below what the old
        // quadratic code would have copied (~4 million x message length at
        // this size/chunk_size) — this bound is only reachable by O(n)
        // reassembly.
        assert!(
            copied <= payload.len() * 4,
            "copied {copied} bytes reassembling a {}-byte message at chunk \
             size 1 — quadratic behaviour crept back in",
            payload.len()
        );
    }
}

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

    fn msg(csid: u32) -> Message {
        Message {
            chunk_stream_id: csid,
            timestamp: 0,
            message_type_id: 20,
            message_stream_id: 1,
            payload: vec![1, 2, 3],
        }
    }

    #[test]
    fn write_rejects_out_of_range_chunk_stream_id_without_panicking() {
        let mut w = ChunkWriter::new();
        for bad in [0u32, 1, 65600, u32::MAX] {
            match w.write(&msg(bad)) {
                Err(RtmpError::InvalidChunkStreamId { chunk_stream_id }) => {
                    assert_eq!(chunk_stream_id, bad);
                }
                other => panic!("csid {bad}: expected InvalidChunkStreamId, got {other:?}"),
            }
        }
        for ok in [2u32, 63, 64, 319, 320, 65599] {
            assert!(w.write(&msg(ok)).is_ok(), "csid {ok} must be accepted");
        }
    }
}