transmux 0.30.0

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
//! MPEG-2 Transport Stream demuxer → hub [`Media`] IR.
//!
//! [`StreamingTsDemux`] (issue #555) is the **one** demux core: an
//! event-driven, incremental engine that consumes TS bytes of any size or
//! alignment and emits [`DemuxEvent`]s (`TrackAdded`/`Sample`/
//! `ClockReference`/`Discontinuity`/`TracksResolved`) as soon as they are
//! known.
//! `TracksResolved` (issue #624) additionally tells a consumer when every
//! currently-known PMT-declared PID has resolved — the "safe to build a
//! multi-track segmenter now" signal. [`TsDemux`] — the
//! **input** side of the any-to-any container hub, implementing the abstract
//! [`broadcast_common::Unpackage`] trait so `{TS} → IR → {any}` composes with
//! the existing [`CmafMux`](crate::media::CmafMux) /
//! [`HlsPackager`](crate::media::HlsPackager) packagers — is now a thin batch
//! wrapper over it: feed the whole buffer, call `finish()`, fold the event
//! stream into a [`Media`]. There is no separate whole-buffer implementation;
//! every behaviour below is produced by the streaming core.
//!
//! Pipeline: TS packet layer ([`mpeg_ts`], resynchronised via
//! [`mpeg_ts::resync::TsResync`]) → follow PAT → PMT → per-PID PES
//! reassembly ([`mpeg_pes`]) → codec-config recovery (H.264 SPS/PPS → `avcC`,
//! H.265 VPS/SPS/PPS → `hvcC`, MPEG-2 video `sequence_header()` → `esds`,
//! ADTS → AudioSpecificConfig →
//! `esds`, MPEG-1/2 audio frame header → `esds`, AC-3/E-AC-3 syncframe BSI →
//! `dac3`/`dec3`, DTS core-frame header → `ddts`) → length-prefixed video /
//! raw audio samples.
//!
//! Config recovery happens incrementally, access unit by access unit: a
//! track's `DemuxEvent::TrackAdded` fires as soon as its config is known —
//! with an opaque [`CodecConfig::Data`] track (issue #557) firing on its very
//! first access unit, since its config needs no in-band header at all.
//!
//! The config is **not** frozen at that point. A stream may change its
//! parameter sets mid-flight (an SD↔HD ad break, a re-encode, a multiplex
//! reconfiguration), and a track whose in-band AVC/HEVC parameter sets or AAC
//! `ADTS` header actually change re-probes on that access unit and emits
//! `DemuxEvent::TrackUpdated` with the new config on the *same* `track_id`
//! (r04-W51) — mirroring `flv_stream`'s handling of a re-sent sequence
//! header. An unchanging repeat, which encoders send routinely, emits
//! nothing.
//!
//! HEVC (H.265) elementary streams are carried into the IR: the in-band
//! VPS/SPS/PPS NAL units are gathered from the Annex-B access units, decoded
//! into an `hvcC` [`HEVCConfigurationBox`], and emitted as a `hvc1`
//! [`CodecConfig::Hevc`] track — identical to the config `Fmp4Demux` recovers
//! from an fMP4 `hvcC` (issue #467). DTS elementary streams (stream_type
//! `0x82`/`0x85`/`0x8A`) are carried: the core-substream frame header
//! (`0x7FFE8001` sync) is parsed into a core-only `ddts` [`CodecConfig::Dts`]
//! track, mirroring the AC-3/E-AC-3 recovery path (issue #560, see
//! [`crate::dts`]).
//!
//! Every video and audio sample additionally carries **absolute** `dts`/`pts`
//! (media plane step 2c) recovered from the PES clock (issue #556): the
//! 33-bit wire PTS/DTS is unwrapped incrementally, once, right here at the
//! demux edge (by this module's internal `WrapState`, matching
//! `timed_metadata::Timeline`'s
//! semantics) — nothing downstream re-derives it. Video/AAC/MPEG-audio
//! samples get the unwrapped PTS/DTS of the access unit they were decoded
//! from (with per-frame interpolation when a PES payload splits into several
//! frames); AC-3/E-AC-3/DTS elementary streams are additionally split into
//! individual syncframes/core frames (rather than one zero-duration `Sample`
//! per PES access unit — see [`crate::ac3`] / [`crate::dts`]) so real
//! durations and exact PES-boundary timestamps survive into the IR.
//! **Field-coded (PAFF) H.264 (issue #1161).** Broadcast PAFF carries one coded
//! field per PES, but an ISO/IEC 14496-15 sample is a whole access unit; the
//! video path parses each access unit's slice header ([`crate::slice_header`])
//! and merges the second field of a complementary field pair (ITU-T H.264
//! §3.35-3.37) into the first field's sample, which keeps the first field's
//! PTS/DTS. Unpaired fields and fields across a timestamp jump are emitted
//! alone; MBAFF and progressive pictures are never merged.
//! **Cross-PES audio frames (issue #1160).** MPEG-1/2 audio (ISO/IEC 11172-3
//! §2.4.1.3), ADTS AAC (ISO/IEC 13818-7 §6.2), AC-3 / E-AC-3 (ETSI TS 102 366
//! §4.3 / Annex E) and DTS core (ETSI TS 102 114 §5.3) PES payloads need not start
//! or end on a frame boundary — ISO/IEC 13818-1 §2.4.3.7 only stamps the first
//! access unit that *commences* in a PES. The unfinished tail of each payload
//! (a valid header whose frame overruns it, or a 1..header-length byte prefix
//! of one) is therefore held in a per-PID carry, strictly bounded by one frame
//! (`AUDIO_CARRY_MAX_BYTES`), and prepended to the next payload of the same
//! PID. The carried frame takes the frame-exact cursor position, i.e. the PTS
//! of the PES in which it *started* plus the durations of the frames before it;
//! the wire stamp of the completing PES is compared against `cursor + the
//! carried frame's duration`. The carry is accepted only when a valid header
//! follows the completed frame (a false sync cannot swallow real frames), and
//! is dropped on a continuity gap, a dropped/over-budget PES or a re-anchor of
//! an unrelated stream; a dangling partial frame at end of stream emits
//! nothing. Resync-on-garbage (issue #638) is unchanged and now applies to
//! every one of those codecs. Config recovery likewise works across PES
//! boundaries: a PES shorter than a header, or a stream whose first PES starts
//! mid-frame, still resolves the track (a bounded probe window joins the held
//! tail of earlier access units to the newest one).
//! Video/data-track sample durations are resolved **one access unit
//! behind**: the timestamp delta to the *next* access unit (unwrapped DTS
//! for video, PTS for data — ISO/IEC 13818-1 §2.4.3.7) finalizes the
//! *previous* sample's duration, with the final sample of a finished stream
//! reusing the previous duration ([`finish`](StreamingTsDemux::finish)).
//!
//! Any PMT `stream_type` that is not a decoded codec is carried losslessly as
//! an opaque [`CodecConfig::Data`] track (issues #557/#576) rather than
//! silently dropped — `stream_type` 0x06 (PES private data — DVB
//! subtitles/teletext/SMPTE 2038/AC-3/E-AC-3/DTS/etc.) and 0x15 (metadata in
//! PES) were the first examples; every other unrecognised `stream_type`
//! follows the same path. A `0x06`/`0x15` stream carrying an AC-3 (`0x6A`),
//! enhanced AC-3 (`0x7A`), or DTS (`0x7B`) ES_info descriptor is instead
//! reclassified to that audio codec (issue #641: DVB's standard descriptor-
//! disambiguated Dolby/DTS carriage), reaching the same syncframe-recovery
//! path as the native `0x81`/`0x87`/`0x8*` stream_types. `descriptors`
//! preserves the raw PMT ES_info descriptor loop for the caller to classify.
//! ISO/IEC 13818-1 §2.4.4.9 / Table 2-34 splits
//! `stream_type` into two carriage families, and the two are reassembled
//! completely differently (PES-reassembling a section stream, or vice versa,
//! silently yields nothing): most `stream_type`s (including every
//! unrecognised one) are PES-packetised and each `Sample` is one verbatim PES
//! payload; a fixed set (`0x05` private_sections, `0x0A`-`0x0D` DSM-CC, `0x14`
//! DSM-CC synchronized download, `0x86` SCTE-35/ANSI-scoped) carry PSI/private
//! *sections* directly on the PID (§2.4.4) — each reassembled via
//! [`mpeg_ts::ts::SectionReassembler`] instead of a PES assembler, and each
//! complete section becomes one `Sample` with no timestamp at all
//! (`dts: None, pts: None` — never fabricated).
//! [`CodecConfig::Data`]'s `carriage` field ([`DataCarriage`]) records which
//! family a track uses. The demuxer also collects every PCR observation on a
//! program's PMT-announced `PCR_PID` (issue #1354: other PIDs' PCRs are
//! dropped once the PMTs are known, and each event carries its
//! `provenance.program_number`), both into [`Media`]'s `pcr` field (batch) and
//! as [`DemuxEvent::ClockReference`] (streaming).
//!
//! # Draining the streaming queue
//! [`StreamingTsDemux`] appends every event to an internal queue that only
//! [`poll_event`](StreamingTsDemux::poll_event) empties: drain it after each
//! [`feed`](StreamingTsDemux::feed), or memory grows linearly with the input
//! (on lossy input about two `InputDegraded` per loss, issue #1352). The
//! diagnostic volume alone can be bounded, with a counted overflow, via
//! [`StreamingTsDemux::with_max_degraded_events`].
//!
//! # E-AC-3: which frame describes the stream
//!
//! The `dec3` is built from the first access unit the probe can trust. Every
//! E-AC-3 syncframe carries one `crc2` over the whole frame, which a decoder
//! "shall verify" (ETSI TS 102 366 §E.2.2), so the probe prefers an access
//! unit whose frames all verify (`Ec3SyncframeInfo::from_es_first_au_crc_verified`),
//! skipping header-shaped `0B 77` pairs inside coded data and frames damaged by
//! lost packets. Waiting for one would stall a lossy capture (and, in PMT order,
//! every track behind it: the zenith report), so when none is held yet the
//! track is announced from the first header-valid frame, as before.
//!
//! `bsmod` is a property of the *stream*, but a frame carries it only when its
//! `infomdate` bit is set, and the encoder of the French TNT audio-description
//! track sets it in some frames only; `dec3.bsmod` of a frame without it is 0
//! (§F.6.2.8). The probe therefore takes `bsmod` from the first intact frame in
//! its window that carries one (`Ec3SpecificBox` `bsmod`, via
//! `Ec3SyncframeInfo::first_crc_verified_bsmod`), not from whichever frame the
//! config happens to be read from. Pinned on `m6-single.ts` and the private
//! zenith capture against an independent parse of every intact frame and the PMT
//! `component_type` (`tests/it/streaming_ts_demux_eac3_bsmod.rs`: 0x82 / 0x84 main,
//! `bsmod` 0; 0x83 visually impaired, `bsmod` 2). **Limit:** an unverified first
//! frame is not corrected later: if the window holds no intact frame carrying
//! `bsmod` at the time the track is announced (only possible on a capture that
//! loses almost every frame), a damaged frame's `bsmod` stands.
//!
//! # Why an E-AC-3 track cannot be announced from the PMT alone
//!
//! ffmpeg lists an E-AC-3 stream from the PMT `enhanced_AC-3_descriptor` (0x7A,
//! ETSI EN 300 468 Table D.7) before any frame arrives. A [`CodecConfig::Eac3`]
//! needs a complete `dec3` (ETSI TS 102 366 §F.6.1, page 198), and the
//! descriptor cannot supply it:
//!
//! | `dec3` field | from the 0x7A descriptor? |
//! |---|---|
//! | `data_rate` (13) | no: a bitrate is not signalled |
//! | `num_ind_sub` (3) | partly: `substream1..3_flag` count extra independent substreams |
//! | `fscod` (2) | no: the sample rate is not signalled |
//! | `bsid` (5) | yes: the descriptor's `bsid` field (only when `bsid_flag`) |
//! | `asvc` (1) | no: the descriptor's `asvc` is a bitmap of main services it attaches to, a different field; the service-type flags of `component_type` only imply it |
//! | `bsmod` (3) | no: not signalled; `component_type` service-type flags merely agree with it by numbering (EN 300 468 Table D.4 / TS 102 366 Table 4.2) |
//! | `acmod` (3) | no: `component_type`'s channel flags give mono / 1+1 / stereo / "> 2 channels" only |
//! | `lfeon` (1) | no |
//! | `num_dep_sub` (4), `chan_loc` (9) | no: dependent substreams are not signalled at all |
//!
//! `fscod`, `data_rate`, `acmod`, `lfeon` and the dependent-substream fields can
//! only come from a syncframe, so the demuxer does not fabricate a `dec3`: an
//! E-AC-3 PID is announced (`TrackAdded`) when a frame has been parsed, never
//! from the PMT alone.
//!
//! # Programs and declared-but-silent PIDs
//!
//! The demuxer follows the **PAT**: every `(program_number, PMT PID)` it lists is
//! followed, and each announced track carries its `TrackSpec::program_number`.
//! A PMT section whose `program_number` is not the PAT's entry for the PID it
//! arrived on is dropped (the #774 cross-check). The real TNT capture shows the
//! consequence: its PAT lists only program 0x0401, while the same PMT PID also
//! carries a PMT for 0x0601 whose components overlap 0x0401's (and contradict
//! it: 0x83/0x84 swap their `component_type`), so 0x0601 yields no tracks. No
//! data is lost: 0x0601's only PIDs of its own (0x96, 0x97, subtitles) have no
//! packets in the capture.
//!
//! A PMT-declared PID that never carries a packet is likewise never announced:
//! a track is announced when its first access unit arrives (an opaque
//! [`CodecConfig::Data`] track, needing no header, on that very first access
//! unit). This is deliberate: announcing it from the PMT would add an empty
//! `Data` track to every service whose subtitle PID is idle, which every ISOBMFF
//! muxer rejects (`Error::UnmuxableDataTrack`, so each consumer
//! would have to filter it) and which would shift `track_id`s. The cost is that
//! [`DemuxEvent::TracksResolved`] is withheld until each such PID has produced
//! data (or [`finish`](StreamingTsDemux::finish) abandons it): PID 0x8D (HD DVB
//! subtitles, no PES in the capture) is one.
//!
//! [`CodecConfig`]: crate::pipeline::CodecConfig
//! [`DataCarriage`]: crate::pipeline::DataCarriage
//!
//! # Spec
//!
//! - **PAT / PMT section syntax**: ITU-T H.222.0 (= ISO/IEC 13818-1) §2.4.4.4 /
//!   §2.4.4.9 — see `private/specs-verified/mpeg/transmux/codec/ts-demux-13818-1.md`.
//! - **stream_type → codec / carriage**: ISO/IEC 13818-1 §2.4.4.9, Table 2-34
//!   (PES- vs section-carried `stream_type`s) + ETSI TS 101 154 §G (DVB
//!   user-private AC-3/E-AC-3/DTS assignments).
//! - **PES-over-TS reassembly + PTS/DTS**: ISO/IEC 13818-1 §2.4.3.6 / §2.4.3.7
//!   (via [`mpeg_pes`], 33-bit @ 90 kHz).
//! - **PSI/private section reassembly**: ISO/IEC 13818-1 §2.4.4, via
//!   [`mpeg_ts::ts::SectionReassembler`].
//! - **PCR**: ISO/IEC 13818-1 §2.4.3.4 (adaptation field) / §2.4.3.5 (PCR encoding).
//! - **Byte-stream resynchronisation**: ISO/IEC 13818-1 §2.4.3.2, via
//!   [`mpeg_ts::resync::TsResync`] (also strips 204-byte Reed-Solomon FEC).

use crate::display_track::{ActivationOutcome, SpsTracker, TrackCodec};
use crate::ir::{AfdPersistence, DisplayChangeSet, DisplayInfo};
use crate::mpeg2_display::{Mpeg2DisplayTracker, Mpeg2Outcome};
use crate::{ProgramNumber, TrackId};
use alloc::collections::btree_map::Entry;
use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
use alloc::sync::Arc;
use alloc::vec::Vec;
use broadcast_common::error::{BufferTooShort, InvalidValue};
use broadcast_common::len::need_in;
use core::marker::PhantomData;
use mpeg_ts::pid::Pid;

use broadcast_common::timescale::{Rounding, rescale};
use broadcast_common::{Demand, Serialize, Stage, Timestamp, Unpackage};
use mpeg_pes::{PesAssembler, PesPacket};
use mpeg_ts::resync::TsResync;
use mpeg_ts::ts::{SectionReassembler, TS_PACKET_SIZE, TsPacket};

use crate::aac_asc::{
    ADTS_HEADER_SIZE, AdtsHeader, AudioSpecificConfig, SamplingFrequencyIndex, parse_adts_header,
};
use crate::ac3::{
    AC3_SAMPLES_PER_SYNCFRAME, AC3_SYNCWORD, Ac3SyncframeInfo, EAC3_STRMTYP_DEPENDENT,
    Ec3SpecificBox, Ec3SyncframeInfo,
};
use crate::annexb::{annexb_to_length_prefixed, iter_annexb_nals};
use crate::avc_config::{AVCConfigurationBox, AVCDecoderConfigurationRecord};
use crate::dts::{DTS_CORE_SYNC_WORD, DtsCoreFrameInfo};
use crate::error::{Error, Result};
use crate::hdr::{HEVC_PREFIX_SEI_NUT, HdrStaticMetadata};
use crate::hevc_config::{HEVCConfigurationBox, HEVCDecoderConfigurationRecord};
use crate::media::{Media, PcrSample, Track};
use crate::mp4esds::{
    DecoderConfigDescriptor, DecoderSpecificInfo, ESDescriptor, EsdsBox, SLConfigDescriptor,
};
use crate::mpeg_legacy::{Mpeg2SeqHeader, MpegAudioFrameHeader};
use crate::mpegh::{MHADecoderConfigurationRecord, find_mpegh3da_config};
use crate::nal::{
    NalCodec, ParamKind, access_unit_is_rap, is_keyframe_nal, nal_unit_type, parameter_set_is_valid,
};
use crate::nalu_types::{AvcPps, AvcSps, HevcNalArray, HevcNalUnit};
use crate::pipeline::{CodecConfig, DataCarriage, Provenance, Sample, SampleFlags, TrackSpec};

// ── PSI constants (ISO/IEC 13818-1 §2.4.4) ──────────────────────────────────

/// PID carrying the Program Association Table (§2.4.4.4).
const PAT_PID: Pid = Pid::new(0x0000);
/// `table_id` of a PAT section (§2.4.4.4, Table 2-31).
pub(crate) const TABLE_ID_PAT: u8 = 0x00;
/// `table_id` of a PMT section (§2.4.4.9, Table 2-31).
pub(crate) const TABLE_ID_PMT: u8 = 0x02;
/// Long-form section header length before the table body: `table_id`(1) +
/// flags/`section_length`(2) + `table_id_extension`(2) + version/cni(1) +
/// `section_number`(1) + `last_section_number`(1) = 8 (§2.4.4.1).
const SECTION_HEADER_LEN: usize = 8;
/// Mask for the 5-bit `version_number` within a long-form section's byte 5
/// (§2.4.4.1: `reserved`(2) + `version_number`(5) + `current_next_indicator`(1)),
/// after shifting right by 1 to drop the `current_next_indicator` bit.
const VERSION_NUMBER_MASK: u8 = 0x1F;
/// Bit for `current_next_indicator` within a long-form section's byte 5
/// (§2.4.4.1) — `1` means the table is applicable now, `0` means it is a
/// not-yet-applicable "next" table (parsed, never acted on).
const CURRENT_NEXT_INDICATOR_BIT: u8 = 0x01;
/// Trailing `CRC_32` on every long-form PSI section (§2.4.4.1).
const CRC32_LEN: usize = 4;
/// `section_syntax_indicator` bit within a section's byte 1 (§2.4.4.1). `1`
/// marks the long form — a `table_id_extension`/`version_number` header **and**
/// a trailing [`CRC32_LEN`]-byte `CRC_32`. A PAT (§2.4.4.4 Table 2-30) and a
/// PMT (§2.4.4.9 Table 2-33) both fix it at `1`, so a PAT/PMT section that
/// clears it is malformed and carries no CRC to check.
const SECTION_SYNTAX_INDICATOR_BIT: u8 = 0x80;
/// Mask for the 12-bit `section_length` high nibble (byte 1 of a section).
const SECTION_LENGTH_HI_MASK: u8 = 0x0F;
/// Mask for the 13-bit PID low byte's high 5 bits.
const PID_HI_MASK: u8 = 0x1F;
/// Bytes per PAT program-loop entry: `program_number`(2) + reserved/PID(2).
const PAT_ENTRY_LEN: usize = 4;
/// Mask for the 12-bit `program_info_length` / `ES_info_length` high nibble.
const INFO_LENGTH_HI_MASK: u8 = 0x0F;
/// A PAT entry with `program_number == 0` gives the network PID, not a PMT PID.
const NETWORK_PROGRAM_NUMBER: u16 = 0x0000;
/// The null packet PID — always stuffing, never meaningful payload
/// (ISO/IEC 13818-1 §2.4.3.2 Table 2-3) — excluded from the
/// `unattributed`-payload replay buffer.
const NULL_PACKET_PID: Pid = Pid::new(0x1FFF);
/// Hard cap on the total bytes retained across all pre-PMT `unattributed` PID
/// buffers before the oldest payloads are evicted (FIFO). Bounds memory on a
/// full-multiplex feed whose unrelated-service PIDs never appear in the
/// followed PMT (live ingest); comfortably above any real capture's pre-PMT
/// lead-in (a PID's PMT entry resolves within the first PES cycle), so a
/// legitimately-claimed PID's buffered payloads are never evicted in practice.
const MAX_UNATTRIBUTED_BYTES: usize = 4 * 1024 * 1024;
/// Largest possible TS payload (no adaptation field at all, ISO/IEC
/// 13818-1 §2.4.3.2): [`TS_PACKET_SIZE`] minus the 4-byte fixed header.
/// [`Stage::demand`](broadcast_common::Stage::demand)'s saturation check uses
/// this as the "one more worst-case packet" margin against
/// [`MAX_UNATTRIBUTED_BYTES`] (see that impl's doc comment).
const TS_MAX_PAYLOAD_BYTES: usize = TS_PACKET_SIZE - 4;
/// Offset just past `PES_packet_length` within a PES packet — the first 6
/// bytes are `packet_start_code_prefix`(3) + `stream_id`(1) +
/// `PES_packet_length`(2) (ISO/IEC 13818-1 §2.4.3.7, Table 2-21).
const PES_LENGTH_FIELD_END: usize = 6;
/// Hard cap on one PID's in-progress PES buffer (issue #663 P5.2,
/// audit-ingest's "bounded reassembly" recommendation applied to TS). A PES
/// runs from one `payload_unit_start_indicator` to the next
/// ([`mpeg_pes::PesAssembler`]'s doc); the unbounded-video case
/// (`PES_packet_length = 0`) means there is no length field to bound it
/// in-band, so a PUSI that never recurs — a wedged/lossy capture, or a
/// hostile stream — would otherwise grow that PID's buffer for the life of
/// the stream. Comfortably above any real elementary-stream PES payload (a
/// 4K IDR frame is typically well under a megabyte), but far below what a
/// malformed input could accumulate unbounded. On overflow the in-progress
/// PES is dropped (never emitted) and a [`DemuxEvent::Discontinuity`] is
/// raised for the PID — reassembly resyncs at the next PUSI. Note:
/// PSI/private-section buffering (`Carrier::Section`) needs no equivalent
/// cap — [`mpeg_ts::ts::SectionReassembler`] is already inherently bounded by
/// `section_length`'s 12-bit field (`MAX_SECTION_SIZE`, 4098 bytes).
const MAX_PES_BUFFER_BYTES: usize = 4 * 1024 * 1024;
/// Hard cap on one PID's accumulated [`TrackState::Probing`]/
/// [`TrackState::Parked`] backlog (issue B8, media plane step 2 fix wave 3).
/// A PMT-listed codec PID whose parameter sets never arrive (a broken
/// encoder, not malice — e.g. an H.264 ES that never carries SPS/PPS) leaves
/// that PID `Probing` forever, growing `backlog` without bound; worse,
/// [`StreamingTsDemux::try_promote_ready`] `break`s at the first `Probing`
/// PID it finds, so a later-ranked PID that *has* resolved (`Parked`)
/// accumulates its own backlog as collateral for as long as the earlier PID
/// never resolves. Tracked incrementally in
/// [`StreamState::backlog_bytes`] (never re-walked per push, matching
/// [`MAX_UNATTRIBUTED_BYTES`]'s own running-total convention). On overflow —
/// whether `Probing` or `Parked` — [`advance_track`] abandons the PID
/// ([`TrackState::Abandoned`]: permanently resolved without ever promoting to
/// `Live`, backlog dropped to free the memory), the same conclusion
/// [`StreamingTsDemux::finish`] already reaches for a probe that never
/// resolves, just reached early via the byte cap instead of end-of-input; a
/// [`DemuxEvent::Discontinuity`] is raised so the loss is visible, and
/// `try_promote_ready` continues past it, unblocking any later-ranked PID.
const MAX_PROBE_BACKLOG_BYTES: usize = 4 * 1024 * 1024;

// ── stream_type → codec (ISO/IEC 13818-1 Table 2-34 + ETSI TS 101 154) ──────

/// MPEG-2 video (ITU-T H.262 / ISO/IEC 13818-2) — ISO/IEC 13818-1 Table 2-34.
pub(crate) const STREAM_TYPE_MPEG2_VIDEO: u8 = 0x02;
/// MPEG-1 audio (ISO/IEC 11172-3) — ISO/IEC 13818-1 Table 2-34.
const STREAM_TYPE_MPEG1_AUDIO: u8 = 0x03;
/// MPEG-2 audio (ISO/IEC 13818-3, LSF) — ISO/IEC 13818-1 Table 2-34.
const STREAM_TYPE_MPEG2_AUDIO: u8 = 0x04;
/// PES private data (ISO/IEC 13818-1 Table 2-34) — DVB's standard carriage
/// for AC-3/E-AC-3/DTS audio, subtitles, teletext, SMPTE 2038, etc., all
/// disambiguated by the ES_info descriptor loop, not the `stream_type` byte
/// itself (issue #641).
const STREAM_TYPE_PES_PRIVATE: u8 = 0x06;
/// ISO/IEC 13818-7 AAC in ADTS — ISO/IEC 13818-1 Table 2-34.
const STREAM_TYPE_AAC_ADTS: u8 = 0x0F;
/// Metadata in PES packets (ISO/IEC 13818-1 Table 2-34) — the other
/// descriptor-disambiguated `stream_type`, per [`STREAM_TYPE_PES_PRIVATE`].
const STREAM_TYPE_METADATA_PES: u8 = 0x15;
/// AVC (H.264) video — ISO/IEC 13818-1 Table 2-34.
const STREAM_TYPE_AVC: u8 = 0x1B;
/// HEVC (H.265) video — ISO/IEC 13818-1 Table 2-34.
const STREAM_TYPE_HEVC: u8 = 0x24;
/// MPEG-H 3D Audio main stream (MHAS, ISO/IEC 23008-3) — ISO/IEC 13818-1
/// Table 2-34 / ETSI TS 101 154 §6.8 (issue #579). §6.8 additionally allows
/// `0x2E` for an auxiliary (non-main) multi-stream MPEG-H component
/// (§6.8.7) — out of scope here; only the single/main-stream `0x2D` is
/// recognised.
const STREAM_TYPE_MPEGH: u8 = 0x2D;
/// AC-3 (ATSC/DVB user-private) — ETSI TS 101 154 §G.
const STREAM_TYPE_AC3: u8 = 0x81;
/// DTS (user-private) — ETSI TS 101 154 §G.
const STREAM_TYPE_DTS_82: u8 = 0x82;
/// DTS-HD (user-private) — ETSI TS 101 154 §G.
const STREAM_TYPE_DTS_85: u8 = 0x85;
/// E-AC-3 (user-private) — ETSI TS 101 154 §G.
const STREAM_TYPE_EAC3: u8 = 0x87;
/// DTS (user-private) — ETSI TS 101 154 §G.
const STREAM_TYPE_DTS_8A: u8 = 0x8A;
/// AC-3 descriptor tag (ETSI EN 300 468 Annex D, issue #641).
const DESC_TAG_AC3: u8 = 0x6A;
/// Enhanced AC-3 (E-AC-3) descriptor tag (ETSI EN 300 468 Annex D).
const DESC_TAG_ENHANCED_AC3: u8 = 0x7A;
/// DTS descriptor tag (ETSI EN 300 468 Annex G, Table G.1).
const DESC_TAG_DTS: u8 = 0x7B;
// ── Section-carried stream_types (ISO/IEC 13818-1 Table 2-34) — issue #576 ──
//
// These stream_types carry PSI/private *sections* directly on their PID, not
// PES packets: PES-reassembling them silently yields nothing (no PES start
// code is ever present), so `data_carriage` routes them to a
// [`mpeg_ts::ts::SectionReassembler`] instead.

/// ISO/IEC 13818-1 `private_sections` carried directly (not in PES packets).
const STREAM_TYPE_PRIVATE_SECTIONS: u8 = 0x05;
/// ISO/IEC 13818-6 DSM-CC Type A (Multiprotocol Encapsulation), sectioned.
const STREAM_TYPE_DSMCC_TYPE_A: u8 = 0x0A;
/// ISO/IEC 13818-6 DSM-CC Type B (Type B), sectioned.
const STREAM_TYPE_DSMCC_TYPE_B: u8 = 0x0B;
/// ISO/IEC 13818-6 DSM-CC Type C (data or object carousel), sectioned.
const STREAM_TYPE_DSMCC_TYPE_C: u8 = 0x0C;
/// ISO/IEC 13818-6 DSM-CC Type D, sectioned.
const STREAM_TYPE_DSMCC_TYPE_D: u8 = 0x0D;
/// ISO/IEC 13818-6 DSM-CC synchronized download protocol, sectioned.
const STREAM_TYPE_DSMCC_SYNC_DOWNLOAD: u8 = 0x14;
/// SCTE-35 / ANSI-scoped applications (splice information table), sectioned.
const STREAM_TYPE_SCTE35: u8 = 0x86;

// ── Codec-config recovery constants ─────────────────────────────────────────

/// NAL length-field width for `mdat` samples: 4-byte prefixes → `lengthSizeMinusOne = 3`.
const NAL_LENGTH_SIZE_MINUS_ONE: u8 = 3;
/// H.264 `nal_unit_type` for SPS (ISO/IEC 14496-10 Table 7-1).
const H264_NAL_SPS: u8 = 7;
/// H.264 `nal_unit_type` for PPS (Table 7-1).
const H264_NAL_PPS: u8 = 8;
/// Mask for the H.264 5-bit `nal_unit_type` in the NAL header byte.
const H264_NAL_TYPE_MASK: u8 = 0x1F;

/// H.265 `nal_unit_type` for VPS (`VPS_NUT`) — ITU-T H.265 Table 7-1 (type 32).
const H265_NAL_VPS: u8 = 32;
/// H.265 `nal_unit_type` for SPS (`SPS_NUT`) — ITU-T H.265 Table 7-1 (type 33).
const H265_NAL_SPS: u8 = 33;
/// H.265 `nal_unit_type` for PPS (`PPS_NUT`) — ITU-T H.265 Table 7-1 (type 34).
const H265_NAL_PPS: u8 = 34;
/// `configurationVersion` for an `hvcC` record (ISO/IEC 14496-15:2017 §8.3.3.1.1).
const HVCC_CONFIGURATION_VERSION: u8 = 1;
/// `constantFrameRate = 0` (not-constant / unspecified) — §8.3.3.1.2.
const HVCC_CONSTANT_FRAME_RATE_UNSPEC: u8 = 0;
/// `numTemporalLayers = 1` when unknown from the ES (single temporal layer).
const HVCC_NUM_TEMPORAL_LAYERS: u8 = 1;
/// `parallelismType = 0` (mixed/unknown) — §8.3.3.1.2.
const HVCC_PARALLELISM_TYPE_UNKNOWN: u8 = 0;
/// `avgFrameRate = 0` (unspecified) — §8.3.3.1.2.
const HVCC_AVG_FRAME_RATE_UNSPEC: u16 = 0;
/// `min_spatial_segmentation_idc = 0` (no constraint) — §8.3.3.1.2.
const HVCC_MIN_SPATIAL_SEGMENTATION_UNSPEC: u16 = 0;

/// `esds` `objectTypeIndication` for MPEG-4 Audio (ISO/IEC 14496-1 Table 5).
const OTI_MPEG4_AUDIO: u8 = 0x40;
/// `esds` `objectTypeIndication` for MPEG-2 Main Visual (ISO/IEC 14496-1 Table 5).
/// `pub(crate)`: also used by `ps_demux` (C6, #1009) to build the same `esds`.
pub(crate) const OTI_MPEG2_VIDEO_MAIN: u8 = 0x61;
/// `esds` `objectTypeIndication` for MPEG-2 Audio, ISO/IEC 13818-3 (Table 5).
const OTI_MPEG2_AUDIO: u8 = 0x69;
/// `esds` `objectTypeIndication` for MPEG-1 Audio, ISO/IEC 11172-3 (Table 5).
const OTI_MPEG1_AUDIO: u8 = 0x6B;
/// `esds` `streamType` for an AudioStream (ISO/IEC 14496-1 Table 6).
const STREAM_TYPE_AUDIO: u8 = 0x05;
/// `esds` `streamType` for a VisualStream (ISO/IEC 14496-1 Table 6).
/// `pub(crate)`: also used by `ps_demux` (C6, #1009).
pub(crate) const STREAM_TYPE_VISUAL: u8 = 0x04;
/// `esds` `ES_ID` assigned to the single audio elementary stream.
const ESDS_ES_ID: u16 = 1;
/// `esds` `ES_ID` assigned to the single video elementary stream.
/// `pub(crate)`: also used by `ps_demux` (C6, #1009).
pub(crate) const ESDS_VIDEO_ES_ID: u16 = 2;
/// `SLConfigDescriptor` predefined body for MP4 file SL packaging
/// (ISO/IEC 14496-1 §7.3.2.3 — `predefined = 0x02`).
/// `pub(crate)`: also used by `ps_demux` (C6, #1009).
/// Audio sample size in bits carried in the sample entry (PCM-equivalent; 16).
const AUDIO_SAMPLE_SIZE_BITS: u16 = 16;

/// `MHADecoderConfigurationRecord.reference_channel_layout` placeholder for
/// TS carriage: the real CICP `ChannelConfiguration` is a field *inside* the
/// opaque `mpegh3daConfig()` bitstream (ISO/IEC 23008-3 §5, paid) that this
/// crate does not decode (config passthrough only — issue #579 scope), and
/// MPEG-2 TS carries no equivalent systems-layer field for it (unlike the
/// ISOBMFF `mhaC` box, whose `referenceChannelLayout` byte is authored
/// out-of-band by the muxer). `0` marks "not derived", mirroring this file's
/// existing `HVCC_*_UNSPEC` placeholders for fields it likewise cannot
/// recover from the elementary stream alone.
const MPEGH_REFERENCE_CHANNEL_LAYOUT_UNSPECIFIED: u8 = 0;
/// `CodecConfig::MpegH.channel_count` placeholder — same rationale as
/// [`MPEGH_REFERENCE_CHANNEL_LAYOUT_UNSPECIFIED`]: MPEG-2 TS carriage (PMT
/// `stream_type`/`MPEG-H_3dAudio_descriptor`) signals no channel count.
const MPEGH_CHANNEL_COUNT_UNSPECIFIED: u16 = 0;
/// `CodecConfig::MpegH.sample_rate` placeholder — same rationale. Samples
/// are still timed correctly: [`LiveKind::MpegH`] anchors durations on the
/// 90 kHz TS clock ([`VIDEO_TIMESCALE`]) rather than an audio sample count,
/// so an unknown `sample_rate` here never affects timing.
const MPEGH_SAMPLE_RATE_UNSPECIFIED: u32 = 0;
/// Largest `mpegh3daConfig()` the `mhaC` record can carry: its
/// `mpegh3daConfigLength` field is `unsigned int(16)` (ISO/IEC 23008-3 §20, `MHADecoderConfigurationRecord`).
/// A damaged MHAS packet may claim a longer payload; it is not a config
/// (issue #1171).
const MPEGH_CONFIG_LEN_MAX: usize = u16::MAX as usize;
/// Video media timescale (90 kHz — the TS/PES timestamp clock).
const VIDEO_TIMESCALE: u32 = 90_000;
/// Samples per AAC access unit (ISO/IEC 14496-3 — one frame = 1024 samples).
const AAC_SAMPLES_PER_FRAME: u32 = 1024;

/// MPEG-2 video `picture_start_code` (0x00000100) — ISO/IEC 13818-2 §6.2.3.
/// `pub(crate)`: also used by `ps_demux` (C6, #1009) to split/flag MPEG-2
/// pictures the same way this module does.
pub(crate) const MPEG2_PICTURE_START_CODE: u8 = 0x00;
/// `picture_coding_type` value for an intra-coded (I) picture — §6.3.9 Table 6-12.
pub(crate) const MPEG2_PICTURE_CODING_TYPE_I: u8 = 0x01;

/// 33-bit PTS/DTS modulus, for wrap-around unrolling (§2.4.3.7, 90 kHz clock).
/// Alias for [`broadcast_common::clock33::WRAP_33BIT`] — the actual
/// wrap-correction math (below, [`WrapState`]) is delegated there so a fix
/// reaches every 33-bit clock consumer in the workspace, not just this one.
const TS_WRAP: u64 = broadcast_common::clock33::WRAP_33BIT;

/// Mask of the 33-bit PTS/DTS field — [`TS_WRAP`] minus one, for reducing a
/// modular difference back onto the wire clock (§2.4.3.7).
const TS_WRAP_MASK: u64 = TS_WRAP - 1;

/// Largest observed inter-access-unit step (90 kHz ticks) still believed to be
/// a frame period when interpolating an unstamped PES (§2.4.2.6, r04-W48) and
/// when lifting a decode timeline at a signalled discontinuity.
///
/// One second on the 90 kHz clock. The earlier value was ten seconds, which is
/// far too loose: an 8-second forward splice is not this stream's cadence, yet
/// it sat inside the window and became *the* frame period for every unstamped
/// access unit that followed (r04-W48/W50 review). No real frame rate is below
/// 1 fps, so a second is a generous ceiling that still excludes every gap,
/// splice and clock jump this is meant to reject.
const MAX_FRAME_PERIOD_TICKS: u64 = VIDEO_TIMESCALE as u64;

/// How many recent inter-access-unit steps
/// [`StreamState::recent_steps`] keeps for the median estimate. Five is the
/// smallest window in which a single outlier (one late access unit) cannot
/// dominate the middle value.
const FRAME_PERIOD_WINDOW: usize = 5;

/// Codec class recovered from a PMT `stream_type` (used to pick the sample /
/// config-recovery path). Data-carrying dispatch discriminant, not a spec label
/// enum — hence no `name()`/`Display` (see `workspace-guards/tests/guards/label.rs` policy).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Codec {
    H264,
    Hevc,
    Mpeg2Video,
    /// MPEG-1/2 audio; the bool is `true` for MPEG-2 audio (stream_type 0x04,
    /// OTI 0x69), `false` for MPEG-1 audio (stream_type 0x03, OTI 0x6B).
    MpegAudio(bool),
    Aac,
    Ac3,
    Eac3,
    Dts,
    /// MPEG-H 3D Audio main stream, MHAS-formatted (issue #579) — see
    /// [`crate::mpegh`].
    MpegH,
    /// Opaque data stream (issue #557/#576): any `stream_type` this demuxer
    /// does not decode to a typed codec — carried losslessly instead of
    /// dropped. The field is the PMT `stream_type` itself, carried through
    /// into [`CodecConfig::Data`]; [`data_carriage`] classifies it as PES- or
    /// section-carried.
    Data(u8),
}

impl Codec {
    /// Map a PMT `stream_type` to a [`Codec`] — a decoded codec when this
    /// demuxer understands it, else an opaque [`Codec::Data`] carrying the
    /// `stream_type` verbatim (issue #576: every PMT-listed elementary stream
    /// gets a track, never silently dropped). ISO/IEC 13818-1 Table 2-34.
    fn from_stream_type(stream_type: u8) -> Self {
        match stream_type {
            STREAM_TYPE_MPEG2_VIDEO => Codec::Mpeg2Video,
            STREAM_TYPE_MPEG1_AUDIO => Codec::MpegAudio(false),
            STREAM_TYPE_MPEG2_AUDIO => Codec::MpegAudio(true),
            STREAM_TYPE_AVC => Codec::H264,
            STREAM_TYPE_HEVC => Codec::Hevc,
            STREAM_TYPE_AAC_ADTS => Codec::Aac,
            STREAM_TYPE_AC3 => Codec::Ac3,
            STREAM_TYPE_EAC3 => Codec::Eac3,
            STREAM_TYPE_DTS_82 | STREAM_TYPE_DTS_85 | STREAM_TYPE_DTS_8A => Codec::Dts,
            STREAM_TYPE_MPEGH => Codec::MpegH,
            _ => Codec::Data(stream_type),
        }
    }

    /// Refine a [`Codec::Data`] classification for `stream_type` `0x06`/`0x15`
    /// (DVB's descriptor-disambiguated PES private data / metadata carriage)
    /// by consulting the ES_info descriptor loop, per ETSI EN 300 468: an
    /// AC-3 (`0x6A`), enhanced AC-3 (`0x7A`), or DTS (`0x7B`) descriptor
    /// reclassifies the stream to the matching audio codec instead of opaque
    /// data (issue #641). Any other `stream_type`, or a `0x06`/`0x15` stream
    /// with none of those descriptors (e.g. DVB subtitles/teletext), is
    /// returned unchanged.
    fn refine_with_descriptors(self, stream_type: u8, descriptors: &[u8]) -> Self {
        if !matches!(
            stream_type,
            STREAM_TYPE_PES_PRIVATE | STREAM_TYPE_METADATA_PES
        ) {
            return self;
        }
        if stream_type == STREAM_TYPE_PES_PRIVATE
            && crate::dovi::has_registration_descriptor(descriptors)
            && let Some(d) = crate::dovi::find_video_stream_descriptor(descriptors)
            && d.record.bl_present
            && d.record.is_hevc_profile()
        {
            return Codec::Hevc;
        }
        let mut off = 0usize;
        while off + 2 <= descriptors.len() {
            let tag = descriptors[off];
            let len = descriptors[off + 1] as usize;
            match tag {
                DESC_TAG_AC3 => return Codec::Ac3,
                DESC_TAG_ENHANCED_AC3 => return Codec::Eac3,
                DESC_TAG_DTS => return Codec::Dts,
                _ => {}
            }
            off += 2 + len;
        }
        self
    }
}

/// Classify a [`Codec::Data`] `stream_type` as PES- or section-carried
/// (ISO/IEC 13818-1 §2.4.4.9 / Table 2-34) — see [`DataCarriage`]. A fixed set
/// of `stream_type`s carry PSI/private sections directly; every other
/// `stream_type` (the historical 0x06/0x15 carriage, plus any unrecognised
/// value) is PES-packetised.
fn data_carriage(stream_type: u8) -> DataCarriage {
    match stream_type {
        STREAM_TYPE_PRIVATE_SECTIONS
        | STREAM_TYPE_DSMCC_TYPE_A
        | STREAM_TYPE_DSMCC_TYPE_B
        | STREAM_TYPE_DSMCC_TYPE_C
        | STREAM_TYPE_DSMCC_TYPE_D
        | STREAM_TYPE_DSMCC_SYNC_DOWNLOAD
        | STREAM_TYPE_SCTE35 => DataCarriage::Sections,
        _ => DataCarriage::Pes,
    }
}

/// Extend a running unwrapped timestamp by the delta to the next raw 33-bit
/// value, correcting for a single 90 kHz wrap in either direction (§2.4.3.7).
///
/// Thin alias for [`broadcast_common::clock33::unwrap_delta`] — see that
/// function's doc comment for why the wrap correction must be bidirectional
/// (a forward-only epoch counter gets a backward-reorder-across-origin case
/// wrong). Kept as a local `fn` (rather than calling the shared function
/// directly at each call site) only so [`WrapState::push`] below reads the
/// same as it always has.
fn unwrap_ts(prev_unwrapped: i128, prev_raw: u64, raw: u64) -> i128 {
    broadcast_common::clock33::unwrap_delta(prev_unwrapped, prev_raw, raw)
}

/// Rescale an unwrapped 90 kHz PES-clock timestamp (ISO/IEC 13818-1 §2.4.3.7)
/// into a track's own media timescale, floored (i128 math so a full 33-bit
/// anchor cannot overflow).
///
/// A **negative** unwrapped anchor is preserved, not clamped to zero. It is a
/// legitimate value: reordering (or a capture that starts mid-GOP) across the
/// 2^33 wrap boundary unwraps to a small negative absolute time, and every
/// other track kind already carries that through to `Sample::dts` verbatim —
/// clamping it only for audio (as this used to, via `.max(0) as u128`)
/// fabricated `dts = 0` for the audio track alone and desynced it from the
/// video it was muxed against.
///
/// The PES clock is always 90 kHz, but an audio track's IR timescale is its
/// **sample rate** (`TrackSpec::timescale`), and since media plane step 2c
/// `Sample::dts`/`Sample::pts` are defined to be in that track timescale — the
/// same unit as `Sample::duration`. Storing the raw 90 kHz value for an audio
/// track would make `dts` deltas (e.g. 2089) disagree with `duration` (1024
/// AAC samples), which is exactly the quantity every downstream consumer
/// (RTP packetisation, segmentation, `tfdt`) reads. For a 90 kHz track (video,
/// opaque `Data`) this is the identity.
fn rescale_to_track(anchor_90k: i128, timescale: u32) -> i64 {
    to_ticks(rescale(
        anchor_90k,
        VIDEO_TIMESCALE,
        timescale,
        Rounding::Floor,
    ))
}

/// Whether an MPEG-2 video access unit is a random-access point: it carries a
/// `sequence_header()` (0x000001B3) or its `picture_header()` codes an I-frame
/// (`picture_coding_type == 1`) — ISO/IEC 13818-2 §6.2.2.1 / §6.3.9.
pub(crate) fn mpeg2_is_sync(au: &[u8]) -> bool {
    let mut i = 0usize;
    while i + 4 <= au.len() {
        if au[i] == 0x00 && au[i + 1] == 0x00 && au[i + 2] == 0x01 {
            let code = au[i + 3];
            if code == crate::mpeg_legacy::SEQUENCE_HEADER_CODE[3] {
                return true;
            }
            if code == MPEG2_PICTURE_START_CODE && i + 6 <= au.len() {
                // picture_coding_type = bits [5:3] of the byte after temporal_ref
                // high byte: header = temporal_reference(10) + coding_type(3).
                let pct = (au[i + 5] >> 3) & 0x07;
                return pct == MPEG2_PICTURE_CODING_TYPE_I;
            }
        }
        i += 1;
    }
    false
}

/// Counts one byte-offset probe of a codec-config sync scanner
/// ([`find_mpeg_audio_sync`] / [`find_adts_sync`]).
///
/// Test-only instrumentation for the r04-W47 complexity bound: the codec probes
/// must scan the *newest* access unit only, so the total probes a demux spends
/// on a never-resolving PID must stay proportional to the input length, not to
/// its square. The counter is read by
/// `probe_sync_scan_work_is_linear_in_the_input_not_quadratic`, which asserts
/// the bound, and is incremented at the actual scan site (inside the sync loop)
/// rather than re-derived by the test, so the number it measures is the work
/// the demux really did. Per-thread because the crate's own test suite runs in
/// parallel: a process-wide counter would be summed across unrelated tests, so
/// the bound would measure other tests' demux work instead of this one's.
///
/// Compiled only for the test build — the crate is `no_std`, where
/// `thread_local!` is not available, and nothing outside a test reads it.
#[cfg(test)]
mod probe_counter {
    thread_local! {
        static SYNC_PROBES: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
    }

    pub(super) fn record() {
        SYNC_PROBES.with(|c| c.set(c.get().wrapping_add(1)));
    }

    pub(super) fn read() -> u64 {
        SYNC_PROBES.with(|c| c.get())
    }
}

/// Record one scan-site byte probe (see [`probe_counter`]).
#[cfg(test)]
fn record_sync_probe() {
    probe_counter::record();
}

/// Record one pass of a codec-config probe over an access unit.
///
/// The H.264/HEVC probes have no byte-by-byte *sync* scan — they walk the
/// access unit's NAL units with [`iter_annexb_nals`], which itself scans for
/// start codes — so `record_sync_probe` does not see them. This counter does,
/// making the "scan only the newest access unit" bound measurable for every
/// probe kind (r04-W47 review).
#[cfg(test)]
fn record_probe_pass() {
    probe_counter::record();
}

/// Non-test build: nothing to record.
#[cfg(not(test))]
#[inline(always)]
fn record_probe_pass() {}

/// Non-test build: nothing to record.
#[cfg(not(test))]
#[inline(always)]
fn record_sync_probe() {}

/// Read this thread's probe total (see [`record_sync_probe`]).
#[cfg(test)]
fn sync_probes() -> u64 {
    probe_counter::read()
}

/// Scan forward from the start of `data` for the first byte offset carrying a
/// valid MPEG audio frame header, returning that offset and the parsed
/// header. A broadcast MP2-in-PES payload is not guaranteed to start on a
/// frame boundary (issue #638: a real DVB-S multiplexer routinely splits PES
/// payloads without regard to the ~1253/1254-byte frame length) -- this
/// resyncs instead of requiring the syncword at offset 0. Bytes before the
/// returned offset are garbage that no frame header could be found in; the
/// tail of a frame that began in the previous PES payload is completed by the
/// per-PID carry buffer ([`AudioAnchor::carry`], issue #1160) before this scan
/// ever sees it.
fn find_mpeg_audio_sync(data: &[u8]) -> Option<(usize, MpegAudioFrameHeader)> {
    let mut off = 0usize;
    while off + 4 <= data.len() {
        record_sync_probe();
        if let Ok(hdr) = MpegAudioFrameHeader::parse(&data[off..]) {
            return Some((off, hdr));
        }
        off += 1;
    }
    None
}

/// Upper bound, in bytes, on one per-PID audio carry buffer (issue #1160).
///
/// A carry only ever holds the *unfinished tail of one frame* — strictly fewer
/// bytes than that frame's own length, or a header prefix — so it is bounded by
/// the largest frame any of the framings can declare: DTS core's 14-bit
/// `FSIZE` (`FSIZE + 1` <= 16384, ETSI TS 102 114 Table 5-1), which exceeds the
/// 13-bit ADTS `aac_frame_length` (max 8191, ISO/IEC 13818-7 §6.2), E-AC-3's
/// 11-bit `frmsiz` of 16-bit words (4096) and AC-3's 3840 (Table 4.13), and the
/// MPEG audio maximum (1729, Layer II at 384 kbit/s / 32 kHz, ISO/IEC 11172-3
/// §2.4.2.3). A tail that somehow exceeds it is discarded rather than held, so
/// hostile input can never grow this buffer.
const AUDIO_CARRY_MAX_BYTES: usize = 16_384;

/// Outcome of looking for one frame header at the start of a buffer.
enum SyncParse<H> {
    /// A valid header, and the whole frame's length in bytes (header included).
    Frame(H, usize),
    /// Too few bytes to decide (the buffer may be the front of a header).
    NeedMore,
    /// Not a frame start.
    NotSync,
}

/// One audio framing's header-walk rules, so [`split_frames_with_tail`] is a
/// single implementation for every codec whose frames can straddle a PES
/// boundary (MPEG audio, ADTS, AC-3, E-AC-3, DTS core).
trait FrameSync {
    /// Parsed header.
    type Hdr: Copy;
    /// Smallest legitimate frame length: a header claiming less is degenerate.
    const MIN_FRAME_LEN: usize;
    /// Look for a header at the start of `data`.
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr>;
    /// Could `prefix` be the front of a header whose remainder has not arrived?
    fn is_partial_sync(prefix: &[u8]) -> bool;
    /// Does a frame with this header belong to the access unit of the frame
    /// before it (E-AC-3 dependent substreams)?
    fn folds_into_previous(_hdr: &Self::Hdr) -> bool {
        false
    }
    /// Does an unfinished `tail` (a frame start that runs past the buffer) begin
    /// a new access unit, as opposed to a dependent substream of the previous
    /// one? Only E-AC-3 distinguishes them (issue #1186).
    fn tail_starts_new_unit(_tail: &[u8]) -> bool {
        true
    }
    /// The sample bytes of a whole frame, given the `header_len` bytes the
    /// caller's shape says to strip. `None` when nothing follows the header.
    fn payload<'a>(
        _hdr: &Self::Hdr,
        frame: &'a [u8],
        header_len: usize,
    ) -> Option<alloc::borrow::Cow<'a, [u8]>> {
        (frame.len() > header_len).then(|| frame[header_len..].into())
    }
}

/// Is `prefix` a leading part of (or equal to) `sync`?
fn is_sync_prefix(prefix: &[u8], sync: &[u8]) -> bool {
    prefix.iter().zip(sync).all(|(a, b)| a == b)
}

/// MPEG-1/2 audio framing (ISO/IEC 11172-3 §2.4.1.3).
struct MpegAudioSync;

impl FrameSync for MpegAudioSync {
    type Hdr = MpegAudioFrameHeader;
    const MIN_FRAME_LEN: usize = 4;
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr> {
        if data.len() < Self::MIN_FRAME_LEN {
            return SyncParse::NeedMore;
        }
        match MpegAudioFrameHeader::parse(data) {
            Ok(hdr) => SyncParse::Frame(hdr, hdr.frame_length),
            Err(_) => SyncParse::NotSync,
        }
    }
    fn is_partial_sync(prefix: &[u8]) -> bool {
        // 11-bit all-ones syncword: byte 0 is 0xFF, byte 1's top three bits set.
        const SYNC_HI_BYTE: u8 = 0xFF;
        const SYNC_LO_MASK: u8 = 0xE0;
        prefix.first() == Some(&SYNC_HI_BYTE)
            && prefix
                .get(1)
                .is_none_or(|b| b & SYNC_LO_MASK == SYNC_LO_MASK)
    }
}

/// ADTS framing (ISO/IEC 13818-7 §6.2).
struct AdtsSync;

impl FrameSync for AdtsSync {
    type Hdr = AdtsHeader;
    const MIN_FRAME_LEN: usize = ADTS_HEADER_SIZE;
    fn payload<'a>(
        hdr: &Self::Hdr,
        frame: &'a [u8],
        _header_len: usize,
    ) -> Option<alloc::borrow::Cow<'a, [u8]>> {
        adts_frame_payload(hdr, frame)
    }
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr> {
        if data.len() < ADTS_HEADER_SIZE {
            return SyncParse::NeedMore;
        }
        match parse_adts_header(data) {
            Ok(hdr) => SyncParse::Frame(hdr, hdr.frame_length as usize),
            Err(_) => SyncParse::NotSync,
        }
    }
    fn is_partial_sync(prefix: &[u8]) -> bool {
        // 12-bit all-ones syncword.
        const SYNC_HI_BYTE: u8 = 0xFF;
        const SYNC_LO_MASK: u8 = 0xF0;
        prefix.first() == Some(&SYNC_HI_BYTE)
            && prefix
                .get(1)
                .is_none_or(|b| b & SYNC_LO_MASK == SYNC_LO_MASK)
    }
}

/// Map a header-parse result to a [`SyncParse`]: running out of bytes is
/// "need more", any other error is "not a frame".
fn sync_from_parse<H>(r: Result<H>, frame_len: impl FnOnce(&H) -> Option<usize>) -> SyncParse<H> {
    match r {
        Ok(h) => match frame_len(&h) {
            Some(len) if len != 0 => SyncParse::Frame(h, len),
            _ => SyncParse::NotSync,
        },
        Err(Error::BufferTooShort(..)) => SyncParse::NeedMore,
        Err(_) => SyncParse::NotSync,
    }
}

/// `syncword` of AC-3 / E-AC-3 as bytes (ETSI TS 102 366 §4.3.1).
const AC3_SYNC_BYTES: [u8; 2] = AC3_SYNCWORD.to_be_bytes();

/// AC-3 framing (ETSI TS 102 366 §4.3 syncinfo, Table 4.13 frame sizes).
struct Ac3Sync;

impl FrameSync for Ac3Sync {
    type Hdr = Ac3SyncframeInfo;
    const MIN_FRAME_LEN: usize = 8;
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr> {
        if data.len() < AC3_SYNC_BYTES.len() {
            return SyncParse::NeedMore;
        }
        if data[..AC3_SYNC_BYTES.len()] != AC3_SYNC_BYTES {
            return SyncParse::NotSync;
        }
        sync_from_parse(Ac3SyncframeInfo::parse_at(data, 0), |i| i.frame_len_bytes())
    }
    fn is_partial_sync(prefix: &[u8]) -> bool {
        is_sync_prefix(prefix, &AC3_SYNC_BYTES)
    }
}

/// E-AC-3 framing (ETSI TS 102 366 Annex E §E.1.2.2); a dependent substream
/// (`strmtyp == 1`) folds into the access unit of the frame before it.
struct Eac3Sync;

impl FrameSync for Eac3Sync {
    type Hdr = Ec3SyncframeInfo;
    const MIN_FRAME_LEN: usize = 8;
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr> {
        if data.len() < AC3_SYNC_BYTES.len() {
            return SyncParse::NeedMore;
        }
        if data[..AC3_SYNC_BYTES.len()] != AC3_SYNC_BYTES {
            return SyncParse::NotSync;
        }
        // `frmsiz` = "number of 16-bit words in the syncframe, minus 1".
        sync_from_parse(Ec3SyncframeInfo::parse_at(data, 0), |i| {
            Some((i.frmsiz as usize + 1) * 2)
        })
    }
    fn is_partial_sync(prefix: &[u8]) -> bool {
        is_sync_prefix(prefix, &AC3_SYNC_BYTES)
    }
    fn folds_into_previous(hdr: &Self::Hdr) -> bool {
        hdr.strmtyp == EAC3_STRMTYP_DEPENDENT
    }
    /// `strmtyp` is the top two bits of the byte after the syncword (ETSI TS
    /// 102 366 §E.1.2.2). Until that byte has arrived the type is unknown and
    /// the tail is not counted as commencing an access unit: a dependent
    /// substream must not move the timeline anchor (issue #1186).
    ///
    /// An AC-3 syncframe standing as independent substream 0 (`bsid` <= 8,
    /// byte 5) has `crc1` where an E-AC-3 header has `strmtyp`, so once `bsid`
    /// is visible it is what decides; before that a byte that *looks* dependent
    /// is not counted (the conservative reading, as for any unjudged tail).
    fn tail_starts_new_unit(tail: &[u8]) -> bool {
        const BSID_BYTE: usize = 5;
        const AC3_MAX_BSID: u8 = 8;
        if tail.len() > BSID_BYTE && tail[BSID_BYTE] >> 3 <= AC3_MAX_BSID {
            return true;
        }
        tail.len() > AC3_SYNC_BYTES.len()
            && (tail[AC3_SYNC_BYTES.len()] >> 6) != EAC3_STRMTYP_DEPENDENT
    }
}

/// `SYNC` of a DTS core frame as bytes (ETSI TS 102 114 Table 5-1).
const DTS_SYNC_BYTES: [u8; 4] = DTS_CORE_SYNC_WORD.to_be_bytes();

/// DTS core-substream framing (ETSI TS 102 114 §5.3, Table 5-1).
struct DtsSync;

impl FrameSync for DtsSync {
    type Hdr = DtsCoreFrameInfo;
    const MIN_FRAME_LEN: usize = 8;
    fn parse(data: &[u8]) -> SyncParse<Self::Hdr> {
        let n = data.len().min(DTS_SYNC_BYTES.len());
        if !is_sync_prefix(&data[..n], &DTS_SYNC_BYTES) {
            return SyncParse::NotSync;
        }
        if n < DTS_SYNC_BYTES.len() {
            return SyncParse::NeedMore;
        }
        sync_from_parse(DtsCoreFrameInfo::parse_at(data, 0), |i| Some(i.frame_size))
    }
    fn is_partial_sync(prefix: &[u8]) -> bool {
        is_sync_prefix(prefix, &DTS_SYNC_BYTES)
    }
}

/// The result of cutting one buffer into frames, see [`split_frames_with_tail`].
struct FrameSplit<'a, H> {
    /// Whole frames: `(start offset in the buffer, frame bytes, header)`. An
    /// E-AC-3 dependent substream is folded into the frame before it.
    frames: Vec<(usize, &'a [u8], H)>,
    /// Offset where the unconsumed tail begins; `== buf.len()` when none. The
    /// tail is a *possible* frame start (a valid header whose frame runs past
    /// the buffer, or a header prefix that cannot be judged yet).
    tail_start: usize,
}

/// Cut `buf` into whole frames using the header length field, resyncing past
/// garbage, and report where the unconsumed tail starts so a caller can carry
/// it into the next PES payload (issue #1160).
///
/// Behaviour on the whole-frame part is the historical (#638) one: a bad sync
/// resyncs to the next valid header, a `frame_length` below the minimum stops
/// the split, and the scan stays linear in `buf`.
fn split_frames_with_tail<F: FrameSync>(buf: &[u8]) -> FrameSplit<'_, F::Hdr> {
    let mut frames: Vec<(usize, &[u8], F::Hdr)> = Vec::new();
    let mut at = 0usize;
    let mut tail_start = buf.len();
    while at < buf.len() {
        record_sync_probe();
        match F::parse(&buf[at..]) {
            SyncParse::Frame(hdr, flen) => {
                if flen < F::MIN_FRAME_LEN {
                    // Degenerate header: historical behaviour, stop splitting.
                    break;
                }
                if at + flen > buf.len() {
                    // A real frame header whose frame runs past the buffer.
                    tail_start = at;
                    break;
                }
                match frames.last_mut() {
                    Some(prev) if F::folds_into_previous(&hdr) && prev.0 + prev.1.len() == at => {
                        prev.1 = &buf[prev.0..at + flen];
                    }
                    // An E-AC-3 dependent substream with no contiguous
                    // independent frame before it (the buffer starts on it
                    // after a continuity gap / dropped PES / re-anchor, or
                    // garbage separates them) is an orphan: ETSI TS 102 366
                    // §E.1.3.1.2 has dependent substreams "immediately follow
                    // the independent substream with which they are
                    // associated", so alone it cannot be decoded and must not
                    // become a sample of its own. Drop it.
                    _ if F::folds_into_previous(&hdr) => {}
                    _ => frames.push((at, &buf[at..at + flen], hdr)),
                }
                at += flen;
            }
            SyncParse::NeedMore if F::is_partial_sync(&buf[at..]) => {
                tail_start = at;
                break;
            }
            SyncParse::NeedMore | SyncParse::NotSync => at += 1,
        }
    }
    FrameSplit { frames, tail_start }
}

/// Scan forward from the start of `data` for the first byte offset carrying a
/// valid ADTS frame header, returning that offset and the parsed header --
/// see [`find_mpeg_audio_sync`] for why a broadcast PES payload isn't
/// guaranteed to start on a frame boundary (issue #638). Bytes before the
/// returned offset are skipped; a straddling tail is completed by the
/// per-PID carry buffer ([`AudioAnchor::carry`], issue #1160) beforehand.
fn find_adts_sync(data: &[u8]) -> Option<(usize, AdtsHeader)> {
    let mut off = 0usize;
    while off + ADTS_HEADER_SIZE <= data.len() {
        record_sync_probe();
        if let Ok(hdr) = parse_adts_header(&data[off..]) {
            return Some((off, hdr));
        }
        off += 1;
    }
    None
}

/// Split a concatenated ADTS payload into individual frames (whole frame
/// bytes — fixed+variable header, the CRC when present, and the raw data
/// block(s) — plus that frame's parsed [`AdtsHeader`]). Resyncs to the next
/// frame boundary on a bad sync (see [`find_adts_sync`]); stops once no
/// further sync is found or a frame would run past the end of `payload` (the
/// tail is carried into the next PES by [`emit_audio_au`], #1160).
/// `frame_length` (ISO/IEC 13818-7 §6.2) already spans the whole frame
/// including any CRC, so this boundary-finding needs no change for C11
/// (#1012) — only the caller's fixed 7-byte strip did.
#[cfg(test)]
fn split_adts_frames(payload: &[u8]) -> Vec<(&[u8], AdtsHeader)> {
    split_frames_with_tail::<AdtsSync>(payload)
        .frames
        .into_iter()
        .map(|(_, f, h)| (f, h))
        .collect()
}

/// `adts_error_check()`'s `crc_check` (ISO/IEC 13818-7 §6.2): a 16-bit CRC
/// immediately after the fixed+variable header when `protection_absent ==
/// 0`.
const ADTS_CRC_SIZE: usize = 2;

/// `raw_data_block_position[i]` (ISO/IEC 13818-7 §6.2, Table 6): 16 bits.
const ADTS_BLOCK_POSITION_SIZE: usize = 2;

/// Bytes to strip from the front of a whole ADTS frame to reach its first raw
/// data block: the header, plus (when `protection_absent == 0`) the
/// `raw_data_block_position[1..=n]` table (`n` =
/// `number_of_raw_data_blocks_in_frame`, only when `n > 0`) and the 16-bit
/// `crc_check` (`adts_error_check()` for `n == 0`, `adts_header_error_check()`
/// otherwise — ISO/IEC 13818-7 §6.2, Tables 5/6/10; C11, #1012). See
/// `private/specs-verified/mpeg/transmux/codec/adts-error-check.md`.
fn adts_header_len(hdr: &AdtsHeader) -> usize {
    if hdr.protection_absent {
        ADTS_HEADER_SIZE
    } else {
        ADTS_HEADER_SIZE
            + ADTS_BLOCK_POSITION_SIZE * hdr.num_raw_data_blocks as usize
            + ADTS_CRC_SIZE
    }
}

/// The AAC sample bytes of one whole ADTS frame: every `raw_data_block()`
/// with the position table and CRC words removed. Single-block and
/// `protection_absent == 1` frames are a plain slice (byte-identical to the
/// pre-#1012 behaviour). A CRC-protected multi-block frame is
/// `hdr | positions | crc | blk0 | crc | blk1 | crc | ...`; block `i` starts
/// at `first_block + raw_data_block_position[i]` (a byte offset within the
/// frame), so block `i-1` ends 2 bytes (its `crc_check`) before it and the
/// last block ends 2 bytes before the frame end. The blocks are concatenated
/// into one sample, as `protection_absent == 1` multi-block frames already
/// are. A malformed position table (non-monotonic or out of range) never
/// rejects the frame: it degrades to everything after the header-level CRC.
fn adts_frame_payload<'a>(
    hdr: &AdtsHeader,
    frame: &'a [u8],
) -> Option<alloc::borrow::Cow<'a, [u8]>> {
    let header_len = adts_header_len(hdr);
    if frame.len() <= header_len {
        return None;
    }
    let n = hdr.num_raw_data_blocks as usize;
    let plain = &frame[header_len..];
    if hdr.protection_absent || n == 0 {
        return Some(plain.into());
    }
    let positions = &frame[ADTS_HEADER_SIZE..ADTS_HEADER_SIZE + ADTS_BLOCK_POSITION_SIZE * n];
    let mut starts = alloc::vec![0usize];
    starts.extend(
        positions
            .chunks_exact(ADTS_BLOCK_POSITION_SIZE)
            .map(|c| u16::from_be_bytes([c[0], c[1]]) as usize),
    );
    // Block i occupies plain[starts[i] .. end_i - CRC]; end_i = starts[i+1].
    let ends = starts[1..].iter().copied().chain([plain.len()]);
    let mut out = Vec::with_capacity(plain.len());
    let mut prev = 0usize;
    for (i, end) in ends.enumerate() {
        let start = starts[i];
        let ok = start >= prev && end >= start + ADTS_CRC_SIZE && end <= plain.len();
        if !ok {
            return Some(plain.into());
        }
        out.extend_from_slice(&plain[start..end - ADTS_CRC_SIZE]);
        prev = end;
    }
    Some(out.into())
}

/// Parse a PAT section, returning every `(program_number, program_map_PID)`
/// pair it lists (network entries — `program_number == 0` — are skipped).
/// ISO/IEC 13818-1 §2.4.4.4. The `program_number` is kept (not just the PID)
/// so a PMT section can be cross-checked against the program it was learned
/// under (issue #774).
fn parse_pat(section: &[u8]) -> Result<Vec<(u16, Pid)>> {
    if section.first().copied() != Some(TABLE_ID_PAT) {
        return Ok(Vec::new());
    }
    let body = section_body(section, "PAT")?;
    let mut programs = Vec::new();
    let mut off = 0usize;
    while off + PAT_ENTRY_LEN <= body.len() {
        let program_number = u16::from_be_bytes([body[off], body[off + 1]]);
        let pid = Pid::new((((body[off + 2] & PID_HI_MASK) as u16) << 8) | body[off + 3] as u16);
        if program_number != NETWORK_PROGRAM_NUMBER {
            programs.push((program_number, pid));
        }
        off += PAT_ENTRY_LEN;
    }
    Ok(programs)
}

/// A PMT section's header fields beyond `table_id` (ISO/IEC 13818-1 §2.4.4.9 /
/// Table 2-33), read directly from `section[]` (the whole section including
/// its 8-byte header) — the version-diffing prerequisite for issue #774.
struct PmtSectionHeader {
    /// `table_id_extension`, which for a PMT is `program_number` (`section[3..5]`).
    program_number: u16,
    /// `version_number` (`section[5]`, bits `[5:1]`).
    version: u8,
    /// `current_next_indicator` (`section[5]`, bit 0). `false` means this
    /// table is not yet applicable — parsed, never diffed/acted on.
    current_next: bool,
    /// `section_number` (`section[6]`).
    section_number: u8,
    /// `last_section_number` (`section[7]`). A PMT is always single-section,
    /// so a genuine PMT always has `section_number == last_section_number == 0`.
    last_section_number: u8,
    /// `PCR_PID` (`section[8..10]`, 13 bits — §2.4.4.9 Table 2-33): the PID
    /// whose adaptation fields carry this program's `PCR`, and therefore the
    /// PID on which a system time-base discontinuity is signalled
    /// (§2.4.3.5). `0x1FFF` means "no PCR for this program".
    pcr_pid: Pid,
}

/// Parse a PMT section's header fields (§2.4.4.9) — everything needed to
/// decide whether a newly-reassembled section should be *applied*
/// (`current_next_indicator == 1` and `version_number` differs from the last
/// **applied** version), before paying for the ES-loop walk in [`parse_pmt`].
fn parse_pmt_section_header(section: &[u8]) -> Result<PmtSectionHeader> {
    if section.first().copied() != Some(TABLE_ID_PMT) {
        return Err(Error::InvalidValue(InvalidValue {
            field: "table_id",
            value: section.first().copied().unwrap_or(0) as u64,
            reason: "not a PMT section",
        }));
    }
    need_in(section, SECTION_HEADER_LEN, "PMT section header")?;
    Ok(PmtSectionHeader {
        program_number: u16::from_be_bytes([section[3], section[4]]),
        version: (section[5] >> 1) & VERSION_NUMBER_MASK,
        current_next: section[5] & CURRENT_NEXT_INDICATOR_BIT != 0,
        section_number: section[6],
        last_section_number: section[7],
        // PCR_PID sits at the start of the section body, which is
        // `section[8..]` (the 8-byte header ends at index 8): reserved(3) +
        // PCR_PID(13).
        pcr_pid: Pid::new((((section[8] & PID_HI_MASK) as u16) << 8) | section[9] as u16),
    })
}

/// Parse a PMT section, returning `(elementary_PID, codec, ES_info
/// descriptors)` for every elementary stream listed (issue #576: every
/// PMT-listed ES becomes a track — typed when the `stream_type` maps to a
/// decoded codec, else opaque [`Codec::Data`]). ISO/IEC 13818-1 §2.4.4.9.
/// `descriptors` is the raw ES_info descriptor-loop bytes for that stream
/// (empty when `ES_info_length` is 0); consumers that don't need it (every
/// codec but [`Codec::Data`]) simply ignore it.
fn parse_pmt(section: &[u8]) -> Result<Vec<(Pid, Codec, Vec<u8>)>> {
    if section.first().copied() != Some(TABLE_ID_PMT) {
        return Ok(Vec::new());
    }
    let body = section_body(section, "PMT")?;
    // PMT body prefix: reserved(3)+PCR_PID(13) = 2 bytes, then
    // reserved(4)+program_info_length(12) = 2 bytes, then the descriptor loop.
    need_in(body, 4, "PMT program-info prefix")?;
    let program_info_length = (((body[2] & INFO_LENGTH_HI_MASK) as usize) << 8) | body[3] as usize;
    let mut off = 4 + program_info_length;
    let mut out = Vec::new();
    // Each ES entry: stream_type(1) + reserved(3)/elementary_PID(13) [2] +
    // reserved(4)/ES_info_length(12) [2] + descriptor()×ES_info_length.
    while off + 5 <= body.len() {
        let stream_type = body[off];
        let es_pid = Pid::new((((body[off + 1] & PID_HI_MASK) as u16) << 8) | body[off + 2] as u16);
        let es_info_length =
            (((body[off + 3] & INFO_LENGTH_HI_MASK) as usize) << 8) | body[off + 4] as usize;
        let desc_start = off + 5;
        let desc_end = (desc_start + es_info_length).min(body.len());
        let descriptors = body[desc_start..desc_end].to_vec();
        let codec =
            Codec::from_stream_type(stream_type).refine_with_descriptors(stream_type, &descriptors);
        out.push((es_pid, codec, descriptors));
        off += 5 + es_info_length;
    }
    Ok(out)
}

/// Slice a long-form PSI section's table body: the bytes between the 8-byte
/// section header and the trailing 4-byte CRC_32 (ISO/IEC 13818-1 §2.4.4.1),
/// bounded by the declared `section_length`.
fn section_body<'a>(section: &'a [u8], what: &'static str) -> Result<&'a [u8]> {
    if section.len() < SECTION_HEADER_LEN + CRC32_LEN {
        return Err(Error::BufferTooShort(BufferTooShort {
            need: SECTION_HEADER_LEN + CRC32_LEN,
            have: section.len(),
            what,
        }));
    }
    // section_length counts the bytes AFTER the 3-byte header, i.e. through CRC.
    let section_length =
        (((section[1] & SECTION_LENGTH_HI_MASK) as usize) << 8) | section[2] as usize;
    let total = 3 + section_length;
    let end = total.min(section.len());
    if end < SECTION_HEADER_LEN + CRC32_LEN {
        return Err(Error::BufferTooShort(BufferTooShort {
            need: SECTION_HEADER_LEN + CRC32_LEN,
            have: end,
            what,
        }));
    }
    Ok(&section[SECTION_HEADER_LEN..end - CRC32_LEN])
}

/// Validate a long-form PSI section's trailing `CRC_32` (ISO/IEC 13818-1
/// §2.4.4.1) — the gate every PAT/PMT section must clear *before* anything
/// acts on it.
///
/// PMT application is **destructive** (issue #774 turned it into a track-set
/// diff that tears a live track down and reassigns its `track_id`), and a PAT
/// entry binds a PID to a `program_number` that every later PMT on that PID is
/// cross-checked against — so a single flipped bit in a version byte or an ES
/// loop must never be believed. Both tables fix `section_syntax_indicator` at
/// `1` (§2.4.4.4 Table 2-30 / §2.4.4.9 Table 2-33), i.e. both always carry the
/// CRC this checks; a PAT/PMT section that clears the bit is malformed and
/// carries no checkable trailer, so it is rejected here rather than acted on
/// unverified.
///
/// A rejected section is **dropped silently**: DEMUX is lenient — a corrupt
/// section is a discarded section, not a stream error — and, critically, it
/// must not disturb any already-applied state (no `TrackRemoved`, no
/// `last_applied_version` bump, no PMT-PID rebinding).
///
/// The CRC itself comes from [`broadcast_common::crc32_mpeg2`] (the shared
/// CRC-32/MPEG-2 every PSI trailer in this workspace uses — never hand-rolled
/// here), computed over `table_id` through the last table byte and compared
/// against the big-endian trailer.
fn psi_section_crc_ok(section: &[u8]) -> bool {
    if section.len() < SECTION_HEADER_LEN + CRC32_LEN {
        return false;
    }
    if section[1] & SECTION_SYNTAX_INDICATOR_BIT == 0 {
        return false;
    }
    // `SectionReassembler` hands out exactly `3 + section_length` bytes, so
    // the declared length and the slice length already agree; re-deriving it
    // keeps this correct for any other caller and bounds the slice either way.
    let section_length =
        (((section[1] & SECTION_LENGTH_HI_MASK) as usize) << 8) | section[2] as usize;
    let total = 3 + section_length;
    if total > section.len() || total < SECTION_HEADER_LEN + CRC32_LEN {
        return false;
    }
    let (covered, trailer) = section[..total].split_at(total - CRC32_LEN);
    let declared = u32::from_be_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
    broadcast_common::crc32_mpeg2::compute(covered) == declared
}

/// A long-form PSI section's `current_next_indicator` (§2.4.4.1, byte 5 bit 0):
/// `true` when the table is applicable now, `false` for a not-yet-applicable
/// "next" table. Only ever called on a section that already cleared
/// [`psi_section_crc_ok`], which guarantees byte 5 exists.
fn section_current_next(section: &[u8]) -> bool {
    section
        .get(5)
        .is_some_and(|b| b & CURRENT_NEXT_INDICATOR_BIT != 0)
}

// ── Streaming core (issue #555) ─────────────────────────────────────────────

/// One buffered access unit awaiting codec-config recovery, held until the
/// owning [`ConfigProbe`] finds enough header data to build a [`CodecConfig`]
/// (mirrors the old whole-file `find_map` scans this replaces, just applied
/// incrementally — see the module docs' bounded-memory note).
struct BufferedAu {
    data: Vec<u8>,
    pts_uw: i128,
    dts_uw: i128,
}

/// Per-PID state accumulated while scanning access units for the codec
/// config. The moment enough header data is seen, [`finalize_probe`] returns
/// the finished [`CodecConfig`] and the owning [`TrackState`] moves to
/// `Parked` (backlog carried over as-is, still accumulating — see
/// [`TrackState`]). A live track whose in-band config header later changes is
/// re-probed through the same function (r04-W51).
enum ConfigProbe {
    H264 {
        sps: Option<Vec<u8>>,
        pps: Option<Vec<u8>>,
    },
    Hevc {
        vps: Option<Vec<u8>>,
        sps: Option<Vec<u8>>,
        pps: Option<Vec<u8>>,
        hdr_sei: Vec<Vec<u8>>,
    },
    Mpeg2Video,
    MpegAudio {
        is_mpeg2: bool,
    },
    Aac,
    Ac3,
    Eac3,
    /// DTS core substream (issue #560): resolves from the first frame whose
    /// header parses — see [`crate::dts::DtsCoreFrameInfo`].
    Dts,
    /// MPEG-H 3D Audio (issue #579): resolves from the first access unit
    /// whose MHAS packets contain a `PACTYP_MPEGH3DACFG` — see
    /// [`crate::mpegh::find_mpegh3da_config`].
    MpegH,
    /// Opaque PES data (#557): the config (`stream_type` + descriptors) is
    /// already fully known from the PMT, so this probe finalizes on the very
    /// first access unit — no header scan needed.
    Data,
}

fn initial_probe(codec: Codec) -> ConfigProbe {
    match codec {
        Codec::H264 => ConfigProbe::H264 {
            sps: None,
            pps: None,
        },
        Codec::Hevc => ConfigProbe::Hevc {
            vps: None,
            sps: None,
            pps: None,
            hdr_sei: Vec::new(),
        },
        Codec::Mpeg2Video => ConfigProbe::Mpeg2Video,
        Codec::MpegAudio(is_mpeg2) => ConfigProbe::MpegAudio { is_mpeg2 },
        Codec::Aac => ConfigProbe::Aac,
        Codec::Ac3 => ConfigProbe::Ac3,
        Codec::Eac3 => ConfigProbe::Eac3,
        Codec::Dts => ConfigProbe::Dts,
        Codec::MpegH => ConfigProbe::MpegH,
        Codec::Data(_) => ConfigProbe::Data,
    }
}

/// Video codec family for a [`LiveKind::Video`] track — selects the sample
/// byte transform (Annex B → length-prefixed, or raw ES bytes for MPEG-2) and
/// the keyframe classification.
#[derive(Clone, Copy, PartialEq, Eq)]
enum VideoCodec {
    H264,
    Hevc,
    Mpeg2,
}

/// Split-frame family for a [`LiveKind::Audio`] track — a PES access unit may
/// carry more than one coded frame (issue #556); each is emitted immediately
/// with its intrinsic duration (no lookahead needed, unlike video/data).
enum AudioKind {
    Aac,
    Ac3,
    Eac3,
    Dts,
    MpegAudio { samples_per_frame: u32 },
}

/// Frame-exact dts/pts accumulator for a live [`LiveKind::Audio`] track
/// (issue B5, media plane step-2 fix wave 1).
///
/// An AAC/AC-3/E-AC-3/DTS/MPEG-audio frame's duration is *exact* in the
/// track's own timescale (e.g. always 1024 samples for an AAC frame), but the
/// 90 kHz PES clock every access unit is stamped with (ISO/IEC 13818-1
/// §2.4.3.7) is a lossy representation of that same instant — 90000 does not
/// evenly divide a typical audio sample rate — so re-deriving the track-tick
/// anchor from the wire clock on *every* access unit (via
/// [`rescale_to_track`]) injects up to ±1 track tick of jitter at every PES
/// boundary, even though the intrinsic per-frame durations within one access
/// unit are exact. The fix: anchor once from the first access unit, then
/// advance the running cursor purely by the accumulated intrinsic durations;
/// only re-anchor — and only then, signal a [`DemuxEvent::Discontinuity`] —
/// when the wire clock drifts from the predicted position by more than
/// [`audio_discontinuity_threshold_90k`], a genuine gap (splice, encoder
/// restart), never the sub-tick rounding noise the old per-AU rescale
/// mistook for one.
#[derive(Default)]
struct AudioAnchor {
    seed: Option<AudioAnchorSeed>,
    /// Track ticks per intrinsic audio sample, `0` meaning `1`: `2` for an
    /// explicitly signalled HE-AAC track, whose media timescale is the SBR
    /// output rate while the ADTS frame spans 1024 core-rate samples.
    duration_scale: u32,
    /// Per-PID cross-PES carry (issue #1160): the unfinished tail of the last
    /// frame of the previous PES payload — bytes that begin a valid frame
    /// header (or a 1..`HEADER_LEN` byte prefix of one) but run past that
    /// payload. Prepended to the next PES payload of the *same* PID by
    /// [`emit_audio_au`], for every audio family (MPEG audio, ADTS, AC-3,
    /// E-AC-3, DTS core). Strictly bounded by [`AUDIO_CARRY_MAX_BYTES`]; empty
    /// after a continuity gap, a dropped PES, a codec-config change or a
    /// re-anchor ([`clear_audio_carry`]); a dangling tail at end of stream is
    /// simply never emitted.
    carry: Vec<u8>,
    /// E-AC-3 with dependent substreams (issue #1186): hold the *final* whole
    /// access unit of each PES back in `carry` instead of emitting it, because
    /// a dependent substream that belongs to it may begin the next PES
    /// (ETSI TS 102 366 §E.1.3.1.2: dependent substreams follow their
    /// independent substream). Set from the track's `dec3` before each
    /// access unit; released with the next PES, or by `finish()`.
    hold_final_au: bool,
    /// The wire stamps of the PES that last set `carry`, for a held access
    /// unit emitted by `finish()` (no later PES supplies one).
    carry_provenance: Option<Provenance>,
}

#[derive(Clone, Copy)]
struct AudioAnchorSeed {
    /// Track-tick cursor for the *next* frame's dts.
    next_dts: i64,
    /// Track-tick cursor for the *next* frame's pts.
    next_pts: i64,
    /// The unwrapped 90 kHz dts this anchor was last (re-)established from —
    /// used only to predict where the wire clock should land next (drift
    /// detection), never to re-derive a per-frame dts/pts.
    anchor_dts_uw: i128,
    /// The unwrapped 90 kHz pts this anchor was last (re-)established from.
    anchor_pts_uw: i128,
    /// Track ticks advanced since `anchor_dts_uw`/`anchor_pts_uw` were set.
    ticks_since_anchor: i64,
}

/// Audio dts/pts re-anchor threshold, in milliseconds of 90 kHz clock —
/// see [`audio_discontinuity_threshold_90k`] for the derivation.
const AUDIO_REANCHOR_THRESHOLD_MS: i128 = 20;

/// Discontinuity threshold for the audio dts/pts anchor (issue B5): a wire PES
/// timestamp further than this from where the frame-exact accumulator predicts
/// it should be is a genuine gap (splice, encoder restart, PID reuse); anything
/// closer is muxer noise the anchor absorbs silently.
///
/// # Derivation
///
/// The original threshold was **one intrinsic sample period** (`ceil(90000 /
/// sample_rate)`, i.e. 3 ticks at 44.1 kHz). That is below what real muxers
/// actually produce, so it fired constantly on clean streams. An AAC frame at
/// 44.1 kHz is `1024 / 44100 s = 2089.795…` ticks of 90 kHz; a muxer that
/// stamps each PES with a constant *integer* increment (2090 is what the
/// common `1024 * 90000 / 44100` rounding yields) therefore accrues
/// `+0.204…` ticks per frame **by construction, on a perfectly continuous
/// stream** — crossing a 3-tick threshold after ~15 frames and every ~15
/// frames thereafter. Non-frame-aligned MP2 PES (issue #638) crosses it on
/// essentially every access unit. So the B5 anchor was inert and
/// [`DiscontinuityKind::TimelineReanchored`] was pure noise.
///
/// The bound instead comes from what a drift of this size *means*: audio that
/// is out of step with the media timeline by less than roughly 15–20 ms is
/// below the lip-sync detectability floor the broadcast recommendations work
/// to (ITU-R BT.1359-1's subjective detectability limits; ATSC A/85's ±15 ms
/// production tolerance), and re-anchoring inside that band trades a real,
/// visible `Discontinuity` event for an inaudible correction. Above it, the
/// wire clock has genuinely moved and the accumulator must follow it.
/// [`AUDIO_REANCHOR_THRESHOLD_MS`] = 20 ms = **1800 ticks** of 90 kHz, which
/// the constant-rounding muxer above reaches only after ~8800 frames (~3.4
/// minutes) — at which point the accumulated error really is 20 ms and
/// re-anchoring is the correct call, not a false positive.
///
/// Floored at two intrinsic sample periods so a degenerate/absurd sample rate
/// (below ~100 Hz, where one frame period exceeds the millisecond bound) still
/// gets a threshold wider than its own quantisation noise.
///
/// `pub(crate)`: also used by [`crate::ps_demux::build_ac3_track`], which has
/// the identical 90 kHz-PES-stamp-vs-sample_rate-track-clock re-anchoring
/// problem (found via the FIX C invariant test, media plane step-2 fix
/// wave 1).
pub(crate) fn audio_discontinuity_threshold_90k(sample_rate: u32) -> i128 {
    let one_sample_period = (VIDEO_TIMESCALE as u128).div_ceil(sample_rate.max(1) as u128) as i128;
    let ms_bound = (VIDEO_TIMESCALE as i128 * AUDIO_REANCHOR_THRESHOLD_MS) / 1000;
    ms_bound.max(one_sample_period * 2)
}

/// A completed-but-not-yet-durationed sample, held until the *next* access
/// unit resolves its duration (video: DTS delta; data: PTS delta — mirrors
/// the old batch demuxer's "duration = delta to the next access unit, last
/// sample reuses the previous duration" rule).
struct PendingOneBehind {
    data: Vec<u8>,
    is_sync: bool,
    pts_uw: i128,
    dts_uw: i128,
    /// The display geometry of the AU this slot was **filled** with, so its
    /// `Sample` carries the state that was in force when it arrived (the
    /// tracker may advance one access unit later).
    display: Option<Arc<DisplayInfo>>,
    /// The `TrackUpdated` / `DisplayChanged` this access unit itself raised,
    /// released immediately before this slot's `Sample` and carrying *this*
    /// access unit's `dts`/`pts`/sync flag (design §6.5).
    pending_events: PendingDisplayEvents,
}

/// The display events one access unit raises when its slot is released
/// (`docs/display-geometry/DESIGN.md` §6.5): a `TrackUpdated` (the codec
/// config bytes changed at this AU) and/or a `DisplayChanged` (the parsed
/// geometry changed at this AU), pushed immediately before its `Sample`.
#[derive(Default)]
struct PendingDisplayEvents {
    config: Option<TrackSpec>,
    display: Option<(Arc<DisplayInfo>, DisplayChangeSet)>,
}

/// H.264 PAFF (field-coded) pairing state of one video track (issue #1161).
///
/// Broadcast PAFF carries one coded *field* per PES, but an ISO/IEC 14496-15
/// sample is a whole access unit — both fields of a complementary field pair
/// (ITU-T H.264 §3.35-3.37). While a first field is the pending (one-behind)
/// sample, `first_field` remembers its identity so the next access unit can be
/// merged into it instead of becoming a sample of its own. The pair keeps the
/// first field's PTS/DTS.
#[derive(Default)]
struct PaffPairing {
    /// In-band SPS/PPS, for parsing slice headers.
    params: crate::slice_header::AvcParamSets,
    /// The pending sample is a first field still awaiting its second field.
    first_field: Option<crate::slice_header::AvcFieldInfo>,
}

/// Largest first-field to second-field DTS distance accepted as one frame: a
/// timestamp jump (discontinuity, rebase) between the two fields is not a pair.
const MAX_FIELD_PAIR_DTS_TICKS: i128 = MAX_FRAME_PERIOD_TICKS as i128;

/// Clamp an unwrapped 33-bit-derived `i128` timestamp into the `i64` range
/// [`Sample::dts`]/[`Sample::pts`] carry. `i128` is only used internally for
/// wrap arithmetic headroom; every real value here is a small non-negative
/// multiple of the 33-bit range and fits `i64` with room to spare for
/// centuries of continuous 90 kHz runtime, so this never actually clamps in
/// practice — it exists to make the conversion a checked one, not a silent
/// truncation.
fn to_ticks(uw: i128) -> i64 {
    uw.clamp(i64::MIN as i128, i64::MAX as i128) as i64
}

/// Debug-only [`Provenance`] for a 33-bit-wrapped TS/PES clock: the raw wire
/// value is exactly the absolute unwrapped value modulo the wrap (unwrap only
/// ever adds whole multiples of it), so it is recovered losslessly from the
/// already-unwrapped `dts`/`pts` with no extra state threaded through the
/// demux (issue #556 successor — media plane step 2c).
fn ts_provenance(dts: i64, pts: i64) -> Provenance {
    Provenance {
        wire_dts: Some((dts as u64) % TS_WRAP),
        wire_pts: Some((pts as u64) % TS_WRAP),
    }
}

/// Per-track live (config-known) processing state.
///
/// `clippy::large_enum_variant` (allow): an AVC/HEVC video track is the
/// large variant once it carries its SPS-activation tracker (a `BTreeMap` of
/// geometries and PPS bindings), but `TrackState::Live` owns one per live
/// PID either way, and boxing it here would only move the allocation, not
/// reduce it.
#[allow(clippy::large_enum_variant)]
enum LiveKind {
    /// H.264/HEVC/MPEG-2 video: one `Sample` per access unit.
    Video {
        pending: Option<PendingOneBehind>,
        last_duration: u32,
        codec: VideoCodec,
        /// H.264 PAFF field-pair state (issue #1161); inert for other codecs.
        paff: PaffPairing,
    },
    /// AAC/AC-3/E-AC-3/MPEG audio: zero-lookahead, intrinsic-duration frames.
    Audio {
        sample_rate: u32,
        kind: AudioKind,
        /// Frame-exact dts/pts accumulator (issue B5, media plane step-2 fix
        /// wave 1) — see [`AudioAnchor`].
        anchor: AudioAnchor,
    },
    /// Opaque PES data (#557): one `Sample` per access unit.
    Data {
        pending: Option<PendingOneBehind>,
        last_duration: u32,
    },
    /// MPEG-H 3D Audio (issue #579): one opaque `Sample` per MHAS access
    /// unit — no MHAS bitstream decode, so (like [`LiveKind::Data`]) there
    /// is no intrinsic per-sample duration to split on; duration is the
    /// one-behind PTS delta. `is_sync` is set from whether the access unit's
    /// MHAS packets contain a `PACTYP_MPEGH3DACFG` (a random-access point,
    /// ETSI TS 101 154 §6.8.4.1), not hardcoded `true`.
    MpegH {
        pending: Option<PendingOneBehind>,
        last_duration: u32,
    },
    /// Opaque section data (#576): each reassembled PSI/private section is
    /// emitted immediately as one `Sample` — sections carry no PTS/DTS, so
    /// there is no one-behind duration lookahead (every duration is `0`).
    Section,
}

struct LiveTrack {
    track_id: TrackId,
    kind: LiveKind,
    /// This track's current codec config, retained so a later PMT metadata
    /// change (issue #774) and a mid-stream config change (r04-W51) can
    /// rebuild a full [`TrackSpec`] for [`DemuxEvent::TrackUpdated`].
    config: CodecConfig,
    /// This track's media timescale, for the same [`DemuxEvent::TrackUpdated`]
    /// reconstruction.
    timescale: u32,
    /// The AVC/HEVC parameter sets this track has seen, tracked as each appears
    /// so a re-probe can tell a real change from a repeat and is not blind to a
    /// parameter set that arrived in an earlier access unit (r04-W51).
    parameter_sets: ParameterSets,
    /// The in-band codec-config header bytes this track's current config was
    /// built from, so a *changed* header can be told apart from a repeat
    /// (r04-W51).
    ///
    /// A broadcast stream changes its parameter sets mid-flight routinely —
    /// an SD↔HD ad break, a re-encode, a multiplex reconfiguration — and a
    /// mid-stream SPS/PPS (or AAC config) otherwise left the track labelled
    /// with the original `avcC`/`esds` for the rest of the stream, so the init
    /// segment described a stream that had stopped being sent. The parameters
    /// are compared byte-for-byte because encoders also repeat them
    /// unchanged, often on every keyframe; an identical repeat must not
    /// trigger a `TrackUpdated` (which tells a consumer to rebuild its init
    /// segment).
    config_header: Option<Vec<u8>>,
    /// Which SPS this track's pictures activate, and the display geometry
    /// that implies (`docs/display-geometry/DESIGN.md` §6.1/§6.2). `Some`
    /// only for AVC/HEVC: those are the demuxers that track display state
    /// (`Sample::display` is `None` elsewhere).
    /// `Some` for AVC/HEVC only: MPEG-2 picture geometry is not an AVC/HEVC
    /// parameter set, so that path stays untracked (`Sample::display` is
    /// `None`).
    sps_tracker: Option<SpsTracker>,
    /// MPEG-2 video's display tracker (`docs/display-geometry/DESIGN.md`
    /// §6.4, Phase 3b): the sequence geometry in force plus the AFD / bar data
    /// under the H.262 `sequence_header()` persistence rule. `Some` only for
    /// `Codec::Mpeg2Video`.
    mpeg2_tracker: Option<Mpeg2DisplayTracker>,
    /// The `TrackUpdated` raised by the access unit being applied, released
    /// with its slot.
    pending_config: Option<TrackSpec>,
    /// The change resolved for the access unit being applied, not yet
    /// attached to its slot.
    display: Option<(Arc<DisplayInfo>, DisplayChangeSet)>,
    /// Suppress the first display change after a damaged-unit promotion
    /// (issue G1), since the tracker state was seeded from a partial backlog.
    suppress_next_display_change: bool,
    /// Persistent marker that this track was promoted from a damaged access
    /// unit (issue G1): AFD-only changes are suppressed, since the backlog
    /// that seeded the tracker may have lacked them.
    damaged_promotion: bool,
    /// Skip the first re-probe after a damaged-unit promotion (issue G1), so
    /// the first intact access unit does not report a spurious config change.
    skip_next_reprobe: bool,
    /// Whether the first access unit carried an HDR10+ T.35 prefix SEI.
    hdr10plus: bool,
}

impl LiveTrack {
    /// Fold one access unit through the display tracker, returning the state
    /// its `Sample` carries and remembering a resolved change for
    /// [`push_live_au`] to park on that sample's slot.
    ///
    /// Before the first resolved access unit the change is *seed-pending*:
    /// it is released with the first sample (the level-triggered start of
    /// design §5.2, Q2 = emit).
    fn display(&mut self, au: &[u8]) -> Option<Arc<DisplayInfo>> {
        if let Some(tracker) = self.mpeg2_tracker.as_mut() {
            if let Mpeg2Outcome::Changed {
                display, changed, ..
            } = tracker.observe(au)
            {
                self.display = Some((display, changed));
            }
            return tracker.state().cloned();
        }
        let tracker = self.sps_tracker.as_mut()?;
        if let ActivationOutcome::Changed {
            display, changed, ..
        } = tracker.observe(au)
        {
            self.display = Some((display, changed));
        }
        tracker.state().cloned()
    }
}

/// A [`StreamState`]'s codec-config **and** PMT-declaration-order lifecycle.
///
/// Track IDs and `DemuxEvent::TrackAdded` order must match the PMT's
/// declaration order (codec tracks first, then data tracks, each group in
/// PMT order — the old batch demuxer's invariant), which need not be the
/// order each PID's config happens to resolve in. So a PID whose config is
/// already known still waits, `Parked`, until every earlier-ranked PID has
/// itself resolved (see [`StreamingTsDemux::try_promote_ready`]) — at which
/// point it becomes `Live` and its whole backlog replays as a burst of
/// `DemuxEvent::Sample`s.
///
/// `clippy::large_enum_variant` (allow): `Live` carries a [`LiveTrack`], whose
/// video `kind` now owns an SPS-activation tracker, so it dwarfs the other
/// arms. Every `StreamingTsDemux` holds exactly one of these per PID either
/// way (probe, parked or live), and boxing `Live` would only add a second
/// allocation per track, not reduce the set.
#[allow(clippy::large_enum_variant)]
enum TrackState {
    /// No config recovered yet; `backlog` accumulates every access unit seen
    /// so far (replayed once config resolves and it's this PID's turn).
    Probing {
        probe: ConfigProbe,
        backlog: Vec<BufferedAu>,
    },
    /// Config resolved, but an earlier-ranked PID hasn't resolved yet.
    /// `backlog` keeps accumulating every access unit that arrives while
    /// parked.
    Parked {
        config: CodecConfig,
        timescale: u32,
        kind: LiveKind,
        backlog: Vec<BufferedAu>,
    },
    /// Config resolved and this PID's turn has come: `TrackAdded` has fired
    /// and samples stream directly.
    Live(LiveTrack),
    /// [`MAX_PROBE_BACKLOG_BYTES`] overflowed while `Probing` or `Parked`
    /// (issue B8): permanently resolved without ever promoting to `Live` —
    /// every further access unit for this PID is silently discarded (no
    /// further growth). Matches [`StreamingTsDemux::finish`]'s own
    /// "never recoverable, skip" conclusion for a probe that never resolves,
    /// just reached early via the byte cap instead of end-of-input.
    Abandoned,
}

/// What [`WrapState::rebase_at_discontinuity`] concluded about a stamp that
/// arrived after a signalled time-base discontinuity (r04-W50 review).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DiscontinuityVerdict {
    /// This stamp reads as a forward step — the old time base's own cadence, or
    /// the new base already starting ahead — so the offset was left alone and
    /// the caller keeps waiting.
    Forward,
    /// This stamp moved backwards, so it is the new time base: the offset was
    /// lifted to make it continue from the last stamp emitted.
    Lifted,
}

/// Incremental 33-bit PTS/DTS wrap-unroll, one access unit at a time —
/// produces the identical sequence the old whole-stream unroll would, applied
/// access-unit-by-access-unit (ISO/IEC 13818-1 §2.4.3.7). A raw value of
/// exactly `0` before any genuine value has been observed is always the
/// caller's fallback for a PES with no header timing at all (never a real
/// 90 kHz wire timestamp landing on tick 0 in practice — e.g. a sparse opaque
/// data-stream "heartbeat" access unit preceding the first timestamped one,
/// issue #557): wrap-jump detection does not run against it.
#[derive(Default)]
struct WrapState {
    initialized: bool,
    dts_seen_real: bool,
    pts_seen_real: bool,
    prev_dts_raw: u64,
    prev_dts_uw: i128,
    prev_pts_raw: u64,
    prev_pts_uw: i128,
    /// Ticks added to every unwrapped timestamp from the most recent
    /// signalled time-base discontinuity onwards (r04-W50).
    ///
    /// `discontinuity_indicator` (ISO/IEC 13818-1 §2.4.3.5) marks "a sample of
    /// a new system time clock": the new time base may start *below* the old
    /// one — the ordinary splice case — and the 33-bit unroll alone cannot see
    /// that (a backward step within half the range is read as a real backward
    /// jump, not a wrap). Every sample after it then carries a `dts` earlier
    /// than the sample before it, which violates the IR's "samples in decode
    /// order with a non-decreasing absolute dts" invariant and makes every
    /// downstream muxer emit negative deltas.
    ///
    /// The demux rebases instead of leaving it to consumers: the offset is the
    /// smallest non-negative constant that keeps the new time base continuing
    /// from the old one, so the decode timeline stays monotonic across the
    /// discontinuity while the *intervals* inside each time base are
    /// untouched.
    discontinuity_offset: i128,
}

impl WrapState {
    /// Feed the next access unit's raw 33-bit `(pts, dts)`, returning the
    /// unwrapped `(pts, dts)` with any accumulated discontinuity offset
    /// applied.
    fn push(&mut self, raw_pts: u64, raw_dts: u64) -> (i128, i128) {
        if !self.initialized {
            self.initialized = true;
            self.dts_seen_real = raw_dts != 0;
            self.pts_seen_real = raw_pts != 0;
            self.prev_dts_raw = raw_dts;
            self.prev_dts_uw = raw_dts as i128;
            self.prev_pts_raw = raw_pts;
            self.prev_pts_uw = raw_pts as i128;
            return (self.prev_pts_uw, self.prev_dts_uw);
        }
        let dts_uw = if self.dts_seen_real {
            unwrap_ts(self.prev_dts_uw, self.prev_dts_raw, raw_dts)
        } else {
            self.dts_seen_real = raw_dts != 0;
            raw_dts as i128
        };
        let pts_uw = if self.pts_seen_real {
            unwrap_ts(self.prev_pts_uw, self.prev_pts_raw, raw_pts)
        } else {
            self.pts_seen_real = raw_pts != 0;
            raw_pts as i128
        };
        // Remember the *un-offset* unwrapped values: the next access unit's
        // wrap arithmetic is a property of the wire clock, which the offset
        // does not move.
        self.prev_dts_raw = raw_dts;
        self.prev_dts_uw = dts_uw;
        self.prev_pts_raw = raw_pts;
        self.prev_pts_uw = pts_uw;
        (
            pts_uw.saturating_add(self.discontinuity_offset),
            dts_uw.saturating_add(self.discontinuity_offset),
        )
    }

    /// Fold in a signalled time-base discontinuity (r04-W50): decide whether
    /// this stamp is the first of the new time base, and if so lift the offset
    /// so the decode timeline continues rather than jumping backwards.
    ///
    /// Returns [`DiscontinuityVerdict::Lifted`] when the offset moved (this
    /// stamp really was the new base) and
    /// [`DiscontinuityVerdict::Forward`] when it reads as a forward step — which
    /// the *old* base also produces, so the caller keeps `pending_rebase` set
    /// and tests the next access unit the same way.
    ///
    /// The rules, each fixing a defect of the earlier attempt:
    ///
    /// * **Lift only, never subtract.** The offset moves *up* only when the
    ///   incoming stamp would land at or before the last one emitted. A forward
    ///   step is a continuation, not a shrinkable jump: the earlier code
    ///   computed `wanted - next` and added a *negative* shortfall, pulling a
    ///   legitimate forward splice back to a single frame period — while its
    ///   doc claimed the lift was "the smallest non-negative constant".
    /// * **Decide by a backward move, never by exact equality.** The earlier
    ///   attempt treated `shortfall == 0` as "still the old base", which cadence
    ///   jitter breaks: at 23.976 fps the frame period alternates 3754/3753
    ///   ticks and at 44.1 kHz 2351/2352, so the old base's last access unit
    ///   lands a tick early or late and the flag is consumed by the wrong unit.
    ///   A backward step is something the old base cannot produce, so that — not
    ///   an exact match — is the signal.
    /// * **Only the new base consumes the flag.** An old-base access unit
    ///   completing after the indicator reads as a forward step, so
    ///   `pending_rebase` stays set for the next access unit.
    fn rebase_at_discontinuity(&mut self, raw_dts: u64, step: i128) -> DiscontinuityVerdict {
        if !self.initialized {
            return DiscontinuityVerdict::Forward;
        }
        // Unrolled position of this stamp *before* the current offset is
        // applied, and the value the caller last received (which already
        // includes any earlier lift).
        let next_uw = if self.dts_seen_real {
            unwrap_ts(self.prev_dts_uw, self.prev_dts_raw, raw_dts)
        } else {
            raw_dts as i128
        };
        let last_emitted = self.prev_dts_uw.saturating_add(self.discontinuity_offset);
        let next_emitted = next_uw.saturating_add(self.discontinuity_offset);
        // `step` bounds the jump the *old* base could still produce: a decoder
        // polled with a nominal frame period may hand out one access unit of
        // slack either way. A move further back than that is the new base.
        let slack = step.max(1);
        if next_emitted + slack > last_emitted {
            // Forward, or level within one nominal period: the old base's own
            // cadence. Never a lift, and never a reduction.
            return DiscontinuityVerdict::Forward;
        }
        // Lift so the new base's first stamp lands *one nominal period past*
        // the last one emitted, not merely level with it: a stamp equal to its
        // predecessor gives the IR a zero step, and every writer in this crate
        // rejects a zero-duration sample. `step` is the track's own last
        // measured frame period, so a steady stream keeps its cadence across
        // the seam.
        let lift = last_emitted
            .saturating_sub(next_emitted)
            .saturating_add(slack);
        self.discontinuity_offset = self.discontinuity_offset.saturating_add(lift);
        self.prev_dts_raw = raw_dts;
        self.prev_dts_uw = next_uw;
        self.prev_pts_raw = raw_dts;
        self.prev_pts_uw = next_uw;
        self.dts_seen_real = true;
        self.pts_seen_real = true;
        DiscontinuityVerdict::Lifted
    }
}

/// A PID's reassembly engine: PES access units, or PSI/private sections
/// (issue #576) — chosen once at PID discovery from [`data_carriage`] (a
/// decoded [`Codec`] or a PES-carried [`Codec::Data`] always gets
/// [`Carrier::Pes`]).
enum Carrier {
    Pes(PesAssembler),
    Section(SectionReassembler),
}

/// The reassembly engine a newly-discovered `codec` should use.
fn initial_carrier(codec: Codec) -> Carrier {
    match codec {
        Codec::Data(stream_type) if data_carriage(stream_type) == DataCarriage::Sections => {
            Carrier::Section(SectionReassembler::default())
        }
        _ => Carrier::Pes(PesAssembler::new()),
    }
}

/// Per-PID (elementary stream) engine state.
struct StreamState {
    codec: Codec,
    descriptors: Vec<u8>,
    carrier: Carrier,
    /// Bytes accumulated in `carrier`'s `Carrier::Pes` assembler since the
    /// last `payload_unit_start` — enforces [`MAX_PES_BUFFER_BYTES`]. Always
    /// `0` and unused for `Carrier::Section` streams.
    pes_bytes: usize,
    /// Previous access unit's resolved `(pts, dts)` — the base a PES carrying
    /// none of its own is interpolated *forward* from (see
    /// [`StreamState::frame_period`]).
    fallback: (u64, u64),
    /// Estimated per-access-unit frame period (90 kHz ticks), measured from
    /// the last two *stamped* PES access units on this PID.
    ///
    /// A PES packet may legally omit both PTS and DTS (ISO/IEC 13818-1
    /// §2.4.3.7: `PTS_DTS_flags == '00'`), and the 2.7.4 interval constraint
    /// only requires them periodically. The demux used to reuse the previous
    /// access unit's stamps verbatim for such a packet, so consecutive video
    /// access units received *identical* `dts` — the one-behind duration rule
    /// then gave the earlier one `duration = 0` and the next stamped access
    /// unit absorbed the whole gap, producing zero-duration samples plus one
    /// long one (r04-W48). The T-STD instead derives them: "Decoding times
    /// tdn(j + 1), tdn(j + 2),... of access units without encoded DTS or PTS
    /// fields which directly follow access unit j may be derived from
    /// information in the elementary stream" (§2.4.2.6). The closest
    /// container-level estimate of that information is the observed spacing
    /// between stamped access units, which is what this holds.
    ///
    /// `None` until two stamped access units have been seen — a lone
    /// unstamped packet has nothing to interpolate from and keeps the old
    /// verbatim-fallback behaviour rather than inventing a period.
    frame_period: Option<u64>,
    /// The DTS of the most recent *stamped* access unit, which is what a new
    /// stamped access unit measures its period against. Kept separate from
    /// [`StreamState::fallback`] because an unstamped access unit advances
    /// `fallback` (that is the interpolation) without being a clock
    /// observation to measure against.
    last_stamped_dts: Option<u64>,
    /// Access units seen since that stamped one, so the span it covers is
    /// divided by the right count when the next stamp arrives.
    units_since_stamped: u64,
    has_any: bool,
    wrap: WrapState,
    /// Always `Some` except transiently inside [`advance_track`].
    track: Option<TrackState>,
    /// This PID's most recent observed inter-access-unit spacing (90 kHz
    /// ticks), used as the step when a signalled discontinuity rebases the
    /// timeline (r04-W50). `0` until a plausible step has been seen, in which
    /// case the rebase falls back to a single tick — monotonic, which is the
    /// invariant that matters.
    last_frame_period: i128,
    /// The last [`FRAME_PERIOD_WINDOW`] plausible inter-access-unit steps, from
    /// which the median — and so both the interpolation period and the rebase
    /// step — is taken (r04-W48/W50 review).
    recent_steps: Vec<u64>,
    /// A signalled time-base discontinuity was observed on this program and
    /// this PID has not yet seen the first access unit of the new base: the
    /// next `(pts, dts)` it resolves is fed to
    /// [`WrapState::rebase_at_discontinuity`] so its decode timeline continues
    /// from where the old base left off instead of jumping backwards
    /// (r04-W50).
    pending_rebase: bool,
    /// Whether the PES the assembler is currently building is whole: `false`
    /// once a continuity-counter gap — or a signalled discontinuity — lost one
    /// of its 184-byte payloads. It is dropped on completion rather than
    /// delivered truncated (r04-W49). Set once and never cleared by a later
    /// packet in the same unit; only the next `payload_unit_start` starts a
    /// fresh, whole unit. Unused for a non-PES carrier.
    current_pes_intact: bool,
    /// The `PES_packet_length` this PID's in-progress PES declared, once its
    /// header bytes have been received; `0` while unknown or for an unbounded
    /// PES (ISO/IEC 13818-1 §2.4.3.7 — `0` means unbounded, the ordinary
    /// video case). Compared against [`StreamState::pes_received`] at
    /// completion to decide whether a gap on the *next* packet actually lost
    /// anything (r04-W49).
    pes_declared_len: u16,
    /// Bytes of the in-progress PES received so far (header + payload), for
    /// the [`StreamState::pes_declared_len`] comparison. Reset on every
    /// `payload_unit_start`.
    pes_received: usize,
    /// Running total of bytes held in `track`'s `Probing`/`Parked` backlog —
    /// enforces [`MAX_PROBE_BACKLOG_BYTES`] (issue B8). Kept in sync on every
    /// [`advance_track`] push (never re-walked from the `Vec`), and reset to
    /// `0` when the backlog is abandoned (see [`abandon_backlog`]); `0` and
    /// unused once `track` is `Live` or `Abandoned`.
    backlog_bytes: usize,
    /// While an audio PID is still `Probing`: the last bytes (at most
    /// [`audio_probe_window`]) of the access units already seen, joined in
    /// front of the next one so a frame header (or, for E-AC-3, a whole frame)
    /// that straddles a PES boundary can still resolve the track's config
    /// (issue #1160). Empty otherwise.
    probe_tail: Vec<u8>,
    /// Access units pushed while this PID was `Probing` (saturating). Bounds
    /// how long an unresolved probe may hold back later PIDs
    /// ([`PROBE_HEAD_BLOCK_AUS`]).
    probe_aus: u32,
    /// E-AC-3 only: payloads that re-walked a non-empty held window (saturating). Past
    /// [`EAC3_PROBE_FULL_WALKS`] the walk is gated (see there).
    probe_walks: u32,
    /// E-AC-3 only: length of the window at the last full walk.
    probe_walked_len: usize,
    /// Payload-bearing TS packets delivered to this PID (saturating), counting
    /// those replayed from `unattributed`. Zero means the PID has been
    /// completely silent since it was declared ([`SILENT_HEAD_PARKED_BYTES`]).
    payload_packets: u32,
    /// Whether this PID's probe was resolved from a damaged access unit
    /// (issue G1), so its initial `DisplayChanged` is suppressed.
    damaged_promotion: bool,
    /// [`StreamingTsDemux::packet_index`] when this PID was declared, the age
    /// base for [`STUCK_HEAD_INPUT_PACKETS`].
    declared_at_packet: u64,
    /// Set by [`StreamingTsDemux::release_silent_heads`] while this PID had
    /// sent nothing: it no longer blocks the PIDs behind it, even after it
    /// starts sending.
    unit_released: bool,
}

impl StreamState {
    /// Forget this PID's old-timeline timing (see
    /// [`StreamingTsDemux::restart_timeline`]); the resolved track stays.
    fn restart_timeline(&mut self) {
        self.carrier = initial_carrier(self.codec);
        self.pes_bytes = 0;
        self.fallback = (0, 0);
        self.frame_period = None;
        self.last_stamped_dts = None;
        self.units_since_stamped = 0;
        self.has_any = false;
        self.wrap = WrapState::default();
        self.last_frame_period = 0;
        self.recent_steps.clear();
        self.pending_rebase = false;
        self.current_pes_intact = true;
        self.pes_declared_len = 0;
        self.pes_received = 0;
        match &mut self.track {
            Some(TrackState::Probing { backlog, .. }) => {
                backlog.clear();
                self.backlog_bytes = 0;
                self.probe_tail.clear();
            }
            Some(TrackState::Live(live)) => match &mut live.kind {
                LiveKind::Audio { anchor, .. } => {
                    anchor.seed = None;
                    anchor.carry.clear();
                    anchor.carry_provenance = None;
                }
                LiveKind::Video { paff, .. } => paff.first_field = None,
                LiveKind::Data { .. } | LiveKind::MpegH { .. } | LiveKind::Section => {}
            },
            _ => {}
        }
    }
}

/// Advance a one-behind (video/data) pending slot with a newly-built sample,
/// emitting the *previous* pending sample now that its duration is known
/// (`duration_from_pts` selects the PTS delta for data tracks, DTS delta for
/// video).
///
/// The display events an access unit raised travel **inside its slot**
/// ([`PendingOneBehind::pending_events`]) and are pushed immediately before
/// that slot's own `Sample`, with that sample's `dts`/`pts`/sync flag
/// (`docs/display-geometry/DESIGN.md` §6.5): a consumer sees the last
/// old-geometry sample, then `TrackUpdated` (if the codec config changed),
/// then `DisplayChanged`, then the first new-geometry sample - exactly the
/// order Phase 1a established for `TrackUpdated`.
#[allow(clippy::too_many_arguments)]
fn advance_one_behind(
    pending: &mut Option<PendingOneBehind>,
    last_duration: &mut u32,
    data: Vec<u8>,
    is_sync: bool,
    pts_uw: i128,
    dts_uw: i128,
    duration_from_pts: bool,
    track_id: TrackId,
    provenance: EventProvenance,
    display: Option<Arc<DisplayInfo>>,
    pending_events: PendingDisplayEvents,
    events: &mut VecDeque<DemuxEvent>,
) {
    if let Some(prev) = pending.take() {
        let duration = if duration_from_pts {
            (pts_uw - prev.pts_uw).max(0) as u32
        } else {
            (dts_uw - prev.dts_uw).max(0) as u32
        };
        *last_duration = duration;
        let dts = to_ticks(prev.dts_uw);
        let pts = to_ticks(prev.pts_uw);
        if let Some(spec) = prev.pending_events.config {
            events.push_back(DemuxEvent::TrackUpdated(spec));
        }
        if let Some((display, changed)) = prev.pending_events.display {
            events.push_back(DemuxEvent::DisplayChanged {
                track_id,
                display,
                changed,
                dts: Some(dts),
                pts: Some(pts),
                random_access: prev.is_sync,
                provenance,
            });
        }
        events.push_back(DemuxEvent::Sample {
            track_id,
            sample: Sample {
                data: prev.data.into(),
                dts: Some(dts),
                pts: Some(pts),
                duration: Some(duration),
                flags: SampleFlags::new(prev.is_sync),
                provenance: Some(ts_provenance(dts, pts)),
                display: prev.display,
            },
        });
    }
    *pending = Some(PendingOneBehind {
        data,
        is_sync,
        pts_uw,
        dts_uw,
        display,
        pending_events: PendingDisplayEvents::default(),
    });
    if let Some(spec) = pending_events.config {
        events.push_back(DemuxEvent::TrackUpdated(spec));
    }
    // `PendingOneBehind::pending_events`' doc claims a change parked here is
    // released with this access unit's own sample; it was instead pushed
    // before the *previous* sample (`docs/display-geometry/DESIGN.md` §6.5
    // forbids that, and it labelled one picture early). The previous slot is
    // already out, so the change belongs to the new `*pending` slot.
    let pending_events = PendingDisplayEvents {
        config: None,
        display: pending_events.display,
    };
    if let Some((display, changed)) = pending_events.display {
        events.push_back(DemuxEvent::DisplayChanged {
            track_id,
            display,
            changed,
            dts: Some(to_ticks(dts_uw)),
            pts: Some(to_ticks(pts_uw)),
            random_access: is_sync,
            provenance,
        });
    }
}

/// Flush a trailing one-behind pending sample at end of stream, reusing the
/// last-known duration (mirrors the batch tail rule: the final sample repeats
/// the previous sample's duration, or `0` if there was only ever one sample),
/// after the display events that access unit raised.
fn flush_one_behind(
    pending: &mut Option<PendingOneBehind>,
    last_duration: u32,
    track_id: TrackId,
    provenance: EventProvenance,
    events: &mut VecDeque<DemuxEvent>,
) {
    if let Some(p) = pending.take() {
        let dts = to_ticks(p.dts_uw);
        let pts = to_ticks(p.pts_uw);
        if let Some(spec) = p.pending_events.config {
            events.push_back(DemuxEvent::TrackUpdated(spec));
        }
        if let Some((display, changed)) = p.pending_events.display {
            events.push_back(DemuxEvent::DisplayChanged {
                track_id,
                display,
                changed,
                dts: Some(dts),
                pts: Some(pts),
                random_access: p.is_sync,
                provenance,
            });
        }
        events.push_back(DemuxEvent::Sample {
            track_id,
            sample: Sample {
                data: p.data.into(),
                dts: Some(dts),
                pts: Some(pts),
                duration: Some(last_duration),
                flags: SampleFlags::new(p.is_sync),
                provenance: Some(ts_provenance(dts, pts)),
                display: p.display,
            },
        });
    }
}

/// [`annexb_to_length_prefixed`] without access unit delimiters (NAL type 9):
/// a second field merged into the first field's sample must not introduce a
/// second AUD into the access unit.
fn annexb_to_length_prefixed_no_aud(annexb: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(annexb.len());
    for nal in iter_annexb_nals(annexb) {
        if nal_unit_type(NalCodec::Avc, nal) == Some(crate::slice_header::NAL_AUD) {
            continue;
        }
        out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
        out.extend_from_slice(nal);
    }
    out
}

/// Build a video sample's coded bytes + sync flag from one Annex B (or raw
/// MPEG-2) access unit.
fn video_sample_bytes(codec: VideoCodec, au_data: &[u8]) -> (Vec<u8>, bool) {
    match codec {
        VideoCodec::H264 => {
            // Random-access anchor: IDR OR an open-GOP RAP signal (a
            // recovery-point SEI, or pragmatically an SPS in the AU) —
            // issue #595. Broadcast H.264 is frequently open-GOP and never
            // codes an IDR at all, so IDR-only detection would never anchor
            // a segment.
            let is_rap = access_unit_is_rap(NalCodec::Avc, au_data, false);
            (annexb_to_length_prefixed(au_data), is_rap)
        }
        VideoCodec::Hevc => {
            let mut irap = false;
            for nal in iter_annexb_nals(au_data) {
                if is_keyframe_nal(NalCodec::Hevc, nal) {
                    irap = true;
                }
            }
            (annexb_to_length_prefixed(au_data), irap)
        }
        VideoCodec::Mpeg2 => (au_data.to_vec(), mpeg2_is_sync(au_data)),
    }
}

fn scale_plan_durations(plan: &mut Option<AudioPlan<'_>>, scale: u32) {
    if scale > 1
        && let Some(p) = plan
    {
        for f in &mut p.frames {
            f.duration = f.duration.saturating_mul(scale);
        }
    }
}

/// One audio frame resolved by [`plan_audio_frames`].
struct PlannedFrame<'a> {
    /// Sample bytes to emit; `None` for a frame with no payload after its
    /// header (still advances the cursor by its duration).
    data: Option<alloc::borrow::Cow<'a, [u8]>>,
    /// Intrinsic duration in track-timescale ticks (= samples).
    duration: u32,
    /// The frame *began* in the carried bytes, i.e. in the previous PES.
    from_carry: bool,
    /// Offset in the planned buffer where the frame (with any E-AC-3 dependent
    /// substreams folded into it) starts.
    start: usize,
    /// Offset in the planned buffer one past the frame's last byte.
    end: usize,
}

/// The frames cut from `carry ++ payload`, plus what to carry forward.
struct AudioPlan<'a> {
    frames: Vec<PlannedFrame<'a>>,
    /// Unfinished tail to carry into the next PES payload.
    tail: &'a [u8],
    /// Some frame (or the start of the tail) *commenced* in this payload —
    /// only then does this PES's wire PTS describe a frame boundary
    /// (ISO/IEC 13818-1 §2.4.3.7: the PTS is of the first access unit that
    /// *commences* in the PES packet).
    commences: bool,
    /// `false` when a non-empty carry did not join cleanly onto this payload
    /// (the carried bytes were not really a frame start, or the frame they
    /// began is not followed by another valid header): the caller drops the
    /// carry and plans the payload alone.
    carry_ok: bool,
}

fn plan_with<'a, F: FrameSync>(
    data: &'a [u8],
    carry_len: usize,
    shape: impl Fn(&F::Hdr) -> (usize, u32),
) -> AudioPlan<'a> {
    let split = split_frames_with_tail::<F>(data);
    let carry_ok = carry_len == 0
        || match split.frames.first() {
            // The carried frame must start at byte 0 and, when enough bytes
            // follow to tell, be followed by another valid header — otherwise
            // a false sync in the previous payload's last bytes would swallow
            // real frames of this one. (An E-AC-3 access unit's dependent
            // substreams are folded in, so what follows is the next AU.)
            Some(&(0, f, _)) => {
                data.len() == f.len() || !matches!(F::parse(&data[f.len()..]), SyncParse::NotSync)
            }
            Some(_) => false,
            None => split.tail_start == 0,
        };
    let frames: Vec<PlannedFrame<'a>> = split
        .frames
        .iter()
        .map(|&(start, f, ref h)| {
            let (header_len, duration) = shape(h);
            PlannedFrame {
                data: F::payload(h, f, header_len),
                duration,
                from_carry: start < carry_len,
                start,
                end: start + f.len(),
            }
        })
        .collect();
    let tail = &data[split.tail_start..];
    let commences = frames.iter().any(|f| !f.from_carry)
        || (!tail.is_empty() && split.tail_start >= carry_len && F::tail_starts_new_unit(tail));
    AudioPlan {
        frames,
        tail,
        commences,
        carry_ok,
    }
}

/// Cut `data` (= carry ++ one PES payload; the first `carry_len` bytes are the
/// carry) into frames for the two families whose frames can straddle a PES
/// boundary. `None` for the other families.
fn plan_audio_frames<'a>(
    kind: &AudioKind,
    data: &'a [u8],
    carry_len: usize,
) -> Option<AudioPlan<'a>> {
    match kind {
        AudioKind::Aac => Some(plan_with::<AdtsSync>(data, carry_len, |h| {
            (
                adts_header_len(h),
                AAC_SAMPLES_PER_FRAME * (h.num_raw_data_blocks as u32 + 1),
            )
        })),
        AudioKind::MpegAudio { samples_per_frame } => {
            let spf = *samples_per_frame;
            Some(plan_with::<MpegAudioSync>(data, carry_len, move |_| {
                (0, spf)
            }))
        }
        AudioKind::Ac3 => Some(plan_with::<Ac3Sync>(data, carry_len, |_| {
            (0, AC3_SAMPLES_PER_SYNCFRAME)
        })),
        AudioKind::Eac3 => Some(plan_with::<Eac3Sync>(data, carry_len, |h| {
            (0, h.samples_per_frame())
        })),
        AudioKind::Dts => Some(plan_with::<DtsSync>(data, carry_len, |h| {
            (0, h.samples_per_frame)
        })),
    }
}

/// How many leading bytes of `data` merely finish the ADTS frame held in the
/// track's carry (0 when nothing is carried or the carry is not a frame start).
/// Those bytes are mid-frame and must not be scanned for a codec-config header.
fn carried_frame_remainder(live: &LiveTrack, data: &[u8]) -> usize {
    let LiveKind::Audio {
        kind: AudioKind::Aac,
        anchor,
        ..
    } = &live.kind
    else {
        return 0;
    };
    if anchor.carry.is_empty() {
        return 0;
    }
    let mut head = [0u8; ADTS_HEADER_SIZE];
    let have = anchor.carry.len().min(ADTS_HEADER_SIZE);
    head[..have].copy_from_slice(&anchor.carry[..have]);
    let need = ADTS_HEADER_SIZE - have;
    if need > data.len() {
        // Header still incomplete after this payload: all of it is mid-frame.
        return data.len();
    }
    head[have..].copy_from_slice(&data[..need]);
    match AdtsSync::parse(&head) {
        SyncParse::Frame(_, flen) => flen.saturating_sub(anchor.carry.len()).min(data.len()),
        _ => 0,
    }
}

/// Drop any held cross-PES carry on a live audio track (issue #1160): called
/// when bytes were lost between two payloads (continuity gap, dropped or
/// over-budget PES) or the codec config changed, so the held tail can no
/// longer be joined to what follows.
///
/// An E-AC-3 track holding back its final access unit (issue #1186) holds a
/// COMPLETE access unit received intact in an earlier PES alongside the
/// partial tail: only the tail is damaged, so the whole held access unit is
/// emitted ([`flush_audio_carry`]) before the carry is dropped.
fn clear_audio_carry(stream: &mut StreamState, events: &mut VecDeque<DemuxEvent>) {
    if let Some(TrackState::Live(LiveTrack {
        track_id,
        kind: LiveKind::Audio { kind, anchor, .. },
        ..
    })) = stream.track.as_mut()
    {
        if anchor.hold_final_au {
            flush_audio_carry(kind, anchor, *track_id, events);
        }
        anchor.carry.clear();
    }
}

/// Split one access unit into its coded frames and emit each immediately
/// (audio needs no lookahead: duration is intrinsic per split-frame family).
///
/// `anchor` carries the frame-exact running dts/pts cursor across access
/// units (issue B5, media plane step-2 fix wave 1): this access unit's base
/// track-tick position (`dts0`/`pts0`) is either that running cursor (the
/// steady state — no dependency on the lossy 90 kHz wire stamp at all) or a
/// fresh rescale of `dts_uw`/`pts_uw` on the very first access unit or a
/// genuine discontinuity (see [`AudioAnchor`]); every frame split out of
/// this AU then advances from that base by its own `elapsed` intrinsic
/// samples, exactly as before.
#[allow(clippy::too_many_arguments)]
fn emit_audio_au(
    kind: &AudioKind,
    sample_rate: u32,
    anchor: &mut AudioAnchor,
    au_data: &[u8],
    pts_uw: i128,
    dts_uw: i128,
    track_id: TrackId,
    events: &mut VecDeque<DemuxEvent>,
) {
    // Resolve this AU's track-tick base: reuse the running frame-exact
    // cursor in the steady state, or (re-)anchor from the wire clock when
    // there is no cursor yet or it has drifted beyond the discontinuity
    // threshold — a genuine gap, not the ±1-tick rounding noise the old
    // per-AU rescale mistook for one.
    // Snapshot the (all-`Copy`) seed up front, so every later "is there a
    // cursor?" decision reads the same value without needing a second
    // borrow-and-`expect` of `anchor.seed` to restate an invariant the
    // compiler cannot see.
    //
    // Cross-PES carry (issue #1160). For the MPEG-audio and ADTS families the
    // unfinished tail of the previous PES payload (`anchor.carry`) is joined in
    // front of this payload, so a frame straddling the boundary is recovered
    // whole. It takes the cursor position — which is exactly the time of the
    // PES in which it *started* (the PES's PTS, plus the intrinsic durations
    // of the frames before it) — and every later frame follows from it by the
    // usual frame-exact accumulation. This PES's own wire stamp refers to the
    // first frame that *commences* in it, i.e. one carried-frame duration
    // past the cursor, so the drift check below compares against
    // `cursor + lead`. When the wire stamp instead re-anchors the track, the
    // carried frame is placed `lead` before it. A carry that does not really
    // continue (a genuine splice: the new payload does not follow the held
    // tail with a valid header) is rejected by `plan_with`, never emitted.
    let carry = core::mem::take(&mut anchor.carry);
    let joined: Vec<u8>;
    let (data, carry_len): (&[u8], usize) = if carry.is_empty() {
        (au_data, 0)
    } else {
        joined = [carry.as_slice(), au_data].concat();
        (joined.as_slice(), carry.len())
    };
    let mut plan = plan_audio_frames(kind, data, carry_len);
    if carry_len > 0 && plan.as_ref().is_none_or(|p| !p.carry_ok) {
        // The carried bytes did not join cleanly (a false sync at the end of
        // the previous payload): resync on this payload alone.
        plan = plan_audio_frames(kind, au_data, 0);
    }
    scale_plan_durations(&mut plan, anchor.duration_scale);
    let lead_ticks: i64 = plan.as_ref().map_or(0, |p| {
        p.frames
            .iter()
            .filter(|f| f.from_carry)
            .map(|f| f.duration as i64)
            .sum()
    });
    let seed = anchor.seed;
    let mut fresh_anchor = match &seed {
        None => true,
        Some(seed) => {
            let expected_dts_uw = seed.anchor_dts_uw
                + ((seed.ticks_since_anchor + lead_ticks) as i128 * VIDEO_TIMESCALE as i128)
                    / sample_rate.max(1) as i128;
            (dts_uw - expected_dts_uw).abs() > audio_discontinuity_threshold_90k(sample_rate)
        }
    };
    // No frame commences in this payload (it only finishes the carried one):
    // its wire stamp, if any, does not describe a frame boundary, so it is
    // no evidence of a discontinuity.
    if seed.is_some() && plan.as_ref().is_some_and(|p| !p.commences) {
        fresh_anchor = false;
    }
    // A COMPLETE access unit held back from the previous PES (E-AC-3
    // dependent-substream hold-back, #1186) belongs to the OLD timeline: it was
    // received whole in that PES and only held for a possible dependent frame.
    // When this PES re-anchors, those frames are emitted at the old cursor
    // (where the hold-back left it) and only a frame that really straddles the
    // PES boundary is placed `lead` before the new wire stamp. (When the PES
    // continues the old timeline, cursor and wire agree and nothing differs.)
    let mut held_done = 0usize;
    let mut held_ticks = 0i64;
    if fresh_anchor
        && carry_len > 0
        && let (Some(seed), Some(p)) = (&seed, &plan)
    {
        for f in p
            .frames
            .iter()
            .take_while(|f| f.from_carry && f.end <= carry_len)
        {
            if let Some(payload) = &f.data {
                let mut sample = Sample::from_raw(
                    payload.to_vec(),
                    Some(seed.next_dts + held_ticks),
                    Some(seed.next_pts + held_ticks),
                    Some(f.duration),
                );
                if let Some(prov) = anchor.carry_provenance {
                    sample = sample.with_provenance(prov);
                }
                events.push_back(DemuxEvent::Sample { track_id, sample });
            }
            held_ticks += f.duration as i64;
            held_done += 1;
        }
    }
    let lead_ticks = lead_ticks - held_ticks;
    // Only signal a discontinuity when re-anchoring an ALREADY-seeded track
    // (the very first access unit establishes the anchor, it doesn't
    // "discontinue" from anything).
    if fresh_anchor && seed.is_some() {
        events.push_back(DemuxEvent::Discontinuity {
            track: Some(track_id),
            kind: DiscontinuityKind::TimelineReanchored,
            provenance: EventProvenance::default(),
        });
    }
    let (dts0, pts0) = match (fresh_anchor, &seed) {
        (false, Some(seed)) => (seed.next_dts, seed.next_pts),
        // (Re-)anchoring on the wire stamp: it describes the first frame that
        // commences in this PES, which is `lead_ticks` after a carried frame.
        _ => (
            rescale_to_track(dts_uw, sample_rate) - lead_ticks,
            rescale_to_track(pts_uw, sample_rate) - lead_ticks,
        ),
    };

    // A live observation of a dependent substream (one folded into its access
    // unit, ETSI TS 102 366 §E.1.3.1.2) turns the hold-back on even when the
    // announced `dec3` carries none: a track promoted from an unverified or
    // broken-chain first frame (a lossy capture) announces no dependent
    // substream, yet a dependent frame can still begin a later PES. The
    // `dec3` is not changed after announcement; this only stops later
    // dependent frames being orphaned. A dependent frame that began a PES
    // before any was observed is still lost (it has nothing to join).
    if matches!(kind, AudioKind::Eac3)
        && !anchor.hold_final_au
        && let Some(p) = &plan
        && p.frames.iter().any(|f| {
            matches!(
                Eac3Sync::parse(&data[f.start..f.end]),
                SyncParse::Frame(_, first_len) if first_len < f.end - f.start
            )
        })
    {
        anchor.hold_final_au = true;
    }

    let mut elapsed = 0u64;
    // E-AC-3 dependent-substream hold-back (issue #1186): the final whole
    // access unit may still gain a dependent substream from the next PES, so it
    // is carried instead of emitted — together with whatever partial tail
    // follows it, provided the two are contiguous and fit the carry bound.
    let held_from: Option<usize> = plan.as_ref().and_then(|p| {
        let last = p.frames.last()?;
        let tail_start = data.len() - p.tail.len();
        (matches!(kind, AudioKind::Eac3)
            && anchor.hold_final_au
            && last.data.is_some()
            && last.end == tail_start
            && data.len() - last.start <= AUDIO_CARRY_MAX_BYTES)
            .then_some(last.start)
    });
    // Every frame split out of this access unit came from the same PES packet,
    // so they share that PES header's raw 90 kHz wire stamps — that, not the
    // rescaled per-frame value, is what `Provenance` means (media plane step
    // 2c: the source container's original stamps, pre-unwrap).
    let au_provenance = ts_provenance(to_ticks(dts_uw), to_ticks(pts_uw));
    // Build one audio Sample at `elapsed` samples into this access unit:
    // `dts0`/`pts0` (the AU's resolved track-tick base) plus the per-frame
    // `elapsed` intrinsic samples (issue #556 semantics preserved exactly —
    // media plane step 2c stores them directly instead of discarding them
    // into a write-only `SourceTiming`; issue B5: `dts0`/`pts0` are now
    // frame-exact rather than re-derived from the lossy wire clock per AU).
    let audio_sample = |data: Vec<u8>, duration: u32, elapsed: u64| -> Sample {
        let dts = dts0 + elapsed as i64;
        let pts = pts0 + elapsed as i64;
        Sample::from_raw(data, Some(dts), Some(pts), Some(duration)).with_provenance(au_provenance)
    };
    match kind {
        // AAC (ISO/IEC 13818-7 §6.2): the CRC (if present) is stripped with the
        // header (C11, #1012) and duration scales with the raw data blocks the
        // frame carries — both folded into `plan_audio_frames`.
        AudioKind::Aac
        | AudioKind::MpegAudio { .. }
        | AudioKind::Ac3
        | AudioKind::Eac3
        | AudioKind::Dts => {
            if let Some(plan) = &plan {
                for (i, f) in plan.frames.iter().enumerate().skip(held_done) {
                    if held_from.is_some() && i + 1 == plan.frames.len() {
                        // Held back in `anchor.carry` below: neither emitted
                        // nor counted into the cursor.
                        break;
                    }
                    if let Some(payload) = &f.data {
                        events.push_back(DemuxEvent::Sample {
                            track_id,
                            sample: audio_sample(payload.to_vec(), f.duration, elapsed),
                        });
                    }
                    elapsed += f.duration as u64;
                }
            }
        }
    }

    // Advance the persistent anchor by this AU's total intrinsic duration so
    // the *next* AU continues the frame-exact cursor instead of re-deriving
    // it from the wire clock (issue B5). `anchor_dts_uw`/`anchor_pts_uw`/
    // `ticks_since_anchor` stay fixed at the point they were last
    // (re-)established (this AU's own values, on a fresh anchor; carried
    // forward otherwise) — they exist purely to predict the *next* AU's
    // expected wire position for drift detection, never to derive a dts/pts.
    let (anchor_dts_uw, anchor_pts_uw, ticks_since_anchor) = match (fresh_anchor, &seed) {
        (false, Some(seed)) => (
            seed.anchor_dts_uw,
            seed.anchor_pts_uw,
            seed.ticks_since_anchor,
        ),
        // The wire anchor sits `lead_ticks` past the cursor's start (the
        // carried frame precedes it), so the cursor is already that far on.
        _ => (dts_uw, pts_uw, -lead_ticks),
    };
    anchor.seed = Some(AudioAnchorSeed {
        next_dts: dts0 + elapsed as i64,
        next_pts: pts0 + elapsed as i64,
        anchor_dts_uw,
        anchor_pts_uw,
        ticks_since_anchor: ticks_since_anchor + elapsed as i64,
    });
    // Hold the unfinished tail for the next PES of this PID — never more than
    // one frame's worth (see [`AUDIO_CARRY_MAX_BYTES`]).
    if let Some(from) = held_from {
        anchor.carry = data[from..].to_vec();
        anchor.carry_provenance = Some(au_provenance);
    } else if let Some(plan) = &plan
        && plan.tail.len() <= AUDIO_CARRY_MAX_BYTES
    {
        anchor.carry = plan.tail.to_vec();
        anchor.carry_provenance = Some(au_provenance);
    }
}

/// Emit the whole frames still held in a live audio track's carry at end of
/// input (issue #1186): the E-AC-3 final access unit held back for a possible
/// dependent substream (see [`AudioAnchor::hold_final_au`]). A partial frame
/// tail yields no whole frame and is dropped, as before.
fn flush_audio_carry(
    kind: &AudioKind,
    anchor: &mut AudioAnchor,
    track_id: TrackId,
    events: &mut VecDeque<DemuxEvent>,
) {
    let carry = core::mem::take(&mut anchor.carry);
    let (Some(seed), false) = (anchor.seed, carry.is_empty()) else {
        return;
    };
    let mut plan = plan_audio_frames(kind, &carry, 0);
    scale_plan_durations(&mut plan, anchor.duration_scale);
    let Some(plan) = plan else {
        return;
    };
    let mut elapsed = 0i64;
    for f in &plan.frames {
        if let Some(payload) = &f.data {
            let mut sample = Sample::from_raw(
                payload.to_vec(),
                Some(seed.next_dts + elapsed),
                Some(seed.next_pts + elapsed),
                Some(f.duration),
            );
            if let Some(p) = anchor.carry_provenance {
                sample = sample.with_provenance(p);
            }
            events.push_back(DemuxEvent::Sample { track_id, sample });
        }
        elapsed += f.duration as i64;
    }
    // Advance the cursor past what was emitted: on a mid-stream flush (the
    // carry is dropped after a loss) the next access unit must not be stamped
    // on top of the one just flushed.
    anchor.seed = Some(AudioAnchorSeed {
        next_dts: seed.next_dts + elapsed,
        next_pts: seed.next_pts + elapsed,
        ticks_since_anchor: seed.ticks_since_anchor + elapsed,
        ..seed
    });
}

/// Does this E-AC-3 config carry dependent substreams (a `dec3` substream entry
/// with `num_dep_sub > 0`, ETSI TS 102 366 §F.6.2.12, or a `chan_loc` built
/// from a dependent frame's `chanmap`, §F.6.2.13)? Only then can a dependent
/// frame begin a PES, so only then is the final access unit held back (see
/// [`AudioAnchor::hold_final_au`]). `num_dep_sub` alone is not enough: it is
/// the dependent frame's `substreamid`, which is 0 for the first one.
fn eac3_has_dependent_substreams(config: &CodecConfig) -> bool {
    matches!(config, CodecConfig::Eac3 { config, .. }
        if config.substreams.iter().any(|s| s.num_dep_sub > 0 || s.chan_loc.is_some()))
}

/// Apply one access unit to an already-live track, emitting whatever
/// [`DemuxEvent::Sample`]s it resolves.
///
/// `provenance` is the track's PID sidecar, stamped on any
/// [`DemuxEvent::DisplayChanged`] raised for this access unit. `display` is
/// the display state decided for it by [`LiveTrack::display`] (after that
/// tracker has advanced), which its `Sample` carries.
fn push_live_au(
    live: &mut LiveTrack,
    data: &[u8],
    pts_uw: i128,
    dts_uw: i128,
    provenance: EventProvenance,
    display: Option<Arc<DisplayInfo>>,
    events: &mut VecDeque<DemuxEvent>,
) {
    let track_id = live.track_id;
    match &mut live.kind {
        LiveKind::Video {
            pending,
            last_duration,
            codec,
            paff,
        } => {
            use crate::slice_header::AvcPicture;
            // The events this access unit raises travel with its own slot and
            // are pushed immediately before its Sample (design §6.5). A PAFF
            // second field merges into the first field's slot below, so its
            // events are carried over into that slot.
            let raised = PendingDisplayEvents {
                config: live.pending_config.take(),
                display: live.display.take(),
            };
            let (bytes, is_sync) = video_sample_bytes(*codec, data);
            let mut this_field = None;
            if *codec == VideoCodec::H264
                && let AvcPicture::Field(second) = paff.params.classify_au(data)
            {
                if let (Some(first), Some(p)) = (paff.first_field, pending.as_mut())
                    && first.pairs_with(&second)
                    && (0..=MAX_FIELD_PAIR_DTS_TICKS).contains(&(dts_uw - p.dts_uw))
                {
                    // Second field of a complementary pair: one sample, the
                    // first field's timestamps; drop its AUD (one AU = one AUD).
                    let raised = PendingDisplayEvents {
                        config: p.pending_events.config.take().or(raised.config),
                        display: p.pending_events.display.take().or(raised.display),
                    };
                    p.data
                        .extend_from_slice(&annexb_to_length_prefixed_no_aud(data));
                    p.pending_events = raised;
                    paff.first_field = None;
                    return;
                }
                this_field = Some(second);
            }
            paff.first_field = this_field;
            advance_one_behind(
                pending,
                last_duration,
                bytes,
                is_sync,
                pts_uw,
                dts_uw,
                false,
                track_id,
                provenance,
                display,
                raised,
                events,
            );
        }
        LiveKind::Data {
            pending,
            last_duration,
        } => {
            advance_one_behind(
                pending,
                last_duration,
                data.to_vec(),
                true,
                pts_uw,
                dts_uw,
                true,
                track_id,
                provenance,
                display,
                PendingDisplayEvents::default(),
                events,
            );
        }
        LiveKind::Audio {
            sample_rate,
            kind,
            anchor,
        } => {
            // Sticky: the announced config says whether dependents exist, and
            // `emit_audio_au` also sets it on seeing one (a track promoted from
            // an unverified first frame announces no dependent substream).
            anchor.hold_final_au |= eac3_has_dependent_substreams(&live.config);
            emit_audio_au(
                kind,
                *sample_rate,
                anchor,
                data,
                pts_uw,
                dts_uw,
                track_id,
                events,
            );
        }
        LiveKind::MpegH {
            pending,
            last_duration,
        } => {
            let is_sync = find_mpegh3da_config(data).is_some();
            advance_one_behind(
                pending,
                last_duration,
                data.to_vec(),
                is_sync,
                pts_uw,
                dts_uw,
                true,
                track_id,
                provenance,
                display,
                PendingDisplayEvents::default(),
                events,
            );
        }
        LiveKind::Section => {
            // Sections carry no timestamp at all (`pts_uw`/`dts_uw` are dummy
            // zeros from `on_completed_section`, never read here) — emit
            // immediately, no lookahead, and never fabricate a dts/pts/duration.
            events.push_back(DemuxEvent::Sample {
                track_id,
                sample: Sample::from_raw(data.to_vec(), None, None, None),
            });
        }
    }
}

/// Track a live track's in-band codec-configuration **content**, access unit by
/// access unit, returning the new config when that content actually changes
/// (r04-W51).
///
/// "The content a decoder configuration would contain" — never the framing, and
/// never a single access unit's view of it:
///
/// * **AVC/HEVC**: the parameter sets themselves. A probe over *one* access
///   unit cannot see an SPS that arrived in an earlier one, and encoders
///   routinely split SPS and PPS across access units (and put both in the
///   first). Each set is therefore remembered as it appears — VPS, SPS and PPS
///   tracked separately — and the event fires only when one of them actually
///   changes value, or one goes from absent to present. That also makes an
///   identical repeat (the common case: the same SPS+PPS in every keyframe)
///   emit nothing.
/// * **AAC**: the `AudioSpecificConfig` the ADTS header implies — its
///   `audioObjectType`, `samplingFrequencyIndex` and `channelConfiguration`
///   only (ISO/IEC 14496-3 §1.6.2.1). The *raw* ADTS header must never be
///   compared: it also carries the 13-bit `aac_frame_length`, which differs on
///   every single frame, so comparing it reported a config change for
///   practically every AAC access unit.
/// * **Anything else** (no in-band config): `None` — MPEG-2 video's config is
///   only geometry and opaque data's comes from the PMT, so a change cannot be
///   seen here. Those keep their original config, exactly as documented.
fn reprobe_if_config_changed(
    stream: &mut StreamState,
    live: &mut LiveTrack,
    data: &[u8],
) -> Option<(CodecConfig, u32)> {
    let changed = match stream.codec {
        Codec::H264 | Codec::Hevc => {
            observe_parameter_sets(stream.codec, data, &mut live.parameter_sets)
        }
        Codec::Aac => {
            let (_, hdr) = find_adts_sync(data)?;
            // Serializing an ADTS-derived config cannot fail (no `trailing`,
            // buffer sized by `serialized_len`); degrade to "no observation"
            // rather than carry an `unwrap` in library code.
            let asc = AudioSpecificConfig::from_adts_header(&hdr)
                .try_to_bytes()
                .ok()?;
            if live.config_header.as_deref() == Some(asc.as_slice()) {
                false
            } else {
                live.config_header = Some(asc);
                true
            }
        }
        _ => return None,
    };
    if !changed {
        return None;
    }
    // A fresh probe recovers the new config with the same code path the first
    // one used. For AVC/HEVC the probe needs the parameter sets, which may be
    // spread over several access units, so it is fed the accumulated set: the
    // probe's own accumulation is seeded from the track's, and this access
    // unit's copies are appended.
    let descriptors = stream.descriptors.clone();
    let mut probe = initial_probe(stream.codec);
    seed_probe_parameter_sets(&mut probe, &live.parameter_sets);
    let recovered = finalize_probe(stream.codec, &descriptors, &mut probe, data);
    let (config, timescale, _kind) = recovered?;
    Some((config, timescale))
}

/// The [`NalCodec`] of a video [`Codec`] whose parameter sets are validated.
fn nal_codec_of(codec: Codec) -> NalCodec {
    match codec {
        Codec::Hevc => NalCodec::Hevc,
        _ => NalCodec::Avc,
    }
}

/// Count the parameter-set NALs in `data` that look like one (header type
/// SPS/PPS, or VPS/SPS/PPS for HEVC) but fail [`parameter_set_is_valid`].
fn count_invalid_parameter_sets(codec: Codec, data: &[u8]) -> usize {
    let mut n = 0;
    match codec {
        Codec::H264 => {
            for nal in iter_annexb_nals(data) {
                let kind = match nal[0] & H264_NAL_TYPE_MASK {
                    H264_NAL_SPS => ParamKind::Sps,
                    H264_NAL_PPS => ParamKind::Pps,
                    _ => continue,
                };
                n += usize::from(!parameter_set_is_valid(nal_codec_of(codec), kind, nal));
            }
        }
        Codec::Hevc => {
            for nal in iter_annexb_nals(data) {
                let kind = match nal_unit_type(NalCodec::Hevc, nal) {
                    Some(H265_NAL_VPS) => ParamKind::Vps,
                    Some(H265_NAL_SPS) => ParamKind::Sps,
                    Some(H265_NAL_PPS) => ParamKind::Pps,
                    _ => continue,
                };
                n += usize::from(!parameter_set_is_valid(nal_codec_of(codec), kind, nal));
            }
        }
        _ => {}
    }
    n
}

/// The parameter sets a track has seen, each remembered separately so an
/// SPS/PPS split across access units still compares as a whole (r04-W51).
#[derive(Default, Clone)]
struct ParameterSets {
    vps: ParamSlot,
    sps: ParamSlot,
    pps: ParamSlot,
}

/// Upper bound on distinct PPS ids remembered. The id spaces are small
/// (64 HEVC / 256 H.264), so a real stream never reaches it; it only bounds a
/// hostile one.
const MAX_SEEN_PARAMETER_SETS: usize = 64;

/// One parameter-set type's state: the NAL the track's config is built from
/// (`current`) and, for PPS, the content last announced for each id (`by_id`).
///
/// Encoders routinely carry several PPS ids at once — orf1 cycles three
/// (issue #1166) — and re-send them in a rotating order. A single "last seen"
/// slot compared against each arrival reads every rotation step as a change
/// (A, B, A, B, ...). The PPS is therefore keyed by its
/// `pic_parameter_set_id` (the first syntax element of H.264 §7.3.2.2 and
/// H.265 §7.3.2.3.1): re-sending an id with the **same** bytes is never a
/// change, however the ids interleave; an id announced for the first time, or
/// re-announced with **different** bytes, is. The latter makes A -> B -> A on
/// one id (an encoder switching settings and back) a change at *every* switch
/// — a "never seen before" test misses the return to an already-seen A
/// (issue #1186). SPS/VPS do not rotate and use [`ParamSlot::record_current`].
#[derive(Default, Clone)]
struct ParamSlot {
    current: Option<Vec<u8>>,
    by_id: Vec<(u64, Vec<u8>)>,
}

impl ParamSlot {
    /// Fold in one NAL of a type that does **not** rotate (SPS, VPS): any
    /// difference from the current set is a change, so switching A -> B -> A
    /// (a resolution change and back) is reported at every switch.
    fn record_current(&mut self, bytes: &[u8]) -> bool {
        if self.current.as_deref() == Some(bytes) {
            return false;
        }
        self.current = Some(bytes.to_vec());
        true
    }

    /// Fold in one PPS announced for `id`; `true` if that id is new or its
    /// bytes changed (it then becomes the `current` set the config is built
    /// from).
    fn record_pps(&mut self, id: u64, bytes: &[u8]) -> bool {
        match self.by_id.iter_mut().find(|(i, _)| *i == id) {
            Some((_, known)) if known.as_slice() == bytes => return false,
            Some((_, known)) => *known = bytes.to_vec(),
            None => {
                if self.by_id.len() >= MAX_SEEN_PARAMETER_SETS {
                    self.by_id.remove(0);
                }
                self.by_id.push((id, bytes.to_vec()));
            }
        }
        self.current = Some(bytes.to_vec());
        true
    }
}

/// `pic_parameter_set_id` of a PPS NAL (`ue(v)`, the first element of the RBSP
/// after the NAL header: 1 byte for H.264, 2 for H.265). `u64::MAX` when it
/// does not decode, so a damaged PPS still compares by its bytes as one slot.
fn pps_id(codec: Codec, nal: &[u8]) -> u64 {
    let header_len = match codec {
        Codec::Hevc => 2,
        _ => 1,
    };
    nal.get(header_len..)
        .and_then(|body| crate::bitreader::BitReader::with_unescape(body, "pps id").ok())
        .and_then(|mut r| r.read_ue("pic_parameter_set_id").ok())
        .unwrap_or(u64::MAX)
}

impl ParameterSets {
    /// Fold in `data`'s parameter sets, reporting whether any of them
    /// **changed**: a NAL whose bytes this track has never carried before
    /// (a set that was absent and is now present, a new id, or a replaced
    /// one). A NAL already seen — which is what an encoder repeating its
    /// headers on every keyframe, in any rotation of its PPS/SPS ids, produces
    /// — is not a change.
    fn observe(&mut self, codec: Codec, data: &[u8]) -> bool {
        let mut changed = false;
        match codec {
            Codec::H264 => {
                for nal in iter_annexb_nals(data) {
                    match nal[0] & H264_NAL_TYPE_MASK {
                        H264_NAL_SPS
                            if parameter_set_is_valid(nal_codec_of(codec), ParamKind::Sps, nal) =>
                        {
                            changed |= self.sps.record_current(nal)
                        }
                        H264_NAL_PPS
                            if parameter_set_is_valid(nal_codec_of(codec), ParamKind::Pps, nal) =>
                        {
                            changed |= self.pps.record_pps(pps_id(codec, nal), nal)
                        }
                        _ => {}
                    }
                }
            }
            Codec::Hevc => {
                for nal in iter_annexb_nals(data) {
                    match nal_unit_type(NalCodec::Hevc, nal) {
                        Some(H265_NAL_VPS)
                            if parameter_set_is_valid(nal_codec_of(codec), ParamKind::Vps, nal) =>
                        {
                            changed |= self.vps.record_current(nal)
                        }
                        Some(H265_NAL_SPS)
                            if parameter_set_is_valid(nal_codec_of(codec), ParamKind::Sps, nal) =>
                        {
                            changed |= self.sps.record_current(nal)
                        }
                        Some(H265_NAL_PPS)
                            if parameter_set_is_valid(nal_codec_of(codec), ParamKind::Pps, nal) =>
                        {
                            changed |= self.pps.record_pps(pps_id(codec, nal), nal)
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
        changed
    }
}

/// Record `data`'s parameter sets on `sets`, returning whether any changed.
fn observe_parameter_sets(codec: Codec, data: &[u8], sets: &mut ParameterSets) -> bool {
    sets.observe(codec, data)
}

/// Harvest parameter sets from a damaged H.264/H.265 access unit: count the
/// invalid ones as `InputDegraded` and, while the track is still probing,
/// resolve its config from the valid sets so a lossy start does not wait for
/// the next access unit (issue G1). Damaged slice data is never delivered.
fn harvest_damaged_au(
    stream: &mut StreamState,
    pid: Pid,
    data: &[u8],
    events: &mut VecDeque<DemuxEvent>,
) {
    if !matches!(stream.codec, Codec::H264 | Codec::Hevc) {
        return;
    }
    // A parameter set from a damaged access unit may only seed a track
    // that is still at its very first access unit: a stray damaged fragment
    // later in a stream must not promote a phantom track.
    if stream.probe_aus > 0 || stream.backlog_bytes > 0 {
        return;
    }
    let Ok(pes) = PesPacket::parse(data) else {
        return;
    };
    if pes.payload.is_empty() {
        return;
    }
    let data = pes.payload;

    let track_id = match &stream.track {
        Some(TrackState::Live(live)) => Some(live.track_id),
        _ => None,
    };
    let _ = track_id;
    for _ in 0..count_invalid_parameter_sets(stream.codec, data) {
        events.push_back(DemuxEvent::InputDegraded {
            track: track_id,
            kind: InputDegradation::InvalidParameterSet,
            provenance: EventProvenance {
                pid: Some(pid),
                packet_index: None,
                program_number: None,
            },
        });
    }
    // Only probing tracks benefit; live tracks are left untouched.
    if !matches!(stream.track, Some(TrackState::Probing { .. })) {
        return;
    }

    let descriptors = stream.descriptors.clone();
    let Some(track) = stream.track.take() else {
        stream.track = None;
        return;
    };
    let new_track = match track {
        TrackState::Probing { mut probe, backlog } => {
            let resolved = finalize_probe(stream.codec, &descriptors, &mut probe, data);
            match resolved {
                Some((config, timescale, kind)) => {
                    stream.damaged_promotion = true;
                    TrackState::Parked {
                        config,
                        timescale,
                        kind,
                        backlog,
                    }
                }
                None => TrackState::Probing { probe, backlog },
            }
        }
        other => other,
    };
    stream.track = Some(new_track);
}

/// Seed a fresh [`ConfigProbe`] with parameter sets already known for the
/// track, so a re-probe of a single access unit is not blind to an SPS that
/// arrived in an earlier one (r04-W51).
fn seed_probe_parameter_sets(probe: &mut ConfigProbe, sets: &ParameterSets) {
    match probe {
        ConfigProbe::H264 { sps, pps } => {
            sps.clone_from(&sets.sps.current);
            pps.clone_from(&sets.pps.current);
        }
        ConfigProbe::Hevc { vps, sps, pps, .. } => {
            vps.clone_from(&sets.vps.current);
            sps.clone_from(&sets.sps.current);
            pps.clone_from(&sets.pps.current);
        }
        _ => {}
    }
}

/// Feed the newest access unit into a probing [`ConfigProbe`], returning the
/// finished config the moment it becomes recoverable. The caller owns
/// transferring the PID's backlog into [`TrackState::Parked`].
///
/// **Only `latest` is ever scanned.** Every probe below used to walk the whole
/// backlog from the start (`backlog.iter().find_map(..)`) on *every* incoming
/// access unit, with byte-by-byte sync scans inside (r04-W47): a PID whose
/// config never resolves — garbage payload, or an ADTS `sampling_frequency_
/// index` of 13/14 that [`sfi_to_hz`] rejects — grew toward
/// [`MAX_PROBE_BACKLOG_BYTES`] while re-scanning it each access unit, costing
/// O(n²) byte probes per PID (≈4 × 10⁹ on a 2 000-PES PID). Scanning only the
/// newest access unit is both what the H.264/HEVC arms already did and
/// sufficient: a codec's config header is repeated in-band often enough that
/// one access unit is representative (a parameter set / frame header / MHAS
/// config arrives within the first access unit or two in any real stream).
fn finalize_probe(
    codec: Codec,
    descriptors: &[u8],
    probe: &mut ConfigProbe,
    latest: &[u8],
) -> Option<(CodecConfig, u32, LiveKind)> {
    // One pass over the newest access unit — the thing the r04-W47 bound is
    // about. Counted here so the H.264/HEVC arms, whose NAL walk has no
    // byte-by-byte sync scanner to count, are covered too.
    record_probe_pass();
    match probe {
        ConfigProbe::Data => {
            let Codec::Data(stream_type) = codec else {
                // Probe/codec mismatch. Unreachable by construction today: a
                // PMT version change that reclassifies a PID's `stream_type`
                // tears the PID down and re-registers it
                // (`StreamingTsDemux::apply_pmt_diff`), which rebuilds the
                // `ConfigProbe` — and the `Carrier` — for the *new* codec,
                // rather than writing `stream.codec` in place under a probe
                // built for the old one.
                //
                // It is not asserted, though. This is a
                // `#![forbid(unsafe_code)]` library parsing untrusted remote
                // broadcast input, so a broken invariant must degrade, never
                // abort the host process: returning `None` simply leaves the
                // PID unresolved, and the existing abandonment paths conclude
                // it — `MAX_PROBE_BACKLOG_BYTES` while running, or `finish()`'s
                // `TrackAbandoned { reason: AbandonReason::ConfigUnrecoverable }`
                // at end of input.
                return None;
            };
            let carriage = data_carriage(stream_type);
            let kind = match carriage {
                DataCarriage::Pes => LiveKind::Data {
                    pending: None,
                    last_duration: 0,
                },
                DataCarriage::Sections => LiveKind::Section,
            };
            Some((
                CodecConfig::Data {
                    stream_type,
                    descriptors: descriptors.to_vec(),
                    carriage,
                },
                VIDEO_TIMESCALE,
                kind,
            ))
        }
        ConfigProbe::H264 { sps, pps } => {
            // Accumulate across access units: a parameter set is often split
            // over one access unit per NAL (an encoder emits SPS and PPS in
            // separate PES packets), and since r04-W47 only the newest access
            // unit is scanned — so the field that held the SPS two access
            // units ago is what carries it forward.
            for nal in iter_annexb_nals(latest) {
                match nal[0] & H264_NAL_TYPE_MASK {
                    H264_NAL_SPS
                        if sps.is_none()
                            && parameter_set_is_valid(nal_codec_of(codec), ParamKind::Sps, nal) =>
                    {
                        *sps = Some(nal.to_vec())
                    }
                    H264_NAL_PPS
                        if pps.is_none()
                            && parameter_set_is_valid(nal_codec_of(codec), ParamKind::Pps, nal) =>
                    {
                        *pps = Some(nal.to_vec())
                    }
                    _ => {}
                }
            }
            let (sps_bytes, pps_bytes) = (sps.as_ref()?, pps.as_ref()?);
            if sps_bytes.len() < 4 {
                return None;
            }
            // Coded dimensions + high-profile chroma/bit-depth from the SPS
            // (ISO/IEC 14496-10 §7.3.2.1.1) — the TS in-band parameter set
            // carries them (0/None if undecodable).
            let info = crate::sps::decode_avc_sps(sps_bytes).ok();
            let (width, height) = info
                .as_ref()
                .map(|i| {
                    (
                        i.width.min(u16::MAX as u32) as u16,
                        i.height.min(u16::MAX as u32) as u16,
                    )
                })
                .unwrap_or((0, 0));
            // The avcC high-profile extension (chroma_format_idc + bit depths)
            // exists only for the High-family profiles that carry it
            // (ISO/IEC 14496-15 §5.3.3.1). Populate it from the SPS for those —
            // previously hardcoded None, so a High 10/4:2:2/4:4:4 TS lost its
            // chroma/bit-depth in the recovered avcC (#563 flagged; #582 owns
            // this file). Gate matches the serializer's emission set via the
            // shared `sps::is_high_profile` source of truth.
            let ext = info
                .as_ref()
                .filter(|i| crate::sps::is_high_profile(i.profile_idc));
            let record = AVCDecoderConfigurationRecord {
                configuration_version: 1,
                // profile_idc / constraint_flags / level_idc live at SPS bytes
                // 1..=3 (after the 1-byte NAL header) — ISO/IEC 14496-15 §5.3.3.1.
                profile_indication: sps_bytes[1],
                profile_compatibility: sps_bytes[2],
                level_indication: sps_bytes[3],
                length_size_minus_one: NAL_LENGTH_SIZE_MINUS_ONE,
                sps: alloc::vec![AvcSps(sps_bytes.clone())],
                pps: alloc::vec![AvcPps(pps_bytes.clone())],
                chroma_format: ext.map(|i| i.chroma_format_idc),
                bit_depth_luma_minus8: ext.map(|i| i.bit_depth_luma.saturating_sub(8)),
                bit_depth_chroma_minus8: ext.map(|i| i.bit_depth_chroma.saturating_sub(8)),
                sps_ext: alloc::vec![],
            };
            Some((
                CodecConfig::Avc {
                    config: AVCConfigurationBox::new(record),
                    width,
                    height,
                },
                VIDEO_TIMESCALE,
                LiveKind::Video {
                    pending: None,
                    last_duration: 0,
                    codec: VideoCodec::H264,
                    paff: PaffPairing::default(),
                },
            ))
        }
        ConfigProbe::Hevc {
            vps,
            sps,
            pps,
            hdr_sei,
        } => {
            // Accumulated across access units, exactly like the H.264 arm
            // above (r04-W47: only the newest access unit is scanned).
            for nal in iter_annexb_nals(latest) {
                match nal_unit_type(NalCodec::Hevc, nal) {
                    Some(H265_NAL_VPS)
                        if vps.is_none()
                            && parameter_set_is_valid(nal_codec_of(codec), ParamKind::Vps, nal) =>
                    {
                        *vps = Some(nal.to_vec())
                    }
                    Some(H265_NAL_SPS)
                        if sps.is_none()
                            && parameter_set_is_valid(nal_codec_of(codec), ParamKind::Sps, nal) =>
                    {
                        *sps = Some(nal.to_vec())
                    }
                    Some(H265_NAL_PPS)
                        if pps.is_none()
                            && parameter_set_is_valid(nal_codec_of(codec), ParamKind::Pps, nal) =>
                    {
                        *pps = Some(nal.to_vec())
                    }
                    Some(HEVC_PREFIX_SEI_NUT) => {
                        let mut have = HdrStaticMetadata::default();
                        for kept in hdr_sei.iter() {
                            have.absorb_hevc_sei_nal(kept);
                        }
                        let mut with = have;
                        with.absorb_hevc_sei_nal(nal);
                        if with != have
                            && let Ok(Some(declarative)) = with.to_hevc_declarative_sei_nal()
                        {
                            hdr_sei.clear();
                            hdr_sei.push(declarative);
                        }
                    }
                    _ => {}
                }
            }
            // Decode the SPS for geometry + profile/tier/level/chroma/bit-depth.
            // Without it the hvcC PTL fields cannot be filled — stay probing
            // (never fatal — issue #467). VPS/PPS are optional: whichever have
            // been seen by the time SPS resolves are included (real encoders
            // always bundle VPS+SPS+PPS in the same access unit).
            let sps_bytes = sps.as_ref()?;
            let info = crate::sps::decode_hevc_sps(sps_bytes).ok()?;
            let width = info.width.min(u16::MAX as u32) as u16;
            let height = info.height.min(u16::MAX as u32) as u16;

            let mut arrays: Vec<HevcNalArray> = Vec::new();
            if let Some(vps_nal) = vps.clone() {
                arrays.push(HevcNalArray::new(
                    true,
                    H265_NAL_VPS,
                    alloc::vec![HevcNalUnit::new(vps_nal)],
                ));
            }
            arrays.push(HevcNalArray::new(
                true,
                H265_NAL_SPS,
                alloc::vec![HevcNalUnit::new(sps_bytes.clone())],
            ));
            if let Some(pps_nal) = pps.clone() {
                arrays.push(HevcNalArray::new(
                    true,
                    H265_NAL_PPS,
                    alloc::vec![HevcNalUnit::new(pps_nal)],
                ));
            }
            if !hdr_sei.is_empty() {
                arrays.push(HevcNalArray::new(
                    false,
                    HEVC_PREFIX_SEI_NUT,
                    hdr_sei.iter().cloned().map(HevcNalUnit::new).collect(),
                ));
            }
            let record = HEVCDecoderConfigurationRecord {
                configuration_version: HVCC_CONFIGURATION_VERSION,
                general_profile_space: info.general_profile_space,
                general_tier_flag: info.general_tier_flag,
                general_profile_idc: info.general_profile_idc,
                general_profile_compatibility_flags: info.general_profile_compatibility_flags,
                general_constraint_indicator_flags: info.general_constraint_indicator_flags,
                general_level_idc: info.general_level_idc,
                min_spatial_segmentation_idc: HVCC_MIN_SPATIAL_SEGMENTATION_UNSPEC,
                parallelism_type: HVCC_PARALLELISM_TYPE_UNKNOWN,
                chroma_format_idc: info.chroma_format_idc,
                // hvcC stores bit_depth_{luma,chroma}_minus8; the SPS decode
                // returns the absolute bit depth (minus8 + 8), so subtract 8
                // back out (saturating — an ES reporting < 8 would be malformed).
                bit_depth_luma_minus8: info.bit_depth_luma.saturating_sub(8),
                bit_depth_chroma_minus8: info.bit_depth_chroma.saturating_sub(8),
                avg_frame_rate: HVCC_AVG_FRAME_RATE_UNSPEC,
                constant_frame_rate: HVCC_CONSTANT_FRAME_RATE_UNSPEC,
                num_temporal_layers: HVCC_NUM_TEMPORAL_LAYERS,
                temporal_id_nested: false,
                length_size_minus_one: NAL_LENGTH_SIZE_MINUS_ONE,
                arrays,
            };
            Some((
                CodecConfig::Hevc {
                    config: HEVCConfigurationBox::new(record),
                    width,
                    height,
                },
                VIDEO_TIMESCALE,
                LiveKind::Video {
                    pending: None,
                    last_duration: 0,
                    codec: VideoCodec::Hevc,
                    paff: PaffPairing::default(),
                },
            ))
        }
        ConfigProbe::Mpeg2Video => {
            // Geometry from the first sequence_header() seen in the stream.
            let seq = Mpeg2SeqHeader::find(latest).ok()?;
            let esds = EsdsBox::new(ESDescriptor::new(
                ESDS_VIDEO_ES_ID,
                0,
                Some(DecoderConfigDescriptor::new(
                    OTI_MPEG2_VIDEO_MAIN,
                    STREAM_TYPE_VISUAL,
                    false,
                    0,
                    0,
                    0,
                    None,
                )),
                Some(SLConfigDescriptor::predefined_two()),
            ));
            Some((
                CodecConfig::Mpeg2Video {
                    esds,
                    width: seq.width,
                    height: seq.height,
                },
                VIDEO_TIMESCALE,
                LiveKind::Video {
                    pending: None,
                    last_duration: 0,
                    codec: VideoCodec::Mpeg2,
                    paff: PaffPairing::default(),
                },
            ))
        }
        ConfigProbe::MpegAudio { is_mpeg2 } => {
            // Resync within the newest buffered PES payload (issue #638) -- a
            // real broadcast payload is not guaranteed to start on a frame
            // sync.
            let (_, first) = find_mpeg_audio_sync(latest)?;
            let sample_rate = first.sample_rate;
            let channel_count = first.channels;
            let samples_per_frame = first.samples_per_frame;
            let oti = if *is_mpeg2 {
                OTI_MPEG2_AUDIO
            } else {
                OTI_MPEG1_AUDIO
            };
            let esds = EsdsBox::new(ESDescriptor::new(
                ESDS_ES_ID,
                0,
                // maxBitrate/avgBitrate (ISO/IEC 14496-1 §7.2.6.6.1) from the
                // first frame header's `bitrate_index` (constant-bitrate MPEG
                // audio: both equal the nominal rate), so
                // `CodecConfig::nominal_bitrate` needs no re-parse (#1162 R2).
                Some(DecoderConfigDescriptor::new(
                    oti,
                    STREAM_TYPE_AUDIO,
                    false,
                    0,
                    first.bitrate_bps,
                    first.bitrate_bps,
                    None,
                )),
                Some(SLConfigDescriptor::predefined_two()),
            ));
            Some((
                CodecConfig::MpegAudio {
                    esds,
                    layer: first.layer,
                    channel_count,
                    sample_rate,
                    sample_size: AUDIO_SAMPLE_SIZE_BITS,
                },
                sample_rate,
                LiveKind::Audio {
                    sample_rate,
                    kind: AudioKind::MpegAudio { samples_per_frame },
                    anchor: AudioAnchor::default(),
                },
            ))
        }
        ConfigProbe::Aac => {
            // Resync within the newest buffered PES payload (issue #638) -- a
            // real broadcast payload is not guaranteed to start on a frame
            // sync.
            let (_, first_hdr) = find_adts_sync(latest)?;
            let asc = AudioSpecificConfig::from_adts_header(&first_hdr);
            let sample_rate =
                SamplingFrequencyIndex::from(first_hdr.sampling_frequency_index).table_hz()?;
            // ISO/IEC 14496-3 Table 1.19: `channel_configuration` is a
            // configuration *index*, not a count — 7 means eight channels
            // (7.1), and 0 means the mapping is carried in-band by a
            // `program_config_element` in the raw data stream, so no count is
            // derivable from the header at all. Using the raw field as the
            // count reported 7.1 as 7 channels and a PCE-signalled stream as
            // zero (r04-W51, extending W16).
            let channel_count = crate::flv::aac_channel_count(&asc);
            let esds = EsdsBox::new(ESDescriptor::new(
                ESDS_ES_ID,
                0,
                Some(DecoderConfigDescriptor::new(
                    OTI_MPEG4_AUDIO,
                    STREAM_TYPE_AUDIO,
                    false,
                    0,
                    0,
                    0,
                    Some(DecoderSpecificInfo::new(asc.try_to_bytes().ok()?)),
                )),
                Some(SLConfigDescriptor::predefined_two()),
            ));
            let config = CodecConfig::Aac {
                esds,
                channel_count,
                sample_rate,
                sample_size: AUDIO_SAMPLE_SIZE_BITS,
            };
            let config = match crate::AudioMetadata::from_es_info(descriptors).he_aac {
                Some(profile) => config
                    .clone()
                    .with_explicit_he_aac(profile)
                    .unwrap_or(config),
                None => config,
            };
            let timescale = config.audio_sample_rate().unwrap_or(sample_rate);
            Some((
                config,
                timescale,
                LiveKind::Audio {
                    sample_rate: timescale,
                    kind: AudioKind::Aac,
                    anchor: AudioAnchor {
                        duration_scale: timescale / sample_rate.max(1),
                        ..AudioAnchor::default()
                    },
                },
            ))
        }
        ConfigProbe::Ac3 => {
            let start = first_sync_offset::<Ac3Sync>(latest)?;
            let info = Ac3SyncframeInfo::from_es(&latest[start..]).ok()?;
            let sample_rate = info.sample_rate;
            let channel_count = info.channel_count() as u16;
            let config = info.into_dac3();
            Some((
                CodecConfig::Ac3 {
                    config,
                    channel_count,
                    sample_rate,
                    sample_size: AUDIO_SAMPLE_SIZE_BITS,
                },
                sample_rate,
                LiveKind::Audio {
                    sample_rate,
                    kind: AudioKind::Ac3,
                    anchor: AudioAnchor::default(),
                },
            ))
        }
        ConfigProbe::Eac3 => eac3_probe_result(latest, Eac3Accept::ChainVerified),
        ConfigProbe::Dts => {
            let info = DtsCoreFrameInfo::from_es(latest).ok()?;
            let sample_rate = info.sample_rate;
            let channel_count = info.channels as u16;
            let config = info.into_ddts();
            Some((
                CodecConfig::Dts {
                    config,
                    codec_fourcc: crate::dts::DTSC_FOURCC,
                    channel_count,
                    sample_rate,
                    sample_size: AUDIO_SAMPLE_SIZE_BITS,
                },
                sample_rate,
                LiveKind::Audio {
                    sample_rate,
                    kind: AudioKind::Dts,
                    anchor: AudioAnchor::default(),
                },
            ))
        }
        ConfigProbe::MpegH => {
            // Scan the newest access unit's MHAS packets for a
            // PACTYP_MPEGH3DACFG (issue #579) — mirrors the Ac3/Eac3/Dts
            // header scans above, just over MHAS packets instead of a
            // sync-frame header.
            let config_bytes = find_mpegh3da_config(latest)?;
            // ATSC A/342-3 §5.2.2.1 / ISO/IEC 23008-3 §5.3.2: the
            // `mpegh3daConfig()` bitstream's leading byte *is*
            // `mpegh3daProfileLevelIndication` — the same value the
            // `MHADecoderConfigurationRecord` duplicates as its own field.
            if config_bytes.len() > MPEGH_CONFIG_LEN_MAX {
                return None;
            }
            let profile_level_indication = *config_bytes.first()?;
            let config = MHADecoderConfigurationRecord::new(
                profile_level_indication,
                MPEGH_REFERENCE_CHANNEL_LAYOUT_UNSPECIFIED,
                config_bytes.to_vec(),
            );
            Some((
                CodecConfig::MpegH {
                    config,
                    channel_count: MPEGH_CHANNEL_COUNT_UNSPECIFIED,
                    sample_rate: MPEGH_SAMPLE_RATE_UNSPECIFIED,
                    sample_size: AUDIO_SAMPLE_SIZE_BITS,
                },
                VIDEO_TIMESCALE,
                LiveKind::MpegH {
                    pending: None,
                    last_duration: 0,
                },
            ))
        }
    }
}

/// [`MAX_PROBE_BACKLOG_BYTES`] tripped for `pid` (issue B8): free the
/// backlog, signal the loss, and permanently abandon this PID's probe —
/// [`StreamingTsDemux::try_promote_ready`] treats [`TrackState::Abandoned`]
/// as resolved-without-promotion on its next pass, exactly like
/// [`StreamingTsDemux::finish`]'s own end-of-input conclusion. Emits
/// [`DemuxEvent::TrackAbandoned`] with [`AbandonReason::BudgetExceeded`]
/// (issue #774) — this PID never reached `Live`, so no `track_id` exists to
/// report; this replaces the mis-typed [`DemuxEvent::Discontinuity`] this
/// path used to emit (a budget overflow is an abandonment, not a
/// discontinuity — no track survives it to "continue" from).
fn abandon_backlog(
    stream: &mut StreamState,
    pid: Pid,
    events: &mut VecDeque<DemuxEvent>,
) -> TrackState {
    stream.backlog_bytes = 0;
    events.push_back(DemuxEvent::TrackAbandoned {
        track_id: None,
        reason: AbandonReason::BudgetExceeded,
        provenance: EventProvenance {
            pid: Some(pid),
            packet_index: None,
            program_number: None,
        },
    });
    TrackState::Abandoned
}

/// Advance a [`StreamState`]'s track lifecycle by one access unit: apply it
/// directly if already live, append it to the backlog if parked, or feed the
/// probe (transitioning `Probing` → `Parked` the moment config becomes
/// recoverable) otherwise. Never assigns a track ID or emits
/// [`DemuxEvent::TrackAdded`] itself — that is
/// [`StreamingTsDemux::try_promote_ready`]'s job, since a `Parked` track must
/// still wait for its PMT-declaration-order turn.
///
/// Every push to a `Probing`/`Parked` backlog counts against
/// [`MAX_PROBE_BACKLOG_BYTES`] (issue B8); an access unit for an already
/// [`TrackState::Abandoned`] PID is silently discarded (no further growth,
/// no re-abandonment).
fn advance_track(
    stream: &mut StreamState,
    pid: Pid,
    data: &[u8],
    pts_uw: i128,
    dts_uw: i128,
    events: &mut VecDeque<DemuxEvent>,
) {
    // `StreamState.track` is `None` only transiently, inside this function and
    // `try_promote_ready` — never on entry. Degrade (drop this access unit)
    // instead of panicking if that ever stops holding: this crate is
    // `#![forbid(unsafe_code)]` and must not abort on remote input.
    let Some(track) = stream.track.take() else {
        return;
    };
    // Damaged input (issue #1171): count parameter-set NALs this access unit
    // carries that were rejected (see [`parameter_set_is_valid`]), so a consumer
    // can see the damage without the garbage ever reaching a config.
    let track_id = match &track {
        TrackState::Live(live) => Some(live.track_id),
        _ => None,
    };
    for _ in 0..count_invalid_parameter_sets(stream.codec, data) {
        events.push_back(DemuxEvent::InputDegraded {
            track: track_id,
            kind: InputDegradation::InvalidParameterSet,
            provenance: EventProvenance {
                pid: Some(pid),
                packet_index: None,
                program_number: None,
            },
        });
    }
    let new_track = match track {
        TrackState::Live(mut live) => {
            // A changed in-band codec-config header re-probes the track and
            // reports the new config (r04-W51). The config used to be
            // single-shot for the life of the stream, so a mid-stream SPS/PPS
            // or AAC-config change (SD↔HD ad break, re-encode, multiplex
            // reconfiguration) left the track labelled with the original
            // `avcC`/`hvcC`/`esds` and the init segment describing a stream
            // that was no longer being sent. An *unchanged* repeat emits
            // nothing — encoders re-send their headers routinely.
            //
            // The first bytes of an ADTS payload that continues a carried frame
            // are mid-frame (issue #1160): they are skipped, because a
            // header-looking byte pair there (`aac_frame_length` bits and
            // `adts_buffer_fullness` routinely read as a 12-bit `0xFFF`
            // syncword) is not a header and would flap the config.
            let skip = carried_frame_remainder(&live, data);
            let new_config = if live.skip_next_reprobe {
                let changed =
                    observe_parameter_sets(stream.codec, &data[skip..], &mut live.parameter_sets);
                if changed || count_invalid_parameter_sets(stream.codec, &data[skip..]) > 0 {
                    live.skip_next_reprobe = false;
                }
                None
            } else {
                reprobe_if_config_changed(stream, &mut live, &data[skip..])
            };
            // The display geometry the access unit activates (see
            // [`LiveTrack::display`]); it must be decided before the access
            // unit is applied, whether or not its codec config changed.
            let display = live.display(data);
            if live.suppress_next_display_change {
                live.display = None;
                live.suppress_next_display_change = false;
            }
            if live.damaged_promotion
                && let Some((_, changed)) = &live.display
                && changed.afd
                && !changed.aspect_ratio
                && !changed.output_rect
                && !changed.default_display_rect
                && !changed.video_signal
                && !changed.overscan
                && !changed.bar_data
                && !changed.initial
            {
                live.display = None;
            }
            let provenance = EventProvenance {
                pid: Some(pid),
                packet_index: None,
                program_number: None,
            };
            if let Some((config, timescale)) = new_config {
                live.config = config;
                live.timescale = timescale;
                let updated = TrackSpec::new(live.track_id, live.timescale, live.config.clone())
                    .with_source(pid, stream.descriptors.clone())
                    .with_hdr10plus(live.hdr10plus);
                // Video is emitted one access unit behind ([`advance_one_behind`]):
                // an event raised while filling this access unit belongs to
                // it and is released (after the previous access unit's
                // sample) when this access unit's own slot is. So the event
                // is parked on the slot the access unit goes into, never
                // pushed immediately — pushing it first labelled the last
                // old-config picture with the new config (Phase 1a fix).
                // Audio emits an access unit's frames immediately, so the new
                // config correctly precedes them.
                if matches!(live.kind, LiveKind::Video { .. }) {
                    // Parked on the video slot this access unit goes into, so
                    // it is released immediately before that sample (§6.5).
                    live.pending_config = Some(updated);
                    push_live_au(&mut live, data, pts_uw, dts_uw, provenance, display, events);
                } else {
                    events.push_back(DemuxEvent::TrackUpdated(updated));
                    push_live_au(&mut live, data, pts_uw, dts_uw, provenance, display, events);
                }
            } else {
                push_live_au(&mut live, data, pts_uw, dts_uw, provenance, display, events);
            }
            TrackState::Live(live)
        }
        TrackState::Abandoned => TrackState::Abandoned,
        TrackState::Parked {
            config,
            timescale,
            kind,
            mut backlog,
        } => {
            stream.backlog_bytes = stream.backlog_bytes.saturating_add(data.len());
            backlog.push(BufferedAu {
                data: data.to_vec(),
                pts_uw,
                dts_uw,
            });
            if stream.backlog_bytes > MAX_PROBE_BACKLOG_BYTES {
                abandon_backlog(stream, pid, events)
            } else {
                TrackState::Parked {
                    config,
                    timescale,
                    kind,
                    backlog,
                }
            }
        }
        TrackState::Probing {
            mut probe,
            mut backlog,
        } => {
            stream.backlog_bytes = stream.backlog_bytes.saturating_add(data.len());
            backlog.push(BufferedAu {
                data: data.to_vec(),
                pts_uw,
                dts_uw,
            });
            // `backlog` is never empty here: the newest access unit was just
            // pushed above. Degrade to "not resolvable yet" rather than
            // panicking if that ever stops holding.
            let Some(latest) = backlog.last() else {
                return;
            };
            // E-AC-3 prefers the window that starts at the EARLIEST held
            // independent frame, so the config describes the stream's first
            // access unit (not whichever later one happens to complete inside
            // the newest PES alone); issue #1186.
            // The held tail joined to the newest payload, built ONCE per
            // payload and shared by the three E-AC-3 users below (the
            // early-window probe, the broken-chain fallback and the next held
            // tail) instead of one allocation + copy each.
            // Gate (see `EAC3_PROBE_FULL_WALKS`): after that many full walks a
            // payload that grew the held window by less than an eighth is not
            // re-walked; it is only appended. Never reached by a stream that
            // resolves in a sane number of payloads.
            let eac3_gated = stream.codec == Codec::Eac3
                && stream.probe_walks >= EAC3_PROBE_FULL_WALKS
                && !stream.probe_tail.is_empty()
                && stream.probe_tail.len() + latest.data.len()
                    < stream.probe_walked_len
                        + Eac3Sync::MIN_FRAME_LEN.max(stream.probe_walked_len / 8);
            let eac3_all: Option<Vec<u8>> = (stream.codec == Codec::Eac3 && !eac3_gated)
                .then(|| [stream.probe_tail.as_slice(), latest.data.as_slice()].concat());
            if let Some(all) = &eac3_all
                && !stream.probe_tail.is_empty()
            {
                // A re-walk of held bytes (a payload walked alone is cheap and
                // is not counted).
                stream.probe_walks = stream.probe_walks.saturating_add(1);
                stream.probe_walked_len = all.len();
            }
            let eac3_window: Option<&[u8]> = eac3_all
                .as_deref()
                .filter(|_| !stream.probe_tail.is_empty());
            let mut resolved = match eac3_window {
                Some(w) => finalize_probe(stream.codec, &stream.descriptors, &mut probe, w),
                None => None,
            };
            if resolved.is_none() {
                resolved =
                    finalize_probe(stream.codec, &stream.descriptors, &mut probe, &latest.data);
            }
            // Audio config recovery across PES boundaries (issue #1160): a PES
            // may be shorter than a frame header, or a header may straddle two
            // of them. When the newest access unit alone does not resolve, the
            // probe is retried over a bounded window joining it to the held
            // tail of the earlier ones. (Tried only after the plain probe
            // fails, so a resolving stream pays nothing.)
            if resolved.is_none()
                && stream.codec != Codec::Eac3
                && let Some(window) =
                    audio_probe_window(stream.codec, &stream.probe_tail, &latest.data)
            {
                resolved = finalize_probe(stream.codec, &stream.descriptors, &mut probe, &window);
            }
            stream.probe_aus = stream.probe_aus.saturating_add(1);
            // Fallbacks for a first access unit that is never proven complete
            // (a lossy capture), tried only after the chain-verified attempts
            // above failed on this payload: accept one whose frame chain broke
            // (a lossy capture's frames are isolated by lost packets, and
            // waiting for a chain-verified one stalls the track, and in PMT
            // order everything behind it, for as long as the loss lasts); and,
            // after `EAC3_PROBE_MAX_FRAMES` chained frames, whatever the access
            // unit holds (as `finish` does).
            if resolved.is_none()
                && let Some(window) = eac3_all.as_deref()
                // A window shorter than one minimum syncframe cannot hold a
                // whole frame, so no fallback can resolve (all need a first
                // frame): skip the walk. Result-identical.
                && window.len() >= Eac3Sync::MIN_FRAME_LEN
            {
                resolved = eac3_probe_result(window, Eac3Accept::BrokenChain);
                // No CRC-valid access unit is held yet. Announce the track from
                // the first (unverified) frame rather than wait for one: on a
                // lossy capture intact frames can be minutes apart and every
                // track behind this one in PMT order waits too. A verified frame
                // is preferred whenever one is already held (the attempts
                // above), and `bsmod` still comes from one when the window has
                // it (`eac3_probe_result`).
                if resolved.is_none() {
                    resolved = eac3_probe_result(window, Eac3Accept::UnverifiedBrokenChain);
                }
                if resolved.is_none()
                    && let Some(start) = first_eac3_independent_offset(window, false)
                    && Ec3SyncframeInfo::from_es_all(&window[start..]).len()
                        >= EAC3_PROBE_MAX_FRAMES
                {
                    resolved = eac3_probe_result(window, Eac3Accept::Anything);
                }
            }
            stream.probe_tail = if resolved.is_some() {
                Vec::new()
            } else if eac3_gated {
                // The held tail already starts at an independent header and
                // only grows here.
                let mut tail = core::mem::take(&mut stream.probe_tail);
                tail.extend_from_slice(&latest.data);
                if tail.len() > EAC3_PROBE_TAIL_MAX {
                    tail.clear();
                }
                tail
            } else if let Some(all) = eac3_all.as_deref() {
                eac3_probe_tail(all)
            } else {
                audio_probe_next_tail(stream.codec, &stream.probe_tail, &latest.data)
            };
            // `probe_walked_len` describes the held window: it follows every
            // clear or replacement of `probe_tail`, else a stale length above
            // ~58 KiB made the gate demand growth past the tail cap, so the
            // tail cleared first and the window was never re-walked in full.
            stream.probe_walked_len = if eac3_gated && !stream.probe_tail.is_empty() {
                stream.probe_walked_len
            } else {
                stream.probe_tail.len()
            };
            match resolved {
                Some((config, timescale, kind)) => TrackState::Parked {
                    config,
                    timescale,
                    kind,
                    backlog,
                },
                None if stream.backlog_bytes > MAX_PROBE_BACKLOG_BYTES => {
                    stream.probe_tail = Vec::new();
                    stream.probe_walked_len = 0;
                    abandon_backlog(stream, pid, events)
                }
                None => TrackState::Probing { probe, backlog },
            }
        }
    };
    stream.track = Some(new_track);
}

/// Bytes of the earlier access units an audio probe keeps/joins at a PES
/// boundary for the header-only framings (MPEG audio, ADTS, AC-3, DTS): a frame
/// header is at most a dozen or so bytes (DTS core's 88-bit fixed fields are the
/// longest), so a window this size across the boundary catches a header split
/// there (issue #1160).
const AUDIO_PROBE_BOUNDARY_BYTES: usize = 16;

/// Syncframes an E-AC-3 probe may hold while waiting for its first access unit
/// to complete (an independent frame, its dependent frames, then the next
/// access unit's independent frame; issue #1186). An implementation bound, not
/// a spec value: an access unit this long never completing means the data is
/// not E-AC-3 framing. Once the probe holds this many chained frames without
/// the access unit completing it resolves from them anyway (as end of input
/// does) rather than wait for a completion that is not coming and, in PMT
/// order, hold up the tracks behind it. Counted in frames, not PES payloads,
/// so it does not depend on how a muxer cuts PES packets (a 1-byte PES must
/// not trigger it). The price is the #1186 hazard in its worst case: a
/// dependent substream that never arrives is not signalled.
const EAC3_PROBE_MAX_FRAMES: usize = 16;

/// Access units a `Probing` PID may hold back later-ranked `Parked` PIDs. PMT
/// declaration order is kept whenever the earlier PID resolves in time, but a
/// probe that has seen this many access units without resolving no longer
/// blocks them: they are promoted past it, and it is promoted whenever (if
/// ever) it does resolve. An implementation bound. It applies to non-video
/// heads only: a *video* probe legitimately waits a whole GOP for its
/// parameter sets, and skipping it would give the video a later track id than
/// audio PIDs that were promoted past it, so a video head blocks until it
/// resolves or [`MAX_PROBE_BACKLOG_BYTES`] abandons it.
const PROBE_HEAD_BLOCK_AUS: u32 = 512;

/// Bytes the PIDs *behind* a completely silent head (not one payload-bearing TS
/// packet since it was declared) must have parked before the head stops holding
/// them back, whatever its codec. This is the bound [`PROBE_HEAD_BLOCK_AUS`]
/// cannot provide: with no packet there is no access unit to count, and nothing
/// on the head's own PID grows toward [`MAX_PROBE_BACKLOG_BYTES`], so a video
/// PID declared in the PMT but never sent (a radio service with a stale video
/// entry, a feed whose video is dropped upstream) blocked every later track
/// until end of input (`finish()`) in 0.26.0, which has no step-over at all
/// (it held later tracks behind a head that never resolved until the byte cap
/// abandoned them, and for a silent head not even then).
///
/// The criterion is the sum of [`StreamState::backlog_bytes`] over every
/// unresolved PID other than the head, compared with half of
/// [`MAX_PROBE_BACKLOG_BYTES`] (2 MiB). The per-PID cap is 4 MiB and a PID that
/// reaches it is abandoned (its track lost), so stepping over at half the cap
/// always happens while the parked audio is still intact, yet never before a
/// late video has had 2 MiB of the *other* tracks' elementary stream (about
/// 2 minutes at 128 kbit/s of audio, regardless of the mux bitrate) to start.
/// A PID that has delivered *any* payload keeps blocking exactly as in 0.26.0
/// (scrambled-but-present video stays bounded by the byte cap only), and a
/// *video* head with data is never stepped over. The silent PID is stepped
/// over, not abandoned: if packets arrive later it resolves, is promoted with a
/// later id and its backlog, and re-arms [`DemuxEvent::TracksResolved`].
const SILENT_HEAD_PARKED_BYTES: usize = MAX_PROBE_BACKLOG_BYTES / 2;

/// Bytes of its own payload-bearing TS packets after which a `Probing` head
/// that has not produced a single access unit stops holding back the PIDs
/// behind it, whatever its codec (video included). A clear PID completes an
/// access unit within a few packets, so this many bytes with none means the
/// payload cannot be framed (scrambled, mis-framed): [`MAX_PROBE_BACKLOG_BYTES`]
/// never trips for it because no access unit ever enters the backlog, so the
/// PIDs behind it, already resolved, waited until `finish()`. Half the byte
/// cap. A head that does produce access units and still cannot resolve (video
/// waiting for parameter sets) is untouched: its backlog reaches the byte cap
/// and abandons it. The head is stepped over, not abandoned: it keeps probing
/// and is announced by a later [`DemuxEvent::TrackAdded`] if it ever resolves,
/// re-arming [`DemuxEvent::TracksResolved`].
const STUCK_HEAD_OWN_BYTES: usize = MAX_PROBE_BACKLOG_BYTES / 2;

/// Packets of input (4 MiB) after a PID was declared past which a still
/// `Probing` *non-video* head (audio, data) stops holding back its program.
/// The backstop for a head too sparse for [`STUCK_HEAD_OWN_BYTES`] (a data PID
/// with ten packets in 20 MB, an audio PID whose PES trickle). 4 MiB of input
/// is about 1.6 seconds of a 20 Mbit/s multiplex. Never applied to video: its
/// legitimate wait for an IDR scales with the video bitrate, and a video that
/// delivers access units is bounded by the byte cap instead.
const STUCK_HEAD_INPUT_PACKETS: u64 = 4 * 1024 * 1024 / TS_PACKET_SIZE as u64;

/// Payloads an E-AC-3 probe gets a full window re-walk for before the walk is
/// gated. Each unresolved payload re-joins the held tail (up to
/// [`EAC3_PROBE_TAIL_MAX`], ~64 KiB) to itself and re-walks it, so a stream of
/// tiny PES whose frames are large would cost O(PES count x 64 KiB). After this
/// many walks a payload that grew the window by less than an eighth (and
/// [`Eac3Sync::MIN_FRAME_LEN`]) is appended without a walk, which bounds the
/// total at this many walks plus a logarithmic number more. A stream that
/// resolves in fewer payloads (every real capture, and the unchanged 16-frame
/// bound for sane PES sizes) is untouched; only the pathological one defers its
/// fallbacks until the window has grown by an eighth (the gate is dropped
/// whenever the held tail is cleared, see `StreamState::probe_walked_len`).
const EAC3_PROBE_FULL_WALKS: u32 = 4096;

/// The most an E-AC-3 probe holds: [`EAC3_PROBE_MAX_FRAMES`] syncframes of at
/// most `2^11` 16-bit words each (ETSI TS 102 366 Annex E §E.1.3.1.3 `frmsiz`),
/// plus a header's worth.
const EAC3_PROBE_TAIL_MAX: usize = EAC3_PROBE_MAX_FRAMES * 2 * 2048 + AUDIO_PROBE_BOUNDARY_BYTES;

/// The window to retry an audio config probe over when the newest access unit
/// alone did not resolve (see [`StreamState::probe_tail`]); `None` when there is
/// nothing held to join (or the codec is not an audio one).
fn audio_probe_window(codec: Codec, tail: &[u8], latest: &[u8]) -> Option<Vec<u8>> {
    if tail.is_empty() {
        return None;
    }
    match codec {
        // A header was found in the newest access unit alone (and still did not
        // resolve, e.g. a reserved sampling-frequency index): joining more
        // bytes cannot help.
        Codec::MpegAudio(_) if first_sync_offset::<MpegAudioSync>(latest).is_some() => None,
        Codec::Aac if first_sync_offset::<AdtsSync>(latest).is_some() => None,
        Codec::Ac3 if first_sync_offset::<Ac3Sync>(latest).is_some() => None,
        Codec::Dts if first_sync_offset::<DtsSync>(latest).is_some() => None,
        Codec::MpegAudio(_) | Codec::Aac | Codec::Ac3 | Codec::Dts => {
            let head = &latest[..latest.len().min(AUDIO_PROBE_BOUNDARY_BYTES)];
            Some([tail, head].concat())
        }
        Codec::Eac3 => Some([tail, latest].concat()),
        _ => None,
    }
}

/// What to hold for the next access unit after an unresolved probe: the last
/// [`AUDIO_PROBE_BOUNDARY_BYTES`] bytes (header-only framings), or for E-AC-3
/// everything from the first valid syncframe header on (bounded by
/// [`EAC3_PROBE_TAIL_MAX`]; a frame that has not completed by then never will).
fn audio_probe_next_tail(codec: Codec, tail: &[u8], latest: &[u8]) -> Vec<u8> {
    match codec {
        Codec::MpegAudio(_) | Codec::Aac | Codec::Ac3 | Codec::Dts => {
            let all = [tail, latest].concat();
            all[all.len().saturating_sub(AUDIO_PROBE_BOUNDARY_BYTES)..].to_vec()
        }
        Codec::Eac3 => eac3_probe_tail(&[tail, latest].concat()),
        _ => Vec::new(),
    }
}

/// The E-AC-3 probe tail to hold after an unresolved payload, given the held
/// tail already joined to that payload (`all`): from the first valid
/// *independent* header (a dependent frame is mid-access-unit, #1186), or a
/// header prefix not yet judgeable; empty when it exceeds
/// [`EAC3_PROBE_TAIL_MAX`] (a frame not complete by then never will be).
fn eac3_probe_tail(all: &[u8]) -> Vec<u8> {
    let start = (0..all.len()).find(|&at| match Eac3Sync::parse(&all[at..]) {
        SyncParse::Frame(hdr, _) => hdr.strmtyp != EAC3_STRMTYP_DEPENDENT,
        SyncParse::NeedMore => Eac3Sync::is_partial_sync(&all[at..]),
        SyncParse::NotSync => false,
    });
    match start {
        Some(start) if all.len() - start <= EAC3_PROBE_TAIL_MAX => all[start..].to_vec(),
        _ => Vec::new(),
    }
}

/// Offset of the first valid *independent* (or AC-3-derived) E-AC-3 frame in
/// `data`. A leading dependent frame belongs to an access unit that began
/// before `data` (ETSI TS 102 366 §E.1.3.1.2: dependent substreams follow the
/// independent substream they belong to), so a config must not be built from it.
///
/// With `crc`, the frame must also be whole in `data` and carry a valid `crc2`
/// (ETSI TS 102 366 §E.2.2): a header-shaped `0B 77` inside coded data, or a
/// frame a lost packet damaged, is skipped instead of becoming the stream's
/// description.
fn first_eac3_independent_offset(data: &[u8], crc: bool) -> Option<usize> {
    (0..data.len()).find(|&at| match Eac3Sync::parse(&data[at..]) {
        SyncParse::Frame(hdr, len) => {
            len >= Eac3Sync::MIN_FRAME_LEN
                && hdr.strmtyp != EAC3_STRMTYP_DEPENDENT
                && (!crc
                    || data
                        .get(at..at + len)
                        .is_some_and(crate::ac3::eac3_frame_crc_ok))
        }
        _ => false,
    })
}

/// How sure an E-AC-3 probe must be that the first access unit is whole (and
/// intact) before it builds a config from it (see [`eac3_probe_result`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Eac3Accept {
    /// The next access unit's independent frame was seen (issue #1186): the
    /// access unit is provably complete, and every frame of it passed its
    /// `crc2` check. What a plain probe requires.
    ChainVerified,
    /// Also an access unit followed by bytes that are not a syncword, or by a
    /// frame whose `crc2` fails (lost packets); see
    /// `Ec3SyncframeInfo::from_es_first_au_crc_verified`. Its own frames are
    /// still CRC-verified.
    BrokenChain,
    /// [`Self::BrokenChain`] without the CRC requirement: the fallback for a
    /// lossy capture that has shown no verified frame yet.
    UnverifiedBrokenChain,
    /// Whatever the access unit holds, unverified: end of input, or the
    /// frame-count backstop ([`EAC3_PROBE_MAX_FRAMES`]).
    Anything,
}

/// Recover an E-AC-3 track config from `latest`.
///
/// The `dec3` describes the bitstream's substream layout and is built from the
/// *first access unit* found: one independent frame plus the dependent frames
/// that follow it (the dependent substreams make a programme 7.1). Scanning the
/// whole backlog would emit one substream per repeated access unit (and
/// re-scan it on every access unit — see the O(n²) note above
/// `finalize_probe`).
///
/// The access unit must be **provably complete** (issue #1186): until a
/// following independent frame has been seen, a dependent frame may still be
/// on its way in the next PES, and a `dec3` built now would silently signal 5.1
/// for a 7.1 stream. And it must be **intact**: frames are chosen by their
/// `crc2` (ETSI TS 102 366 §E.2.2), so on a capture that lost packets the config
/// is never read from a corrupted frame, and `bsmod` is the one the stream's
/// verified frames carry (`Ec3SyncframeInfo::first_crc_verified_bsmod`: a frame
/// without `infomdate` carries none, which says nothing about the stream).
/// [`Eac3Accept`] says how much of that the first access unit must show.
fn eac3_probe_result(latest: &[u8], accept: Eac3Accept) -> Option<(CodecConfig, u32, LiveKind)> {
    let verified = matches!(accept, Eac3Accept::ChainVerified | Eac3Accept::BrokenChain);
    let start = first_eac3_independent_offset(latest, verified)?;
    let mut frames: alloc::vec::Vec<Ec3SyncframeInfo> = match accept {
        Eac3Accept::Anything => Ec3SyncframeInfo::from_es_first_au(&latest[start..]),
        Eac3Accept::ChainVerified => {
            Ec3SyncframeInfo::from_es_first_au_crc_verified(&latest[start..], false)?
        }
        Eac3Accept::BrokenChain => {
            Ec3SyncframeInfo::from_es_first_au_crc_verified(&latest[start..], true)?
        }
        Eac3Accept::UnverifiedBrokenChain => {
            Ec3SyncframeInfo::from_es_first_au_or_broken_chain(&latest[start..])?
        }
    };
    for f in frames
        .iter_mut()
        .filter(|f| f.strmtyp != EAC3_STRMTYP_DEPENDENT)
    {
        if let Some(bsmod) =
            Ec3SyncframeInfo::first_crc_verified_bsmod(&latest[start..], f.substreamid)
        {
            f.bsmod = bsmod;
        }
    }
    let info = *frames.first()?;
    let sample_rate = info.sample_rate;
    let channel_count = info.channel_count() as u16;
    let config = Ec3SpecificBox::from_syncframes(&frames).ok()?;
    Some((
        CodecConfig::Eac3 {
            config,
            channel_count,
            sample_rate,
            sample_size: AUDIO_SAMPLE_SIZE_BITS,
        },
        sample_rate,
        LiveKind::Audio {
            sample_rate,
            kind: AudioKind::Eac3,
            anchor: AudioAnchor::default(),
        },
    ))
}

/// Offset of the first *valid* frame header in `data` (a header that parses and
/// declares a plausible length), for config recovery from a PES that starts
/// mid-frame. Unlike a bare syncword scan it is not fooled by a `0x0B77` that
/// merely occurs inside coded data.
fn first_sync_offset<F: FrameSync>(data: &[u8]) -> Option<usize> {
    (0..data.len()).find(
        |&at| matches!(F::parse(&data[at..]), SyncParse::Frame(_, len) if len >= F::MIN_FRAME_LEN),
    )
}

/// Feeds one TS payload to a PID's `Carrier::Pes` assembler with
/// [`MAX_PES_BUFFER_BYTES`] enforced (issue #663 P5.2). Mirrors
/// [`mpeg_pes::PesAssembler::feed`]'s own bookkeeping (reset the running
/// total on `payload_unit_start`, else add) so the cap can be checked
/// without a private accessor into the assembler's buffer. On overflow the
/// in-progress PES is dropped (`assembler.flush()`'s return discarded) and a
/// [`DemuxEvent::Discontinuity`] is raised for `pid` — any PES that had
/// *already* completed at this same call (a `payload_unit_start` whose
/// previous buffer was ready) is still returned normally; only the
/// newly-started, now-oversized buffer is affected.
fn feed_pes_bounded(
    stream: &mut StreamState,
    pid: Pid,
    pusi: bool,
    payload: &[u8],
    events: &mut VecDeque<DemuxEvent>,
) -> Option<Vec<u8>> {
    let Carrier::Pes(assembler) = &mut stream.carrier else {
        return None;
    };
    // Track how much of the in-progress PES has arrived and what it declared,
    // so a later CC gap can tell "the unit was already complete" from "the unit
    // lost bytes" (r04-W49). The declared length sits at bytes 4..6 of the PES
    // (start code prefix + stream_id + `PES_packet_length`), which the first
    // packet of a unit always carries.
    if pusi {
        stream.pes_received = payload.len();
        stream.pes_declared_len = if payload.len() >= PES_LENGTH_FIELD_END {
            u16::from_be_bytes([payload[4], payload[5]])
        } else {
            0
        };
    } else {
        stream.pes_received = stream.pes_received.saturating_add(payload.len());
    }
    if pusi {
        stream.pes_bytes = payload.len();
    } else if stream.pes_bytes > 0 {
        // Only accumulate once a real `payload_unit_start` has been seen for
        // this PID — mirrors `PesAssembler::feed`'s own "ignore a
        // continuation before the first start" rule (relevant for the
        // `unattributed`-replay path, whose buffered payloads can begin
        // mid-PES), so this counter never diverges from what the assembler
        // is actually buffering.
        stream.pes_bytes = stream.pes_bytes.saturating_add(payload.len());
    }
    let completed = assembler.feed(pusi, payload);
    if stream.pes_bytes > MAX_PES_BUFFER_BYTES {
        let dropped_bytes = stream.pes_bytes as u64;
        let _ = assembler.flush();
        stream.pes_bytes = 0;
        clear_audio_carry(stream, events);
        let track = match stream.track.as_ref() {
            Some(TrackState::Live(live)) => Some(live.track_id),
            _ => None,
        };
        events.push_back(DemuxEvent::Discontinuity {
            track,
            kind: DiscontinuityKind::BudgetExceeded {
                bytes: dropped_bytes,
            },
            provenance: EventProvenance {
                pid: Some(pid),
                packet_index: None,
                program_number: None,
            },
        });
    }
    completed
}

/// Resolve a completed PES packet's `(pts, dts)` and drive it through
/// [`advance_track`] (parked/probing) or [`push_live_au`] (already live).
///
/// A PES packet may legally carry neither PTS nor DTS (`PTS_DTS_flags ==
/// '00'`, ISO/IEC 13818-1 §2.4.3.7) — the 2.7.4 constraint only requires them
/// periodically. Such an access unit is interpolated *forward* from the
/// previous one by [`StreamState::frame_period`] (the measured spacing
/// between the last two stamped access units), rather than being handed the
/// previous stamps verbatim: an identical `dts` pair gave the earlier of the
/// two access units `duration = 0` and made the next stamped one absorb the
/// whole gap (r04-W48). The T-STD permits exactly this derivation —
/// "Decoding times tdn(j + 1), tdn(j + 2),... of access units without encoded
/// DTS or PTS fields which directly follow access unit j may be derived from
/// information in the elementary stream" (§2.4.2.6).
///
/// With no measured period yet (fewer than two stamped access units seen) the
/// previous stamps are reused, exactly as before — there is nothing to
/// interpolate from, and inventing a frame rate would fabricate a timeline.
fn on_completed_pes(
    stream: &mut StreamState,
    pid: Pid,
    pes_bytes: &[u8],
    events: &mut VecDeque<DemuxEvent>,
) {
    let Ok(pes) = PesPacket::parse(pes_bytes) else {
        return;
    };
    if pes.payload.is_empty() {
        return;
    }
    // `(pts, dts)` this access unit resolved, and whether either came off the
    // wire — the only values that may update the measured frame period.
    let (pts, dts, stamped) = match pes.header.as_ref() {
        Some(h) => {
            let hp = h.pts.map(|p| p.0);
            let hd = h.dts.map(|d| d.0);
            match (hp, hd) {
                // Both present (PTS_DTS_flags '11').
                (Some(p), Some(d)) => (p, d, true),
                // PTS only ('10'): DTS defaults to PTS, and the pair is a
                // real observation of the clock.
                (Some(p), None) => (p, p, true),
                // DTS only is not a legal wire combination, but a PES parsed
                // from a stream that set only `DTS` (or an in-band PES the
                // assembler synthesised) still yields one — treat it as
                // stamped, with PTS defaulting to DTS.
                (None, Some(d)) => (d, d, true),
                // Neither: interpolate (§2.4.2.6). Never a clock observation.
                (None, None) => (0, 0, false),
            }
        }
        None => (0, 0, false),
    };
    let (pts, dts) = if stamped {
        // The span to the previous stamped access unit covers one period per
        // access unit between them (`units_since_stamped` counts the *other*
        // units, plus one for this one) — what §2.4.3.7's periodic-only
        // requirement makes the raw difference over-count by.
        //
        // The first stamp after a rebase spans the discontinuity itself, so its
        // "period" is meaningless: the estimate is left alone in that case.
        // Both the interpolation period and the rebase step come from this one
        // measurement, behind one validity gate — only a small forward step is
        // evidence of the stream's own cadence, so a gap or a clock jump cannot
        // become either.
        if let Some(prev) = stream.last_stamped_dts
            && !stream.pending_rebase
        {
            let span = dts.wrapping_sub(prev) & TS_WRAP_MASK;
            let periods = stream.units_since_stamped.saturating_add(1);
            let period = span / periods;
            // Feed the window with every *plausible* step and take the median:
            // a single late access unit (or one short gap inside the window)
            // then cannot become "the frame period", which is what a
            // last-observation estimate did. An implausible step is not
            // evidence of cadence at all, so it is not recorded.
            if period > 0 && period <= MAX_FRAME_PERIOD_TICKS {
                if stream.recent_steps.len() == FRAME_PERIOD_WINDOW {
                    stream.recent_steps.remove(0);
                }
                stream.recent_steps.push(period);
                let mut sorted = stream.recent_steps.clone();
                sorted.sort_unstable();
                let median = sorted[sorted.len() / 2];
                stream.frame_period = Some(median);
                stream.last_frame_period = median as i128;
            }
        }
        stream.last_stamped_dts = Some(dts);
        stream.units_since_stamped = 0;
        stream.fallback = (pts, dts);
        stream.has_any = true;
        (pts, dts)
    } else if stream.has_any {
        // Unstamped: continue the timeline one measured frame period past the
        // previous access unit. Until a period has been measured (the first
        // stamped pair may not have arrived yet) the previous stamps are
        // reused, exactly as before this fix — there is nothing to
        // interpolate from, and inventing a frame rate would fabricate a
        // timeline.
        let step = stream.frame_period.unwrap_or(0);
        stream.units_since_stamped = stream.units_since_stamped.saturating_add(1);
        let pts = stream.fallback.0.wrapping_add(step) & TS_WRAP_MASK;
        let dts = stream.fallback.1.wrapping_add(step) & TS_WRAP_MASK;
        stream.fallback = (pts, dts);
        (pts, dts)
    } else {
        // First access unit on this PID carries no timing at all: nothing to
        // anchor to. Keep the zero anchor (a real 90 kHz timestamp on tick 0 is
        // not distinguishable, and `WrapState` already treats a leading zero as
        // "no genuine value yet") — but do **not** let it seed the timeline,
        // because a `(0, 0)` anchor would make the first *stamped* access unit
        // look like a jump of however far the real clock is from zero, and that
        // inflated span would become both the interpolation period and the
        // rebase step. `has_any` stays false, so the next stamped access unit
        // anchors from the wire clock, and `units_since_stamped` still counts
        // this one so a later measurement divides by the right count.
        stream.units_since_stamped = stream.units_since_stamped.saturating_add(1);
        (0, 0)
    };
    if stream.pending_rebase {
        // The first stamp of the new time base lifts the whole timeline by
        // whatever the jump backwards would have been, so decode order stays
        // monotonic across the discontinuity (r04-W50). The indicator may
        // arrive while the *old* base's last unit is still completing, in which
        // case this call is a no-op and the wait continues.
        stream.pending_rebase = stream
            .wrap
            .rebase_at_discontinuity(dts, stream.last_frame_period)
            == DiscontinuityVerdict::Forward;
    }
    let (pts_uw, dts_uw) = stream.wrap.push(pts, dts);
    advance_track(stream, pid, pes.payload, pts_uw, dts_uw, events);
}

/// Drive one reassembled PSI/private section through [`advance_track`]
/// (issue #576) — sections carry no PTS/DTS at all, so `pts_uw`/`dts_uw` are
/// dummy zeros (never read by [`LiveKind::Section`]'s immediate-emit push).
fn on_completed_section(
    stream: &mut StreamState,
    pid: Pid,
    section: &[u8],
    events: &mut VecDeque<DemuxEvent>,
) {
    if section.is_empty() {
        return;
    }
    advance_track(stream, pid, section, 0, 0, events);
}

/// [`DemuxEvent`] moved to `crate::ir::event` (media plane step 2e: it is
/// not TS-only — [`crate::flv_stream::StreamingFlvDemux`] emits it too).
/// Re-exported from this path so `transmux::ts_demux::DemuxEvent` keeps
/// resolving unchanged.
pub use crate::ir::{
    AbandonReason, DegradationRecord, DemuxEvent, DiscontinuityKind, EventProvenance,
    InputDegradation,
};

/// `program_clock_reference`'s native clock rate (ISO/IEC 13818-1 §2.4.3.5) —
/// the `clock_hz` [`DemuxEvent::ClockReference`] carries for every PCR this
/// demuxer emits.
const PCR_CLOCK_HZ: u32 = broadcast_common::clock33::PCR_HZ as u32;

/// Per-PID continuity-counter state for [`StreamingTsDemux`] (issue #778).
///
/// Tracks the last-seen CC and its payload bytes for duplicate detection
/// (ISO/IEC 13818-1 §2.4.3.3: a legal duplicate is a re-transmitted packet
/// with same CC + identical payload). Skipping non-payload-bearing packets
/// (AFC `00`/`10`) on this PID, as they do not advance the counter.
#[derive(Debug, Clone)]
struct CcState {
    /// Whether we've seen the first payload-bearing packet for this PID.
    initialized: bool,
    /// Last continuity counter value on this PID (payload-bearing only).
    last_cc: u8,
    /// The whole last packet, for the §2.4.3.3 legal-duplicate comparison —
    /// which is defined over every byte with only the PCR field excepted, so
    /// the payload slice alone is not enough (r04-W49).
    last_packet: Option<[u8; TS_PACKET_SIZE]>,
    /// Whether `last_packet` was itself already accepted as the one legal
    /// repeat of its predecessor: §2.4.3.3 permits "two, and only two
    /// consecutive" packets, so a third identical repeat is a fault.
    dup_used_for_last: bool,
}

/// What [`StreamingTsDemux::check_cc`] concluded about a payload-bearing
/// packet (r04-W49).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CcVerdict {
    /// Feed the packet to the reassembler as normal.
    Deliver,
    /// A legal §2.4.3.3 duplicate: the decoder shall discard it, so its
    /// payload must not reach the reassembler (it would duplicate 184 bytes
    /// inside the access unit under construction).
    Duplicate,
    /// A continuity-counter gap: at least one packet on this PID was lost, so
    /// the access unit currently being reassembled is missing bytes and must
    /// be dropped rather than delivered truncated. The packet itself is still
    /// fed, since a `payload_unit_start` begins a *new* access unit that is
    /// intact from its first byte.
    Gap,
}

/// Event-driven, incremental MPEG-2 Transport Stream demuxer (issue #555) —
/// the one demux core [`TsDemux`] is a thin batch wrapper over.
///
/// Feed TS bytes of any size/alignment with [`feed`](Self::feed) (backed by
/// [`mpeg_ts::resync::TsResync`], so mid-packet chunk boundaries — down to a
/// single byte at a time — and 204-byte RS-coded input are both handled
/// transparently); drain [`DemuxEvent`]s with [`poll_event`](Self::poll_event);
/// call [`finish`](Self::finish) once, at end of input, to flush trailing
/// partial access units.
///
/// # Memory
///
/// Bounded, independent of stream length: per-PID PES reassembly + PSI
/// section-reassembly state, one pending (duration-incomplete) sample per
/// live video/data track, and — until a track's codec config first becomes
/// recoverable — a small backlog of that PID's buffered access units. In real
/// broadcast streams parameter sets / frame headers appear in the first
/// access unit or two, so this backlog is tiny in practice. The one caveat:
/// a PMT-listed codec PID whose config is *never* recoverable (e.g. no SPS
/// ever arrives on that PID) holds that PID's own backlog for the life of the
/// stream — exactly mirroring the old batch demuxer, which also needed the
/// whole file to reach the same "never recoverable, skip" conclusion; it does
/// not delay or affect any other PID's event delivery.
///
/// One more source has the same shape: a captured excerpt need not start at
/// a clean PAT/PMT boundary, so a PID's own payload can arrive on the wire
/// before its PMT registration has finished reassembling (observed in a
/// committed real DVB capture). Those payloads are held in `unattributed`
/// (keyed by PID) and replayed the instant that PID's PMT entry resolves —
/// restoring the full-file view the old two-pass batch demuxer had "for
/// free". A PID that never appears in any PMT (e.g. an unrelated service's
/// traffic in a full-multiplex capture) is FIFO-evicted once the total
/// buffered size exceeds a fixed byte cap (`MAX_UNATTRIBUTED_BYTES`), keeping
/// this buffer bounded regardless of stream length; null packets (PID `0x1FFF`)
/// are excluded from it entirely.
///
/// Track IDs / `TrackAdded` order follow PMT declaration order (codec tracks
/// first, then data tracks, each group in PMT order — the old batch
/// demuxer's invariant, see `TrackState`), tracked via `codec_order` /
/// `data_order` / `resolved`; these hold one `u16` PID per known ES, not
/// per-sample data, so they stay tiny regardless of stream length.
///
/// The one exception to strict PMT order is a *non-video* head PID whose probe
/// has seen `PROBE_HEAD_BLOCK_AUS` (512) access units without resolving: the
/// PIDs behind it are promoted past it (it gets a later id if it ever
/// resolves). A *video* head is never stepped over — a long GOP legitimately
/// takes that long, and a video PID must keep the lower track id (track 1 for
/// a video-first PMT), which `ts_hls`/`multimux` rely on. A video that never
/// resolves is bounded by the 4 MiB probe-backlog cap instead (it is then
/// abandoned and the PIDs behind it proceed) — unless it is *silent*: a
/// declared PID (of any codec) that has delivered no payload packet at all for
/// while the PIDs behind it have parked `SILENT_HEAD_PARKED_BYTES` (2 MiB) in
/// total is stepped over too, since nothing would ever grow toward the cap. A stepped-over PID counts
/// toward [`DemuxEvent::TracksResolved`] and, if it resolves later, is promoted
/// with a later track id and re-arms that signal.
///
/// # Chunk-size invariance
///
/// The event stream is a function of the input *bytes*, not of how they are
/// split across [`feed`](Self::feed) calls: for any partition of the same
/// input (1 byte at a time, 188-byte packets, 189, 64 KiB, random sizes) the
/// complete sequence of [`DemuxEvent`]s — kinds, order, track ids,
/// provenance, and every sample's `pts`/`dts`/`duration`/bytes — is identical,
/// and so is the result of draining with [`poll_event`](Self::poll_event) after
/// every `feed` versus only after [`finish`](Self::finish). Input need not
/// start on a packet boundary (`TsResync` locks on `0x47`); an event is never
/// withheld waiting for "the rest of a chunk". This is pinned by
/// `tests/it/streaming_chunk_invariance.rs` (whole buffer vs 1, 7, 187, 188, 189,
/// 1000, 65536 B and 32 fixed-seed random chunkings, over audio+video,
/// multi-track, discontinuity and track-update captures). Only the *moment*
/// (which `feed` call) an event becomes pollable depends on chunking, never
/// its content or position in the sequence.
///
/// # Event semantics worth knowing
///
/// - **`TrackAdded`** fires once per track, once its codec config is
///   recoverable (PMT order for codec tracks, then data tracks; see
///   `TrackState`). The `track_id` is stable for the life of the PID.
/// - **`TrackUpdated`** carries the track's full current [`TrackSpec`] on the
///   *same* `track_id` and fires in two cases: (1) the PMT-derived metadata
///   changed (its `es_info_descriptors`, e.g. a corrected language) with the
///   codec config unchanged (#774); (2) the in-band AVC/HEVC parameter sets or
///   the AAC ADTS header changed (SD↔HD switch, re-encode) so the config
///   itself differs (r04-W51) — treat it as "rebuild the init segment /
///   decoder". An unchanged repeat of a parameter set emits nothing.
///   [`TsDemux`] folds these into the final track spec.
/// - **`Discontinuity`** says the *timeline or data* is not continuous at this
///   point, and carries a [`DiscontinuityKind`]: `Signalled` — an adaptation
///   field `discontinuity_indicator` (§2.4.3.5) on any packet (`track` is the
///   PID's track when already resolved, else `None`); when that packet's PID is
///   a program's PCR_PID, that program's elementary streams are re-based so
///   the first sample of the new time base continues one nominal frame period
///   past the last emitted `dts` (sample timestamps stay monotonic across the
///   seam; a forward step is left untouched). `TimelineReanchored` — a live
///   audio track's frame-exact timeline was re-anchored to the wire clock after
///   drifting past a threshold (splice, encoder restart): timestamps *do* jump
///   at this point. `BudgetExceeded` — a PES (4 MiB) or probe backlog cap was
///   hit and in-flight data was dropped. A consumer should flush/resync its
///   decoder on `Discontinuity`; [`LiveJoin::rejoin`](crate::LiveJoin::rejoin) is
///   the video-side helper. Transport errors (TEI) and continuity-counter gaps
///   are **not** `Discontinuity`: they are [`DemuxEvent::InputDegraded`].
/// - **`ClockReference`** is every PCR on a program's PMT-announced `PCR_PID` (issue #1354; see [`DemuxEvent::ClockReference`] for the pre-PMT policy), carrying `provenance.program_number`, with `discontinuous` set on the packet
///   that carries the indicator.
pub struct StreamingTsDemux {
    resync: TsResync,
    packet_index: u64,
    /// Opt-in cap on queued [`DemuxEvent::InputDegraded`] events (issue
    /// #1352); `None` (default) = unbounded, the historical behaviour.
    degraded_cap: Option<usize>,
    /// `InputDegraded` events dropped because `degraded_cap` was reached.
    degraded_dropped: u64,
    /// Leading `events` entries already counted against `degraded_cap`.
    queue_scanned: usize,
    /// `InputDegraded` events among those `queue_scanned` entries.
    degraded_queued: usize,
    pat_reasm: SectionReassembler,
    pmt_reasm: BTreeMap<Pid, PmtState>,
    es_seen: BTreeSet<Pid>,
    streams: BTreeMap<Pid, StreamState>,
    /// Payloads for a PID not yet classified as PAT/PMT/a known ES — a real
    /// capture excerpt need not start at a clean PAT/PMT boundary, so an ES's
    /// own packets can arrive before its PMT registration completes (see the
    /// module-level `# Memory` note). Replayed into the new [`StreamState`]
    /// the moment that PID is discovered in a PMT, restoring the same
    /// full-file view the old two-pass batch demuxer had for free. FIFO-bounded
    /// by [`MAX_UNATTRIBUTED_BYTES`] (see `unattributed_order` /
    /// `unattributed_bytes`).
    unattributed: BTreeMap<Pid, VecDeque<(bool, Vec<u8>)>>,
    /// ES PIDs whose declaration was withdrawn by an applied PMT diff, and
    /// which no PMT has declared since. Payload arriving on such a PID is
    /// dropped outright rather than buffered into `unattributed`: that buffer
    /// is strictly a *pre*-registration replay window, and replaying
    /// post-removal orphan traffic into a later re-registration would deliver
    /// stale bytes as the re-added track's first samples and anchor its
    /// `start_decode_time` in the past. Cleared per PID by
    /// [`Self::register_new_es`]. Bounded by the 13-bit PID space.
    removed_pids: BTreeSet<Pid>,
    /// Which PMT PIDs currently declare each elementary PID — the refcount
    /// behind PMT-diff removal. `streams`/`es_seen` are global but `applied_es`
    /// is per-PMT, so without this a PID declared by two programs is torn down
    /// the moment *either* program's PMT stops listing it.
    es_declarers: BTreeMap<Pid, BTreeSet<Pid>>,
    /// One entry per buffered `unattributed` payload, in insertion order — the
    /// FIFO eviction queue backing [`MAX_UNATTRIBUTED_BYTES`]. Stale entries
    /// (for a PID already replayed into `streams`) are skipped harmlessly when
    /// popped.
    unattributed_order: VecDeque<u16>,
    /// Running total of bytes held in `unattributed`, kept in sync on push,
    /// eviction, and replay to enforce [`MAX_UNATTRIBUTED_BYTES`].
    unattributed_bytes: usize,
    /// Codec-track PIDs, in PMT discovery order.
    codec_order: Vec<Pid>,
    /// Data-track (opaque PES, issue #557) PIDs, in PMT discovery order.
    data_order: Vec<Pid>,
    /// PIDs that have reached a final disposition: promoted to `Live` (a
    /// track_id assigned and `TrackAdded` fired) or abandoned (config never
    /// recoverable / no access units ever arrived, concluded at `finish()`).
    resolved: BTreeSet<Pid>,
    /// Unresolved `Probing` heads that [`PROBE_HEAD_BLOCK_AUS`] (or
    /// [`SILENT_HEAD_PARKED_BYTES`]) stepped over. Disjoint from `resolved`.
    /// They count toward [`DemuxEvent::TracksResolved`] (the declared set is
    /// "stable enough": nothing more is being waited on) but are *not*
    /// resolved: such a PID is still promoted, with a `TrackAdded` and its
    /// whole backlog, if it later resolves, and that promotion re-arms
    /// `TracksResolved` so a consumer learns of the late track.
    skipped: BTreeSet<Pid>,
    next_track_id: TrackId,
    events: VecDeque<DemuxEvent>,
    /// Monotonic track-set generation (issue #774): bumped exactly once per
    /// *applied* PMT diff (add/update/remove), never per PID count. This is
    /// the [`DemuxEvent::TracksResolved`] de-dup key — a PID count is not
    /// reliable (a removal immediately followed by an addition can return the
    /// count to a previously-seen value, which a count-keyed de-dup would
    /// wrongly treat as "already signalled").
    generation: u32,
    /// The [`generation`](Self::generation) value at which
    /// [`DemuxEvent::TracksResolved`] last fired, if ever — re-arms whenever
    /// `generation` advances past this value (issue #624 original mechanism;
    /// re-keyed off `generation` instead of a PID count by issue #774).
    tracks_resolved_signalled_at: Option<u32>,
    /// Per-PID continuity-counter state for `InputDegraded::ContinuityGap`
    /// detection (issue #778). Only populated for payload-bearing, non-null
    /// packets; non-payload-bearing packets (AFC `00`/`10`) are skipped and do
    /// not create entries or advance the counter. Null PID (0x1FFF) is always
    /// excluded.
    cc_states: BTreeMap<Pid, CcState>,
    afd_persistence: AfdPersistence,
    strict_pmt_order: bool,
}

/// Per-PMT-PID reassembly + version-diffing state (issue #774): the
/// `program_number` this PID was learned under from the PAT (a defensive
/// cross-check against the PMT section's own `program_number`), the last
/// **applied** `version_number` (so a carousel-repeated identical-version
/// section — PMTs repeat several times a second on a real broadcast — is
/// parsed but never re-diffed), and the ES PID set this PMT last applied (the
/// diff baseline: only PIDs *this* PMT declared can be removed by it, never
/// another program's).
struct PmtState {
    reasm: SectionReassembler,
    program_number: u16,
    /// The program's `PCR_PID` (§2.4.4.9 Table 2-33), or `None` until a PMT
    /// has been applied. A system time-base discontinuity is signalled on this
    /// PID (§2.4.3.5), and only this program's elementary streams are rebased
    /// by it (r04-W50 review).
    pcr_pid: Option<Pid>,
    last_applied_version: Option<u8>,
    applied_es: BTreeSet<Pid>,
}

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

impl StreamingTsDemux {
    /// Create a new streaming demuxer with empty state.
    pub fn new() -> Self {
        Self {
            resync: TsResync::new(),
            packet_index: 0,
            degraded_cap: None,
            degraded_dropped: 0,
            queue_scanned: 0,
            degraded_queued: 0,
            pat_reasm: SectionReassembler::default(),
            pmt_reasm: BTreeMap::new(),
            es_seen: BTreeSet::new(),
            streams: BTreeMap::new(),
            unattributed: BTreeMap::new(),
            removed_pids: BTreeSet::new(),
            es_declarers: BTreeMap::new(),
            unattributed_order: VecDeque::new(),
            unattributed_bytes: 0,
            codec_order: Vec::new(),
            data_order: Vec::new(),
            resolved: BTreeSet::new(),
            skipped: BTreeSet::new(),
            next_track_id: TrackId::new(1),
            events: VecDeque::new(),
            generation: 0,
            tracks_resolved_signalled_at: None,
            cc_states: BTreeMap::new(),
            afd_persistence: AfdPersistence::UntilReplaced,
            strict_pmt_order: false,
        }
    }

    /// Promote tracks strictly in PMT-declaration order across *all*
    /// programs, with only the pre-existing step-over bounds
    /// (`PROBE_HEAD_BLOCK_AUS`, `SILENT_HEAD_PARKED_BYTES`).
    ///
    /// The default is the live policy: an unresolved head holds back only the
    /// PIDs of its own program, and a head that cannot be a legitimate wait is
    /// stepped over after `STUCK_HEAD_OWN_BYTES` / `STUCK_HEAD_INPUT_PACKETS`,
    /// so a stuck PID never keeps a multi-program capture from delivering
    /// until `finish()`. The cost is that track ids follow resolution order,
    /// not PMT order. A caller that holds the whole input and calls `finish()`
    /// has no liveness to protect and wants stable PMT-order ids; this keeps
    /// them (it is what [`TsDemux`] uses).
    #[must_use]
    pub fn with_strict_pmt_order(mut self) -> Self {
        self.strict_pmt_order = true;
        self
    }

    /// Cap the number of [`DemuxEvent::InputDegraded`] events that may sit
    /// undrained in the queue (issue #1352). Once `cap` are queued, further
    /// `InputDegraded` events are dropped and counted in
    /// [`degraded_events_dropped`](Self::degraded_events_dropped) instead of
    /// growing the queue; every other event kind is unaffected (their volume
    /// is bounded by the input itself, and dropping a sample or track event
    /// would corrupt the stream). The default is **no cap** — a caller that
    /// drains [`poll_event`](Self::poll_event) after each
    /// [`feed`](Self::feed) never needs one. The cap is enforced at the end of
    /// each `feed`/`finish`, so one call may transiently queue more than `cap`.
    #[must_use]
    pub fn with_max_degraded_events(mut self, cap: usize) -> Self {
        self.degraded_cap = Some(cap);
        self
    }

    #[must_use]
    pub fn with_afd_persistence(mut self, policy: AfdPersistence) -> Self {
        self.afd_persistence = policy;
        self
    }
    pub fn degraded_events_dropped(&self) -> u64 {
        self.degraded_dropped
    }

    /// Enforce `degraded_cap` over the events queued since the last call.
    fn enforce_degraded_cap(&mut self) {
        let Some(cap) = self.degraded_cap else {
            return;
        };
        let tail: Vec<DemuxEvent> = self.events.drain(self.queue_scanned..).collect();
        for ev in tail {
            if matches!(ev, DemuxEvent::InputDegraded { .. }) {
                if self.degraded_queued >= cap {
                    self.degraded_dropped += 1;
                    continue;
                }
                self.degraded_queued += 1;
            }
            self.events.push_back(ev);
        }
        self.queue_scanned = self.events.len();
    }

    /// Feed `data` — any size, any alignment (mid-packet chunk boundaries are
    /// legal, including one byte at a time). Internally resynchronises to
    /// `0x47` TS packet boundaries via [`mpeg_ts::resync::TsResync`] and
    /// processes every newly-aligned packet.
    ///
    /// **Drain after every call.** Every event produced is appended to an
    /// internal queue that only [`poll_event`](Self::poll_event) empties; a
    /// caller that feeds without polling grows memory linearly with the input
    /// (samples, and — on lossy input — roughly two `InputDegraded` events per
    /// loss). Loop `while let Some(ev) = demux.poll_event()` after each
    /// `feed`. If events may legitimately go undrained, bound the
    /// diagnostic volume with
    /// [`with_max_degraded_events`](Self::with_max_degraded_events).
    pub fn feed(&mut self, data: &[u8]) {
        let packets = self.resync.feed(data);
        let mut losses = self.resync.take_losses().into_iter().peekable();
        for raw in &packets {
            // A loss sits *between* two packets: report it before the first
            // intact packet that follows it.
            while let Some(loss) = losses.next_if(|l| l.packet_index <= self.packet_index) {
                self.push_resync_loss(loss);
            }
            self.process_packet(raw);
        }
        for loss in losses {
            self.push_resync_loss(loss);
        }
        self.enforce_degraded_cap();
    }

    /// Surface one [`mpeg_ts::resync::ResyncLoss`] as a
    /// [`DemuxEvent::InputDegraded`]: a bad sync byte, garbage or a truncated
    /// tail is data the demuxer discarded and must not pass silently.
    fn push_resync_loss(&mut self, loss: mpeg_ts::resync::ResyncLoss) {
        let kind = if loss.truncated_tail {
            InputDegradation::TruncatedPacket {
                offset: loss.offset,
                dropped_bytes: loss.dropped_bytes,
            }
        } else {
            InputDegradation::SyncLoss {
                offset: loss.offset,
                dropped_bytes: loss.dropped_bytes,
            }
        };
        self.events.push_back(DemuxEvent::InputDegraded {
            track: None,
            kind,
            provenance: EventProvenance {
                pid: None,
                packet_index: Some(loss.packet_index),
                program_number: None,
            },
        });
    }

    /// Best-effort resolved track ID for `pid`, when it has already been
    /// promoted to [`TrackState::Live`] — used to populate
    /// [`DemuxEvent::Discontinuity`]'s `track` field. `None` (never
    /// fabricated) when the PID is not yet known, still `Probing`/`Parked`,
    /// or has no [`StreamState`] at all (e.g. a discontinuity observed before
    /// this PID's PMT entry has been seen).
    fn live_track_id(&self, pid: Pid) -> Option<TrackId> {
        match self.streams.get(&pid)?.track.as_ref()? {
            TrackState::Live(live) => Some(live.track_id),
            _ => None,
        }
    }

    fn process_packet(&mut self, raw: &[u8; TS_PACKET_SIZE]) {
        let idx = self.packet_index;
        self.packet_index += 1;
        let Ok(pkt) = TsPacket::parse(raw) else {
            return;
        };

        // TEI degradation (issue #778) — the demodulator-set flag on an
        // uncorrectable packet error, independent of PID classification or
        // adaptation field handling.
        if pkt.header.tei {
            let provenance = EventProvenance {
                pid: Some(pkt.header.pid),
                packet_index: Some(idx),
                program_number: None,
            };
            self.events.push_back(DemuxEvent::InputDegraded {
                track: self.live_track_id(pkt.header.pid),
                kind: InputDegradation::TransportError,
                provenance,
            });
        }

        // CC check (issue #778) — payload-bearing, non-null packets only,
        // excluding signalled discontinuities (the adaptation-field check
        // that follows).
        let discontinuity_signalled = pkt.header.has_adaptation
            && raw
                .get(4)
                .is_some_and(|af_len| *af_len > 0 && raw.get(5).is_some_and(|b| b & 0x80 != 0));

        // PCR / discontinuity — independent of PID classification, matches
        // every packet's adaptation field regardless of payload routing.
        if let Some(Ok(af)) = pkt.adaptation_field() {
            let provenance = EventProvenance {
                pid: Some(pkt.header.pid),
                packet_index: Some(idx),
                program_number: None,
            };
            if af.discontinuity_indicator {
                // §2.4.3.5: a system time-base discontinuity is signalled by
                // the `discontinuity_indicator` in a packet of the program's
                // **PCR_PID** — "When the discontinuity state is true for a
                // transport stream packet of a PID designated as a PCR_PID, the
                // next PCR in a transport stream packet with that same PID
                // represents a sample of a new system time clock for the
                // associated program." So the rebase is scoped twice over:
                // only the packet's own PID can carry it, and only that PID's
                // *program* is rebased. A multi-program multiplex therefore
                // leaves the other programs' timelines untouched (r04-W50
                // review), where the first attempt marked every stream in the
                // demux.
                let pid = pkt.header.pid;
                let program_ok = self.pmt_reasm.values().any(|pmt| pmt.pcr_pid == Some(pid));
                if program_ok {
                    // Every elementary stream of this program: the ones whose
                    // declaring PMT is this PCR_PID's.
                    let members: Vec<Pid> = self
                        .es_declarers
                        .iter()
                        .filter(|(_, pmt_pids)| {
                            pmt_pids.iter().any(|pmt_pid| {
                                self.pmt_reasm
                                    .get(&Pid::new((pmt_pid).value()))
                                    .is_some_and(|pmt| pmt.pcr_pid == Some(pid))
                            })
                        })
                        .map(|(&es_pid, _)| es_pid)
                        .collect();
                    for es_pid in members {
                        if let Some(stream) = self.streams.get_mut(&es_pid) {
                            stream.pending_rebase = true;
                        }
                    }
                }
                self.events.push_back(DemuxEvent::Discontinuity {
                    track: self.live_track_id(pid),
                    kind: DiscontinuityKind::Signalled,
                    provenance,
                });
            }
            if let Some(pcr) = af.pcr {
                // Issue #1354 / §2.4.3.5 + §2.4.4.9: only a program's
                // PCR_PID carries that program's clock. One event per
                // program naming this PID; see `DemuxEvent::ClockReference`
                // for the pre-PMT (`program_number: None`) policy.
                let mut programs: Vec<u16> = self
                    .pmt_reasm
                    .values()
                    .filter(|pmt| pmt.pcr_pid == Some(pkt.header.pid))
                    .map(|pmt| pmt.program_number)
                    .collect();
                programs.sort_unstable();
                programs.dedup();
                let pmts_pending = self.pmt_reasm.is_empty()
                    || self.pmt_reasm.values().any(|pmt| pmt.pcr_pid.is_none());
                let mut emit = |program_number: Option<u16>| {
                    self.events.push_back(DemuxEvent::ClockReference {
                        ticks: pcr.as_27mhz(),
                        clock_hz: PCR_CLOCK_HZ,
                        discontinuous: af.discontinuity_indicator,
                        provenance: EventProvenance {
                            program_number,
                            ..provenance
                        },
                    });
                };
                if programs.is_empty() {
                    if pmts_pending {
                        emit(None);
                    }
                } else {
                    for program in programs {
                        emit(Some(program));
                    }
                }
            }
        }

        let mut cc_verdict = CcVerdict::Deliver;
        // CC gap degradation (issue #778) — payload-bearing, non-null packets
        // only. The discontinuity flag is passed in so check_cc can suppress
        // the EVENT but STILL UPDATE the per-PID state (matching both in-repo
        // reference implementations: dvb-conformance's check_cc at
        // lib.rs:979-982 and media-doctor's CcAnomalyCheck at cc_anomaly.rs:110-113
        // — both update last_cc unconditionally on every payload-bearing packet,
        // including those with discontinuity_indicator set).
        if pkt.header.has_payload && pkt.header.pid != NULL_PACKET_PID {
            cc_verdict = self.check_cc(
                pkt.header.pid,
                pkt.header.continuity_counter,
                raw,
                discontinuity_signalled,
                idx,
            );
        }

        let pid = pkt.header.pid;
        let pusi = pkt.header.pusi;
        let Some(payload) = pkt.payload else {
            return;
        };

        // r04-W49. A legal §2.4.3.3 duplicate is discarded outright — feeding
        // it on would append its 184 payload bytes a second time to the access
        // unit under construction. (`check_cc` already updated the per-PID
        // baseline, exactly as the spec's "same continuity_counter as the
        // original" requires.)
        if cc_verdict == CcVerdict::Duplicate {
            self.try_promote_ready();
            return;
        }
        // A gap left the access unit currently in the reassembler short of
        // bytes, so it must not be delivered: the IR cannot tell a complete
        // PES from a truncated one, and every downstream muxer would write the
        // corruption out. Mark it abandoned (`keep_payload = false`) rather
        // than resetting the assembler — a reset would also stop the byte
        // accounting that bounds a runaway PES. A `payload_unit_start` clears
        // the mark, because it begins a new, intact access unit from its first
        // byte. Adaptation-field-only packets never reach here.

        if pid == PAT_PID {
            self.pat_reasm.feed(payload, pusi);
            while let Some(section) = self.pat_reasm.pop_section() {
                // A corrupt PAT must never rebind a PID: an ES PID wrongly
                // landing in `pmt_reasm` shadows `streams` for the rest of the
                // stream (see `psi_section_crc_ok`).
                if !psi_section_crc_ok(&section) {
                    continue;
                }
                // A "next" PAT (§2.4.4.1) is parsed but not applied — the same
                // `current_next_indicator == 1` rule PMT application uses.
                if !section_current_next(&section) {
                    continue;
                }
                if let Ok(programs) = parse_pat(&section) {
                    for (program_number, pmt_pid) in programs {
                        self.learn_pmt_pid(pmt_pid, program_number);
                    }
                }
            }
            return;
        }

        if let Some(pmt_state) = self.pmt_reasm.get_mut(&pid) {
            pmt_state.reasm.feed(payload, pusi);
            let mut sections: Vec<Vec<u8>> = Vec::new();
            while let Some(section) = pmt_state.reasm.pop_section() {
                sections.push(section.to_vec());
            }
            let program_number = pmt_state.program_number;
            let mut to_apply: Option<Vec<(Pid, Codec, Vec<u8>)>> = None;
            for section in &sections {
                // CRC first, before *anything* observable happens: PMT
                // application is destructive (it can tear a live track down
                // and reassign track_ids), and even bumping
                // `last_applied_version` off a corrupt section would suppress
                // the genuine version that follows. See `psi_section_crc_ok`.
                if !psi_section_crc_ok(section) {
                    continue;
                }
                let Ok(header) = parse_pmt_section_header(section) else {
                    continue;
                };
                if header.program_number != program_number {
                    // Defensive cross-check (issue #774): a PMT PID's
                    // program_number must match the PAT entry it was learned
                    // under. A mismatch is stream corruption or a PAT/PMT
                    // race — never act on it.
                    continue;
                }
                if header.section_number != 0 || header.last_section_number != 0 {
                    // A PMT is always single-section (§2.4.4.9) — a
                    // multi-section claim is malformed, ignore it.
                    continue;
                }
                if !header.current_next {
                    // A "next" table: parsed, never applied.
                    continue;
                }
                if pmt_state.last_applied_version == Some(header.version) {
                    // Carousel repeat (identical applied version) — dropped
                    // before the diff, never re-processed.
                    continue;
                }
                pmt_state.last_applied_version = Some(header.version);
                // Record the PCR_PID the program just declared: it is the PID
                // on which a system time-base discontinuity for this program is
                // signalled (§2.4.3.5), and the key for scoping a rebase to
                // this program's streams (r04-W50 review).
                pmt_state.pcr_pid = Some(header.pcr_pid);
                if let Ok(es_list) = parse_pmt(section) {
                    to_apply = Some(es_list);
                }
            }
            if let Some(es_list) = to_apply {
                let old_applied_es = pmt_state.applied_es.clone();
                let new_applied_es: BTreeSet<Pid> = es_list.iter().map(|(p, _, _)| *p).collect();
                self.apply_pmt_diff(pid, &old_applied_es, es_list);
                if let Some(pmt_state) = self.pmt_reasm.get_mut(&pid) {
                    pmt_state.applied_es = new_applied_es;
                }
            }
            self.try_promote_ready();
            return;
        }

        if let Some(stream) = self.streams.get_mut(&pid) {
            stream.payload_packets = stream.payload_packets.saturating_add(1);
            let mut sections: Vec<Vec<u8>> = Vec::new();
            // ── r04-W49 intactness rule ────────────────────────────────────
            //
            // An access unit is delivered only when nothing was lost from it:
            //
            //  * **A gap on a continuation packet** (`cc_verdict == Gap`,
            //    `pusi == false`) means 184 bytes of the unit in progress are
            //    missing. It is marked damaged, and the mark survives to the
            //    end of the unit — no later packet may clear it.
            //  * **A gap on a `payload_unit_start` packet** is benign: a
            //    `payload_unit_start` *ends* the previous unit, so nothing
            //    after the jump belongs to it. The byte stream simply
            //    restarts — which is what every independently muxed segment
            //    does (its counter begins wherever its own muxer chose), and
            //    what a splice looks like when the source sets no
            //    `discontinuity_indicator`. Anything genuinely lost inside the
            //    completing unit shows up as a gap on one of its own
            //    continuation packets, which the first rule catches.
            //  * **A signalled discontinuity** (`discontinuity_indicator`) is
            //    **This is not, by itself, a reason to drop anything.** The
            //    indicator says the source's byte stream is discontinuous here,
            //    and when it lands on a *continuation* packet that packet's
            //    bytes are indeed missing (the gap rule above marks it). But a
            //    packet carrying the indicator which *completes* a whole unit —
            //    a normal HLS or splice seam, where the last unit of the old
            //    segment is intact and the indicator merely precedes the new
            //    one — must still be delivered. Dropping it lost the last old
            //    access unit at every seam, which is exactly the loss this
            //    rule exists to avoid. Only an actual CC gap inside the unit,
            //    or a bounded PES short of its declared length, damages it.
            //
            // A `payload_unit_start` always begins a *new*, whole unit.
            let gap_here = cc_verdict == CcVerdict::Gap;
            // An independent, length-based check: a *bounded* PES
            // (`PES_packet_length != 0`) that received fewer bytes than its own
            // header declared is truncated, whatever the continuity counter
            // says. `PES_packet_length` counts the bytes after its own field,
            // so the whole packet is `PES_LENGTH_FIELD_END + declared`; the
            // received count is TS-payload bytes, which can exceed that by the
            // last packet's `0xFF` stuffing, so the test is `<`.
            let short_of_declared = stream.pes_declared_len > 0
                && stream.pes_received < PES_LENGTH_FIELD_END + stream.pes_declared_len as usize;
            // A unit is damaged only by something that actually lost bytes from
            // it: a continuity-counter gap on one of its own packets (the mark)
            // or a bounded PES that arrived short of its declared length. A
            // `discontinuity_indicator` is *not* such evidence on its own —
            // see the rule above.
            let completed_intact = stream.current_pes_intact && !short_of_declared;
            let mut completed_pes = None;
            if gap_here
                && !pusi
                && matches!(stream.codec, Codec::H264 | Codec::Hevc)
                && matches!(stream.carrier, Carrier::Pes(_))
            {
                if let Carrier::Pes(assembler) = &mut stream.carrier
                    && let Some(bytes) = assembler.flush()
                {
                    harvest_damaged_au(stream, pid, &bytes, &mut self.events);
                }
                stream.current_pes_intact = false;
                clear_audio_carry(stream, &mut self.events);
            } else if matches!(stream.carrier, Carrier::Pes(_)) {
                completed_pes = feed_pes_bounded(stream, pid, pusi, payload, &mut self.events);
            } else if let Carrier::Section(reasm) = &mut stream.carrier {
                reasm.feed(payload, pusi);
                while let Some(s) = reasm.pop_section() {
                    sections.push(s.to_vec());
                }
            }
            // `completed_intact` false means dropped, not delivered (r04-W49).
            if completed_pes.is_some() && !completed_intact {
                // A dropped unit loses its bytes, so an audio frame tail held
                // from the previous unit can no longer be joined to what
                // follows (issue #1160).
                clear_audio_carry(stream, &mut self.events);
            }
            if completed_intact && let Some(completed) = completed_pes {
                on_completed_pes(stream, pid, &completed, &mut self.events);
            } else if let Some(completed) = completed_pes
                && matches!(stream.codec, Codec::H264 | Codec::Hevc)
            {
                harvest_damaged_au(stream, pid, &completed, &mut self.events);
            }
            if gap_here {
                // Bytes were lost on this PID: whatever frame tail an audio
                // track holds (including the one the unit just completed
                // above may have left) is no longer contiguous with the next
                // payload (issue #1160).
                clear_audio_carry(stream, &mut self.events);
            }
            if matches!(stream.carrier, Carrier::Pes(_)) {
                if pusi {
                    // A new unit begins whole from its first byte.
                    stream.current_pes_intact = true;
                } else if gap_here {
                    // The unit in progress lost bytes. Two things are needed:
                    // the mark (so the unit is dropped, never delivered
                    // truncated), and an assembler reset — without it the
                    // bytes arriving *after* the gap would be appended to the
                    // pre-gap bytes as if contiguous, welding two unrelated
                    // fragments into one buffer that some later
                    // `payload_unit_start` would hand on. The byte accounting
                    // is deliberately left alone: `pes_bytes` continues to
                    // count what this PID is buffering, so a runaway PES is
                    // still bounded.
                    stream.current_pes_intact = false;
                    if let Carrier::Pes(assembler) = &mut stream.carrier {
                        let _ = assembler.flush();
                    }
                }
            }
            for s in sections {
                on_completed_section(stream, pid, &s, &mut self.events);
            }
        } else if pid != NULL_PACKET_PID && !self.removed_pids.contains(&pid) {
            self.unattributed
                .entry(pid)
                .or_default()
                .push_back((pusi, payload.to_vec()));
            self.unattributed_order.push_back(pid.value());
            self.unattributed_bytes += payload.len();
            self.evict_unattributed();
        }
        self.try_promote_ready();
    }

    /// Check the continuity counter for `pid` against the tracking state,
    /// emitting [`DemuxEvent::InputDegraded`]`(`[`InputDegradation::ContinuityGap`]`)`
    /// when a genuine gap is detected (issue #778), and returning what the
    /// caller must do with this packet's payload (r04-W49).
    ///
    /// Does **not** fire for:
    /// - Signalled discontinuities (`discontinuity_signalled`): the event is
    ///   suppressed, but `last_cc` and `last_payload` are still updated to
    ///   this packet (matching the dvb-conformance and media-doctor reference
    ///   implementations — both update the CC baseline unconditionally).
    /// - Legal duplicates: same CC + byte-identical packet with only the PCR
    ///   field excepted (ITU-T H.222.0 §2.4.3.3) — see [`CcVerdict::Duplicate`].
    ///
    /// # Arguments
    /// - `pid` — the TS PID.
    /// - `cc` — the 4-bit continuity counter from the packet header.
    /// - `raw` — the whole 188-byte packet, for the §2.4.3.3 duplicate
    ///   comparison (which the adapter must have handled: `pkt.payload`
    ///   excludes the adaptation field, so a PCR-only difference between an
    ///   original and its duplicate is invisible to it).
    /// - `discontinuity_signalled` — `true` when the adaptation field's
    ///   `discontinuity_indicator` is set. Suppresses the event but NOT the
    ///   state update.
    /// - `packet_index` — 0-based index of this packet in the stream.
    fn check_cc(
        &mut self,
        pid: Pid,
        cc: u8,
        raw: &[u8; TS_PACKET_SIZE],
        discontinuity_signalled: bool,
        packet_index: u64,
    ) -> CcVerdict {
        let track = self.live_track_id(pid);
        match self.cc_states.entry(pid) {
            Entry::Occupied(mut e) => {
                let state = e.get_mut();
                if !state.initialized {
                    state.initialized = true;
                    state.last_cc = cc;
                    state.last_packet = Some(*raw);
                    return CcVerdict::Deliver;
                }
                // §2.4.3.3: a legal duplicate repeats the previous packet
                // byte-for-byte (PCR field excepted), same continuity_counter.
                // The decoder shall discard it — it carries no new data, and
                // feeding it to the reassembler duplicated 184 payload bytes
                // into the access unit under construction (r04-W49).
                //
                // `pkt.payload` alone cannot decide this: a duplicate's PCR is
                // legally re-encoded, so the comparison must cover the whole
                // packet. `check_duplicate` also folds in the "two, and only
                // two consecutive" rule — a third identical repeat is an error,
                // not a duplicate.
                if cc == state.last_cc
                    && let Some(prev) = state.last_packet
                {
                    match broadcast_common::ts_dup::check_duplicate(
                        &prev,
                        raw,
                        state.dup_used_for_last,
                    ) {
                        // §2.4.3.3's one legal repeat. `dup_used_for_last`
                        // records that this PID has now spent it.
                        broadcast_common::ts_dup::DuplicateVerdict::Legal => {
                            state.dup_used_for_last = true;
                            state.last_packet = Some(*raw);
                            return CcVerdict::Duplicate;
                        }
                        // A third (or later) identical repeat: "two, and only
                        // two" consecutive packets (§2.4.3.3; TR 101 290 1.4
                        // "duplicate more than twice") makes it a continuity
                        // fault, reported once PER excess packet. No packet
                        // was lost - it is a redundant copy - so its payload
                        // is discarded like a duplicate rather than dropping
                        // the access unit under construction, and the run
                        // stays "spent" (`dup_used_for_last` is NOT reset),
                        // so a 5-packet run reports 3 faults, not an
                        // alternating legal/illegal pattern.
                        broadcast_common::ts_dup::DuplicateVerdict::IllegalThirdRepeat => {
                            if !discontinuity_signalled {
                                self.events.push_back(DemuxEvent::InputDegraded {
                                    track,
                                    kind: InputDegradation::ContinuityGap {
                                        expected: (state.last_cc + 1) & 0x0F,
                                        got: cc,
                                    },
                                    provenance: EventProvenance {
                                        pid: Some(pid),
                                        packet_index: Some(packet_index),
                                        program_number: None,
                                    },
                                });
                            }
                            state.last_packet = Some(*raw);
                            return CcVerdict::Duplicate;
                        }
                        _ => {}
                    }
                }
                let expected = (state.last_cc + 1) & 0x0F;
                let mut verdict = CcVerdict::Deliver;
                if !discontinuity_signalled && cc != expected {
                    self.events.push_back(DemuxEvent::InputDegraded {
                        track,
                        kind: InputDegradation::ContinuityGap { expected, got: cc },
                        provenance: EventProvenance {
                            pid: Some(pid),
                            packet_index: Some(packet_index),
                            program_number: None,
                        },
                    });
                    // The gap lost at least one packet, so the access unit the
                    // reassembler is part-way through is missing bytes. Let it
                    // be delivered as if complete and it is corrupt — the
                    // coarse timeline repair (`rebase`) cannot tell a complete
                    // PES from a truncated one. Request the drop, matching
                    // `rtp_stream`'s own response to loss.
                    verdict = CcVerdict::Gap;
                }
                state.last_cc = cc;
                state.last_packet = Some(*raw);
                state.dup_used_for_last = false;
                verdict
            }
            Entry::Vacant(e) => {
                e.insert(CcState {
                    initialized: true,
                    last_cc: cc,
                    last_packet: Some(*raw),
                    dup_used_for_last: false,
                });
                CcVerdict::Deliver
            }
        }
    }

    /// Bind `pmt_pid` to the `program_number` a currently-applicable PAT
    /// (§2.4.4.4) just listed it under.
    ///
    /// The binding is **updatable**, not write-once. A PAT may legitimately
    /// remap a PMT PID to a different program mid-stream, and the previous
    /// `entry().or_insert_with()` froze the first `program_number` ever seen —
    /// after which the defensive `header.program_number != program_number`
    /// cross-check in [`Self::process_packet`] rejected *every* PMT on that
    /// PID forever, silently demuxing the program to zero tracks.
    ///
    /// A re-bind also clears `last_applied_version`: the version counter
    /// belongs to the program's PMT, not to the PID, so the new program's PMT
    /// may legitimately re-use a `version_number` the old program had already
    /// applied. `applied_es` is deliberately kept — it is the diff baseline of
    /// what this PID last put into `streams`, and the incoming PMT must still
    /// be diffed against it so the outgoing program's tracks are torn down.
    fn learn_pmt_pid(&mut self, pmt_pid: Pid, program_number: u16) {
        match self.pmt_reasm.get_mut(&pmt_pid) {
            Some(state) if state.program_number != program_number => {
                state.program_number = program_number;
                state.last_applied_version = None;
            }
            Some(_) => {}
            None => {
                self.pmt_reasm.insert(
                    pmt_pid,
                    PmtState {
                        reasm: SectionReassembler::default(),
                        program_number,
                        pcr_pid: None,
                        last_applied_version: None,
                        applied_es: BTreeSet::new(),
                    },
                );
            }
        }
    }

    /// Enforce [`MAX_UNATTRIBUTED_BYTES`] by FIFO-evicting the oldest buffered
    /// `unattributed` payloads. Order entries whose PID has already been
    /// replayed into `streams` (and thus removed from the map) are stale and
    /// skipped without touching the byte counter.
    fn evict_unattributed(&mut self) {
        while self.unattributed_bytes > MAX_UNATTRIBUTED_BYTES {
            let Some(pid) = self.unattributed_order.pop_front() else {
                break;
            };
            if let Some(buf) = self.unattributed.get_mut(&Pid::new(pid)) {
                if let Some((_, payload)) = buf.pop_front() {
                    self.unattributed_bytes = self.unattributed_bytes.saturating_sub(payload.len());
                }
                if buf.is_empty() {
                    self.unattributed.remove(&Pid::new(pid));
                }
            }
        }
    }

    /// Register a genuinely new elementary-stream PID discovered from an
    /// applied PMT (first ever registration, or a version diff's "added"
    /// side — issue #774): rank it into `codec_order`/`data_order`, build its
    /// fresh [`StreamState`] (`Probing` from scratch), and replay any
    /// `unattributed` payloads that arrived on this PID before its PMT
    /// registration completed. Never emits an event itself — `TrackAdded`
    /// fires once this PID reaches its PMT-declaration-order turn in
    /// [`Self::try_promote_ready`].
    ///
    /// Appends to the back of its destination order list — the correct slot
    /// for a PID never seen before. A codec-changed *re*-registration (see
    /// `apply_pmt_diff`) instead goes through [`Self::register_new_es_at`] to
    /// preserve the PID's original PMT-declaration-order slot.
    fn register_new_es(&mut self, es_pid: Pid, codec: Codec, descriptors: Vec<u8>) {
        self.register_new_es_at(es_pid, codec, descriptors, None);
    }

    /// As [`Self::register_new_es`], but inserts the PID at `reinsert_at`
    /// within its destination order list instead of always appending
    /// (issue: re-registration losing PMT-declaration order). Used by
    /// `apply_pmt_diff`'s codec-changed path to restore the PID to the slot
    /// it occupied before `remove_track` erased it, instead of losing that
    /// slot to the back of the list — which would reorder `TrackAdded`
    /// emission and could block a later-ranked PID's promotion behind it.
    /// `None` (this PID has never been ranked, or it is crossing between the
    /// codec/data lists — see the caller) appends, exactly like
    /// `register_new_es`.
    fn register_new_es_at(
        &mut self,
        es_pid: Pid,
        codec: Codec,
        descriptors: Vec<u8>,
        reinsert_at: Option<usize>,
    ) {
        // A PID declared again is no longer an orphan: lift the post-removal
        // buffering blacklist (see `remove_track`) so its fresh traffic is
        // routed normally from here on.
        self.removed_pids.remove(&es_pid);
        let order = if matches!(codec, Codec::Data(_)) {
            &mut self.data_order
        } else {
            &mut self.codec_order
        };
        match reinsert_at {
            Some(idx) if idx <= order.len() => order.insert(idx, es_pid),
            _ => order.push(es_pid),
        }
        let mut stream = StreamState {
            codec,
            descriptors,
            carrier: initial_carrier(codec),
            last_frame_period: 0,
            recent_steps: Vec::new(),
            pending_rebase: false,
            current_pes_intact: true,
            pes_declared_len: 0,
            pes_received: 0,
            pes_bytes: 0,
            fallback: (0, 0),
            frame_period: None,
            last_stamped_dts: None,
            units_since_stamped: 0,
            has_any: false,
            wrap: WrapState::default(),
            track: Some(TrackState::Probing {
                probe: initial_probe(codec),
                backlog: Vec::new(),
            }),
            backlog_bytes: 0,
            probe_tail: Vec::new(),
            probe_aus: 0,
            probe_walks: 0,
            probe_walked_len: 0,
            payload_packets: 0,
            damaged_promotion: false,
            declared_at_packet: self.packet_index,
            unit_released: false,
        };
        // Replay any payloads that arrived on this PID before its PMT
        // registration completed (see `unattributed`'s doc).
        if let Some(buffered) = self.unattributed.remove(&es_pid) {
            for (buf_pusi, buf_payload) in buffered {
                stream.payload_packets = stream.payload_packets.saturating_add(1);
                self.unattributed_bytes = self.unattributed_bytes.saturating_sub(buf_payload.len());
                let mut sections: Vec<Vec<u8>> = Vec::new();
                let completed_pes = if matches!(stream.carrier, Carrier::Pes(_)) {
                    feed_pes_bounded(
                        &mut stream,
                        es_pid,
                        buf_pusi,
                        &buf_payload,
                        &mut self.events,
                    )
                } else if let Carrier::Section(reasm) = &mut stream.carrier {
                    reasm.feed(&buf_payload, buf_pusi);
                    while let Some(s) = reasm.pop_section() {
                        sections.push(s.to_vec());
                    }
                    None
                } else {
                    None
                };
                if let Some(completed) = completed_pes {
                    on_completed_pes(&mut stream, es_pid, &completed, &mut self.events);
                }
                for s in sections {
                    on_completed_section(&mut stream, es_pid, &s, &mut self.events);
                }
            }
        }
        self.streams.insert(es_pid, stream);
    }

    /// Drop a PID that a PMT no longer declares (issue #774): remove it from
    /// every bookkeeping set (`es_seen`/`codec_order`/`data_order`/`resolved`)
    /// and drop its [`StreamState`] entirely — any in-flight PES/backlog for
    /// it goes with it, so no [`DemuxEvent::Sample`] can ever follow the
    /// [`DemuxEvent::TrackRemoved`] this emits below. Only emits
    /// `TrackRemoved` when the PID had actually reached `Live` (a real
    /// `track_id` a consumer has seen via `TrackAdded`) — a PID removed while
    /// still `Probing`/`Parked`/`Abandoned` was never surfaced to a consumer
    /// in the first place, so there is nothing to report removing.
    ///
    /// Also purges — and then blacklists — this PID's `unattributed` backlog.
    /// That buffer exists solely to replay payloads that arrived *before* a
    /// PID's very first PMT registration; anything on a PID the declaration has
    /// since dropped is orphan traffic. Left in place it would accumulate to
    /// [`MAX_UNATTRIBUTED_BYTES`] and then be replayed as the *re-added*
    /// track's first samples, anchoring its `start_decode_time` in the past.
    /// The blacklist is lifted by [`Self::register_new_es`] the moment a PMT
    /// declares the PID again.
    fn remove_track(&mut self, pid: Pid) {
        self.es_seen.remove(&pid);
        self.codec_order.retain(|&p| p != pid);
        self.data_order.retain(|&p| p != pid);
        self.resolved.remove(&pid);
        self.skipped.remove(&pid);
        if let Some(buffered) = self.unattributed.remove(&pid) {
            for (_, payload) in &buffered {
                self.unattributed_bytes = self.unattributed_bytes.saturating_sub(payload.len());
            }
        }
        self.removed_pids.insert(pid);
        // Drop the continuity-counter baseline too: the PID's reassembly state
        // is gone with the track, so the CC of the first packet after a re-add
        // is judged against nothing, not against the pre-removal sequence
        // (which the source is under no obligation to continue — r04-W49's
        // gap handling would otherwise drop that first, perfectly good access
        // unit as truncated).
        self.cc_states.remove(&pid);
        if let Some(stream) = self.streams.remove(&pid)
            && let Some(TrackState::Live(mut live)) = stream.track
        {
            // An E-AC-3 track holding back its final access unit for a
            // possible dependent substream (#1186) received that unit whole:
            // emit it before the track goes (as `finish()` does), or the
            // removal silently drops the last access unit.
            if let LiveKind::Audio { kind, anchor, .. } = &mut live.kind
                && anchor.hold_final_au
            {
                flush_audio_carry(kind, anchor, live.track_id, &mut self.events);
            }
            self.events.push_back(DemuxEvent::TrackRemoved {
                track_id: live.track_id,
                provenance: EventProvenance {
                    pid: Some(pid),
                    packet_index: None,
                    program_number: None,
                },
            });
        }
    }

    /// Apply one PMT's newly-parsed, version-changed ES list against
    /// `old_applied_es` (that same PMT's previous applied ES set — issue
    /// #774): diff removed/added/kept-but-changed PIDs, then bump
    /// [`Self::generation`] once so [`Self::maybe_signal_tracks_resolved`]
    /// re-evaluates `TracksResolved`. Called only for a section that has
    /// already been confirmed `current_next_indicator == 1` with a
    /// genuinely new `version_number` — a carousel repeat never reaches here.
    fn apply_pmt_diff(
        &mut self,
        pmt_pid: Pid,
        old_applied_es: &BTreeSet<Pid>,
        es_list: Vec<(Pid, Codec, Vec<u8>)>,
    ) {
        let new_pids: BTreeSet<Pid> = es_list.iter().map(|(p, _, _)| *p).collect();

        let removed: Vec<Pid> = old_applied_es
            .iter()
            .copied()
            .filter(|p| !new_pids.contains(p))
            .collect();
        for pid in removed {
            // Refcounted by declaring PMT (`es_declarers`): the same
            // elementary PID may legally appear in more than one program's
            // PMT (a shared audio/subtitle component), and `streams`/`es_seen`
            // are global while `applied_es` is per-PMT — so one program
            // dropping the PID must not tear down a stream another program
            // still declares. Only the *last* declarer's drop removes it.
            let declarers = self.es_declarers.get_mut(&pid);
            let still_declared = match declarers {
                Some(declarers) => {
                    declarers.remove(&pmt_pid);
                    let empty = declarers.is_empty();
                    if empty {
                        self.es_declarers.remove(&pid);
                    }
                    !empty
                }
                None => false,
            };
            if !still_declared {
                self.remove_track(pid);
            }
        }

        for (es_pid, codec, descriptors) in es_list {
            self.es_declarers.entry(es_pid).or_default().insert(pmt_pid);
            if self.es_seen.insert(es_pid) {
                self.register_new_es(es_pid, codec, descriptors);
                continue;
            }
            // Compare through a shared borrow first, then act — the two
            // outcomes need different (and mutually exclusive) mutable
            // borrows of `self`.
            let Some(existing) = self.streams.get(&es_pid) else {
                continue;
            };
            let old_codec = existing.codec;
            let codec_changed = old_codec != codec;
            let descriptors_changed = existing.descriptors != descriptors;
            if !codec_changed && !descriptors_changed {
                continue;
            }
            if codec_changed {
                // Refcount check (the same one the "removed" loop above
                // applies, F1): the same elementary PID may legally be
                // declared by more than one program's PMT (a shared
                // audio/subtitle component). `es_declarers[es_pid]` already
                // has `pmt_pid` inserted (the unconditional insert above), so
                // any *other* entry means some other program still declares
                // this PID — and `streams`/`codec_order`/`data_order` are
                // global, not per-program, so tearing down here would also
                // destroy that other program's still-valid track (wrong
                // `track_id` churn: a spurious `TrackRemoved` + `TrackAdded`
                // for a change only *this* program asked for).
                //
                // Two programs declaring the same PID under two different
                // codecs is a malformed multiplex — there is only one global
                // stream for a PID, so at most one classification can be
                // active. Decision (stated here, not left implicit): refuse
                // to reclassify while any other declarer remains. The
                // existing classification wins and this PMT's update is
                // dropped for this PID; last-writer-wins was rejected because
                // it would let either program's routine version bump flip the
                // shared track back and forth. Once every *other* declarer
                // has itself dropped or stopped disagreeing, `es_declarers`
                // shrinks to just this PMT and a later reclassification by it
                // proceeds normally below.
                let other_declarers_remain = self
                    .es_declarers
                    .get(&es_pid)
                    .is_some_and(|declarers| declarers.iter().any(|&p| p != pmt_pid));
                if other_declarers_remain {
                    continue;
                }

                // A reclassified `stream_type` is a **different elementary
                // stream**, not an in-place relabel. Writing `stream.codec`
                // through (as this used to) left three pieces of derived state
                // built for the OLD codec:
                //
                //  * the `ConfigProbe` — e.g. `stream_type` 0x06 gaining an
                //    AC-3 descriptor turns `Codec::Data(0x06)` into
                //    `Codec::Ac3` while `ConfigProbe::Data` remains, which
                //    used to reach an `unreachable!` in `finalize_probe`;
                //  * the `Carrier` — ISO/IEC 13818-1 Table 2-34 splits
                //    `stream_type` into PES- and section-carried families, and
                //    feeding one family's bytes to the other's reassembler
                //    (0x86 → 0x1B: H.264 PES into a `SectionReassembler`)
                //    silently yields nothing while the track claims to exist;
                //  * any buffered access units, decoded under the old
                //    framing.
                //
                // Teardown-and-re-register rebuilds all three in one move:
                // `remove_track` drops the stream (emitting `TrackRemoved` if
                // it had reached `Live`) and `register_new_es_at` rebuilds
                // `initial_carrier`/`initial_probe` for the new codec.
                //
                // F3: capture this PID's current slot in its *old*
                // classification's order list before `remove_track` erases it,
                // so re-registration can restore the same slot instead of
                // losing it to the back of the list (which would reorder
                // `TrackAdded` emission and could block a later-ranked PID's
                // promotion behind it). Only meaningful when the old and new
                // classification share the same order list (codec vs. data):
                // a PID crossing between the two has no old slot to preserve
                // in the list it's moving to, so it appends there like any
                // other first-time registration into that list.
                let old_is_data = matches!(old_codec, Codec::Data(_));
                let new_is_data = matches!(codec, Codec::Data(_));
                let order_slot = if old_is_data == new_is_data {
                    let order = if old_is_data {
                        &self.data_order
                    } else {
                        &self.codec_order
                    };
                    order.iter().position(|&p| p == es_pid)
                } else {
                    None
                };
                self.remove_track(es_pid);
                // `es_seen` is the "currently declared" set, which
                // `remove_track` clears — but this PID *is* still declared,
                // just as something else.
                self.es_seen.insert(es_pid);
                self.register_new_es_at(es_pid, codec, descriptors, order_slot);
                continue;
            }
            // Descriptors-only change: nothing derived from the codec is
            // stale, so the track keeps its identity and is updated in place.
            let Some(stream) = self.streams.get_mut(&es_pid) else {
                continue;
            };
            stream.descriptors = descriptors.clone();
            if let Some(TrackState::Live(live)) = stream.track.as_ref() {
                let spec = TrackSpec::new(live.track_id, live.timescale, live.config.clone())
                    .with_source(es_pid, descriptors)
                    .with_hdr10plus(live.hdr10plus);
                self.events.push_back(DemuxEvent::TrackUpdated(spec));
            }
        }

        self.generation = self.generation.wrapping_add(1);
    }

    /// Promote every `Parked` PID that has reached its PMT-declaration-order
    /// turn to `Live`: assign the next sequential track ID, emit
    /// `DemuxEvent::TrackAdded`, and replay its accumulated backlog as a
    /// burst of `DemuxEvent::Sample`s — repeating while the *next*-ranked PID
    /// is also already `Parked`. A PID that is still `Probing` blocks the PIDs
    /// after it *of its own program* only (other programs' PIDs are promoted
    /// past it unless [`with_strict_pmt_order`](Self::with_strict_pmt_order));
    /// a PID not yet known at all stops the scan — except that a `Probing`
    /// PID that has seen [`PROBE_HEAD_BLOCK_AUS`] access units without
    /// resolving is stepped over rather than stopped at, so one probe that
    /// cannot resolve never holds back every track behind it.
    fn try_promote_ready(&mut self) {
        // PIDs still awaiting promotion, in PMT-declaration order. A snapshot:
        // nothing below adds or reorders PIDs.
        let pending: Vec<Pid> = self
            .codec_order
            .iter()
            .chain(self.data_order.iter())
            .copied()
            .filter(|p| !self.resolved.contains(p))
            .collect();
        let mut held_programs: BTreeSet<Option<Pid>> = BTreeSet::new();
        for next_pid in pending {
            let program = self
                .es_declarers
                .get(&next_pid)
                .and_then(|pmt_pids| pmt_pids.iter().next())
                .copied();
            if held_programs.contains(&program) {
                continue;
            }
            let Some(stream) = self.streams.get_mut(&next_pid) else {
                break;
            };
            // See `advance_track`: `track` is `None` only transiently, inside
            // these two functions. Degrade rather than panic.
            let Some(track) = stream.track.take() else {
                break;
            };
            match track {
                TrackState::Parked {
                    config,
                    timescale,
                    kind,
                    backlog,
                } => {
                    let track_id = self.next_track_id;
                    self.next_track_id = track_id.next();
                    // `Track::start_decode_time` is no longer carried by this
                    // event (issue #774 reshape dropped it along with
                    // `samples`/`encryption` when `TrackAdded` became
                    // `TrackSpec`-only) — every consumer that builds a `Track`
                    // derives it from `samples[0].dts` instead (media plane
                    // step 2c invariant: the two are always equal), so no
                    // anchor value needs computing here at all.
                    let hdr10plus = matches!(config, CodecConfig::Hevc { .. })
                        && backlog.first().is_some_and(|au| {
                            crate::hdr10plus::Hdr10PlusMetadata::annexb_access_unit_carries_hdr10plus(
                                &au.data,
                            )
                        });
                    let spec = TrackSpec::new(track_id, timescale, config.clone())
                        .with_source(next_pid, stream.descriptors.clone())
                        .with_hdr10plus(hdr10plus);
                    // Look up the program_number for this ES PID via its
                    // declaring PMT.
                    let program_number = self
                        .es_declarers
                        .get(&next_pid)
                        .and_then(|pmt_pids| pmt_pids.iter().next())
                        .and_then(|&pmt_pid| self.pmt_reasm.get(&pmt_pid))
                        .map(|state| ProgramNumber::new(state.program_number));
                    let spec = if let Some(pn) = program_number {
                        spec.with_program(pn)
                    } else {
                        spec
                    };
                    let sps_tracker = match stream.codec {
                        Codec::H264 => Some(
                            SpsTracker::new(TrackCodec::Avc)
                                .with_afd_persistence(self.afd_persistence),
                        ),
                        Codec::Hevc => Some(
                            SpsTracker::new(TrackCodec::Hevc)
                                .with_afd_persistence(self.afd_persistence),
                        ),
                        _ => None,
                    };
                    let mpeg2_tracker =
                        (stream.codec == Codec::Mpeg2Video).then(Mpeg2DisplayTracker::new);

                    let mut live = LiveTrack {
                        track_id,
                        kind,
                        config,
                        timescale,
                        parameter_sets: ParameterSets::default(),
                        config_header: None,
                        sps_tracker,
                        mpeg2_tracker,
                        pending_config: None,
                        display: None,
                        suppress_next_display_change: stream.damaged_promotion,
                        damaged_promotion: stream.damaged_promotion,
                        skip_next_reprobe: stream.damaged_promotion,
                        hdr10plus,
                    };
                    // Geometry-only seed state (active format filled in below from
                    // the first access unit, if any).
                    // The config's own geometry, except for MPEG-2: its probe
                    // carries only the two sizes (no sequence header in the
                    // `esds`), so its geometry comes from the backlog's first
                    // `sequence_header()` and is `None` until one was seen.
                    let config_geometry =
                        TrackSpec::new(track_id, timescale, live.config.clone()).display;
                    let geom_display = if live.mpeg2_tracker.is_some() {
                        let es: Vec<u8> = backlog
                            .iter()
                            .flat_map(|au| au.data.iter().copied())
                            .collect();
                        crate::ir::DisplayGeometry::from_mpeg2_es(&es).ok()
                    } else {
                        config_geometry
                    }
                    .and_then(|g| DisplayInfo::from_geometry(Some(g)));
                    if let Some(display) = &geom_display
                        && let Some(tracker) = live.sps_tracker.as_mut()
                    {
                        tracker.seed_state(display.geometry.clone());
                    }
                    // Process the whole backlog through the tracker (suppressing
                    // events) so its parameter sets and AFD are folded into the
                    // state before the initial event is emitted (one event, not
                    // two).
                    for au in &backlog {
                        if let Some(tracker) = live.sps_tracker.as_mut() {
                            let _ = tracker.observe(&au.data);
                        }
                        if let Some(tracker) = live.mpeg2_tracker.as_mut() {
                            let _ = tracker.observe(&au.data);
                        }
                    }
                    // Restore the sequence geometry to the (authoritative)
                    // TrackSpec value while keeping the backlog-derived active
                    // format.
                    if let Some(tracker) = live.sps_tracker.as_mut() {
                        let af = tracker.state().and_then(|s| s.active_format.clone());
                        let geom = geom_display.as_ref().and_then(|d| d.geometry.clone());
                        tracker.set_state(Some(Arc::new(
                            DisplayInfo::new(geom).with_active_format(af),
                        )));
                    }
                    // MPEG-2 keeps its own (backlog-derived) geometry: AFD
                    // persistence is the H.262 rule, so the tracker's state is
                    // authoritative, not the config's sizes.

                    let initial_display = live
                        .sps_tracker
                        .as_ref()
                        .and_then(|t| t.state().cloned())
                        .or_else(|| live.mpeg2_tracker.as_ref().and_then(|t| t.state().cloned()))
                        .or_else(|| geom_display.clone().map(Arc::new));
                    self.events.push_back(DemuxEvent::TrackAdded(spec));
                    if let Some(display) = &initial_display {
                        self.events.push_back(DemuxEvent::DisplayChanged {
                            track_id,
                            display: display.clone(),
                            changed: DisplayChangeSet::initial(),
                            dts: None,
                            pts: None,
                            random_access: false,
                            provenance: EventProvenance {
                                pid: Some(next_pid),
                                packet_index: None,
                                program_number: None,
                            },
                        });
                    }
                    // seed_state already done; ensure state matches initial_display
                    if let Some(display) = &initial_display
                        && let Some(tracker) = live.sps_tracker.as_mut()
                        && tracker.state().is_none()
                    {
                        tracker.seed_full(Some(display.clone()));
                    }
                    if let Some(tracker) = live.mpeg2_tracker.as_mut()
                        && tracker.state().is_none()
                    {
                        tracker.seed_full(initial_display.clone());
                    }
                    // Seed the changed-config comparison from the access units
                    // the config was actually recovered from, so the track's
                    // first header repeat after promotion is not mistaken for a
                    // change (r04-W51). The whole backlog is walked, not just
                    // its last access unit: SPS and PPS may be split across
                    // several of them, and the sets must be complete before the
                    // next access unit is compared against them.
                    for au in &backlog {
                        let _ = observe_parameter_sets(
                            stream.codec,
                            &au.data,
                            &mut live.parameter_sets,
                        );
                    }
                    if stream.codec == Codec::Aac
                        && let Some(au) = backlog.last()
                        && let Some((_, hdr)) = find_adts_sync(&au.data)
                    {
                        live.config_header = AudioSpecificConfig::from_adts_header(&hdr)
                            .try_to_bytes()
                            .ok();
                    }
                    let provenance = EventProvenance {
                        pid: Some(next_pid),
                        packet_index: None,
                        program_number: None,
                    };
                    for au in backlog {
                        let display = live.display(&au.data);
                        push_live_au(
                            &mut live,
                            &au.data,
                            au.pts_uw,
                            au.dts_uw,
                            provenance,
                            display,
                            &mut self.events,
                        );
                    }
                    stream.track = Some(TrackState::Live(live));
                    stream.backlog_bytes = 0;
                    self.resolved.insert(next_pid);
                    if self.skipped.remove(&next_pid) {
                        // A previously stepped-over head resolved late:
                        // `TracksResolved` already fired without it, so
                        // re-arm the signal (consumers learn of the new
                        // track via this `TrackAdded` + a fresh signal).
                        self.tracks_resolved_signalled_at = None;
                    }
                    // loop again: the next-ranked PID may also already be parked
                }
                other @ TrackState::Probing { .. } => {
                    stream.track = Some(other);
                    let never_sent = stream.payload_packets == 0;
                    let aus_stalled = stream.probe_aus >= PROBE_HEAD_BLOCK_AUS
                        && !matches!(stream.codec, Codec::H264 | Codec::Hevc | Codec::Mpeg2Video);
                    let is_video =
                        matches!(stream.codec, Codec::H264 | Codec::Hevc | Codec::Mpeg2Video);
                    let no_access_unit = stream.probe_aus == 0
                        && usize::try_from(stream.payload_packets)
                            .map_or(usize::MAX, |n| n.saturating_mul(TS_PACKET_SIZE))
                            >= STUCK_HEAD_OWN_BYTES;
                    let declared_at = stream.declared_at_packet;
                    let released = stream.unit_released;
                    let silent =
                        never_sent && self.parked_behind(next_pid) >= SILENT_HEAD_PARKED_BYTES;
                    let live_stuck = !self.strict_pmt_order
                        && (no_access_unit
                            || (!is_video
                                && self.packet_index.saturating_sub(declared_at)
                                    >= STUCK_HEAD_INPUT_PACKETS));
                    let stuck = released || live_stuck;
                    if silent || aus_stalled || stuck {
                        // Stalled: it no longer holds back the PIDs after it
                        // (see `PROBE_HEAD_BLOCK_AUS`); it stays unresolved and
                        // is promoted whenever it does resolve. Never applied
                        // to a *video* head: its probe legitimately waits a
                        // whole GOP, and stepping over it would hand the
                        // video a later (higher) track id than the audio that
                        // overtook it — consumers (ts_hls, multimux) expect
                        // PMT order. A video that truly never resolves is
                        // bounded by `MAX_PROBE_BACKLOG_BYTES` instead —
                        // unless it is entirely silent (`silent`: no packet
                        // at all while the PIDs behind it parked
                        // `SILENT_HEAD_PARKED_BYTES`), which is stepped over
                        // whatever its codec.
                        self.skipped.insert(next_pid);
                        continue;
                    }
                    if self.strict_pmt_order {
                        break;
                    }
                    held_programs.insert(program);
                    continue;
                }
                other @ TrackState::Live(_) => {
                    // Already resolved; `resolved` should already contain it,
                    // but stay consistent defensively and keep scanning.
                    stream.track = Some(other);
                    self.resolved.insert(next_pid);
                    self.skipped.remove(&next_pid);
                }
                TrackState::Abandoned => {
                    // [`MAX_PROBE_BACKLOG_BYTES`] overflowed for this PID
                    // (issue B8): permanently resolved without ever
                    // promoting — the same conclusion `finish()` reaches for
                    // a probe that never resolves at end-of-input, just
                    // reached early. Marking it resolved here is what lets a
                    // later-ranked `Parked` PID (blocked behind this one)
                    // proceed on the next loop iteration.
                    stream.track = Some(TrackState::Abandoned);
                    self.resolved.insert(next_pid);
                    self.skipped.remove(&next_pid);
                }
            }
        }
        self.maybe_signal_tracks_resolved();
    }

    /// Declare that the input fed so far is a complete, self-contained unit
    /// (an HLS media segment: it carries its own PAT/PMT and every PID that
    /// is in it), so a PID the PMT declares that has not sent a single
    /// payload packet is absent from it, not late. Such a head stops holding
    /// back the rest of its program (`SILENT_HEAD_PARKED_BYTES` is a
    /// parked-bytes bound a short unit never reaches).
    ///
    /// The head is stepped over, not abandoned: if packets arrive later it
    /// resolves and is announced by a later [`DemuxEvent::TrackAdded`] with a
    /// later track id, re-arming [`DemuxEvent::TracksResolved`]. Nothing else
    /// changes: a PES that continues into the next unit is untouched, so a
    /// conformant or non-conformant cut yields the same samples as without
    /// this call, only earlier.
    pub fn release_silent_heads(&mut self) {
        for stream in self.streams.values_mut() {
            if stream.payload_packets == 0
                && matches!(stream.track, Some(TrackState::Probing { .. }))
            {
                stream.unit_released = true;
            }
        }
        self.try_promote_ready();
    }

    /// Bytes currently held in the `Probing`/`Parked` backlogs of every
    /// unresolved PID except `head` (the [`SILENT_HEAD_PARKED_BYTES`]
    /// criterion).
    fn parked_behind(&self, head: Pid) -> usize {
        self.codec_order
            .iter()
            .chain(self.data_order.iter())
            .filter(|p| **p != head && !self.resolved.contains(*p))
            .filter_map(|p| self.streams.get(p))
            .fold(0usize, |sum, s| sum.saturating_add(s.backlog_bytes))
    }

    /// Emit [`DemuxEvent::TracksResolved`] (issue #624) when every currently
    /// known PID (`codec_order` + `data_order`) has resolved to `Live` — i.e.
    /// [`try_promote_ready`](Self::try_promote_ready) just ran to a fixed
    /// point with no PID left `Probing` — and [`Self::generation`] differs
    /// from the generation the signal last fired at (de-dup: a PMT
    /// re-processed with no applied change, or plain sample traffic on an
    /// already-fully-resolved stream, must not re-fire the event every time
    /// this is called).
    ///
    /// De-duping on `generation` rather than the known-PID count (issue
    /// #774) fixes a real bug the count-keyed version had: once a track is
    /// removable, the count can return to a previously-seen value (a removal
    /// immediately followed by an addition), which a count-keyed de-dup would
    /// wrongly treat as "already signalled" and never re-fire for.
    fn maybe_signal_tracks_resolved(&mut self) {
        let known = self.codec_order.len() + self.data_order.len();
        if known == 0 {
            return;
        }
        if self.resolved.len() + self.skipped.len() == known
            && self.tracks_resolved_signalled_at != Some(self.generation)
        {
            self.tracks_resolved_signalled_at = Some(self.generation);
            self.events.push_back(DemuxEvent::TracksResolved {
                generation: self.generation,
            });
        }
    }

    /// Drain the next pending event, if any (FIFO).
    ///
    /// This is the only thing that empties the event queue: call it in a loop
    /// after every [`feed`](Self::feed) / [`finish`](Self::finish) (see
    /// `feed` for what an undrained queue costs).
    pub fn poll_event(&mut self) -> Option<DemuxEvent> {
        let ev = self.events.pop_front()?;
        if self.queue_scanned > 0 {
            self.queue_scanned -= 1;
            if matches!(ev, DemuxEvent::InputDegraded { .. }) {
                self.degraded_queued -= 1;
            }
        }
        Some(ev)
    }

    /// Flush trailing partial access units (no more input coming): completes
    /// every PID's buffered PES payload, definitively abandons any PID whose
    /// config never became recoverable (unblocking later-ranked `Parked`
    /// PIDs — mirrors the old batch demuxer's own "never resolved, skip"
    /// conclusion, which likewise needed the whole file), and emits the
    /// final one-behind pending sample for every live video/data track.
    pub fn finish(&mut self) {
        self.flush_pes_tails();
        self.resolve_eac3_probes_from_tail();
        self.try_promote_ready();

        while let Some(&next_pid) = self
            .codec_order
            .iter()
            .chain(self.data_order.iter())
            .find(|p| !self.resolved.contains(p))
        {
            match self.streams.get(&next_pid).and_then(|s| s.track.as_ref()) {
                Some(TrackState::Probing { .. }) => {
                    self.resolved.insert(next_pid);
                    // A head stepped over earlier is still in `skipped`;
                    // keep the two sets disjoint (their sizes are summed).
                    self.skipped.remove(&next_pid);
                    // This PID's codec config never became recoverable before
                    // end of input — `TrackAdded` never fired for it, so no
                    // `track_id` exists to report (issue #774).
                    self.events.push_back(DemuxEvent::TrackAbandoned {
                        track_id: None,
                        reason: AbandonReason::ConfigUnrecoverable,
                        provenance: EventProvenance {
                            pid: Some(next_pid),
                            packet_index: None,
                            program_number: None,
                        },
                    });
                    self.try_promote_ready();
                }
                _ => break,
            }
        }

        self.flush_live_tails();
        self.enforce_degraded_cap();
    }

    /// Declare that a new, unrelated timeline begins with the next input (an
    /// HLS `EXT-X-DISCONTINUITY`): flush everything the old timeline still
    /// holds, then forget its timing, but keep what the stream *is*.
    ///
    /// Unlike [`finish`](Self::finish) nothing is abandoned. Resolved tracks
    /// keep their id, codec config and parameter sets, so a PID that carried a
    /// track before the seam carries the same track after it, and a new
    /// timeline that opens mid-GOP (no parameter sets until the next IDR)
    /// does not lose a track a fresh demuxer could never re-probe. What is
    /// reset is per-PID timing — 33-bit unwrap, interpolated frame periods,
    /// the audio frame anchor and carry, the in-flight PES, continuity
    /// counters — so the first access unit of the new timeline is stamped from
    /// the wire exactly as a fresh demuxer would. PMT versions are forgotten
    /// so the new timeline's PMT is diffed against the old (an unchanged PMT
    /// is a no-op; a changed one adds, removes or updates tracks). PIDs still
    /// `Probing` keep probing but drop their old-timeline backlog, and stop
    /// holding back the PIDs behind them (as [`finish`](Self::finish) would
    /// have released them).
    pub fn restart_timeline(&mut self) {
        self.flush_pes_tails();
        for stream in self.streams.values_mut() {
            if matches!(stream.track, Some(TrackState::Probing { .. })) {
                stream.unit_released = true;
            }
        }
        self.try_promote_ready();
        self.flush_live_tails();
        for pmt in self.pmt_reasm.values_mut() {
            pmt.last_applied_version = None;
        }
        self.cc_states.clear();
        for stream in self.streams.values_mut() {
            stream.restart_timeline();
        }
        self.enforce_degraded_cap();
    }

    /// Complete every PID's buffered PES payload at end of a timeline.
    fn flush_pes_tails(&mut self) {
        self.resync.finish();
        for loss in self.resync.take_losses() {
            self.push_resync_loss(loss);
        }
        for (&pid, stream) in self.streams.iter_mut() {
            // Only a PES assembler has a trailing partial payload to flush; a
            // trailing partial (incomplete) section is genuinely undecodable
            // and is simply dropped by `SectionReassembler` itself.
            let completed = match &mut stream.carrier {
                Carrier::Pes(assembler) => assembler.flush(),
                Carrier::Section(_) => None,
            };
            if let Some(completed) = completed {
                // The same two-part intactness rule the mid-stream path uses
                // (r04-W49): the CC mark, *and* — for a bounded PES — the
                // declared length actually having arrived. A trailing PES that
                // stopped short of what its own header declared is truncated,
                // and flushing it at end of input would deliver that
                // truncation as if it were complete.
                let short_of_declared = stream.pes_declared_len > 0
                    && completed.len() < PES_LENGTH_FIELD_END + stream.pes_declared_len as usize;
                if stream.current_pes_intact && !short_of_declared {
                    on_completed_pes(stream, pid, &completed, &mut self.events);
                } else if matches!(stream.codec, Codec::H264 | Codec::Hevc) {
                    harvest_damaged_au(stream, pid, &completed, &mut self.events);
                }
            }
        }
    }

    fn resolve_eac3_probes_from_tail(&mut self) {
        // End of input is the only thing that can complete a first E-AC-3 access
        // unit that no later independent frame closed (issue #1186): resolve
        // from what the probe holds rather than abandoning the track.
        for stream in self.streams.values_mut() {
            if stream.codec != Codec::Eac3
                || stream.probe_tail.is_empty()
                || !matches!(stream.track, Some(TrackState::Probing { .. }))
            {
                continue;
            }
            let Some(TrackState::Probing { probe, backlog }) = stream.track.take() else {
                continue;
            };
            let resolved = eac3_probe_result(&stream.probe_tail, Eac3Accept::Anything);
            stream.probe_tail = Vec::new();
            stream.track = Some(match resolved {
                Some((config, timescale, kind)) => TrackState::Parked {
                    config,
                    timescale,
                    kind,
                    backlog,
                },
                None => TrackState::Probing { probe, backlog },
            });
        }
    }

    /// Emit the one-behind pending sample and the held audio carry of every
    /// live track.
    fn flush_live_tails(&mut self) {
        for (&pid, stream) in self.streams.iter_mut() {
            if let Some(TrackState::Live(live)) = &mut stream.track {
                let provenance = EventProvenance {
                    pid: Some(pid),
                    packet_index: None,
                    program_number: None,
                };
                match &mut live.kind {
                    LiveKind::Video {
                        pending,
                        last_duration,
                        ..
                    } => {
                        flush_one_behind(
                            pending,
                            *last_duration,
                            live.track_id,
                            provenance,
                            &mut self.events,
                        );
                    }
                    LiveKind::Data {
                        pending,
                        last_duration,
                    }
                    | LiveKind::MpegH {
                        pending,
                        last_duration,
                    } => {
                        flush_one_behind(
                            pending,
                            *last_duration,
                            live.track_id,
                            provenance,
                            &mut self.events,
                        );
                    }
                    LiveKind::Audio { kind, anchor, .. } => {
                        flush_audio_carry(kind, anchor, live.track_id, &mut self.events);
                    }
                    LiveKind::Section => {}
                }
            }
        }
    }
}

/// [`Stage`] adoption (media plane step 2e): a thin, honest delegation to the
/// inherent [`feed`](StreamingTsDemux::feed)/[`poll_event`
/// ](StreamingTsDemux::poll_event)/[`finish`](StreamingTsDemux::finish) —
/// every existing inherent method keeps working unchanged; this trait impl is
/// an additional, uniform way to drive the same engine, not a replacement.
///
/// `StreamingTsDemux` never needs deadline-driven work: it only ever produces
/// output in reaction to `feed`/`finish`, so `next_deadline` is always `None`
/// and `on_deadline` is a no-op.
impl Stage for StreamingTsDemux {
    type In<'a> = &'a [u8];
    type Out = DemuxEvent;
    /// `feed`/`finish` are infallible here — TS resynchronises on `0x47`
    /// rather than erroring on malformed input (see the type's own docs).
    type Error = core::convert::Infallible;

    fn feed(&mut self, input: &[u8], _now: Timestamp) -> core::result::Result<(), Self::Error> {
        self.feed(input);
        Ok(())
    }

    fn poll(&mut self) -> Option<Self::Out> {
        self.poll_event()
    }

    fn finish(&mut self) -> core::result::Result<(), Self::Error> {
        self.finish();
        Ok(())
    }

    /// Honest against the one bound this demuxer actually enforces
    /// end-to-end: `MAX_UNATTRIBUTED_BYTES` (the never-claimed-PID replay
    /// buffer). Both this buffer and the per-PID PES overflow
    /// (`MAX_PES_BUFFER_BYTES`, see `feed_pes_bounded`) self-correct
    /// (evict/reset) *within* the same `feed` call that trips them, so
    /// `unattributed_bytes` is never observed sitting exactly at or over the
    /// cap once `feed` returns — only, in the flooding steady state, within
    /// one TS packet's payload of it. Reporting `saturated` only once that
    /// exact byte count is reached would therefore be true in name only
    /// (unreachable in practice — see this step's report); this instead
    /// predicts it one packet ahead: `saturated` once the worst case (another
    /// full-size payload) would push the buffer past the cap, which the
    /// eviction dynamics above make an always-reachable, real signal in
    /// sustained-flood conditions, not a fabricated one.
    fn demand(&self) -> Demand {
        if self.unattributed_bytes.saturating_add(TS_MAX_PAYLOAD_BYTES) > MAX_UNATTRIBUTED_BYTES {
            Demand::saturated()
        } else {
            Demand::new(TS_PACKET_SIZE)
        }
    }
}

// ── Batch wrapper ────────────────────────────────────────────────────────────

/// Demux an MPEG-2 Transport Stream byte slice into a [`Media`].
///
/// A thin wrapper over [`StreamingTsDemux`] (issue #555): follows the PAT to
/// every PMT, enumerates each program's elementary streams into IR [`Track`]s,
/// reassembles per-PID PES into access units with PTS/DTS, recovers codec
/// config from the in-band headers, and emits length-prefixed video / raw
/// audio samples in decode order — by feeding the whole input to a
/// [`StreamingTsDemux`], calling `finish()`, and folding the resulting
/// [`DemuxEvent`]s into a [`Media`].
///
/// The `'a` parameter ties the demuxer to the byte-slice lifetime it consumes
/// via [`Unpackage::Input`]; construct one per call with [`TsDemux::new`].
#[derive(Debug, Default, Clone)]
pub struct TsDemux<'a> {
    _marker: PhantomData<&'a [u8]>,
    afd_persistence: AfdPersistence,
}

impl<'a> TsDemux<'a> {
    /// Create a new demuxer.
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
            afd_persistence: AfdPersistence::UntilReplaced,
        }
    }

    #[must_use]
    pub fn with_afd_persistence(mut self, policy: AfdPersistence) -> Self {
        self.afd_persistence = policy;
        self
    }

    /// Demux `input` (a whole MPEG-2 TS byte stream) into a [`Media`].
    ///
    /// This is the inherent form of [`Unpackage::unpackage`]; both produce the
    /// same result. See the type-level docs for the pipeline.
    pub fn demux(&mut self, input: &'a [u8]) -> Result<Media> {
        let mut demux = StreamingTsDemux::new()
            .with_afd_persistence(self.afd_persistence)
            .with_strict_pmt_order();
        demux.feed(input);
        demux.finish();

        let mut tracks: Vec<Track> = Vec::new();
        let mut index_by_id: BTreeMap<TrackId, usize> = BTreeMap::new();
        let mut pcr: Vec<PcrSample> = Vec::new();
        let mut degraded: Vec<InputDegradation> = Vec::new();
        let mut degraded_at: Vec<DegradationRecord> = Vec::new();
        while let Some(event) = demux.poll_event() {
            match event {
                DemuxEvent::TrackAdded(spec) => {
                    index_by_id.insert(spec.track_id, tracks.len());
                    tracks.push(Track::new(spec, Vec::new()));
                }
                DemuxEvent::TrackUpdated(spec) => {
                    // Whole-buffer batch demux: reflect the final PMT-derived
                    // metadata (issue #774) — samples already collected under
                    // the earlier spec are untouched, only the spec itself
                    // (e.g. corrected descriptors) is refreshed.
                    if let Some(&i) = index_by_id.get(&spec.track_id) {
                        tracks[i].spec = spec;
                    }
                }
                // A one-shot whole-buffer `Media` has no removal/abandonment
                // shape (its `tracks` is a flat, final list) — a track that
                // was removed or abandoned mid-file simply keeps whatever it
                // had already collected, exactly like `Discontinuity` below.
                DemuxEvent::TrackRemoved { .. } => {}
                DemuxEvent::TrackAbandoned { .. } => {}
                DemuxEvent::Sample { track_id, sample }
                    if let Some(&i) = index_by_id.get(&track_id) =>
                {
                    let track = &mut tracks[i];
                    // `Track::start_decode_time` is no longer carried by
                    // `TrackAdded` (issue #774 reshape) — it is exactly
                    // the first sample's own `dts` (media plane step 2c
                    // invariant, unconditionally true for every track
                    // kind), so derive it here instead.
                    if track.samples.is_empty()
                        && let Some(dts) = sample.dts
                    {
                        track.start_decode_time = dts as u64;
                    }
                    track.samples.push(sample);
                }
                DemuxEvent::Sample { .. } => {}
                DemuxEvent::ClockReference {
                    ticks,
                    discontinuous,
                    provenance,
                    ..
                } => pcr.push(PcrSample {
                    pcr_27mhz: ticks,
                    // This batch wrapper only ever demuxes TS, whose
                    // ClockReference always carries a PID/packet_index — the
                    // fallbacks are unreachable in practice, not a silent
                    // downgrade.
                    pid: provenance.pid.unwrap_or(Pid::new(0)),
                    packet_index: provenance.packet_index.unwrap_or(0),
                    discontinuity: discontinuous,
                }),
                DemuxEvent::Discontinuity { .. } => {}
                DemuxEvent::InputDegraded {
                    track,
                    kind,
                    provenance,
                } => {
                    degraded.push(kind);
                    degraded_at.push(DegradationRecord::new(kind, track, provenance));
                }
                DemuxEvent::TracksResolved { .. } => {}
                // The per-AU tag is lossless in a `Media` (design §5.3): every
                // video `Sample` already carries its own `display`, so the
                // batch path needs no event list. The event itself is not
                // kept — a `Media` has no react-to-a-change surface.
                DemuxEvent::DisplayChanged { .. } => {}
            }
        }
        // The streaming core stamps `track: None` on damage seen before its PID
        // resolved to a track (a Data/DSM-CC PID is announced only once its
        // first section completes or at `finish()`, issue #1348). `tracks` is
        // final here, so resolve every still-unresolved record against it by
        // source PID. A PID that never became a track, and stream-wide damage
        // (`pid: None`), stay `None`.
        for record in &mut degraded_at {
            if record.track.is_none()
                && let Some(pid) = record.provenance.pid
                && let Some(t) = tracks.iter().find(|t| t.spec.source_pid == Some(pid))
            {
                record.track = Some(t.spec.track_id);
            }
        }
        let mut media = Media::new(tracks, VIDEO_TIMESCALE).with_pcr(pcr);
        media.degraded = degraded;
        media.degraded_at = degraded_at;
        Ok(media)
    }
}

impl<'a> Unpackage for TsDemux<'a> {
    type Input = &'a [u8];
    type Media = Media;
    type Error = Error;

    fn unpackage(&mut self, input: &'a [u8]) -> Result<Media> {
        self.demux(input)
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::ts_mux::TsMux;
    use broadcast_common::{Package, Parse};

    /// Every section-carried `stream_type` (Table 2-34) classifies as
    /// [`DataCarriage::Sections`]; the historical PES-carried 0x06/0x15 and
    /// any unrecognised `stream_type` classify as [`DataCarriage::Pes`]
    /// (issue #576).
    #[test]
    fn data_carriage_classifies_every_known_stream_type() {
        assert_eq!(data_carriage(0x06), DataCarriage::Pes, "PES private data");
        assert_eq!(data_carriage(0x15), DataCarriage::Pes, "metadata in PES");
        assert_eq!(data_carriage(0x7F), DataCarriage::Pes, "unrecognised → PES");

        for &st in &[
            STREAM_TYPE_PRIVATE_SECTIONS,
            STREAM_TYPE_DSMCC_TYPE_A,
            STREAM_TYPE_DSMCC_TYPE_B,
            STREAM_TYPE_DSMCC_TYPE_C,
            STREAM_TYPE_DSMCC_TYPE_D,
            STREAM_TYPE_DSMCC_SYNC_DOWNLOAD,
            STREAM_TYPE_SCTE35,
        ] {
            assert_eq!(
                data_carriage(st),
                DataCarriage::Sections,
                "stream_type {st:#04X} must be section-carried"
            );
        }
    }

    /// Any `stream_type` not mapped to a decoded codec becomes opaque
    /// [`Codec::Data`] (never `None`/dropped — issue #576).
    #[test]
    fn from_stream_type_unknown_becomes_opaque_data() {
        assert_eq!(Codec::from_stream_type(STREAM_TYPE_AVC), Codec::H264);
        assert_eq!(Codec::from_stream_type(0x7F), Codec::Data(0x7F));
        assert_eq!(
            Codec::from_stream_type(STREAM_TYPE_SCTE35),
            Codec::Data(STREAM_TYPE_SCTE35)
        );
    }

    /// Bytes of TS payload each crafted payload-only packet contributes
    /// (188 − 4-byte TS header, adaptation_field_control = payload-only).
    const PACKET_PAYLOAD_LEN: usize = TS_PACKET_SIZE - 4;

    /// One valid payload-only TS packet on `pid` (no adaptation field), payload
    /// filled with stuffing. `cc` is the 4-bit continuity counter.
    fn payload_only_packet(pid: Pid, cc: u8) -> [u8; TS_PACKET_SIZE] {
        let mut p = [0xFFu8; TS_PACKET_SIZE];
        p[0] = 0x47; // sync_byte
        p[1] = ((pid.value() >> 8) as u8) & PID_HI_MASK; // pusi=0, priority=0, PID hi
        p[2] = (pid.value() & 0xFF) as u8; // PID lo
        p[3] = 0x10 | (cc & 0x0F); // AFC=01 (payload only) + continuity counter
        p
    }

    /// A PID whose payload floods in but which never appears in any PAT/PMT
    /// (the full-multiplex unrelated-service case) must not grow the
    /// `unattributed` buffer without bound: it is FIFO-capped at
    /// `MAX_UNATTRIBUTED_BYTES` regardless of how much arrives.
    #[test]
    fn unattributed_buffer_is_bounded_for_never_claimed_pid() {
        // Enough packets that the raw payload total is several times the cap,
        // so eviction must have run.
        let target_bytes = MAX_UNATTRIBUTED_BYTES * 3;
        let packet_count = target_bytes / PACKET_PAYLOAD_LEN + 1;
        let unclaimed_pid: Pid = Pid::new(0x0123); // never introduced via PAT/PMT

        let mut demux = StreamingTsDemux::new();
        for i in 0..packet_count {
            demux.feed(&payload_only_packet(unclaimed_pid, i as u8));
        }

        // The counter is capped …
        assert!(
            demux.unattributed_bytes <= MAX_UNATTRIBUTED_BYTES,
            "unattributed_bytes {} exceeded cap {}",
            demux.unattributed_bytes,
            MAX_UNATTRIBUTED_BYTES
        );
        // … eviction genuinely fired (we fed far more than the cap) …
        assert!(
            demux.unattributed_bytes > 0,
            "expected the never-claimed PID's payload to be buffered"
        );
        // … and the counter matches the bytes actually retained in the map
        // (accounting stays consistent through eviction).
        let actual: usize = demux
            .unattributed
            .values()
            .flat_map(|q| q.iter())
            .map(|(_, payload)| payload.len())
            .sum();
        assert_eq!(
            actual, demux.unattributed_bytes,
            "unattributed_bytes drifted from the real retained size"
        );
    }

    /// A PID whose PES never completes (`payload_unit_start` never recurs —
    /// a wedged encoder, a lossy capture, or a hostile stream) must not grow
    /// its `Carrier::Pes` buffer without bound: [`MAX_PES_BUFFER_BYTES`] must
    /// trip, dropping the partial PES and raising a
    /// [`DemuxEvent::Discontinuity`], and the PID must keep working normally
    /// afterward (resync proof) rather than being wedged or OOMing.
    #[test]
    fn runaway_pes_without_payload_unit_start_is_bounded_not_unbounded() {
        use crate::TsMux;
        use crate::media::{Media, Track};
        use crate::pipeline::{CodecConfig, Sample, TrackSpec};
        use crate::rtp_sdp::avc_config_from_sprop;
        use broadcast_common::Package;

        // A tiny real single-video-track TS (PAT + PMT + a few PES access
        // units), muxed by this crate's own `TsMux` — registers one H.264 ES
        // (`Carrier::Pes`) at the single-track convention PID (`ES_PID_BASE`
        // in `ts_mux.rs`, `0x0100`).
        const ES_PID: Pid = Pid::new(0x0100);
        let avc = avc_config_from_sprop("Z0IAKeKQFAe2AtwEBAaQeJEV,aM48gA==").unwrap();
        let spec = TrackSpec::new(
            TrackId::new(1),
            VIDEO_TIMESCALE,
            CodecConfig::Avc {
                config: avc,
                width: 0,
                height: 0,
            },
        );
        let frame_dur = VIDEO_TIMESCALE / 30;
        let samples: Vec<Sample> = (0..3u32)
            .map(|i| {
                let nal = [0x65u8, 0xAA, i as u8];
                let mut data = (nal.len() as u32).to_be_bytes().to_vec();
                data.extend_from_slice(&nal);
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(data, Some(dts), Some(dts), Some(frame_dur), i == 0)
            })
            .collect();
        let track = Track::new(spec, samples);
        let media = Media::new(vec![track], VIDEO_TIMESCALE);
        let ts_bytes = TsMux::default().package(&media).expect("mux to TS");

        let mut demux = StreamingTsDemux::new();
        demux.feed(&ts_bytes);
        // Drain the legitimate startup events (TrackAdded/Sample/…) — not
        // under test here, just clearing the queue for a clean assertion
        // below.
        while demux.poll_event().is_some() {}
        assert!(
            demux.streams.contains_key(&ES_PID),
            "expected the muxed video ES at PID {ES_PID:#06X} — TsMux's ES_PID_BASE convention"
        );

        // Now flood that PID with continuation-only packets (pusi = 0): the
        // PES never completes, exactly the audit-ingest scenario.
        // Each continuation packet contributes `PACKET_PAYLOAD_LEN` (184)
        // bytes; comfortably more than `MAX_PES_BUFFER_BYTES / 184` packets
        // are fed so the cap must trip well before the loop ends.
        let mut cc: u8 = 0;
        let mut hit_cap = false;
        for _ in 0..30_000u32 {
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = ((ES_PID.value() >> 8) as u8) & PID_HI_MASK; // pusi = 0
            pkt[2] = (ES_PID.value() & 0xFF) as u8;
            pkt[3] = 0x10 | (cc & 0x0F);
            cc = cc.wrapping_add(1);
            demux.feed(&pkt);
            if matches!(
                demux.poll_event(),
                Some(DemuxEvent::Discontinuity { provenance, .. }) if provenance.pid == Some(ES_PID)
            ) {
                hit_cap = true;
                break;
            }
        }
        assert!(
            hit_cap,
            "expected MAX_PES_BUFFER_BYTES to trip well within 30000 continuation \
             packets (never grow unbounded)"
        );
        assert_eq!(
            demux.streams.get(&ES_PID).unwrap().pes_bytes,
            0,
            "pes_bytes must reset to 0 once the cap trips"
        );

        // Resync proof: a fresh payload_unit_start after the overflow is
        // accepted normally (the assembler was reset, not wedged).
        const PUSI_BIT: u8 = 0x40; // payload_unit_start_indicator (ISO/IEC 13818-1 §2.4.3.2)
        let mut pkt = [0xFFu8; TS_PACKET_SIZE];
        pkt[0] = 0x47;
        pkt[1] = PUSI_BIT | (((ES_PID.value() >> 8) as u8) & PID_HI_MASK);
        pkt[2] = (ES_PID.value() & 0xFF) as u8;
        pkt[3] = 0x10 | (cc & 0x0F);
        pkt[4] = 0; // pointer/no-op first byte for a PES (not a pointer_field — PES has none)
        demux.feed(&pkt);
        assert_eq!(
            demux.streams.get(&ES_PID).unwrap().pes_bytes,
            PACKET_PAYLOAD_LEN,
            "a fresh payload_unit_start must be accepted and start a new count"
        );
    }

    /// The B8 attack (media plane step 2 fix wave 3): a PMT declares two
    /// PIDs — PID A (rank 0, H.264) whose parameter sets never arrive (a
    /// broken encoder, not malice: every sample here is deliberately
    /// non-sync so `TsMux` never injects SPS/PPS in-band), and PID B (rank
    /// 1, opaque data) whose config resolves on its very first access unit.
    /// PID A's `ConfigProbe` never resolves, so it stays `Probing` forever;
    /// before this fix its `backlog` grew without bound, and — because
    /// `try_promote_ready` `break`s at the first still-`Probing` PID — PID
    /// B's `Parked` backlog grew as collateral for exactly as long. Both
    /// PIDs' own `backlog_bytes` must stay capped at
    /// `MAX_PROBE_BACKLOG_BYTES` regardless of which path (its own overflow,
    /// or being unblocked once the other is abandoned) it actually takes.
    #[test]
    fn probe_backlog_is_bounded_for_both_the_never_resolving_pid_and_its_collateral_pid() {
        use crate::TsMux;
        use crate::media::{Media, Track};
        use crate::pipeline::{CodecConfig, DataCarriage, Sample, TrackSpec};
        use crate::rtp_sdp::avc_config_from_sprop;
        use broadcast_common::Package;

        // Comfortably more than MAX_PROBE_BACKLOG_BYTES per track (~4.9 MiB).
        const SAMPLE_BYTES: usize = 4096;
        const SAMPLE_COUNT: u32 = 1200;
        let frame_dur = VIDEO_TIMESCALE / 30;

        // PID A (rank 0, ES_PID_BASE = 0x0100 in `ts_mux.rs`): H.264, never
        // carries SPS/PPS — every sample is deliberately non-sync, so
        // `build_annexb_au` never injects the parameter sets it otherwise
        // would on a keyframe. This probe can never resolve.
        let avc = avc_config_from_sprop("Z0IAKeKQFAe2AtwEBAaQeJEV,aM48gA==").unwrap();
        let video_spec = TrackSpec::new(
            TrackId::new(1),
            VIDEO_TIMESCALE,
            CodecConfig::Avc {
                config: avc,
                width: 0,
                height: 0,
            },
        );
        let video_samples: Vec<Sample> = (0..SAMPLE_COUNT)
            .map(|i| {
                let mut nal = alloc::vec![0x41u8]; // nal_unit_type = 1 (non-IDR slice)
                nal.resize(SAMPLE_BYTES, 0xAA);
                let mut data = (nal.len() as u32).to_be_bytes().to_vec();
                data.extend_from_slice(&nal);
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(data, Some(dts), Some(dts), Some(frame_dur), false)
            })
            .collect();
        let video_track = Track::new(video_spec, video_samples);

        // PID B (rank 1): opaque data — `ConfigProbe::Data` resolves on its
        // very first access unit (already fully known from the PMT alone),
        // so it goes straight to `Parked` and stays there for as long as PID
        // A blocks it.
        let data_spec = TrackSpec::new(
            TrackId::new(2),
            VIDEO_TIMESCALE,
            CodecConfig::Data {
                stream_type: 0x7F,
                descriptors: Vec::new(),
                carriage: DataCarriage::Pes,
            },
        );
        let data_samples: Vec<Sample> = (0..SAMPLE_COUNT)
            .map(|i| {
                let payload = alloc::vec![0xBBu8; SAMPLE_BYTES];
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(payload, Some(dts), Some(dts), Some(frame_dur), true)
            })
            .collect();
        let data_track = Track::new(data_spec, data_samples);

        let media = Media::new(vec![video_track, data_track], VIDEO_TIMESCALE);
        let ts_bytes = TsMux::default().package(&media).expect("mux to TS");

        let mut demux = StreamingTsDemux::new();
        demux.feed(&ts_bytes);
        let mut abandoned_pids: Vec<Pid> = Vec::new();
        while let Some(ev) = demux.poll_event() {
            if let DemuxEvent::TrackAbandoned {
                reason: AbandonReason::BudgetExceeded,
                provenance,
                ..
            } = ev
                && let Some(pid) = provenance.pid
            {
                abandoned_pids.push(pid);
            }
        }
        assert!(
            !abandoned_pids.is_empty(),
            "expected at least one TrackAbandoned{{BudgetExceeded}} from an abandoned probe backlog \
             (issue #774: this replaced the mis-typed Discontinuity this path used to emit)"
        );

        // issue #774: this path used to emit a mis-typed `Discontinuity` for
        // exactly this condition — re-feed and confirm none appears anymore.
        let mut demux2 = StreamingTsDemux::new();
        demux2.feed(&ts_bytes);
        let saw_discontinuity_for_abandoned_pid = std::iter::from_fn(|| demux2.poll_event())
            .any(|ev| matches!(ev, DemuxEvent::Discontinuity { provenance, .. } if provenance.pid == Some(PID_A)));
        assert!(
            !saw_discontinuity_for_abandoned_pid,
            "a probe-backlog-budget abandonment (issue #774) must be a TrackAbandoned, \
             never a Discontinuity"
        );

        // The invariant this fix establishes: neither PID's own tracked
        // backlog byte total ever exceeded the cap.
        for (&pid, stream) in demux.streams.iter() {
            assert!(
                stream.backlog_bytes <= MAX_PROBE_BACKLOG_BYTES,
                "PID {pid:#06X} backlog_bytes {} exceeded cap {MAX_PROBE_BACKLOG_BYTES}",
                stream.backlog_bytes
            );
        }

        // PID A specifically must never have resolved — its parameter sets
        // never arrived, so it must be Abandoned, not Live.
        const PID_A: Pid = Pid::new(0x0100);
        let abandoned = matches!(
            demux.streams.get(&PID_A).and_then(|s| s.track.as_ref()),
            Some(TrackState::Abandoned)
        );
        assert!(abandoned, "PID A must be Abandoned, never Live");

        // PID B (rank 1, ES_PID_BASE + 1) must have made progress — either
        // promoted to Live once PID A was abandoned, or itself abandoned —
        // never left permanently wedged in Probing/Parked with an
        // ever-growing backlog.
        const PID_B: Pid = Pid::new(0x0101);
        let pid_b_resolved = matches!(
            demux.streams.get(&PID_B).and_then(|s| s.track.as_ref()),
            Some(TrackState::Live(_)) | Some(TrackState::Abandoned)
        );
        assert!(
            pid_b_resolved,
            "PID B must reach a final disposition (Live or Abandoned), not stay wedged"
        );
    }

    /// `TrackAbandoned { reason: AbandonReason::ConfigUnrecoverable, .. }`
    /// (issue #774): a PMT-listed H.264 PID whose SPS/PPS never arrive stays
    /// `Probing` for the life of the input — well under
    /// `MAX_PROBE_BACKLOG_BYTES` here (the B8 byte-cap path is a *different*
    /// abandonment reason, covered above), so it only reaches a final
    /// disposition once `finish()` concludes end-of-input that the config
    /// will never resolve. No `track_id` was ever assigned (`TrackAdded`
    /// never fired), so `track_id` must be `None`.
    #[test]
    fn track_abandoned_config_unrecoverable_fires_at_finish() {
        use crate::TsMux;
        use crate::media::{Media, Track};
        use crate::pipeline::{CodecConfig, Sample, TrackSpec};
        use crate::rtp_sdp::avc_config_from_sprop;
        use broadcast_common::Package;

        const PID_A: Pid = Pid::new(0x0100);
        let frame_dur = VIDEO_TIMESCALE / 30;
        let avc = avc_config_from_sprop("Z0IAKeKQFAe2AtwEBAaQeJEV,aM48gA==").unwrap();
        let video_spec = TrackSpec::new(
            TrackId::new(1),
            VIDEO_TIMESCALE,
            CodecConfig::Avc {
                config: avc,
                width: 0,
                height: 0,
            },
        );
        // A handful of small, deliberately non-sync access units — never
        // enough to trip MAX_PROBE_BACKLOG_BYTES, so the only way this PID
        // ever reaches a final disposition is `finish()`'s end-of-input
        // conclusion.
        let video_samples: Vec<Sample> = (0..5u32)
            .map(|i| {
                let nal = alloc::vec![0x41u8, 0xAA, 0xBB]; // non-IDR slice, no SPS/PPS
                let mut data = (nal.len() as u32).to_be_bytes().to_vec();
                data.extend_from_slice(&nal);
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(data, Some(dts), Some(dts), Some(frame_dur), false)
            })
            .collect();
        let video_track = Track::new(video_spec, video_samples);
        let media = Media::new(vec![video_track], VIDEO_TIMESCALE);
        let ts_bytes = TsMux::default().package(&media).expect("mux to TS");

        let mut demux = StreamingTsDemux::new();
        demux.feed(&ts_bytes);
        assert!(
            !matches!(
                demux.streams.get(&PID_A).and_then(|s| s.track.as_ref()),
                Some(TrackState::Abandoned)
            ),
            "sanity: PID A must still be Probing before finish() — the byte cap must not \
             have tripped (this test is about the end-of-input path, not the budget one)"
        );
        while demux.poll_event().is_some() {}

        demux.finish();
        let mut saw_config_unrecoverable = false;
        while let Some(ev) = demux.poll_event() {
            if let DemuxEvent::TrackAbandoned {
                track_id,
                reason: AbandonReason::ConfigUnrecoverable,
                provenance,
            } = ev
            {
                assert_eq!(
                    track_id, None,
                    "a track abandoned before ever resolving has no track_id to report"
                );
                assert_eq!(provenance.pid, Some(PID_A));
                saw_config_unrecoverable = true;
            }
        }
        assert!(
            saw_config_unrecoverable,
            "expected TrackAbandoned{{ConfigUnrecoverable}} once finish() concludes PID A's \
             config will never resolve"
        );
    }

    /// Bytes of long-form section header between the 3-byte
    /// `table_id`/`section_length` prefix and the table body:
    /// `table_id_extension`(2) + `version`(1) + `section_number`(1) +
    /// `last_section_number`(1) -- ISO/IEC 13818-1 §2.4.4.1.
    const SECTION_BODY_PREFIX_LEN: usize = 5;

    /// PES `stream_id` for an H.264 video elementary stream (ISO/IEC
    /// 13818-1 Table 2-22).
    pub(crate) const ES_STREAM_ID_VIDEO: u8 = 0xE0;

    /// Wrap `au` in a PES packet that carries **no** timing at all:
    /// `PTS_DTS_flags == '00'` and an empty `PES_header_data_length`
    /// (ISO/IEC 13818-1 §2.4.3.7).
    fn pes_packet_untimed(stream_id: u8, au: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&[0x00, 0x00, 0x01, stream_id]);
        let payload_len = au.len() + 3;
        out.extend_from_slice(&(payload_len as u16).to_be_bytes());
        out.push(0x80); // '10' marker, not scrambled
        out.push(0x00); // PTS_DTS_flags = '00'
        out.push(0x00); // PES_header_data_length = 0
        out.extend_from_slice(au);
        out
    }

    /// `stream_id` for `private_stream_1` (ISO/IEC 13818-1 Table 2-22) —
    /// what a `stream_type` 0x06 PES uses.
    const ES_STREAM_ID_PRIVATE_DATA: u8 = 0xBD;

    /// One 300-byte access unit payload (fits in two TS packets).
    fn data_au(seed: usize) -> Vec<u8> {
        (0..300).map(|i| ((i + seed) & 0xFF) as u8).collect()
    }

    /// Access unit A for the CC-gap test.
    fn long_data_au() -> Vec<u8> {
        data_au(0)
    }

    /// Access unit B for the CC-gap test — different bytes, so a delivered
    /// sample is unambiguously one or the other.
    fn long_data_au_alt() -> Vec<u8> {
        data_au(0x55)
    }

    /// A PES carrying `au` with **no** timing and `PES_packet_length == 0`
    /// (unbounded — the ordinary video form, ISO/IEC 13818-1 §2.4.3.7).
    fn unbounded_pes(stream_id: u8, au: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&[0x00, 0x00, 0x01, stream_id]);
        out.extend_from_slice(&0u16.to_be_bytes()); // PES_packet_length = 0
        out.push(0x80); // '10' marker, not scrambled
        out.push(0x00); // PTS_DTS_flags = '00'
        out.push(0x00); // PES_header_data_length = 0
        out.extend_from_slice(au);
        out
    }

    /// A PES carrying `au` with no timing at all (`PTS_DTS_flags == '00'`).
    fn untimed_pes(stream_id: u8, au: &[u8]) -> Vec<u8> {
        pes_packet_untimed(stream_id, au)
    }

    /// PES `stream_id` for a private_stream_1-carried audio elementary
    /// stream (ISO/IEC 13818-1 Table 2-22) — the demux only requires a
    /// well-formed PES header, not a particular stream_id.
    const ES_STREAM_ID_AUDIO: u8 = 0xBD;

    /// Encode a 33-bit PTS/DTS field (ISO/IEC 13818-1 §2.4.3.7) with the
    /// given 4-bit prefix (`0010` for PTS-only, `0011` for PTS in a
    /// both-present pair, `0001` for DTS).
    fn encode_ts_field(prefix: u8, value: i64) -> [u8; 5] {
        broadcast_common::clock33::pack_marked(value as u64, prefix)
    }

    /// Wrap `au` in a PES packet with a PTS, and a DTS too when `dts` is
    /// `Some` (`PTS_DTS_flags` `10` / `11` — ISO/IEC 13818-1 §2.4.3.7).
    pub(crate) fn pes_packet(stream_id: u8, pts: i64, dts: Option<i64>, au: &[u8]) -> Vec<u8> {
        let header_data_len = if dts.is_some() { 10 } else { 5 };
        let mut out = Vec::new();
        out.extend_from_slice(&[0x00, 0x00, 0x01, stream_id]);
        let payload_len = au.len() + 3 + header_data_len;
        // A video access unit too long for the 16-bit field is sent unbounded
        // (`PES_packet_length == 0`, ISO/IEC 13818-1 §2.4.3.7) rather than
        // wrapped, which would silently truncate it.
        out.extend_from_slice(&u16::try_from(payload_len).unwrap_or(0).to_be_bytes());
        out.push(0x80); // '10' marker, not scrambled
        out.push(if dts.is_some() { 0xC0 } else { 0x80 });
        out.push(header_data_len as u8);
        if let Some(d) = dts {
            out.extend_from_slice(&encode_ts_field(0b0011, pts));
            out.extend_from_slice(&encode_ts_field(0b0001, d));
        } else {
            out.extend_from_slice(&encode_ts_field(0b0010, pts));
        }
        out.extend_from_slice(au);
        out
    }

    /// PID/table constants for [`probe_sync_scan_work_is_linear_in_the_input_not_quadratic`].
    pub(crate) const PAT_PID_UNDER_TEST: Pid = Pid::new(0x0000);
    pub(crate) const PMT_PID_UNDER_TEST: Pid = Pid::new(0x1000);
    pub(crate) const ES_PID_UNDER_TEST: Pid = Pid::new(0x1100);
    /// PMT `program_number` for the one-program PAT below.
    const PROGRAM_NUMBER_UNDER_TEST: u16 = 1;

    /// PAT section body (ISO/IEC 13818-1 Table 2-30): one program. Returned
    /// without the 8-byte section header and without the CRC, which
    /// [`psi_section_packets`] adds.
    pub(crate) fn pat_body() -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&PROGRAM_NUMBER_UNDER_TEST.to_be_bytes());
        body.extend_from_slice(&(0xE000 | PMT_PID_UNDER_TEST.value()).to_be_bytes());
        body
    }

    /// PMT section body (ISO/IEC 13818-1 Table 2-33): one elementary stream.
    pub(crate) fn pmt_body(es_pid: Pid, stream_type: u8) -> Vec<u8> {
        pmt_body_with_pcr_pid(es_pid, stream_type, Pid::new(0))
    }

    /// A PMT body with **two** elementary streams, declaring `pcr_pid` as the
    /// program's `PCR_PID` (§2.4.4.9 Table 2-33) — the A/V program shape the
    /// multi-PID discontinuity tests need.
    fn pmt_body_two_es_with_pcr_pid(
        video_pid: Pid,
        video_type: u8,
        audio_pid: Pid,
        audio_type: u8,
        pcr_pid: Pid,
    ) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&(0xE000 | pcr_pid.value()).to_be_bytes());
        body.extend_from_slice(&0xF000u16.to_be_bytes()); // program_info_length 0
        for (pid, stream_type) in [(video_pid, video_type), (audio_pid, audio_type)] {
            body.push(stream_type);
            body.extend_from_slice(&(0xE000 | pid.value()).to_be_bytes());
            body.extend_from_slice(&0xF000u16.to_be_bytes()); // ES_info_length 0
        }
        body
    }

    /// A PMT body declaring `pcr_pid` as the program's `PCR_PID`
    /// (§2.4.4.9 Table 2-33) — what a real multiplexer sets to the video PID
    /// (or a dedicated PCR PID).
    fn pmt_body_with_pcr_pid(es_pid: Pid, stream_type: u8, pcr_pid: Pid) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&(0xE000 | pcr_pid.value()).to_be_bytes());
        body.extend_from_slice(&0xF000u16.to_be_bytes()); // reserved + program_info_length 0
        body.push(stream_type);
        body.extend_from_slice(&(0xE000 | es_pid.value()).to_be_bytes());
        body.extend_from_slice(&0xF000u16.to_be_bytes()); // reserved + ES_info_length 0
        body
    }

    /// Wrap `body` in a long-form PSI section (header + CRC_32) and packetise
    /// it onto `pid` with `pusi` set on the first packet. The CRC_32 is
    /// computed by the workspace's own `CRC-32/MPEG-2` so the section passes
    /// [`psi_section_crc_ok`].
    pub(crate) fn psi_section_packets(pid: Pid, cc0: u8, table_id: u8, body: &[u8]) -> Vec<u8> {
        psi_section_packets_for(pid, cc0, table_id, PROGRAM_NUMBER_UNDER_TEST, body)
    }

    /// As [`psi_section_packets`], but with an explicit `table_id_extension`
    /// — the `program_number` for a PAT's entries and for a PMT's own header —
    /// so a multi-program multiplex can be built.
    fn psi_section_packets_for(
        pid: Pid,
        cc0: u8,
        table_id: u8,
        table_id_extension: u16,
        body: &[u8],
    ) -> Vec<u8> {
        psi_section_packets_versioned(pid, cc0, table_id, table_id_extension, 0, body)
    }

    /// As [`psi_section_packets_for`], with an explicit 5-bit `version_number`.
    fn psi_section_packets_versioned(
        pid: Pid,
        cc0: u8,
        table_id: u8,
        table_id_extension: u16,
        version: u8,
        body: &[u8],
    ) -> Vec<u8> {
        let mut section = Vec::new();
        let section_length = (SECTION_BODY_PREFIX_LEN + body.len() + CRC32_LEN) as u16;
        section.push(table_id);
        section.push(SECTION_SYNTAX_INDICATOR_BIT | (section_length >> 8) as u8);
        section.push(section_length as u8);
        // table_id_extension / version / current_next / section numbers.
        section.extend_from_slice(&table_id_extension.to_be_bytes());
        section.push(0xC1 | (version << 1)); // reserved '11', version, current_next 1
        section.push(0x00); // section_number
        section.push(0x00); // last_section_number
        section.extend_from_slice(body);
        let crc = broadcast_common::crc32_mpeg2::compute(&section);
        section.extend_from_slice(&crc.to_be_bytes());
        // A section starts with a `pointer_field` (§2.4.3.4 Table 2-6: the
        // number of bytes before the first section start in this packet's
        // payload) — here 0, i.e. the section begins immediately.
        let mut packetised = Vec::with_capacity(section.len() + 1);
        packetised.push(0x00);
        packetised.extend_from_slice(&section);
        pes_packets(pid, cc0, &packetised)
    }

    /// Packetise `payload` like [`pes_packets`], but with an 8-byte adaptation
    /// field whose `discontinuity_indicator` is set on the **first** packet
    /// (§2.4.3.4 Table 2-6). Used to build the "source says the stream broke
    /// here" packet a real multiplexer emits.
    fn pes_packets_with_discontinuity(pid: Pid, cc0: u8, payload: &[u8]) -> Vec<u8> {
        /// Adaptation-field bytes *after* the length byte: the flags byte plus
        /// stuffing.
        const AF_LEN: usize = 8;
        /// First payload byte: 4-byte TS header + the length byte + the field.
        const PAYLOAD_START: usize = 4 + 1 + AF_LEN;
        let first_take = (TS_PACKET_SIZE - PAYLOAD_START).min(payload.len());
        let mut out = Vec::new();
        let mut p = [0xFFu8; TS_PACKET_SIZE];
        p[0] = 0x47;
        p[1] = ((pid.value() >> 8) as u8 & PID_HI_MASK) | 0x40; // pusi
        p[2] = (pid.value() & 0xFF) as u8;
        p[3] = 0x30 | (cc0 & 0x0F); // afc = '11'
        p[4] = AF_LEN as u8;
        p[5] = 0x80; // discontinuity_indicator = 1
        p[6..PAYLOAD_START].fill(0xFF); // stuffing
        p[PAYLOAD_START..PAYLOAD_START + first_take].copy_from_slice(&payload[..first_take]);
        out.extend_from_slice(&p);
        // The remainder is a *continuation*, never a new unit start.
        out.extend_from_slice(&continuation_packets(
            pid,
            cc0.wrapping_add(1),
            &payload[first_take..],
        ));
        out
    }

    /// Packetise `payload` as **continuation** packets (`pusi` clear),
    /// `0xFF`-stuffed, counters incrementing from `cc0`.
    fn continuation_packets(pid: Pid, cc0: u8, payload: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut off = 0usize;
        let mut cc = cc0;
        while off < payload.len() {
            let take = (payload.len() - off).min(TS_PACKET_SIZE - 4);
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = (pid.value() >> 8) as u8 & PID_HI_MASK;
            p[2] = (pid.value() & 0xFF) as u8;
            p[3] = 0x10 | (cc & 0x0F);
            p[4..4 + take].copy_from_slice(&payload[off..off + take]);
            out.extend_from_slice(&p);
            off += take;
            cc = cc.wrapping_add(1);
        }
        out
    }

    /// Packetise `payload` onto `pid`, `payload_unit_start` set on the first
    /// 188-byte packet only, CC incrementing from `cc0`, `0xFF` stuff.
    pub(crate) fn pes_packets(pid: Pid, cc0: u8, payload: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut off = 0usize;
        let mut first = true;
        let mut cc = cc0;
        while off < payload.len() {
            let take = (payload.len() - off).min(TS_PACKET_SIZE - 4);
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = ((pid.value() >> 8) as u8 & PID_HI_MASK) | if first { 0x40 } else { 0x00 };
            p[2] = (pid.value() & 0xFF) as u8;
            p[3] = 0x10 | (cc & 0x0F);
            p[4..4 + take].copy_from_slice(&payload[off..off + take]);
            out.extend_from_slice(&p);
            off += take;
            first = false;
            cc = cc.wrapping_add(1);
        }
        out
    }

    /// Mux a never-resolving head PID (rank 0) followed by `data_pids` opaque
    /// data PIDs (each resolves on its first access unit), `video_aus` access
    /// units on the head and `data_aus` on each data PID. The head is H.264
    /// with every sample non-sync (no SPS/PPS ever carried) unless
    /// `audio_head`, in which case it is an MPEG-2 audio (`stream_type` 0x04)
    /// PID whose payload never carries a frame sync.
    /// With `resolve_last` the final head access unit is a sync sample, so a
    /// *video* head does resolve (on the second-to-last access unit: the last one
    /// flushes the one-behind PES).
    fn stalled_head_ts(
        video_aus: u32,
        data_pids: usize,
        data_aus: u32,
        audio_head: bool,
        resolve_last: bool,
    ) -> Vec<u8> {
        use crate::TsMux;
        use crate::media::{Media, Track};
        use crate::pipeline::{CodecConfig, DataCarriage, Sample, TrackSpec};
        use crate::rtp_sdp::avc_config_from_sprop;
        use broadcast_common::Package;

        let frame_dur = VIDEO_TIMESCALE / 30;
        let avc = avc_config_from_sprop("Z0IAKeKQFAe2AtwEBAaQeJEV,aM48gA==").unwrap();
        let video_samples: Vec<Sample> = (0..video_aus)
            .map(|i| {
                let sync = resolve_last && i + 2 == video_aus;
                let nal = if audio_head {
                    alloc::vec![0xBBu8; 3]
                } else {
                    alloc::vec![0x41u8, 0xAA, 0xBB]
                };
                let mut data = if audio_head {
                    Vec::new()
                } else {
                    (nal.len() as u32).to_be_bytes().to_vec()
                };
                data.extend_from_slice(&nal);
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(data, Some(dts), Some(dts), Some(frame_dur), sync)
            })
            .collect();
        let head_config = if audio_head {
            CodecConfig::Data {
                stream_type: 0x04,
                descriptors: Vec::new(),
                carriage: DataCarriage::Pes,
            }
        } else {
            CodecConfig::Avc {
                config: avc,
                width: 0,
                height: 0,
            }
        };
        let mut tracks = vec![Track::new(
            TrackSpec::new(TrackId::new(1), VIDEO_TIMESCALE, head_config),
            video_samples,
        )];
        for k in 0..data_pids {
            let samples: Vec<Sample> = (0..data_aus)
                .map(|i| {
                    let dts = i64::from(i) * i64::from(frame_dur);
                    Sample::new(
                        alloc::vec![0xBBu8; 32],
                        Some(dts),
                        Some(dts),
                        Some(frame_dur),
                        true,
                    )
                })
                .collect();
            tracks.push(Track::new(
                TrackSpec::new(
                    TrackId::new(2 + k as u32),
                    VIDEO_TIMESCALE,
                    CodecConfig::Data {
                        stream_type: 0x7F,
                        descriptors: Vec::new(),
                        carriage: DataCarriage::Pes,
                    },
                ),
                samples,
            ));
        }
        TsMux::default()
            .package(&Media::new(tracks, VIDEO_TIMESCALE))
            .expect("mux to TS")
    }

    /// TrackAdded source PIDs seen while feeding `ts` (no `finish()`: a live
    /// feed never ends).
    fn live_track_added_pids(ts: &[u8]) -> Vec<u16> {
        let mut demux = StreamingTsDemux::new();
        let mut pids = Vec::new();
        for chunk in ts.chunks(TS_PACKET_SIZE * 16) {
            demux.feed(chunk);
            while let Some(ev) = demux.poll_event() {
                if let DemuxEvent::TrackAdded(spec) = ev {
                    pids.push(spec.source_pid.map_or(0, |p| p.value()));
                }
            }
        }
        pids
    }

    /// A one-program TS whose only PID is an E-AC-3 stream (`stream_type` 0x87)
    /// with one PES per element of `payloads`.
    fn eac3_pes_ts(payloads: &[Vec<u8>]) -> Vec<u8> {
        single_es_pes_ts(STREAM_TYPE_EAC3, payloads)
    }

    /// A one-program TS whose only PID has `stream_type`, one PES (private
    /// stream 1, stamped) per element of `payloads`.
    fn single_es_pes_ts(stream_type: u8, payloads: &[Vec<u8>]) -> Vec<u8> {
        let mut ts = psi_section_packets(PAT_PID_UNDER_TEST, 0, 0x00, &pat_body());
        ts.extend(psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            0x02,
            &pmt_body(ES_PID_UNDER_TEST, stream_type),
        ));
        let mut cc = 0u8;
        for (n, es) in payloads.iter().enumerate() {
            let pts = 90_000u64 + 2_880 * n as u64;
            let mut pes = alloc::vec![0, 0, 1, 0xBD];
            pes.extend_from_slice(&((3 + 5 + es.len()) as u16).to_be_bytes());
            pes.extend_from_slice(&[0x80, 0x80, 5]);
            pes.push(0x21 | ((pts >> 29) as u8 & 0x0E));
            pes.push((pts >> 22) as u8);
            pes.push(0x01 | ((pts >> 14) as u8 & 0xFE));
            pes.push((pts >> 7) as u8);
            pes.push(0x01 | ((pts << 1) as u8 & 0xFE));
            pes.extend_from_slice(es);
            ts.extend(pes_packets(ES_PID_UNDER_TEST, cc, &pes));
            cc = cc.wrapping_add(pes.len().div_ceil(TS_PACKET_SIZE - 4) as u8);
        }
        ts
    }

    /// E-AC-3 `TrackAdded`s seen feeding `ts` live (no `finish()`).
    fn live_eac3_tracks(ts: &[u8]) -> usize {
        let mut demux = StreamingTsDemux::new();
        demux.feed(ts);
        let mut n = 0;
        while let Some(ev) = demux.poll_event() {
            if let DemuxEvent::TrackAdded(spec) = ev
                && matches!(spec.config, CodecConfig::Eac3 { .. })
            {
                n += 1;
            }
        }
        n
    }

    /// `dec3.bsmod` of the first (only) track of `ts`, live (no `finish()`).
    fn live_eac3_bsmod(ts: &[u8]) -> Option<u8> {
        let mut demux = StreamingTsDemux::new();
        demux.feed(ts);
        while let Some(ev) = demux.poll_event() {
            if let DemuxEvent::TrackAdded(spec) = ev
                && let CodecConfig::Eac3 { config, .. } = spec.config
            {
                return Some(config.substreams[0].bsmod);
            }
        }
        None
    }

    /// The probe chooses its frame by `crc2` (ETSI TS 102 366 §E.2.2): a
    /// header-shaped frame a lost packet damaged, in front of an intact one,
    /// must not describe the stream. The damaged frame says `bsmod` 5, the
    /// intact one 0; the first PES holds both, then a second PES completes the
    /// first. Unfixed (the first header-valid frame was used) this is 5.
    #[test]
    fn eac3_probe_skips_a_damaged_frame_in_front_of_an_intact_one() {
        use crate::ac3::tests::{damaged_for_tests, eac3_bsi};
        let bad = damaged_for_tests(eac3_bsi(0, 0, 63, 2, false, 0, 3, None, Some(5)));
        let good = eac3_bsi(0, 0, 63, 2, false, 0, 3, None, Some(0));
        let pes = [bad, good.clone(), good].concat();
        assert_eq!(live_eac3_bsmod(&eac3_pes_ts(&[pes.clone(), pes])), Some(0));
    }

    /// `bsmod` is the stream's, not the chosen frame's: the first intact frame
    /// carries no `infomdate` (so `0` in isolation, §F.6.2.8) and a later one
    /// in the same window carries `bsmod` 2 (the TNT audio-description track
    /// alternates exactly so). Unfixed (the isolated first frame's `bsmod`) this
    /// is 0, the value `m6-single`'s second track wrongly had before #1315.
    #[test]
    fn eac3_bsmod_comes_from_the_first_intact_frame_that_carries_it() {
        use crate::ac3::tests::eac3_bsi;
        let none = eac3_bsi(0, 0, 63, 2, false, 0, 3, None, None);
        let two = eac3_bsi(0, 0, 63, 2, false, 0, 3, None, Some(2));
        let pes = [none.clone(), two, none].concat();
        assert_eq!(live_eac3_bsmod(&eac3_pes_ts(&[pes.clone(), pes])), Some(2));
    }

    /// Liveness is kept: when no intact frame is held at all (every frame of a
    /// very lossy capture damaged) the track is still announced from the first
    /// header-valid frame rather than never, as in #1315.
    #[test]
    fn eac3_probe_with_no_intact_frame_still_announces_the_track() {
        use crate::ac3::tests::{damaged_for_tests, eac3_bsi};
        let bad = damaged_for_tests(eac3_bsi(0, 0, 63, 2, false, 0, 3, None, Some(2)));
        let pes = [bad.clone(), bad].concat();
        assert_eq!(live_eac3_bsmod(&eac3_pes_ts(&[pes.clone(), pes])), Some(2));
    }

    /// An E-AC-3 PID whose first access unit can never be proven complete (an
    /// independent frame followed only by dependent frames, every one chained,
    /// so neither a repeated independent frame nor a broken chain ever ends the
    /// access unit) resolves from the frames held once it has
    /// `EAC3_PROBE_MAX_FRAMES` of them, with no `finish()`. One frame fewer and
    /// it must still be waiting.
    #[test]
    fn eac3_probe_that_never_completes_resolves_after_the_bound() {
        use crate::ac3::Ec3SyncframeInfo;
        use crate::ac3::tests::seven_one_eac3_es;

        let au = seven_one_eac3_es();
        let frames = Ec3SyncframeInfo::from_es_all(&au);
        assert_eq!(frames.len(), 2, "independent + dependent");
        let dep_at = (frames[0].frmsiz as usize + 1) * 2;
        let dep_only = au[dep_at..].to_vec();
        let build = |pes_count: usize| {
            let mut v = alloc::vec![au.clone()];
            v.extend((1..pes_count).map(|_| dep_only.clone()));
            eac3_pes_ts(&v)
        };
        // A PES is only delivered when the next one starts, so `k` access units
        // reach the probe from `k + 1` PES; the first access unit holds two
        // frames and every later one a dependent, so `k` of them are `k + 1`
        // chained frames, i.e. as many frames as PES sent.
        let bound = EAC3_PROBE_MAX_FRAMES;
        assert_eq!(live_eac3_tracks(&build(bound - 1)), 0, "one frame short");
        assert_eq!(live_eac3_tracks(&build(bound)), 1, "bound reached");
    }

    /// A lossy capture: every PES is an access unit followed by bytes that are
    /// not a syncword, so a chain-verified access unit never appears. The probe
    /// settles for the broken-chain access unit on the first payload instead of
    /// stalling; but an access unit that merely ends (more of it may follow,
    /// #1186) is still waited on.
    #[test]
    fn eac3_probe_on_lossy_capture_settles_for_a_broken_chain() {
        use crate::ac3::tests::seven_one_eac3_es;

        let clean = seven_one_eac3_es();
        let mut lossy = clean.clone();
        lossy.extend_from_slice(&[0x43, 0x8B, 0x88, 0xBC, 0xA9, 0xB4, 0x00, 0x15]);
        // A PES is only delivered when the next one starts: two PES, one payload.
        assert_eq!(
            live_eac3_tracks(&eac3_pes_ts(&[lossy.clone(), lossy])),
            1,
            "broken chain"
        );
        assert_eq!(
            live_eac3_tracks(&eac3_pes_ts(&[clean.clone(), clean])),
            0,
            "the access unit merely ends"
        );
    }

    /// `(source PID, track_id)` of every `TrackAdded`, in event order.
    fn live_track_added_ids(ts: &[u8]) -> Vec<(u16, u32)> {
        let mut demux = StreamingTsDemux::new();
        let mut out = Vec::new();
        for chunk in ts.chunks(TS_PACKET_SIZE * 16) {
            demux.feed(chunk);
            while let Some(ev) = demux.poll_event() {
                if let DemuxEvent::TrackAdded(spec) = ev {
                    out.push((
                        spec.source_pid.map_or(0, |p| p.value()),
                        spec.track_id.value(),
                    ));
                }
            }
        }
        out
    }

    /// Head-of-line blocking: a PMT-first (non-video) PID whose probe never
    /// resolves must not hold back the PIDs after it forever. Two later PIDs
    /// (one stalled head, two unstalled followers) must both be promoted, in
    /// PMT order, once the head has been `Probing` for `PROBE_HEAD_BLOCK_AUS`
    /// access units — with no `finish()`.
    #[test]
    fn stalled_probe_does_not_block_later_pids_forever() {
        let ts = stalled_head_ts(PROBE_HEAD_BLOCK_AUS + 20, 2, 4, true, false);
        let pids = live_track_added_pids(&ts);
        assert_eq!(
            pids,
            vec![0x0101, 0x0102],
            "both data PIDs promoted, in PMT order, past the stalled head"
        );
    }

    /// The other half of the bound: below `PROBE_HEAD_BLOCK_AUS` the head
    /// still blocks, so PMT declaration order (track ids) is preserved for a
    /// probe that is merely slow.
    #[test]
    fn slow_probe_still_blocks_later_pids_below_the_bound() {
        let ts = stalled_head_ts(PROBE_HEAD_BLOCK_AUS - 20, 2, 4, true, false);
        assert!(
            live_track_added_pids(&ts).is_empty(),
            "a probe below the bound keeps PMT-order promotion"
        );
    }

    /// Round-2 audit: a *video* head that is slow to resolve (a long GOP: more
    /// than `PROBE_HEAD_BLOCK_AUS` access units before the first parameter
    /// sets) must NOT be stepped over. Otherwise the two later PIDs would be
    /// promoted first as tracks 1 and 2 and the video would surface as track
    /// 3, breaking consumers (`ts_hls`, `multimux`) that treat the PMT-first
    /// video as track 1. Video must be track 1 and the others 2 and 3, in PMT
    /// order, and nothing is announced before the video resolves.
    #[test]
    fn slow_video_head_keeps_track_id_one() {
        // Still unresolved after the bound: nothing may be promoted.
        let unresolved = stalled_head_ts(PROBE_HEAD_BLOCK_AUS + 20, 2, 4, false, false);
        assert!(
            live_track_added_ids(&unresolved).is_empty(),
            "a video head past the bound must still block later PIDs"
        );
        // Resolves late (after the bound): ids follow PMT order.
        let resolved = stalled_head_ts(PROBE_HEAD_BLOCK_AUS + 20, 2, 4, false, true);
        assert_eq!(
            live_track_added_ids(&resolved),
            vec![(0x0100, 1), (0x0101, 2), (0x0102, 3)],
            "slow video must be track 1, later PIDs 2 and 3"
        );
    }

    /// PMT body (Table 2-33) with one ES entry per `(pid, stream_type)`, in order.
    fn pmt_body_multi(es: &[(Pid, u8)]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&(0xE000 | es[0].0.value()).to_be_bytes());
        body.extend_from_slice(&0xF000u16.to_be_bytes());
        for &(pid, stream_type) in es {
            body.push(stream_type);
            body.extend_from_slice(&(0xE000 | pid.value()).to_be_bytes());
            body.extend_from_slice(&0xF000u16.to_be_bytes());
        }
        body
    }

    /// What a live feed reported, in order.
    #[derive(Debug, PartialEq, Eq, Clone)]
    enum Seen {
        Added(u16, u32),
        Resolved,
        Sample(u32),
        Removed(u32),
    }

    /// Feed `ts` live (never `finish()`) and record the events that matter.
    fn seen_events(ts: &[u8]) -> Vec<Seen> {
        let mut demux = StreamingTsDemux::new();
        let mut out = Vec::new();
        for chunk in ts.chunks(TS_PACKET_SIZE * 16) {
            demux.feed(chunk);
            while let Some(ev) = demux.poll_event() {
                match ev {
                    DemuxEvent::TrackAdded(spec) => out.push(Seen::Added(
                        spec.source_pid.map_or(0, |p| p.value()),
                        spec.track_id.value(),
                    )),
                    DemuxEvent::TracksResolved { .. } => out.push(Seen::Resolved),
                    DemuxEvent::Sample { track_id, .. } => out.push(Seen::Sample(track_id.value())),
                    DemuxEvent::TrackRemoved { track_id, .. } => {
                        out.push(Seen::Removed(track_id.value()));
                    }
                    _ => {}
                }
            }
        }
        out
    }

    fn added(seen: &[Seen]) -> Vec<(u16, u32)> {
        seen.iter()
            .filter_map(|e| match e {
                Seen::Added(p, t) => Some((*p, *t)),
                _ => None,
            })
            .collect()
    }

    /// Round-3 audit A: a stalled non-video head that the 512-AU bound steps
    /// over counts toward `TracksResolved`, so a consumer that waits for it
    /// (multimux `ProgramTracker`) announces the programme. The signal comes
    /// after both promoted tracks' `TrackAdded`, exactly once.
    #[test]
    fn stalled_head_counts_toward_tracks_resolved() {
        let ts = stalled_head_ts(PROBE_HEAD_BLOCK_AUS + 20, 2, 4, true, false);
        let seen = seen_events(&ts);
        assert_eq!(added(&seen), vec![(0x0101, 1), (0x0102, 2)]);
        let resolved: Vec<usize> = seen
            .iter()
            .enumerate()
            .filter(|(_, e)| **e == Seen::Resolved)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(resolved.len(), 1, "exactly one TracksResolved: {seen:?}");
        let last_added = seen
            .iter()
            .rposition(|e| matches!(e, Seen::Added(..)))
            .unwrap();
        assert!(resolved[0] > last_added, "after every TrackAdded");
        assert!(
            seen.contains(&Seen::Sample(1)) && seen.contains(&Seen::Sample(2)),
            "the promoted tracks' samples flow: {seen:?}"
        );
    }

    /// A TS with a PMT-first head `(0x100, head_type)` sending `head_pes`
    /// (stamped PES, after `flood_packets` TS packets of `flood` traffic) and a
    /// healthy flood PID `(0x101, flood_type)` sending `flood_payload(n)` as
    /// one PES each.
    fn silent_head_ts(
        head_type: u8,
        head_pes: &[Vec<u8>],
        flood_type: u8,
        flood_payload: impl Fn(usize) -> Vec<u8>,
        flood_packets: usize,
    ) -> Vec<u8> {
        let head = Pid::new(0x0100);
        let flood = Pid::new(0x0101);
        let mut ts = psi_section_packets(PAT_PID_UNDER_TEST, 0, 0x00, &pat_body());
        ts.extend(psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            0x02,
            &pmt_body_multi(&[(head, head_type), (flood, flood_type)]),
        ));
        let mut cc = [0u8; 2];
        let mut push = |ts: &mut Vec<u8>, which: usize, pes: &[u8]| {
            let pid = if which == 0 { head } else { flood };
            let packets = pes_packets(pid, cc[which], pes);
            cc[which] = cc[which].wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            ts.extend_from_slice(&packets);
        };
        let start = ts.len();
        let mut n = 0usize;
        while (ts.len() - start) / TS_PACKET_SIZE < flood_packets {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + n as i64 * 1920,
                None,
                &flood_payload(n),
            );
            push(&mut ts, 1, &pes);
            n += 1;
        }
        for (i, h) in head_pes.iter().enumerate() {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + i as i64 * 2160,
                None,
                h,
            );
            push(&mut ts, 0, &pes);
        }
        // Two more flood PES so the last head/flood PES is delivered.
        for k in 0..2 {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + (n + k) as i64 * 1920,
                None,
                &flood_payload(n + k),
            );
            push(&mut ts, 1, &pes);
        }
        ts
    }

    /// Round-3 audit A (late resolve): the stepped-over head still resolves
    /// when its frames arrive. It is promoted with a `TrackAdded` (a later id)
    /// and its backlog, and `TracksResolved` fires AGAIN so a consumer learns
    /// of the new track (multimux emits `TracksChanged` on that signal).
    #[test]
    fn stepped_over_head_resolving_late_is_promoted_and_rearms_the_signal() {
        let garbage: Vec<Vec<u8>> = (0..PROBE_HEAD_BLOCK_AUS as usize + 20)
            .map(|_| alloc::vec![0xBBu8; 3])
            .collect();
        let real = mp2_frame(1);
        let mut head = garbage;
        head.extend((0..4).map(|_| real.clone()));
        let ts = silent_head_ts(0x04, &head, 0x7F, |n| alloc::vec![n as u8; 32], 40);
        let seen = seen_events(&ts);
        assert_eq!(added(&seen), vec![(0x0101, 1), (0x0100, 2)], "{seen:?}");
        let resolved: Vec<usize> = seen
            .iter()
            .enumerate()
            .filter(|(_, e)| **e == Seen::Resolved)
            .map(|(i, _)| i)
            .collect();
        let head_added = seen
            .iter()
            .position(|e| *e == Seen::Added(0x0100, 2))
            .unwrap();
        assert_eq!(
            resolved.len(),
            2,
            "fires again after the late promotion: {seen:?}"
        );
        assert!(resolved[0] < head_added && resolved[1] > head_added);
        assert!(
            seen.contains(&Seen::Sample(2)),
            "the late track's samples flow"
        );
    }

    /// Feed `ts` one TS packet at a time; return the packet index at which the
    /// first `TrackAdded` appeared and the backlog bytes PID 0x0101 held just
    /// before that packet.
    fn first_announce(ts: &[u8]) -> Option<(usize, usize)> {
        let mut demux = StreamingTsDemux::new();
        let mut prev = 0usize;
        for (i, chunk) in ts.chunks(TS_PACKET_SIZE).enumerate() {
            demux.feed(chunk);
            while let Some(ev) = demux.poll_event() {
                if matches!(ev, DemuxEvent::TrackAdded(_)) {
                    return Some((i, prev));
                }
            }
            prev = demux
                .streams
                .get(&Pid::new(0x0101))
                .map_or(0, |s| s.backlog_bytes);
        }
        None
    }

    /// Enough flood packets (one-frame ADTS PES, ~100 ES bytes per TS packet) to
    /// park well over `SILENT_HEAD_PARKED_BYTES`, but under the 4 MiB cap.
    const FLOOD_PAST_CRITERION: usize = 25_000;

    /// Round-4 audit 1: a video PID declared in the PMT that never sends a
    /// packet no longer holds the audio back forever, but is stepped over only
    /// once the audio behind it has parked `SILENT_HEAD_PARKED_BYTES`, not a
    /// packet earlier.
    #[test]
    fn declared_but_absent_video_does_not_block_audio() {
        let ts = silent_head_ts(
            STREAM_TYPE_AVC,
            &[],
            STREAM_TYPE_AAC_ADTS,
            adts_frame,
            FLOOD_PAST_CRITERION,
        );
        let seen = seen_events(&ts);
        assert_eq!(added(&seen), vec![(0x0101, 1)], "{seen:?}");
        assert!(seen.contains(&Seen::Resolved), "TracksResolved fires");
        assert!(seen.contains(&Seen::Sample(1)), "audio samples flow");
        // Exactly at the criterion: the announcing push is the one that took
        // the parked bytes from below to at-or-above it.
        let (_, before) = first_announce(&ts).expect("audio announced");
        assert!(
            before < SILENT_HEAD_PARKED_BYTES && before + 512 >= SILENT_HEAD_PARKED_BYTES,
            "announced with {before} parked bytes, criterion {SILENT_HEAD_PARKED_BYTES}"
        );
        // Below the criterion (past the old 8192-packet bound) the head blocks.
        let early = silent_head_ts(
            STREAM_TYPE_AVC,
            &[],
            STREAM_TYPE_AAC_ADTS,
            adts_frame,
            15_000,
        );
        assert!(first_announce(&early).is_none());
    }

    /// Round-4 audit 1 (the regression): a video whose first packet arrives
    /// after 9000 TS packets of other traffic (past the old 8192-packet bound,
    /// well below the parked-bytes criterion) is still track 1, with the audio
    /// announced after it.
    #[test]
    fn late_video_after_8192_stream_packets_keeps_track_one() {
        let frames: Vec<Vec<u8>> = (0..4).map(|_| mp2_frame(1)).collect();
        let ts = silent_head_ts(0x04, &frames, STREAM_TYPE_AAC_ADTS, adts_frame, 9000);
        let seen = seen_events(&ts);
        assert_eq!(added(&seen), vec![(0x0100, 1), (0x0101, 2)], "{seen:?}");
    }

    /// The bound must not cost a slow-but-present head its place. A head whose
    /// first packet arrives after 5000 packets of other traffic is track 1; one
    /// that is silent past the criterion is stepped over (later id) but still
    /// announced when its frames do arrive.
    #[test]
    fn slow_but_present_head_keeps_track_one_and_a_late_one_is_still_announced() {
        let frames: Vec<Vec<u8>> = (0..4).map(|_| mp2_frame(1)).collect();
        let slow = silent_head_ts(0x04, &frames, STREAM_TYPE_AAC_ADTS, adts_frame, 5000);
        assert_eq!(
            added(&seen_events(&slow)),
            vec![(0x0100, 1), (0x0101, 2)],
            "present before the bound: PMT order"
        );
        let late = silent_head_ts(
            0x04,
            &frames,
            STREAM_TYPE_AAC_ADTS,
            adts_frame,
            FLOOD_PAST_CRITERION,
        );
        let seen = seen_events(&late);
        assert_eq!(
            added(&seen),
            vec![(0x0101, 1), (0x0100, 2)],
            "silent past the criterion: stepped over, announced when it arrives: {seen:?}"
        );
    }

    /// A head that has delivered ANY payload keeps blocking past the parked-bytes
    /// criterion, exactly as in 0.26.0: an AVC head that sent three PES of
    /// garbage (never any parameter sets) before a flood of 25 000 audio packets
    /// is not a silent head, so only the byte cap can release the audio.
    #[test]
    fn present_but_unresolved_video_head_still_blocks_past_the_silent_bound() {
        let head = Pid::new(0x0100);
        let flood = Pid::new(0x0101);
        let mut ts = psi_section_packets(PAT_PID_UNDER_TEST, 0, 0x00, &pat_body());
        ts.extend(psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            0x02,
            &pmt_body_multi(&[(head, STREAM_TYPE_AVC), (flood, STREAM_TYPE_AAC_ADTS)]),
        ));
        let mut cc = 0u8;
        for i in 0..3 {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + i as i64 * 2160,
                None,
                &[0xBB; 3],
            );
            let packets = pes_packets(head, cc, &pes);
            cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            ts.extend_from_slice(&packets);
        }
        let mut fcc = 0u8;
        for n in 0..FLOOD_PAST_CRITERION / 2 {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + n as i64 * 1920,
                None,
                &adts_frame(n),
            );
            let packets = pes_packets(flood, fcc, &pes);
            fcc = fcc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            ts.extend_from_slice(&packets);
        }
        let mut demux = StreamingTsDemux::new();
        let mut parked = 0usize;
        for chunk in ts.chunks(TS_PACKET_SIZE) {
            demux.feed(chunk);
            parked = parked.max(demux.streams.get(&flood).map_or(0, |s| s.backlog_bytes));
        }
        assert!(
            parked >= SILENT_HEAD_PARKED_BYTES,
            "the audio parked past the criterion ({parked})"
        );
        assert!(
            live_track_added_pids(&ts).is_empty(),
            "a head that has sent data is not a silent head"
        );
    }

    /// Round-4 audit 3: `finish()` abandoning a stepped-over head must remove
    /// it from `skipped` (the two sets are summed by `TracksResolved`).
    #[test]
    fn finish_abandoning_a_skipped_head_keeps_resolved_and_skipped_disjoint() {
        let garbage: Vec<Vec<u8>> = (0..4).map(|_| alloc::vec![0xBBu8; 3]).collect();
        let ts = silent_head_ts(
            STREAM_TYPE_AVC,
            &garbage,
            STREAM_TYPE_AAC_ADTS,
            adts_frame,
            FLOOD_PAST_CRITERION,
        );
        let mut demux = StreamingTsDemux::new();
        demux.feed(&ts);
        assert!(
            demux.skipped.contains(&Pid::new(0x0100)),
            "the silent head was stepped over"
        );
        demux.finish();
        assert!(
            demux.resolved.contains(&Pid::new(0x0100)),
            "finish abandoned the head"
        );
        assert!(
            demux.resolved.is_disjoint(&demux.skipped),
            "resolved {:?} and skipped {:?} double-count",
            demux.resolved,
            demux.skipped
        );
    }

    /// Round-3 audit C: a PMT-version removal of an E-AC-3 track that is
    /// holding back its final access unit (dependent-substream hold-back,
    /// #1186) must emit that whole access unit before `TrackRemoved`.
    #[test]
    fn removing_an_eac3_track_flushes_the_held_final_access_unit() {
        let au = crate::ac3::tests::seven_one_eac3_es();
        let k = 6usize;
        let mut ts = eac3_pes_ts(&vec![au; k]);
        // PMT version 1 declaring nothing: the track is removed. The first PMT
        // took one packet, so its counter continues at 1.
        let mut empty_pmt = Vec::new();
        empty_pmt.extend_from_slice(&0xE000u16.to_be_bytes());
        empty_pmt.extend_from_slice(&0xF000u16.to_be_bytes());
        ts.extend(psi_section_packets_versioned(
            PMT_PID_UNDER_TEST,
            1,
            0x02,
            PROGRAM_NUMBER_UNDER_TEST,
            1,
            &empty_pmt,
        ));
        let seen = seen_events(&ts);
        let removed = seen
            .iter()
            .position(|e| matches!(e, Seen::Removed(_)))
            .expect("TrackRemoved");
        let before = seen[..removed]
            .iter()
            .filter(|e| matches!(e, Seen::Sample(_)))
            .count();
        // PES k-1 never completes (the PID is removed under it); every earlier
        // PES is delivered, and the last of those was held back.
        assert_eq!(
            before,
            k - 1,
            "held final AU emitted before removal: {seen:?}"
        );
    }

    /// Round-3 audit F: a track promoted from an unverified, broken-chain first
    /// frame announces no dependent substream (`dec3` 5.1), but once a
    /// dependent frame is SEEN the hold-back is on, so a dependent frame that
    /// begins a later PES joins its access unit instead of being orphaned.
    #[test]
    fn observed_dependent_substream_enables_the_hold_back() {
        let au = crate::ac3::tests::seven_one_eac3_es();
        let ind_len = {
            let f = Ec3SyncframeInfo::from_es_all(&au);
            (f[0].frmsiz as usize + 1) * 2
        };
        let (ind, dep) = (au[..ind_len].to_vec(), au[ind_len..].to_vec());
        let mut lossy = ind.clone();
        lossy.extend_from_slice(&[0x43, 0x8B, 0x88, 0xBC, 0xA9, 0xB4, 0x00, 0x15]);
        let payloads = alloc::vec![
            lossy,
            [au.clone(), au.clone()].concat(),
            ind.clone(),
            [dep, au.clone()].concat(),
            au.clone(),
            au.clone(),
            au.clone(),
        ];
        let ts = single_es_pes_ts(STREAM_TYPE_EAC3, &payloads);
        let mut demux = StreamingTsDemux::new();
        demux.feed(&ts);
        demux.finish();
        let mut samples: Vec<Vec<u8>> = Vec::new();
        while let Some(ev) = demux.poll_event() {
            match ev {
                DemuxEvent::TrackAdded(spec) => {
                    let CodecConfig::Eac3 { config, .. } = spec.config else {
                        panic!("E-AC-3");
                    };
                    assert!(
                        config.substreams[0].chan_loc.is_none(),
                        "precondition: promoted without a dependent substream"
                    );
                }
                DemuxEvent::Sample { sample, .. } => samples.push(sample.data.to_vec()),
                _ => {}
            }
        }
        assert_eq!(samples[0], ind, "the broken-chain first frame");
        assert!(samples.len() >= 6, "{}", samples.len());
        for (n, s) in samples.iter().enumerate().skip(1) {
            assert_eq!(
                s, &au,
                "sample {n} must be a whole independent+dependent AU"
            );
        }
    }

    /// Round-3 audit D: an E-AC-3 probe fed one byte per PES (large frames, so
    /// the held window grows to tens of KiB) re-walked the whole window per PES.
    /// The walk is gated after `EAC3_PROBE_FULL_WALKS`, bounding the work: an
    /// independent frame followed by a chain of dependents that never completes
    /// an access unit costs a bounded number of walks (ungated: one per byte,
    /// ~30 000), and a stream that DOES complete (the next independent frame
    /// arrives) still resolves under the gate.
    #[test]
    fn eac3_probe_rewalk_is_bounded_for_tiny_pes() {
        let real = {
            let path = test_fixtures::path("ts/dolby/eac3.ts");
            let ts = std::fs::read(path).expect("committed Dolby E-AC-3 capture");
            let media = TsDemux::new().demux(&ts).expect("demux real E-AC-3");
            media.tracks[0].samples[0].data.to_vec()
        };
        let run = |es: &[u8]| {
            let payloads: Vec<Vec<u8>> = es.chunks(1).map(<[u8]>::to_vec).collect();
            let ts = single_es_pes_ts(STREAM_TYPE_EAC3, &payloads);
            let mut demux = StreamingTsDemux::new();
            demux.feed(&ts);
            let walks = demux.streams[&ES_PID_UNDER_TEST].probe_walks;
            let mut tracks = 0;
            while let Some(ev) = demux.poll_event() {
                tracks += usize::from(matches!(ev, DemuxEvent::TrackAdded(_)));
            }
            (walks, tracks)
        };
        // Never completes: one independent frame, then dependents forever.
        let mut endless = real.clone();
        for n in 0..40 {
            endless.extend(eac3_dependent_frame_sized(n, 2048));
        }
        let (walks, _) = run(&endless);
        assert!(
            walks < 4096 + 256,
            "{walks} full window walks for {} one-byte PES",
            endless.len()
        );
        // Completes: the next access unit's independent frame arrives. The
        // window passes the gate (> 4096 bytes) and the track still resolves.
        let mut complete = real.clone();
        for n in 0..8 {
            complete.extend(eac3_dependent_frame_sized(n, 2048));
        }
        complete.extend_from_slice(&real);
        complete.extend(eac3_dependent_frame_sized(9, 2048));
        let (walks, tracks) = run(&complete);
        assert!(walks > 4096, "the gate was exercised: {walks}");
        assert_eq!(tracks, 1, "the track resolves under the gate");
    }

    /// Round-4 audit 2: `probe_walked_len` describes the held window, so it must
    /// never exceed the held tail (a stale length above ~58 KiB made the gate
    /// demand growth past the 64 KiB tail cap, so the window was never
    /// re-walked in full). One-byte PES, past `EAC3_PROBE_FULL_WALKS`, checked
    /// after every TS packet.
    #[test]
    fn eac3_walked_len_follows_the_held_tail() {
        let real = {
            let path = test_fixtures::path("ts/dolby/eac3.ts");
            let ts = std::fs::read(path).expect("committed Dolby E-AC-3 capture");
            let media = TsDemux::new().demux(&ts).expect("demux real E-AC-3");
            media.tracks[0].samples[0].data.to_vec()
        };
        let mut es = real;
        for n in 0..40 {
            es.extend(eac3_dependent_frame_sized(n, 2048));
        }
        let payloads: Vec<Vec<u8>> = es.chunks(1).map(<[u8]>::to_vec).collect();
        let ts = single_es_pes_ts(STREAM_TYPE_EAC3, &payloads);
        let mut demux = StreamingTsDemux::new();
        let mut gated_with_tail = false;
        for chunk in ts.chunks(TS_PACKET_SIZE) {
            demux.feed(chunk);
            let Some(stream) = demux.streams.get(&ES_PID_UNDER_TEST) else {
                continue;
            };
            assert!(
                stream.probe_walked_len <= stream.probe_tail.len(),
                "walked_len {} outlived the held tail ({})",
                stream.probe_walked_len,
                stream.probe_tail.len()
            );
            gated_with_tail |=
                stream.probe_walks >= EAC3_PROBE_FULL_WALKS && !stream.probe_tail.is_empty();
        }
        assert!(gated_with_tail, "the gated branch was exercised");
    }

    /// r04-W51 review: an AAC track must NOT report a config change merely
    /// because the ADTS *frame length* varies.
    ///
    /// The first attempt compared the raw 7-byte ADTS header as the
    /// "config header", but that header carries the 13-bit
    /// `aac_frame_length` — different on every single frame — so nearly every
    /// AAC access unit raised `TrackUpdated` and told a consumer to rebuild
    /// its init segment thousands of times a stream.
    ///
    /// Real AAC bitstream, twice over. First: `fixtures/ts/aac-5-1-640k.ts`
    /// is a real 5.1 AAC-LC capture whose ADTS frame lengths vary (ffprobe:
    /// 742, 792, 763, 764, 767, 759 ...) and which must yield **zero**
    /// `TrackUpdated`. Second: its elementary stream re-headered with a
    /// different `channel_configuration` (5 instead of 6) and appended to the
    /// same PID, which must yield **exactly one** event carrying the new
    /// Table 1.19 count.
    #[test]
    fn aac_frame_length_variation_is_not_a_config_change() {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("aac-5-1-640k.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));

        let count_updates = |bytes: &[u8]| -> (usize, Vec<u16>) {
            let mut demux = StreamingTsDemux::new();
            demux.feed(bytes);
            demux.finish();
            let mut n = 0usize;
            let mut channels = Vec::new();
            while let Some(event) = demux.poll_event() {
                if let DemuxEvent::TrackUpdated(spec) = event {
                    n += 1;
                    if let CodecConfig::Aac { channel_count, .. } = spec.config {
                        channels.push(channel_count);
                    }
                }
            }
            (n, channels)
        };

        let (updates, _) = count_updates(&source);
        assert_eq!(
            updates, 0,
            "a varying ADTS frame_length must not read as a config change; got {updates} TrackUpdated events on a real AAC capture"
        );

        // The fixture's own config, read from its recovered ASC rather than
        // assumed.
        let mut demux = TsDemux::new();
        let media = demux.demux(&source).expect("demux aac fixture");
        let audio = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Aac { .. }))
            .expect("the fixture has an AAC track");
        assert!(!audio.samples.is_empty(), "fixture must carry AAC frames");
        let (sfi, seeded_channels) = match audio.config() {
            CodecConfig::Aac {
                esds,
                channel_count,
                ..
            } => {
                let dsi = esds
                    .es_descriptor
                    .decoder_config
                    .as_ref()
                    .and_then(|dc| dc.decoder_specific_info.as_ref())
                    .expect("AAC esds carries a DecoderSpecificInfo");
                let asc = AudioSpecificConfig::parse(&dsi.data).expect("parse ASC");
                (asc.sampling_frequency_index.raw(), *channel_count)
            }
            _ => unreachable!(),
        };
        /// Table 1.19 configuration 6 is 5.1 (six channels) — what a real
        /// 5.1 capture must report (r04-W51).
        const SEEDED_CHANNELS: u16 = 6;
        assert_eq!(
            seeded_channels, SEEDED_CHANNELS,
            "the fixture is a real 5.1 capture, so its config is Table 1.19 configuration 6"
        );
        /// The rebuilt stream's `channel_configuration`: 5 = five channels,
        /// deliberately different from the fixture's own 5.1.
        const CONFIG_REBUILT: u8 = 5;

        const PES_PAYLOAD_BYTES: usize = 1800;
        let aac_pid = audio
            .spec
            .source_pid
            .expect("a TS-demuxed track carries its source PID");
        let mut input = source.clone();
        let mut cc = 0u8;
        let mut buf: Vec<u8> = Vec::new();
        let flush = |buf: &mut Vec<u8>, cc: &mut u8, input: &mut Vec<u8>| {
            if buf.is_empty() {
                return;
            }
            let pes = pes_packet(ES_STREAM_ID_AUDIO, 0, None, buf);
            let packets = pes_packets(aac_pid, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
            buf.clear();
        };
        // Whole frames per PES payload, as a real muxer packs them.
        for sample in &audio.samples {
            let frame_len = (ADTS_HEADER_SIZE + sample.data.len()) as u16;
            let hdr = crate::aac_asc::build_adts_header(1, sfi, CONFIG_REBUILT, frame_len);
            if buf.len() + frame_len as usize > PES_PAYLOAD_BYTES {
                flush(&mut buf, &mut cc, &mut input);
            }
            buf.extend_from_slice(&hdr);
            buf.extend_from_slice(&sample.data);
        }
        flush(&mut buf, &mut cc, &mut input);

        let (updates, channels) = count_updates(&input);
        assert_eq!(
            updates, 1,
            "a real channel_configuration change must raise exactly one TrackUpdated, got {updates} (channels: {channels:?})"
        );
        assert_eq!(
            channels,
            vec![5],
            "the event must carry the new Table 1.19 count"
        );
    }

    /// r04-W47: the codec-config probes must scan only the *newest* access
    /// unit, so the byte-probe work a never-resolving PID costs stays
    /// proportional to the input length, not to its square.
    ///
    /// A PID whose config never resolves (here: an AAC PID whose ADTS frames
    /// claim `sampling_frequency_index` 13, which [`sfi_to_hz`] rejects, so
    /// [`finalize_probe`] never returns a config) accumulates every access
    /// unit into its backlog while probing. Before the fix each new access
    /// unit re-walked the whole backlog with [`find_adts_sync`], whose
    /// byte-by-byte sync scan is counted by [`record_sync_probe`] at its own
    /// scan site -- measured, not re-derived in the test. Each access unit
    /// here is one 1400-byte ADTS frame carrying no second syncword, so a
    /// scan of one access unit stops at its very first probe, while the
    /// pre-fix shape re-probed every earlier access unit on every push.
    #[test]
    fn probe_sync_scan_work_is_linear_in_the_input_not_quadratic() {
        use crate::aac_asc::build_adts_header;

        /// `sampling_frequency_index` 13 (reserved) -- `sfi_to_hz` returns
        /// `None`, so the AAC probe can never finalize.
        const REJECTED_SFI: u8 = 13;
        /// Frame body bytes after the 7-byte ADTS header.
        const FRAME_BODY: usize = 1400;
        /// ADTS frames per PES access unit.
        const FRAMES_PER_AU: usize = 3;
        /// Access units fed -- chosen so the backlog stays under
        /// [`MAX_PROBE_BACKLOG_BYTES`] (500 × 3 × 1407 B ≈ 2.1 MiB) while the
        /// quadratic shape's total probe count still grows like
        /// `frames^2` (≈ 2.25 × 10^6), orders past the linear bound.
        const ACCESS_UNITS: usize = 500;

        let frame_len = (ADTS_HEADER_SIZE + FRAME_BODY) as u16;
        let mut frame = alloc::vec![0u8; frame_len as usize];
        frame[..ADTS_HEADER_SIZE].copy_from_slice(&build_adts_header(
            1,
            REJECTED_SFI,
            2,
            frame_len,
        ));
        let mut au = Vec::with_capacity(frame.len() * FRAMES_PER_AU);
        for _ in 0..FRAMES_PER_AU {
            au.extend_from_slice(&frame);
        }

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_AAC_ADTS),
        ));
        // One PES packet per access unit; CC runs continuously over the
        // whole elementary stream (each `pes_packets` call increments from
        // the value it is given).
        let mut cc = 0u8;
        for i in 0..ACCESS_UNITS {
            let pes = pes_packet(ES_STREAM_ID_AUDIO, i as i64 * 1024, None, &au);
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        }

        let before = sync_probes();
        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let probes = sync_probes() - before;

        // The PID must genuinely still be probing when the input ends, so this
        // measures a never-resolving probe rather than a resolved one.
        assert!(
            matches!(
                demux
                    .streams
                    .get(&ES_PID_UNDER_TEST)
                    .and_then(|s| s.track.as_ref()),
                Some(TrackState::Probing { .. })
            ),
            "the reserved-SFI AAC PID must never resolve its config, so it stays Probing"
        );
        // Bound: per access unit, exactly one probe pass and one sync scan —
        // and the scan returns at its very first probe, because the syncword is
        // at offset 0. The total is therefore exactly twice the number of access
        // units however long each one is. Re-derived from the fixture's own
        // shape, not from the demux's internals; a backlog rescan would instead
        // be ACCESS_UNITS^2/2 = 125 000.
        let expected = ACCESS_UNITS as u64 * 2;
        assert_eq!(
            probes, expected,
            "the AAC probe must scan only the newest access unit              ({ACCESS_UNITS} accesses => {expected} probes: one pass + one              sync scan each); {probes} recorded"
        );
    }

    /// The same linearity bound for the two probes that walk the access unit
    /// rather than scanning for a syncword — H.264 (a NAL walk) and MPEG audio
    /// (a header scan counted by [`record_sync_probe`]) — so all three probe
    /// families are covered, not just ADTS (r04-W47 review).
    ///
    /// A never-resolving PID of each kind is built from real elementary-stream
    /// bytes and flood-fed access units. The total *probe passes* must stay
    /// proportional to the number of access units, never their sum of lengths.
    #[test]
    fn video_and_mpeg_audio_probe_work_is_linear_in_the_input() {
        /// Access units fed; comfortably more than one, so a linear bound and a
        /// quadratic one differ by orders of magnitude.
        const ACCESS_UNITS: u32 = 400;
        /// Bytes per access unit — large enough that re-walking an accumulated
        /// backlog would be unmistakable.
        const AU_BYTES: usize = 1024;

        // Real H.264 parameter sets, but deliberately *not* a decodable SPS, so
        // the H.264 probe never finalizes: take a real SPS and truncate it.
        let (sps, pps, _) = real_avc_parameter_sets();
        let broken_sps = &sps[..sps.len().min(3)];

        for (stream_type, au) in [
            // H.264: SPS and PPS present but the SPS is unusable, so
            // `decode_avc_sps` never yields a geometry and the probe stays
            // unresolved forever.
            (
                STREAM_TYPE_AVC,
                annexb_au(&[broken_sps, &pps, &[0x41u8; 8]]),
            ),
            // MPEG-1 audio: bytes that never form a valid frame header (a
            // syncword followed by a reserved bit-rate index), so the probe
            // scans the whole access unit and still never resolves.
            (
                STREAM_TYPE_MPEG1_AUDIO,
                // No syncword anywhere in the access unit.
                alloc::vec![0xE0u8; AU_BYTES],
            ),
        ] {
            let mut au = au;
            au.resize(AU_BYTES, 0x33);

            let mut input = Vec::new();
            for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
                input.extend_from_slice(&null_packet());
            }
            input.extend_from_slice(&psi_section_packets(
                PAT_PID_UNDER_TEST,
                0,
                TABLE_ID_PAT,
                &pat_body(),
            ));
            input.extend_from_slice(&psi_section_packets(
                PMT_PID_UNDER_TEST,
                0,
                TABLE_ID_PMT,
                &pmt_body(ES_PID_UNDER_TEST, stream_type),
            ));
            let mut cc = 0u8;
            for i in 0..ACCESS_UNITS {
                let pes = pes_packet(ES_STREAM_ID_AUDIO, i as i64 * 1024, None, &au);
                let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
                cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
                input.extend_from_slice(&packets);
            }

            let before = sync_probes();
            let mut demux = StreamingTsDemux::new();
            demux.feed(&input);
            demux.finish();
            let probes = sync_probes() - before;

            assert!(
                matches!(
                    demux
                        .streams
                        .get(&ES_PID_UNDER_TEST)
                        .and_then(|s| s.track.as_ref()),
                    Some(TrackState::Probing { .. }) | Some(TrackState::Abandoned)
                ),
                "stream_type {stream_type:#04X} must never resolve its config"
            );
            // Exactly one probe pass per access unit for the H.264 probe,
            // whose NAL walk has no byte-by-byte sync scanner of its own — an
            // exact equality, which is the strongest statement the counter can
            // make and cannot be satisfied by a rescan. The MPEG-audio probe
            // *does* scan, so it costs one pass plus up to one probe per byte
            // of the single access unit it examined; its bound stays an
            // inequality (ACCESS_UNITS² / 2 would be ~80 000).
            if stream_type == STREAM_TYPE_AVC {
                assert_eq!(
                    probes, ACCESS_UNITS as u64,
                    "the H.264 probe must make exactly one pass per access                      unit, never a backlog rescan: {probes} probes over                      {ACCESS_UNITS} access units"
                );
            } else {
                // Plus, for the audio probes, the bounded boundary window retried
                // when the access unit holds no header at all (#1160): at most
                // two boundary-widths of probes per access unit — still linear.
                let bound = ACCESS_UNITS as u64
                    * (1 + AU_BYTES as u64 + 2 * AUDIO_PROBE_BOUNDARY_BYTES as u64);
                assert!(
                    probes <= bound,
                    "stream_type {stream_type:#04X}: {probes} probes over                      {ACCESS_UNITS} access units of {AU_BYTES} bytes — bound is                      {bound}; a quadratic rescan is ~{}",
                    (ACCESS_UNITS as u64).pow(2) / 2
                );
            }
        }
    }

    // ── r04-W51 review: parameter-set tracking, not a one-AU snapshot ───────

    /// Build a TS carrying one AVC PID whose access units are exactly the
    /// `aus` given, each in its own PES packet, preceded by a PAT/PMT and the
    /// resync bootstrap. Returns the bytes and the PID used.
    fn avc_ts_over(aus: &[Vec<u8>]) -> Vec<u8> {
        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_AVC),
        ));
        for (i, au) in aus.iter().enumerate() {
            let pes = pes_packet(
                ES_STREAM_ID_VIDEO,
                i as i64 * 3600,
                Some(i as i64 * 3600),
                au,
            );
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        }
        input
    }

    /// The `TrackUpdated` width a TS produces, if any.
    fn updated_avc_width(bytes: &[u8]) -> Option<u16> {
        let mut demux = StreamingTsDemux::new();
        demux.feed(bytes);
        demux.finish();
        std::iter::from_fn(|| demux.poll_event()).find_map(|e| match e {
            DemuxEvent::TrackUpdated(spec) => match spec.config {
                CodecConfig::Avc { width, .. } => Some(width),
                _ => None,
            },
            _ => None,
        })
    }

    /// A two-program multiplex where **program A**'s PCR PID signals a
    /// time-base discontinuity. Program B's timeline must be completely
    /// untouched: §2.4.3.5 scopes the indicator to "the associated program"
    /// (the one whose PCR_PID carries it), so a rebase that reached every
    /// stream in the demux would corrupt an unrelated service (r04-W50
    /// review — the first attempt marked every stream across every program).
    #[test]
    fn signalled_discontinuity_is_scoped_to_the_signalling_program() {
        /// Program A: PMT PID, ES PIDs (the first is also its PCR PID),
        /// program_number.
        const A_PMT: Pid = Pid::new(0x1000);
        const A_ES: Pid = Pid::new(0x1100);
        /// Program A's second elementary stream (audio).
        const A_ES2: Pid = Pid::new(0x1101);
        /// Program B: likewise.
        const B_PMT: Pid = Pid::new(0x1001);
        const B_ES: Pid = Pid::new(0x1200);
        /// Program numbers for the two PAT entries.
        const A_PROGRAM: u16 = 1;
        const B_PROGRAM: u16 = 2;
        /// Frame period, 90 kHz ticks (25 fps).
        const FRAME_PERIOD: i64 = 3600;
        /// Frames per base, per program.
        const FRAMES: i64 = 8;
        /// Program A's second base — well *below* its first, so it needs a lift.
        const A_BASE_B: i64 = 40_000;
        /// Both programs' first base.
        const BASE_A: i64 = 900_000;

        let annexb = real_annexb_frames();

        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        // One PAT listing both programs.
        let mut pat = Vec::new();
        for (program, pmt_pid) in [(A_PROGRAM, A_PMT), (B_PROGRAM, B_PMT)] {
            pat.extend_from_slice(&program.to_be_bytes());
            pat.extend_from_slice(&(0xE000 | pmt_pid.value()).to_be_bytes());
        }
        input.extend_from_slice(&psi_section_packets_for(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            0,
            &pat,
        ));
        // Program A carries *two* elementary streams (video + audio) and the
        // video PID is its PCR_PID: both must be rebased by A's discontinuity,
        // while program B's single stream is untouched (r04-W50 review).
        input.extend_from_slice(&psi_section_packets_for(
            A_PMT,
            0,
            TABLE_ID_PMT,
            A_PROGRAM,
            &pmt_body_two_es_with_pcr_pid(A_ES, STREAM_TYPE_AVC, A_ES2, STREAM_TYPE_AVC, A_ES),
        ));
        input.extend_from_slice(&psi_section_packets_for(
            B_PMT,
            0,
            TABLE_ID_PMT,
            B_PROGRAM,
            &pmt_body_with_pcr_pid(B_ES, STREAM_TYPE_AVC, B_ES),
        ));
        let push_au = |input: &mut Vec<u8>, cc: &mut u8, pid: Pid, au: &[u8], dts: i64| {
            let wire = dts.rem_euclid(1i64 << 33) as u64;
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire as i64, Some(wire as i64), au);
            let packets = pes_packets(pid, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        // Program A: base 1, then a signalled discontinuity on its PCR PID,
        // then base 2 (below base 1).
        for i in 0..FRAMES {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push_au(&mut input, &mut cc, A_ES, &au, BASE_A + i * FRAME_PERIOD);
        }
        {
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = (A_ES.value() >> 8) as u8 & PID_HI_MASK;
            pkt[2] = (A_ES.value() & 0xFF) as u8;
            pkt[3] = 0x20 | (cc & 0x0F); // AFC=10: adaptation field only
            pkt[4] = 8;
            pkt[5] = 0x80; // discontinuity_indicator
            input.extend_from_slice(&pkt);
            cc = cc.wrapping_add(1);
        }
        for i in 0..FRAMES {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push_au(&mut input, &mut cc, A_ES, &au, A_BASE_B + i * FRAME_PERIOD);
        }
        // Program A's *second* elementary stream: its own timeline with the
        // same base change, so the rebase must reach every stream of the
        // program, not just the PID that carried the indicator.
        for i in 0..FRAMES * 2 {
            let au = annexb[(i as usize) % annexb.len()].clone();
            let dts = if i < FRAMES {
                BASE_A + i * FRAME_PERIOD
            } else {
                A_BASE_B + (i - FRAMES) * FRAME_PERIOD
            };
            push_au(&mut input, &mut cc, A_ES2, &au, dts);
        }
        // Program B: one base, no discontinuity at all.
        for i in 0..FRAMES * 2 {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push_au(&mut input, &mut cc, B_ES, &au, BASE_A + i * FRAME_PERIOD);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let events: Vec<DemuxEvent> = std::iter::from_fn(|| demux.poll_event()).collect();
        let ids: BTreeMap<TrackId, Pid> = events
            .iter()
            .filter_map(|e| match e {
                DemuxEvent::TrackAdded(spec) => spec.source_pid.map(|pid| (spec.track_id, pid)),
                _ => None,
            })
            .collect();
        let mut samples_by_pid: BTreeMap<Pid, Vec<i64>> = BTreeMap::new();
        for event in &events {
            if let DemuxEvent::Sample { track_id, sample } = event
                && let Some(pid) = ids.get(track_id)
                && let Some(dts) = sample.dts
            {
                samples_by_pid
                    .entry(Pid::new((*pid).value()))
                    .or_default()
                    .push(dts);
            }
        }
        let a_dts = samples_by_pid
            .get(&A_ES)
            .cloned()
            .expect("program A's video PID must deliver samples");
        let b_dts = samples_by_pid
            .get(&B_ES)
            .cloned()
            .expect("program B must deliver samples");

        assert!(
            b_dts.len() >= FRAMES as usize,
            "program B must deliver its samples, got {}",
            b_dts.len()
        );
        // Program B's timeline must be exactly what it would be without any
        // discontinuity: the declared base, advancing by one frame period.
        let expected: Vec<i64> = (0..FRAMES * 2).map(|i| BASE_A + i * FRAME_PERIOD).collect();
        let got: Vec<i64> = b_dts.iter().copied().take(expected.len()).collect();
        assert_eq!(
            got, expected,
            "program B's dts must be untouched by program A's signalled              discontinuity"
        );
        // And program A did get rebased — on *both* of its elementary streams,
        // so the test is not vacuous and the scope is not accidentally
        // narrowed to the PID that happened to carry the indicator.
        let a_steps: Vec<i64> = a_dts.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            !a_steps.is_empty() && a_steps.iter().all(|&d| d > 0),
            "program A's video timeline must be strictly increasing across its              discontinuity: {a_dts:?}"
        );
        let a2 = samples_by_pid
            .get(&A_ES2)
            .expect("program A's second elementary stream must deliver samples");
        let a2_steps: Vec<i64> = a2.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            !a2_steps.is_empty() && a2_steps.iter().all(|&d| d > 0),
            "program A's *second* PID must be rebased by the discontinuity on              its PCR_PID too: {a2:?}"
        );
    }

    /// Real Annex-B H.264 access units from the committed `h264-aac.ts`
    /// capture: the first sample carries the SPS/PPS, so a track resolves on
    /// the first one fed. Reused by every test that needs a decodable video
    /// elementary stream without hand-rolling one.
    fn real_annexb_frames() -> Vec<Vec<u8>> {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new().demux(&source).expect("demux h264-aac.ts");
        let video = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .expect("h264-aac.ts has an AVC track");
        video
            .samples
            .iter()
            .map(|sample| {
                let mut au = Vec::new();
                for nal in crate::annexb::iter_length_prefixed_nals(&sample.data)
                    .expect("TsMux writes valid NAL prefixes")
                {
                    au.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
                    au.extend_from_slice(nal);
                }
                au
            })
            .collect()
    }

    /// A backward discontinuity with a **jittered** cadence. The earlier
    /// attempt decided "old base vs new base" by exact equality
    /// (`shortfall == 0`), which cadence jitter breaks: at 23.976 fps the frame
    /// period alternates 3754/3753 ticks (90000/23.976 = 3753.75), so the old
    /// base's last access unit lands a tick early or late and consumes the
    /// `pending_rebase` flag — leaving the real new-base unit unrebase
    /// (r04-W50 review). A backward move is the signal instead, because the old
    /// base cannot produce one.
    ///
    /// The timeline fed in is the *real* alternating cadence, not a synthetic
    /// constant: that is the whole point, since a constant cadence cannot
    /// reproduce the defect.
    #[test]
    fn jittered_cadence_backward_discontinuity_rebases() {
        /// 23.976 fps at 90 kHz: 3753.75 ticks, emitted as 3754/3753 —
        /// exactly what a real encoder hands out.
        const PERIODS: [i64; 2] = [3754, 3753];
        /// First time base.
        const BASE_A: i64 = 900_000;
        /// Second base: **below** the first, the ordinary splice shape.
        const BASE_B: i64 = 120_000;
        /// Access units per base — enough for the jitter to bite.
        const FRAMES: i64 = 30;

        let annexb = real_annexb_frames();
        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            // The ES PID is the program's PCR_PID, so the indicator is carried
            // where §2.4.3.5 requires.
            &pmt_body_with_pcr_pid(ES_PID_UNDER_TEST, STREAM_TYPE_AVC, ES_PID_UNDER_TEST),
        ));

        let push = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], dts: i64| {
            let wire = dts.rem_euclid(1i64 << 33);
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire, Some(wire), au);
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        let mut dts = BASE_A;
        for i in 0..FRAMES * 2 {
            if i == FRAMES {
                let mut pkt = [0xFFu8; TS_PACKET_SIZE];
                pkt[0] = 0x47;
                pkt[1] = (ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK;
                pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
                pkt[3] = 0x20 | (cc & 0x0F);
                pkt[4] = 8;
                pkt[5] = 0x80; // discontinuity_indicator
                input.extend_from_slice(&pkt);
                cc = cc.wrapping_add(1);
                dts = BASE_B;
            }
            let au = annexb[(i as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, dts);
            dts += PERIODS[(i as usize) % PERIODS.len()];
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<i64> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => sample.dts,
                _ => None,
            })
            .collect();
        assert!(
            got.len() >= FRAMES as usize,
            "expected the access units of both bases, got {}",
            got.len()
        );
        let steps: Vec<i64> = got.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d > 0),
            "dts must be strictly increasing across a jittered discontinuity;              dts={got:?}"
        );
        // The seam continues the cadence: one nominal period, within the
        // jitter the input itself carries.
        let seam = steps
            .iter()
            .copied()
            .filter(|&d| d > PERIODS[1])
            .max()
            .unwrap_or(0);
        assert!(
            seam <= PERIODS[0] + 1,
            "the seam must continue the cadence (one period), not jump:              largest step {seam}, steps={steps:?}"
        );
    }

    /// An 8-second forward splice must **not** become the frame period. The
    /// first estimator accepted any step up to ten seconds, so a splice sat
    /// inside the window and was then used as the constant period for every
    /// unstamped access unit after it — stretching them all out by 8 seconds
    /// (r04-W48/W50 review). The window is now a median of the last few steps
    /// and its ceiling is one second.
    #[test]
    fn an_eight_second_splice_does_not_become_the_frame_period() {
        /// Frame period, 90 kHz ticks (25 fps).
        const FRAME_PERIOD: i64 = 3600;
        /// A splice far longer than any real frame period, and longer than the
        /// one-second ceiling.
        const SPLICE: i64 = 8 * 90_000;
        /// Stamped frames before the splice.
        const STAMPED: i64 = 8;
        /// Forced frame-rate PES packets after the splice — the frames whose
        /// duration the interpolator would stretch if the splice were adopted.
        const UNSTAMPED: usize = 4;

        let annexb = real_annexb_frames();
        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_AVC),
        ));

        let push = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], dts: Option<i64>| {
            let pes = match dts {
                Some(d) => {
                    let wire = d.rem_euclid(1i64 << 33);
                    pes_packet(ES_STREAM_ID_VIDEO, wire, Some(wire), au)
                }
                None => pes_packet_untimed(ES_STREAM_ID_VIDEO, au),
            };
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        // A regular cadence, then a *run* of 8-second steps — enough of them
        // that even a median of the window is dominated by the splice, which is
        // exactly what the one-second ceiling exists to reject.
        for i in 0..STAMPED {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, Some(90_000 + i * FRAME_PERIOD));
        }
        let mut at = 90_000 + (STAMPED - 1) * FRAME_PERIOD + SPLICE;
        for i in 0..6usize {
            let au = annexb[i % annexb.len()].clone();
            push(&mut input, &mut cc, &au, Some(at));
            at += SPLICE;
        }
        let after_splice = at - SPLICE;
        for i in 1..=UNSTAMPED {
            let au = annexb[i % annexb.len()].clone();
            push(&mut input, &mut cc, &au, None);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let dts: Vec<i64> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => sample.dts,
                _ => None,
            })
            .collect();
        // The unstamped frames must be spaced by the *measured* frame period,
        // not by the splice.
        let tail: Vec<i64> = dts.iter().copied().filter(|&d| d > after_splice).collect();
        assert!(
            tail.len() >= UNSTAMPED - 1,
            "expected the unstamped frames to be delivered, got {dts:?}"
        );
        let steps: Vec<i64> = tail.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d == FRAME_PERIOD),
            "the splice must not become the frame period: steps={steps:?}              (an adopted 8-second period would give {SPLICE})"
        );
    }

    /// A **bounded** PES that stops short of its declared length is dropped at
    /// `finish()` too, not just mid-stream: end of input is not evidence that
    /// the missing bytes were never needed (r04-W49 review).
    #[test]
    fn truncated_final_bounded_pes_is_dropped_at_flush() {
        /// A payload long enough to need two TS packets, so the declared
        /// length can be left unmet.
        const BODY: usize = 300;
        let au: Vec<u8> = (0..BODY).map(|i| (i & 0xFF) as u8).collect();
        let pes = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, &au);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));
        // Only the first of the unit's two packets: the declared length is
        // never reached, and nothing follows to complete it.
        let packets = pes_packets(ES_PID_UNDER_TEST, 0, &pes);
        assert_eq!(
            packets.len(),
            2 * TS_PACKET_SIZE,
            "the unit spans two packets"
        );
        input.extend_from_slice(&packets[..TS_PACKET_SIZE]);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let samples = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::Sample { .. }))
            .count();
        assert_eq!(
            samples, 0,
            "a bounded PES that never reached its declared length must not be              delivered by finish()"
        );
    }

    /// A discontinuity that coincides with the 33-bit wrap. Base A ends at raw
    /// `2^33 - 3*3600`; the indicator signals a new base whose first raw stamp
    /// is `1000` — just past the wrap, and *continuing* the old base once the
    /// 33-bit unroll is applied. Reading the raw number instead of the unrolled
    /// one makes that look like a jump backwards by nearly the whole modulus,
    /// so the lift is inflated by ~2³³ and the timeline runs away
    /// (r04-W50 review; the earlier round claimed this was untestable).
    ///
    /// The assertion is exact: every step stays one frame period — across the
    /// wrap and across the signalled seam alike.
    #[test]
    fn wrap_coincident_discontinuity_keeps_one_frame_period_steps() {
        /// Frame period, 90 kHz ticks.
        const FRAME_PERIOD: i64 = 3600;
        /// Frames in base A.
        const FRAMES_A: i64 = 3;
        /// The 33-bit clock modulus.
        const WRAP: i64 = 1i64 << 33;
        /// Base A's anchor: its last stamp is exactly one period short of the
        /// wrap.
        const BASE_A: i64 = WRAP - (FRAMES_A + 1) * FRAME_PERIOD;
        /// Base A's last raw (= unrolled) stamp.
        const A_LAST: i64 = BASE_A + (FRAMES_A - 1) * FRAME_PERIOD;
        /// Base B's first raw stamp. On the wire it is a small number just
        /// past zero; unrolled, `BASE_B + WRAP` is exactly one frame period
        /// after base A's last stamp, so the honest timeline is a perfectly
        /// regular cadence across the wrap.
        const BASE_B: i64 = BASE_A + FRAMES_A * FRAME_PERIOD - WRAP;

        let annexb = real_annexb_frames();
        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body_with_pcr_pid(ES_PID_UNDER_TEST, STREAM_TYPE_AVC, ES_PID_UNDER_TEST),
        ));

        let push = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], raw: i64| {
            let wire = raw.rem_euclid(WRAP);
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire, Some(wire), au);
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        // Base A, ending one frame period short of the wrap.
        for i in 0..FRAMES_A {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, BASE_A + i * FRAME_PERIOD);
        }
        // The signalled discontinuity, at the wrap.
        {
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = (ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK;
            pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
            pkt[3] = 0x20 | (cc & 0x0F);
            pkt[4] = 8;
            pkt[5] = 0x80; // discontinuity_indicator
            input.extend_from_slice(&pkt);
            cc = cc.wrapping_add(1);
        }
        // Base B: raw stamps just past zero, i.e. unrolled one frame past base
        // A's last stamp.
        for i in 0..FRAMES_A + 2 {
            let au = annexb[((FRAMES_A + i) as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, BASE_B + i * FRAME_PERIOD);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let dts: Vec<i64> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => sample.dts,
                _ => None,
            })
            .collect();
        assert!(
            dts.len() >= (FRAMES_A + 2) as usize,
            "expected the access units of both bases, got {}",
            dts.len()
        );
        let steps: Vec<i64> = dts.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d == FRAME_PERIOD),
            "every step must stay exactly one frame period across the wrap and              the seam; dts={dts:?} steps={steps:?}"
        );
        // The absolute values also pin the *unroll*: base B's raw stamps are
        // near zero, so a demux that did not unroll across the wrap would place
        // them ~2^33 below base A instead of continuing it.
        let first_of_b = dts[dts.len() - (FRAMES_A as usize + 2)];
        assert!(
            first_of_b > A_LAST && first_of_b - A_LAST < 2 * FRAME_PERIOD,
            "base B must continue base A across the wrap, not restart near zero:              first_of_b={first_of_b} last_of_a={A_LAST}"
        );
    }

    /// A **forward** jump at a signalled discontinuity must not be collapsed.
    /// Round 2 computed `wanted - next` and added it even when negative, so a
    /// legitimate forward splice — the new base starting well *ahead* — was
    /// pulled back to a single frame period, destroying the real gap
    /// (r04-W50 review).
    #[test]
    fn forward_jump_at_a_signalled_discontinuity_is_not_collapsed() {
        /// Frame period.
        const FRAME_PERIOD: i64 = 3600;
        /// Frames in the first base.
        const FRAMES: i64 = 6;
        /// The first base.
        const BASE_A: i64 = 900_000;
        /// The new base: a full 8 seconds **ahead** of the first's last stamp.
        const FORWARD_JUMP: i64 = 8 * 90_000;

        let annexb = real_annexb_frames();
        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body_with_pcr_pid(ES_PID_UNDER_TEST, STREAM_TYPE_AVC, ES_PID_UNDER_TEST),
        ));

        let push = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], dts: i64| {
            let wire = dts.rem_euclid(1i64 << 33);
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire, Some(wire), au);
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };
        for i in 0..FRAMES {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, BASE_A + i * FRAME_PERIOD);
        }
        let base_b = BASE_A + (FRAMES - 1) * FRAME_PERIOD + FORWARD_JUMP;
        {
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = (ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK;
            pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
            pkt[3] = 0x20 | (cc & 0x0F);
            pkt[4] = 8;
            pkt[5] = 0x80;
            input.extend_from_slice(&pkt);
            cc = cc.wrapping_add(1);
        }
        for i in 0..FRAMES {
            let au = annexb[(i as usize) % annexb.len()].clone();
            push(&mut input, &mut cc, &au, base_b + i * FRAME_PERIOD);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let dts: Vec<i64> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => sample.dts,
                _ => None,
            })
            .collect();
        assert!(dts.len() >= 2, "expected samples from both bases");
        let steps: Vec<i64> = dts.windows(2).map(|w| w[1] - w[0]).collect();
        let seam = steps
            .iter()
            .copied()
            .find(|&d| d > FRAME_PERIOD)
            .unwrap_or_else(|| {
                panic!("the forward jump must survive as a large step, got {steps:?}")
            });
        assert!(
            seam >= FORWARD_JUMP,
            "a forward jump of {FORWARD_JUMP} ticks must not be collapsed to              {seam}; the offset must never be reduced"
        );
        assert!(
            steps.iter().all(|&d| d > 0),
            "and the timeline must still be strictly increasing: {steps:?}"
        );
    }

    /// Real SPS/PPS bytes from a committed capture: the fixture's own first
    /// access unit carries them, and they decode to a known geometry used as
    /// the oracle below.
    fn real_avc_parameter_sets() -> (Vec<u8>, Vec<u8>, u16) {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new().demux(&source).expect("demux h264-aac.ts");
        let video = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .expect("h264-aac.ts has an AVC track");
        let width = match video.config() {
            CodecConfig::Avc { width, .. } => *width,
            _ => unreachable!(),
        };
        let first = &video.samples[0].data;
        let nals = crate::annexb::iter_length_prefixed_nals(first)
            .expect("TsMux writes valid NAL prefixes");
        let sps = nals
            .iter()
            .find(|n| (n[0] & H264_NAL_TYPE_MASK) == H264_NAL_SPS)
            .expect("the first access unit carries an SPS");
        let pps = nals
            .iter()
            .find(|n| (n[0] & H264_NAL_TYPE_MASK) == H264_NAL_PPS)
            .expect("the first access unit carries a PPS");
        (sps.to_vec(), pps.to_vec(), width)
    }

    /// Annex-B access unit from the given NALs.
    fn annexb_au(nals: &[&[u8]]) -> Vec<u8> {
        let mut au = Vec::new();
        for nal in nals {
            au.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
            au.extend_from_slice(nal);
        }
        au
    }

    /// An access unit carrying **only** a slice NAL: no parameter sets at all,
    /// which is how the tail of a real stream looks between keyframes.
    fn slice_only_au(tag: u8) -> Vec<u8> {
        annexb_au(&[&[0x65, 0x88, 0x84, tag]])
    }

    /// The anti-spam half of item 5, first case: an encoder that repeats the
    /// identical SPS+PPS in its first access unit and then sends slice-only
    /// access units must produce exactly one `TrackUpdated` set — none.
    ///
    /// The first attempt compared the parameter sets of a *single* access unit
    /// against a snapshot seeded from the backlog's last one, so the very next
    /// slice-only access unit (no parameter sets at all) compared unequal and
    /// raised a spurious event.
    #[test]
    fn parameter_sets_in_one_access_unit_then_slices_emit_no_update() {
        let (sps, pps, width) = real_avc_parameter_sets();
        let mut aus = vec![annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, 0x01]])];
        for i in 0..4u8 {
            aus.push(slice_only_au(i));
        }
        let bytes = avc_ts_over(&aus);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let added_width = std::iter::from_fn(|| demux.poll_event()).find_map(|e| match e {
            DemuxEvent::TrackAdded(spec) => match spec.config {
                CodecConfig::Avc { width, .. } => Some(width),
                _ => None,
            },
            _ => None,
        });
        assert_eq!(
            added_width,
            Some(width),
            "the track must resolve from the parameter sets in the first access unit"
        );
        assert_eq!(
            updated_avc_width(&bytes),
            None,
            "slice-only access units carry no parameter sets, so nothing changed; a per-access-unit comparison raised a spurious TrackUpdated here"
        );
    }

    /// Second case: SPS and PPS arriving in *separate* access units (which real
    /// encoders do) must not read as a change either — the sets are tracked
    /// separately and each is only "new" once.
    #[test]
    fn parameter_sets_split_across_access_units_emit_no_update() {
        let (sps, pps, width) = real_avc_parameter_sets();
        let aus = vec![
            annexb_au(&[&sps, &[0x65, 0x88, 0x84, 0x01]]),
            annexb_au(&[&pps, &[0x65, 0x88, 0x84, 0x02]]),
            slice_only_au(0x03),
        ];
        let bytes = avc_ts_over(&aus);
        assert_eq!(
            updated_avc_width(&bytes),
            None,
            "the PPS arriving one access unit after the SPS is not a change; a one-access-unit comparison reported one (and would have reported the SPS's access unit too). Track added at width {width}"
        );
    }

    /// And the real change: a *different* SPS mid-stream must raise exactly one
    /// `TrackUpdated`, carrying the new geometry.
    #[test]
    fn a_changed_sps_raises_exactly_one_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        // A second, genuinely different SPS: the same bytes with the level_idc
        // byte altered is enough to be a different parameter set, but it must
        // still decode, so take a real SPS from another committed capture.
        let path = test_fixtures::path("ts/h264-two-resolutions.ts");
        let other =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new()
            .demux(&other)
            .expect("demux two-resolution fixture");
        let second_sps = media
            .tracks
            .iter()
            .filter(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .flat_map(|t| t.samples.iter())
            .flat_map(|s| {
                crate::annexb::iter_length_prefixed_nals(&s.data)
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|n| (n[0] & H264_NAL_TYPE_MASK) == H264_NAL_SPS)
                    .map(|n| n.to_vec())
                    .collect::<Vec<_>>()
            })
            .find(|s| s.as_slice() != sps.as_slice())
            .expect("the two-resolution fixture carries a second, different SPS");
        assert_ne!(second_sps, sps, "the two SPS really differ");

        let aus = vec![
            annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, 0x01]]),
            slice_only_au(0x02),
            annexb_au(&[&second_sps, &pps, &[0x65, 0x88, 0x84, 0x03]]),
            slice_only_au(0x04),
        ];
        let bytes = avc_ts_over(&aus);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let updates: Vec<(u16, u16)> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::TrackUpdated(spec) => match spec.config {
                    CodecConfig::Avc { width, height, .. } => Some((width, height)),
                    _ => None,
                },
                _ => None,
            })
            .collect();
        assert_eq!(
            updates.len(),
            1,
            "exactly one SPS change, so exactly one TrackUpdated: {updates:?}"
        );
        assert_ne!(
            updates[0],
            (0, 0),
            "the event must carry the newly-decoded geometry, not zeros"
        );
    }

    /// The discriminating case for the one-access-unit mistake: the SPS and the
    /// PPS arrive in **separate** access units, and the per-access-unit
    /// comparison treats the first of them (which carries no PPS at all) as a
    /// change against the empty snapshot, then the second again. Tracking each
    /// set on its own fires only on the real changes.
    #[test]
    fn parameter_sets_split_across_access_units_raise_exactly_one_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        // AU0: SPS only (carries the parameter set a decoder config needs, but
        // not the PPS yet). AU1: PPS only. AU2: a slice. AU3: a *different*
        // slice-only access unit.
        let aus = vec![
            annexb_au(&[&sps, &[0x65, 0x88, 0x84, 0x01]]),
            annexb_au(&[&[0x65, 0x88, 0x84, 0x02]]),
            annexb_au(&[&pps, &[0x65, 0x88, 0x84, 0x03]]),
            slice_only_au(0x04),
            slice_only_au(0x05),
        ];
        let bytes = avc_ts_over(&aus);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let updates = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::TrackUpdated(_)))
            .count();
        assert_eq!(
            updates, 0,
            "no parameter set ever changes value here — the SPS and the PPS just arrive in different access units — so nothing may be reported"
        );
    }

    /// The spurious-event case, precisely: a stream that alternates
    /// "SPS+PPS" and "PPS only" access units (some encoders resend only the PPS
    /// on a non-IDR keyframe). A per-access-unit snapshot loses the SPS during
    /// the PPS-only units, so the next SPS+PPS unit *looks* like a change even
    /// though the configuration is byte-for-byte the same — and because that
    /// access unit does carry a complete set, the re-probe succeeds and the
    /// spurious `TrackUpdated` is really emitted.
    #[test]
    fn alternating_parameter_set_carriage_emits_no_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let mut aus = vec![annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, 0x01]])];
        for i in 0..4u8 {
            // PPS-only…
            aus.push(annexb_au(&[&pps, &[0x65, 0x88, 0x84, i + 2]]));
            // …then the full set again, unchanged.
            aus.push(annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, i + 10]]));
        }
        let bytes = avc_ts_over(&aus);
        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let updates = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::TrackUpdated(_)))
            .count();
        assert_eq!(
            updates, 0,
            "the configuration never changes, so no TrackUpdated may be raised; a per-access-unit snapshot loses the SPS during the PPS-only units and reports each following full set as a change"
        );
    }

    /// Rewrite a real H.264 PPS NAL so its `pic_parameter_set_id` (the first
    /// `ue(v)` of the RBSP, H.264 §7.3.2.2) is `id`, keeping every later field
    /// bit-for-bit: unescape, swap the leading `ue(v)`, drop the old
    /// alignment, re-pad after the stop bit, re-escape (§7.4.1.1).
    fn pps_with_id(pps: &[u8], id: u64) -> Vec<u8> {
        let rbsp = crate::bitreader::unescape(&pps[1..]);
        let bits: Vec<bool> = rbsp
            .iter()
            .flat_map(|b| (0..8).rev().map(move |i| (b >> i) & 1 == 1))
            .collect();
        let zeros = bits.iter().take_while(|b| !**b).count();
        let rest = &bits[2 * zeros + 1..];
        let stop = rest.iter().rposition(|b| *b).expect("stop bit");
        let v = id + 1;
        let width = 64 - v.leading_zeros() as usize;
        let mut out_bits: Vec<bool> = vec![false; width - 1];
        out_bits.extend((0..width).rev().map(|i| (v >> i) & 1 == 1));
        out_bits.extend_from_slice(&rest[..=stop]);
        while !out_bits.len().is_multiple_of(8) {
            out_bits.push(false);
        }
        let mut out = vec![pps[0]];
        let mut zero_run = 0;
        for chunk in out_bits.chunks(8) {
            let byte = chunk.iter().fold(0u8, |a, b| (a << 1) | u8::from(*b));
            if zero_run >= 2 && byte <= 3 {
                out.push(3);
                zero_run = 0;
            }
            zero_run = if byte == 0 { zero_run + 1 } else { 0 };
            out.push(byte);
        }
        out
    }

    /// Three PPS NALs with DIFFERENT `pic_parameter_set_id`s 0, 1, 2 and
    /// otherwise the real PPS's content (issue #1166: an encoder cycling
    /// several PPS ids). `pps` must carry id 0 (the real capture's does).
    fn rotating_pps_set(pps: &[u8]) -> Vec<Vec<u8>> {
        assert_eq!(pps_id(Codec::H264, pps), 0, "the real PPS is id 0");
        (0u64..3).map(|i| pps_with_id(pps, i)).collect()
    }

    #[test]
    fn pps_with_id_helper_changes_only_the_id() {
        let (_, pps, _) = real_avc_parameter_sets();
        assert_eq!(pps_with_id(&pps, 0), pps, "id 0 reproduces the real PPS");
        for id in [1u64, 2, 3, 17, 255] {
            let v = pps_with_id(&pps, id);
            assert_eq!(pps_id(Codec::H264, &v), id);
            assert!(parameter_set_is_valid(NalCodec::Avc, ParamKind::Pps, &v));
        }
    }

    /// Updates + the whole event log (Debug lines) for `bytes` fed in `chunk`s.
    fn events_chunked(bytes: &[u8], chunk: usize) -> (usize, Vec<String>) {
        let mut demux = StreamingTsDemux::new();
        let mut log = Vec::new();
        let mut updates = 0;
        for c in bytes.chunks(chunk) {
            demux.feed(c);
            while let Some(e) = demux.poll_event() {
                if matches!(e, DemuxEvent::TrackUpdated(_)) {
                    updates += 1;
                }
                log.push(format!("{e:?}"));
            }
        }
        demux.finish();
        while let Some(e) = demux.poll_event() {
            if matches!(e, DemuxEvent::TrackUpdated(_)) {
                updates += 1;
            }
            log.push(format!("{e:?}"));
        }
        (updates, log)
    }

    /// Issue #1166: an encoder carrying several PPS ids and re-sending them in a
    /// rotating order (orf1 cycles three, one per access unit) must not raise a
    /// `TrackUpdated` per rotation step. The old single "last seen PPS" slot
    /// read every step as a change.
    #[test]
    fn rotating_pps_ids_emit_no_update_and_are_chunk_invariant() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let set = rotating_pps_set(&pps);
        let mut aus = vec![annexb_au(&[&sps, &set[0], &[0x65, 0x88, 0x84, 0x01]])];
        for i in 0..12usize {
            aus.push(annexb_au(&[
                &set[(i + 1) % 3],
                &[0x65, 0x88, 0x84, 0x10 + i as u8],
            ]));
        }
        let bytes = avc_ts_over(&aus);
        let (baseline, base_log) = events_chunked(&bytes, bytes.len());
        // First sight of PPS 1 and PPS 2 is two updates (their bytes are new);
        // the 12 rotation steps after that add none (the old code gave ~13).
        assert!(
            baseline == 2,
            "rotation must not flap: got {baseline} updates"
        );
        let all_in_first_unit: Vec<Vec<u8>> = vec![annexb_au(&[
            &sps,
            &set[0],
            &set[1],
            &set[2],
            &[0x65, 0x88, 0x84, 0x01],
        ])]
        .into_iter()
        .chain(
            (0..12usize)
                .map(|i| annexb_au(&[&set[(i + 1) % 3], &[0x65, 0x88, 0x84, 0x10 + i as u8]])),
        )
        .collect();
        let bytes2 = avc_ts_over(&all_in_first_unit);
        for chunk in [1usize, 7, 187, 188, 189, 1000] {
            let (u, log) = events_chunked(&bytes2, chunk);
            assert_eq!(u, 0, "chunk {chunk}: all ids announced up front, so none");
            let (_, ref_log) = events_chunked(&bytes2, bytes2.len());
            assert_eq!(log, ref_log, "chunk {chunk}: event sequence differs");
            let (ub, lb) = events_chunked(&bytes, chunk);
            assert_eq!(ub, baseline, "chunk {chunk}: update count differs");
            assert_eq!(lb, base_log, "chunk {chunk}: event sequence differs");
        }
    }

    /// A genuinely new PPS (same length, different bytes) after a rotation has
    /// settled is still exactly one `TrackUpdated`.
    #[test]
    fn same_length_pps_change_after_rotation_raises_exactly_one_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let set = rotating_pps_set(&pps);
        // A genuinely new PPS: a fourth id, announced after the rotation settled.
        let changed = pps_with_id(&pps, 3);
        assert!(!set.contains(&changed));
        let mut aus = vec![annexb_au(&[
            &sps,
            &set[0],
            &set[1],
            &set[2],
            &[0x65, 0x88, 0x84, 0x01],
        ])];
        for i in 0..6usize {
            aus.push(annexb_au(&[
                &set[i % 3],
                &[0x65, 0x88, 0x84, 0x10 + i as u8],
            ]));
        }
        aus.push(annexb_au(&[&changed, &[0x65, 0x88, 0x84, 0x40]]));
        for i in 0..6usize {
            aus.push(annexb_au(&[
                &set[i % 3],
                &[0x65, 0x88, 0x84, 0x50 + i as u8],
            ]));
            aus.push(annexb_au(&[&changed, &[0x65, 0x88, 0x84, 0x60 + i as u8]]));
        }
        let bytes = avc_ts_over(&aus);
        let (updates, base) = events_chunked(&bytes, bytes.len());
        assert_eq!(updates, 1, "exactly one update for the one real change");
        for chunk in [1usize, 188, 1000] {
            assert_eq!(events_chunked(&bytes, chunk).1, base, "chunk {chunk}");
        }
    }

    /// Issue #1186 (follow-up of #1166): one PPS id whose content switches
    /// A -> B -> A (an encoder changing settings and back) is re-reported at
    /// EVERY switch. The old "never seen before" test reported A -> B but
    /// missed B -> A because A had been seen.
    #[test]
    fn pps_a_b_a_on_one_id_is_reported_at_every_switch() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let a = pps.clone();
        // Same id (0), different content: flip a bit inside the body.
        let mut b = pps.clone();
        let mid = b.len() - 2;
        b[mid] ^= 0x04;
        assert!(parameter_set_is_valid(NalCodec::Avc, ParamKind::Pps, &b));
        assert_eq!(pps_id(Codec::H264, &a), pps_id(Codec::H264, &b));
        assert_ne!(a, b);
        let idr = [0x65u8, 0x88, 0x84, 0x01];
        // A, then B (x3 repeats), then A again (x3), then B, then A.
        let mut aus = vec![annexb_au(&[&sps, &a, &idr])];
        let mut seq: Vec<&Vec<u8>> = Vec::new();
        for _ in 0..3 {
            seq.push(&b);
        }
        for _ in 0..3 {
            seq.push(&a);
        }
        seq.push(&b);
        seq.push(&a);
        for (i, p) in seq.iter().enumerate() {
            aus.push(annexb_au(&[p, &[0x65, 0x88, 0x84, 0x10 + i as u8]]));
        }
        let bytes = avc_ts_over(&aus);
        let (updates, base) = events_chunked(&bytes, bytes.len());
        // A->B, B->A, A->B, B->A: four real switches (repeats are silent).
        assert_eq!(updates, 4, "every A<->B switch on one id is a change");
        for chunk in [1usize, 188, 1000] {
            assert_eq!(events_chunked(&bytes, chunk).1, base, "chunk {chunk}");
        }
    }

    /// The same switching on a *different id* per set is rotation, not change:
    /// ids 0 and 1 coexist, so A, B, A, B is silent after B's first sight.
    #[test]
    fn pps_alternating_between_two_ids_is_rotation_not_change() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let a = pps_with_id(&pps, 0);
        let b = pps_with_id(&pps, 1);
        let idr = [0x65u8, 0x88, 0x84, 0x01];
        let mut aus = vec![annexb_au(&[&sps, &a, &idr])];
        for i in 0..8usize {
            let p = if i % 2 == 0 { &b } else { &a };
            aus.push(annexb_au(&[p, &[0x65, 0x88, 0x84, 0x10 + i as u8]]));
        }
        let bytes = avc_ts_over(&aus);
        let (updates, _) = events_chunked(&bytes, bytes.len());
        assert_eq!(updates, 1, "only the first sight of id 1");
    }

    /// Issue #1171: parameter sets that are over the `avcC` u16 length limit,
    /// or whose body does not parse, are ignored — no `TrackUpdated` is
    /// raised, the track's config stays serializable, each rejection is an
    /// `InputDegraded::InvalidParameterSet`, and the event sequence is
    /// identical at every chunk size.
    #[test]
    fn invalid_parameter_sets_are_ignored_and_counted() {
        let (sps, pps, _) = real_avc_parameter_sets();
        // The 85 704-byte "SPS" of the report: real header, garbage body.
        let mut huge_sps = sps.clone();
        huge_sps.resize(85_704, 0xA5);
        // Right type, truncated: cannot parse to a geometry.
        let stub_sps = vec![0x67u8, 0x42, 0x00, 0x1E, 0xAB, 0x40];
        let idr = [0x65u8, 0x88, 0x84, 0x01];
        let aus = vec![
            annexb_au(&[&sps, &pps, &idr]),
            annexb_au(&[&huge_sps, &pps, &idr]),
            annexb_au(&[&stub_sps, &idr]),
            annexb_au(&[&sps, &pps, &idr]),
        ];
        let bytes = avc_ts_over(&aus);
        let (updates, base) = events_chunked(&bytes, bytes.len());
        assert_eq!(updates, 0, "invalid sets must not raise TrackUpdated");
        let added = base.iter().filter(|l| l.starts_with("TrackAdded")).count();
        assert_eq!(added, 1, "one track, from the valid set only");
        let rejected = base
            .iter()
            .filter(|l| l.contains("InvalidParameterSet"))
            .count();
        assert_eq!(rejected, 2, "the huge and the stub SPS: {base:?}");
        // Every config the demuxer emitted serializes.
        let media = TsDemux::new().demux(&bytes).expect("demux");
        for t in &media.tracks {
            let CodecConfig::Avc { config, .. } = t.config() else {
                continue;
            };
            assert!(config.try_to_bytes().is_ok());
        }
        for chunk in [1usize, 7, 187, 188, 189, 1000] {
            assert_eq!(events_chunked(&bytes, chunk).1, base, "chunk {chunk}");
        }
    }

    /// The same PPS remembering applies to HEVC; VPS/SPS still compare to the current set.
    #[test]
    fn hevc_rotating_parameter_sets_are_not_changes() {
        let hdr = |t: u8| [t << 1, 0x01];
        let nal = |t: u8, tag: u8| {
            let mut n = hdr(t).to_vec();
            n.push(tag);
            n
        };
        // The SPS must be a real, parseable one (invalid sets are ignored,
        // #1171): a verbatim 320x240 Main SPS from a committed capture.
        let real_sps: Vec<u8> = test_fixtures::vectors::HEVC_MAIN_SPS_320X240.to_vec();
        let mut real_sps_b = real_sps.clone();
        *real_sps_b.last_mut().unwrap() ^= 0x01;
        let (v, s) = (nal(H265_NAL_VPS, 1), real_sps);
        // PPS bodies whose first byte is `ue(pps_pic_parameter_set_id)` followed
        // by the stop bit (H.265 §7.3.2.3.1): id 1 = `010`, id 2 = `011`, id 3 =
        // `00100`, each then `1` and zero padding. Distinct ids = rotation.
        let ppss = [
            nal(H265_NAL_PPS, 0b0101_0000),
            nal(H265_NAL_PPS, 0b0111_0000),
        ];
        let mut sets = ParameterSets::default();
        let au = |p: &Vec<u8>| annexb_au(&[&v, &s, p]);
        assert!(sets.observe(Codec::Hevc, &au(&ppss[0])));
        assert!(
            sets.observe(Codec::Hevc, &au(&ppss[1])),
            "first sight of PPS 2"
        );
        for i in 0..8 {
            assert!(
                !sets.observe(Codec::Hevc, &au(&ppss[i % 2])),
                "rotation step {i} is a repeat"
            );
        }
        assert!(sets.observe(Codec::Hevc, &au(&nal(H265_NAL_PPS, 0b0010_0100))));
        // Issue #1186: id 1 re-announced with different bytes, then back to the
        // original — a change at BOTH switches (the second is an already-seen
        // set, which a "never seen before" test would have missed).
        let id1_other = nal(H265_NAL_PPS, 0b0101_1000);
        assert!(sets.observe(Codec::Hevc, &au(&id1_other)), "id 1 content B");
        assert!(sets.observe(Codec::Hevc, &au(&ppss[0])), "id 1 back to A");
        let sps2 = real_sps_b;
        assert!(sets.observe(Codec::Hevc, &annexb_au(&[&sps2])), "SPS B");
        assert!(
            sets.observe(Codec::Hevc, &annexb_au(&[&s])),
            "SPS back to A"
        );
    }

    /// The (SPS, PPS, width) of the fixture's first and second resolution.
    fn two_resolution_sets() -> [(Vec<u8>, Vec<u8>, u16); 2] {
        let path = test_fixtures::path("ts/h264-two-resolutions.ts");
        let bytes = std::fs::read(&path).unwrap();
        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let mut out = Vec::new();
        while let Some(e) = demux.poll_event() {
            let spec = match e {
                DemuxEvent::TrackAdded(s) | DemuxEvent::TrackUpdated(s) => s,
                _ => continue,
            };
            if let CodecConfig::Avc { config, width, .. } = spec.config {
                let r = &config.config;
                out.push((r.sps[0].0.clone(), r.pps[0].0.clone(), width));
            }
        }
        assert!(out.len() >= 2 && out[0].2 != out[1].2, "two resolutions");
        [out[0].clone(), out[1].clone()]
    }

    /// SPS A -> B -> A (a resolution change and back) is a real config change
    /// at EVERY switch, even though A was seen before; PPS rotation tolerance
    /// must not leak into the SPS.
    #[test]
    fn sps_switch_a_b_a_raises_an_update_per_switch() {
        let [a, b] = two_resolution_sets();
        let au =
            |x: &(Vec<u8>, Vec<u8>, u16), t: u8| annexb_au(&[&x.0, &x.1, &[0x65, 0x88, 0x84, t]]);
        let aus = vec![au(&a, 1), au(&b, 2), slice_only_au(3), au(&a, 4), au(&b, 5)];
        let bytes = avc_ts_over(&aus);
        let (n, base) = events_chunked(&bytes, bytes.len());
        assert_eq!(n, 3, "one update for each of the three switches");
        for chunk in [1usize, 7, 187, 188, 189, 1000] {
            assert_eq!(events_chunked(&bytes, chunk).1, base, "chunk {chunk}");
        }
    }

    /// A same-length, different-bytes SPS is exactly one update.
    #[test]
    fn same_length_sps_change_raises_exactly_one_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        let mut other = sps.clone();
        let last = other.len() - 1;
        other[last] ^= 0x01;
        let aus = vec![
            annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, 1]]),
            annexb_au(&[&other, &pps, &[0x65, 0x88, 0x84, 2]]),
            annexb_au(&[&other, &pps, &[0x65, 0x88, 0x84, 3]]),
        ];
        let bytes = avc_ts_over(&aus);
        let (n, base) = events_chunked(&bytes, bytes.len());
        assert_eq!(n, 1);
        for chunk in [1usize, 7, 187, 188, 189, 1000] {
            assert_eq!(events_chunked(&bytes, chunk).1, base, "chunk {chunk}");
        }
    }

    /// A PPS-only change is also a real config change and must raise one.
    #[test]
    fn a_changed_pps_raises_exactly_one_update() {
        let (sps, pps, _) = real_avc_parameter_sets();
        // Same SPS, different PPS: flip a byte in the PPS payload.
        let mut other_pps = pps.clone();
        let last = other_pps.len() - 1;
        other_pps[last] ^= 0x55;
        assert_ne!(other_pps, pps, "the two PPS really differ");

        let aus = vec![
            annexb_au(&[&sps, &pps, &[0x65, 0x88, 0x84, 0x01]]),
            annexb_au(&[&sps, &other_pps, &[0x65, 0x88, 0x84, 0x02]]),
            slice_only_au(0x03),
        ];
        let bytes = avc_ts_over(&aus);
        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();
        let updates = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::TrackUpdated(_)))
            .count();
        assert_eq!(
            updates, 1,
            "a changed PPS is a config change, so exactly one TrackUpdated"
        );
    }

    /// r04-W51: a broadcast stream changes its parameter sets mid-flight
    /// routinely (an SD↔HD ad break, a re-encode, a multiplex reconfiguration).
    /// Codec config recovery used to be single-shot for the life of the stream,
    /// so the track kept the *first* `avcC` and the init segment described a
    /// stream that had stopped being sent; a decoder then fails from the change
    /// onwards. The fixture is a real two-resolution capture (see
    /// `../fixtures/ts/PROVENANCE.md`), demuxed through the streaming core so the
    /// `TrackUpdated` event is observable.
    ///
    /// The second half is the anti-spam half: the same fixture shows the
    /// encoder repeating its parameter sets on every keyframe, and an
    /// *unchanged* repeat must emit nothing.
    #[test]
    fn mid_stream_config_change_emits_track_updated_once_and_only_when_it_changes() {
        let path = test_fixtures::path("ts/h264-two-resolutions.ts");
        let bytes =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&bytes);
        demux.finish();

        let mut added: Option<(u32, u16, u16)> = None;
        let mut updates: Vec<(u32, u16, u16)> = Vec::new();
        while let Some(event) = demux.poll_event() {
            match event {
                DemuxEvent::TrackAdded(spec) => {
                    if let CodecConfig::Avc { width, height, .. } = spec.config {
                        added = Some((spec.track_id.value(), width, height));
                    }
                }
                DemuxEvent::TrackUpdated(spec) => {
                    if let CodecConfig::Avc { width, height, .. } = spec.config {
                        updates.push((spec.track_id.value(), width, height));
                    }
                }
                _ => {}
            }
        }

        let (track_id, w0, h0) = added.expect("the fixture has one AVC track");
        assert_eq!(
            (w0, h0),
            (320, 240),
            "the first half of the fixture is 320x240 (ffprobe oracle)"
        );
        assert_eq!(
            updates.len(),
            1,
            "the config changes exactly once in this fixture (320x240 -> 640x480); the encoder's repeated, unchanged SPS must not raise more. Got {updates:?}"
        );
        assert_eq!(
            updates[0],
            (track_id, 640, 480),
            "TrackUpdated must carry the *new* config, on the same track id"
        );
    }

    /// The AAC half of r04-W51: `channel_configuration` is a Table 1.19
    /// *index*, not a channel count. Configuration 7 is eight channels (7.1)
    /// and 0 means the mapping is in-band (a `program_config_element` in the
    /// raw data stream), which this crate does not decode — so no count is
    /// fabricated for it.
    ///
    /// Real ADTS headers, built by this crate's own spec-correct encoder
    /// (`aac_asc::build_adts_header`), fed through the demux as a real AAC
    /// PID.
    #[test]
    fn adts_channel_configuration_is_mapped_through_table_1_19() {
        /// `sampling_frequency_index` 3 = 48000 Hz (ISO/IEC 14496-3 Table 1.16).
        const SFI_48000: u8 = 3;
        /// AAC-LC: `profile = audio_object_type - 1`.
        const ADTS_PROFILE_AAC_LC: u8 = 1;
        /// Table 1.19 configuration 7 (7.1, eight channels).
        const CONFIG_7_1: u8 = 7;
        /// Configuration 0: the mapping is carried in-band by a PCE.
        const CONFIG_IN_BAND: u8 = 0;

        for (config, expected) in [(CONFIG_7_1, 8u16), (CONFIG_IN_BAND, 0u16)] {
            let frame_len = (ADTS_HEADER_SIZE + 64) as u16;
            let mut au = crate::aac_asc::build_adts_header(
                ADTS_PROFILE_AAC_LC,
                SFI_48000,
                config,
                frame_len,
            )
            .to_vec();
            au.resize(frame_len as usize, 0x21);

            let mut input = Vec::new();
            for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
                input.extend_from_slice(&null_packet());
            }
            input.extend_from_slice(&psi_section_packets(
                PAT_PID_UNDER_TEST,
                0,
                TABLE_ID_PAT,
                &pat_body(),
            ));
            input.extend_from_slice(&psi_section_packets(
                PMT_PID_UNDER_TEST,
                0,
                TABLE_ID_PMT,
                &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_AAC_ADTS),
            ));
            let mut cc = 0u8;
            for i in 0..4 {
                let pes = pes_packet(ES_STREAM_ID_AUDIO, i * 1024, None, &au);
                let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
                cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
                input.extend_from_slice(&packets);
            }

            let mut demux = StreamingTsDemux::new();
            demux.feed(&input);
            demux.finish();
            let channel_count = std::iter::from_fn(|| demux.poll_event())
                .find_map(|e| match e {
                    DemuxEvent::TrackAdded(spec) => match spec.config {
                        CodecConfig::Aac { channel_count, .. } => Some(channel_count),
                        _ => None,
                    },
                    _ => None,
                })
                .expect("the AAC PID must resolve a track");
            assert_eq!(
                channel_count, expected,
                "ADTS channel_configuration {config} must map through Table 1.19"
            );
        }
    }

    // ── r04-W50: signalled discontinuity rebases the decode timeline ────────

    /// A TS adaptation-field `discontinuity_indicator` marks "a sample of a new
    /// system time clock" (ISO/IEC 13818-1 §2.4.3.5) — a splice, an encoder
    /// switch, or a remultiplex. The new time base routinely starts *below* the
    /// old one, and nothing in the 33-bit unroll can tell that from a genuine
    /// backward jump within the range: `dts` then goes non-monotonic, violating
    /// the IR's "samples in decode order with a non-decreasing absolute dts"
    /// invariant and making every downstream muxer write negative deltas.
    ///
    /// Real elementary-stream bytes from the committed `h264-aac.ts` fixture,
    /// re-stamped onto two time bases 2 s apart, with the discontinuity
    /// signalled exactly as a muxer does it: the bit set on an
    /// adaptation-field-only packet, then the new base's PES packets.
    #[test]
    fn signalled_discontinuity_keeps_dts_monotonic() {
        /// First time base's anchor, 90 kHz ticks.
        const BASE_A_DTS: i64 = 90_000;
        /// Second time base's anchor, *below* the first on the wire clock —
        /// the ordinary splice shape (new content whose first stamp is
        /// earlier). Both bases sit in the same 33-bit period, so the unroll
        /// reads the step as a small backward jump rather than a wrap.
        const BASE_B_DTS: i64 = 9_000;
        const FRAME_PERIOD: i64 = 3600;
        /// Frames per time base.
        const FRAMES: usize = 12;
        /// Unwrapped clock modulus — the wire stamps below stay inside one
        /// period, so the values are unambiguous.
        const WRAP: i64 = 1i64 << 33;

        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new().demux(&source).expect("demux h264-aac.ts");
        let video = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .expect("h264-aac.ts has an AVC track");
        assert!(
            video.samples.len() >= FRAMES * 2,
            "fixture too small for two time bases"
        );

        // Annex-B access units, and a first access unit that still carries the
        // parameter sets (the fixture's real ES has no SPS outside those).
        let annexb: Vec<Vec<u8>> = video
            .samples
            .iter()
            .map(|sample| {
                let mut au = Vec::new();
                for nal in crate::annexb::iter_length_prefixed_nals(&sample.data)
                    .expect("TsMux writes valid NAL prefixes")
                {
                    au.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
                    au.extend_from_slice(nal);
                }
                au
            })
            .collect();

        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            // The ES PID is the program's PCR_PID, so the indicator is
            // carried where §2.4.3.5 requires and scopes to this program.
            &pmt_body_with_pcr_pid(ES_PID_UNDER_TEST, STREAM_TYPE_AVC, ES_PID_UNDER_TEST),
        ));

        let push_au = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], dts: i64| {
            let wire = (dts.rem_euclid(WRAP)) as u64;
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire as i64, Some(wire as i64), au);
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        // Time base A.
        for i in 0..FRAMES {
            let au = annexb[i % annexb.len()].clone();
            push_au(
                &mut input,
                &mut cc,
                &au,
                BASE_A_DTS + i as i64 * FRAME_PERIOD,
            );
        }

        // The signalled discontinuity: an adaptation-field-only packet with
        // `discontinuity_indicator` set (§2.4.3.4 Table 2-6, bit 7 of the
        // flags byte) and no payload.
        {
            let af = [
                0x80u8, // discontinuity_indicator=1, nothing else
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // stuffing
            ];
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = (ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK;
            pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
            pkt[3] = 0x20 | (cc & 0x0F); // AFC=10: adaptation only, no payload
            pkt[4] = af.len() as u8;
            pkt[5..5 + af.len()].copy_from_slice(&af);
            input.extend_from_slice(&pkt);
            cc = cc.wrapping_add(1);
        }

        // Time base B, starting 2 s lower on the wire clock.
        for i in 0..FRAMES {
            let au = annexb[i % annexb.len()].clone();
            push_au(
                &mut input,
                &mut cc,
                &au,
                BASE_B_DTS + i as i64 * FRAME_PERIOD,
            );
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let mut saw_signalled = false;
        let samples: Vec<Sample> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Discontinuity {
                    kind: DiscontinuityKind::Signalled,
                    ..
                } => {
                    saw_signalled = true;
                    None
                }
                DemuxEvent::Sample { sample, .. } => Some(sample),
                _ => None,
            })
            .collect();
        assert!(
            saw_signalled,
            "the adaptation-field discontinuity_indicator must surface as a Signalled Discontinuity"
        );
        let dts: Vec<i64> = samples
            .iter()
            .map(|s| s.dts.expect("stamped dts"))
            .collect();
        assert!(
            dts.len() >= FRAMES,
            "expected one sample per access unit, got {}",
            dts.len()
        );
        assert!(
            dts.windows(2).all(|w| w[1] >= w[0]),
            "dts must stay monotonic across a signalled discontinuity; got {dts:?}"
        );
        // The rebase is *only* a lift: the second base's own intervals are
        // untouched, so the steps stay one frame period apart throughout.
        let steps: Vec<i64> = dts.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d == FRAME_PERIOD),
            "every decode step must remain one frame period; got {steps:?}"
        );
    }

    /// Three signalled discontinuities in a row: each new time base starts
    /// *below* the previous one, so every lift compounds. The second attempt at
    /// this fix compared an offset-free "previous" value against an
    /// offset-bearing "next" one, so from the second discontinuity on the lift
    /// was too small and `dts` stepped backwards again.
    #[test]
    fn three_signalled_discontinuities_keep_dts_monotonic() {
        /// Frame period, 90 kHz ticks.
        const FRAME_PERIOD: i64 = 3600;
        /// Frames per time base.
        const FRAMES: i64 = 6;
        /// The bases, each starting *below* the one before.
        const BASES: [i64; 3] = [90_000, 30_000, 5_000];

        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new().demux(&source).expect("demux h264-aac.ts");
        let video = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .expect("h264-aac.ts has an AVC track");
        let annexb: Vec<Vec<u8>> = video
            .samples
            .iter()
            .map(|sample| {
                let mut au = Vec::new();
                for nal in crate::annexb::iter_length_prefixed_nals(&sample.data)
                    .expect("TsMux writes valid NAL prefixes")
                {
                    au.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
                    au.extend_from_slice(nal);
                }
                au
            })
            .collect();

        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            // The ES PID is the program's PCR_PID, so a
            // `discontinuity_indicator` on it rebases this program's streams
            // (§2.4.3.5).
            &pmt_body_with_pcr_pid(ES_PID_UNDER_TEST, STREAM_TYPE_AVC, ES_PID_UNDER_TEST),
        ));

        let push_au = |input: &mut Vec<u8>, cc: &mut u8, au: &[u8], dts: i64| {
            let wire = dts.rem_euclid(1i64 << 33) as u64;
            let pes = pes_packet(ES_STREAM_ID_VIDEO, wire as i64, Some(wire as i64), au);
            let packets = pes_packets(ES_PID_UNDER_TEST, *cc, &pes);
            *cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        };

        for base in BASES {
            for i in 0..FRAMES {
                let au = annexb[(i as usize) % annexb.len()].clone();
                push_au(&mut input, &mut cc, &au, base + i * FRAME_PERIOD);
            }
            // The signalled discontinuity packet (§2.4.3.4 Table 2-6: an
            // adaptation field, no payload, flags bit 7 set).
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = (ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK;
            pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
            pkt[3] = 0x20 | (cc & 0x0F); // AFC=10, adaptation only
            pkt[4] = 8;
            pkt[5] = 0x80; // discontinuity_indicator
            input.extend_from_slice(&pkt);
            cc = cc.wrapping_add(1);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let dts: Vec<i64> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => sample.dts,
                _ => None,
            })
            .collect();
        assert!(
            dts.len() >= (BASES.len() as i64 * FRAMES) as usize - 3,
            "expected the access units of all three time bases, got {} (first few: {:?})",
            dts.len(),
            &dts[..dts.len().min(6)]
        );
        let steps: Vec<i64> = dts.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d > 0),
            "dts must be strictly increasing across every discontinuity; dts={dts:?} steps={steps:?}"
        );
    }

    /// A CC gap on a **continuation** packet misses 184 bytes of the access
    /// unit being assembled, so that unit must be dropped and its neighbours
    /// delivered unharmed. (The first W49 attempt set `current_pes_intact`
    /// back to `true` unconditionally after every packet, so a gap followed by
    /// any further continuation packet of the same unit was forgotten and the
    /// truncated unit was delivered anyway.)
    ///
    /// Units here are four TS packets long and the gap is placed in the
    /// *middle*, so there really are continuation packets after it — which is
    /// exactly what the old rule let clear the damage mark.
    #[test]
    fn cc_gap_on_a_continuation_drops_only_that_access_unit() {
        /// Each access unit spans four TS packets (a 9-byte PES header plus
        /// the body).
        const PACKETS_PER_AU: usize = 4;
        /// TS payload per packet.
        const PER_PACKET: usize = TS_PACKET_SIZE - 4;
        /// Bytes of PES header [`untimed_pes`] writes before the body.
        const PES_HEADER_BYTES: usize = 9;
        // Exactly `PACKETS_PER_AU` TS packets per PES: the header plus a body
        // sized to fill the rest precisely, so no stuffing is involved.
        let body_len = PACKETS_PER_AU * PER_PACKET - PES_HEADER_BYTES;
        let aus: Vec<Vec<u8>> = (0..3)
            .map(|i| (0..body_len).map(|b| ((b + i * 53) & 0xFF) as u8).collect())
            .collect();

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        let mut cc = 0u8;
        let mut expected = Vec::new();
        for (i, au) in aus.iter().enumerate() {
            let pes = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, au);
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            let n = packets.len() / TS_PACKET_SIZE;
            assert_eq!(
                n, PACKETS_PER_AU,
                "AU {i} must span {PACKETS_PER_AU} packets"
            );
            if i == 1 {
                // Drop only packet 1 of this unit: packet 0 starts it and
                // packets 2.. follow the gap, so the old "clear the mark after
                // every packet" rule would forget the damage.
                input.extend_from_slice(&packets[..TS_PACKET_SIZE]);
                input.extend_from_slice(&packets[2 * TS_PACKET_SIZE..]);
            } else {
                input.extend_from_slice(&packets);
                expected.push(au.clone());
            }
            cc = cc.wrapping_add(n as u8);
        }

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<Vec<u8>> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(
            got, expected,
            "only the unit whose middle packet was lost may be dropped"
        );
    }

    /// A CC jump exactly at a `payload_unit_start` does NOT damage the unit
    /// that just completed, when that unit's own declared length was fully
    /// received. This is the segment-concatenation case: every segment is
    /// muxed independently, so the counter jumps at the seam while the last
    /// unit of the previous segment is complete. Treating every such jump as
    /// truncation dropped one access unit per boundary.
    #[test]
    fn cc_jump_at_a_pes_start_keeps_the_previous_complete_access_unit() {
        // A *bounded* PES (PES_packet_length != 0), which is what a private
        // data stream uses — the length is what proves completeness.
        let au1 = data_au(0x00);
        let au2 = data_au(0x80);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        let pes1 = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, &au1);
        let pes2 = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, &au2);
        let pkt1 = pes_packets(ES_PID_UNDER_TEST, 0, &pes1);
        assert_eq!(pkt1.len(), 2 * TS_PACKET_SIZE, "unit 1 spans two packets");
        // Unit 1 used counters 0 and 1; unit 2 restarts at 0 (a freshly muxed
        // segment always does), so the counter *jumps backwards* at exactly
        // the second unit's `payload_unit_start`.
        let pkt2 = pes_packets(ES_PID_UNDER_TEST, 0, &pes2);
        input.extend_from_slice(&pkt1);
        input.extend_from_slice(&pkt2);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<Vec<u8>> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(
            got,
            vec![au1.clone(), au2.clone()],
            "a counter jump at a `payload_unit_start` must not drop the previous unit when its declared length was fully received"
        );
    }

    /// An **unbounded** unit (`PES_packet_length == 0`, what every video PES
    /// uses) whose own packets are all present survives a counter restart at
    /// the next `payload_unit_start`. This is the segment-concatenation and
    /// doubled-file seam: each piece is muxed independently, so its counter
    /// begins wherever its own muxer started, and nothing inside the
    /// completing unit was lost — a `payload_unit_start` *ends* that unit.
    #[test]
    fn cc_restart_at_a_pes_start_keeps_an_unbounded_unit() {
        let au1 = data_au(0x10);
        let au2 = data_au(0x90);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        let pes1 = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au1);
        let pes2 = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au2);
        let pkt1 = pes_packets(ES_PID_UNDER_TEST, 0, &pes1);
        assert_eq!(pkt1.len(), 2 * TS_PACKET_SIZE, "unit 1 spans two packets");
        // Unit 2's counter restarts at 0, as an independently muxed segment's
        // does.
        let pkt2 = pes_packets(ES_PID_UNDER_TEST, 0, &pes2);
        input.extend_from_slice(&pkt1);
        input.extend_from_slice(&pkt2);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<Vec<u8>> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(
            got.len(),
            2,
            "both units are whole on the wire, so a counter restart between them must drop neither: {got:?}"
        );
        assert!(got[0].starts_with(&au1), "first unit preserved");
        assert!(got[1].starts_with(&au2), "second unit preserved");
    }

    /// The seam case for a **bounded** unit, checked through the real segmenter:
    /// concatenating independently muxed segments must keep every access unit
    /// of both. A counter restart at a `payload_unit_start` is not truncation.
    #[test]
    fn concatenated_segments_seam_keeps_every_access_unit() {
        use crate::TsMux;
        use crate::media::{Media, Track};
        use crate::pipeline::{CodecConfig, Sample, TrackSpec};
        use crate::rtp_sdp::avc_config_from_sprop;
        use broadcast_common::Package;

        let frame_dur = VIDEO_TIMESCALE / 25;
        let avc = avc_config_from_sprop("Z0IAKeKQFAe2AtwEBAaQeJEV,aM48gA==").unwrap();
        let spec = TrackSpec::new(
            TrackId::new(1),
            VIDEO_TIMESCALE,
            CodecConfig::Avc {
                config: avc,
                width: 0,
                height: 0,
            },
        );
        let samples: Vec<Sample> = (0..6u32)
            .map(|i| {
                let nal = [0x65u8, 0xAA, i as u8];
                let mut data = (nal.len() as u32).to_be_bytes().to_vec();
                data.extend_from_slice(&nal);
                let dts = i64::from(i) * i64::from(frame_dur);
                Sample::new(data, Some(dts), Some(dts), Some(frame_dur), true)
            })
            .collect();
        let media = Media::new(vec![Track::new(spec, samples)], VIDEO_TIMESCALE);

        // Two separately muxed copies of the same track, concatenated as a
        // segmenter would emit (and as `transmux/tests/it/ts_hls.rs` does): each
        // begins with its own PAT/PMT and its own counter sequence.
        let segment = TsMux::default().package(&media).expect("mux to TS");
        let mut concatenated = segment.clone();
        concatenated.extend_from_slice(&segment);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&concatenated);
        demux.finish();
        let video_samples = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::Sample { .. }))
            .count();
        assert_eq!(
            video_samples, 12,
            "a segment seam restarts the counter but loses nothing, so all 12 access units must survive"
        );
    }

    /// A gap *inside* an unbounded unit — on one of its own continuation
    /// packets — still drops it: that packet's bytes provably belong to the
    /// unit, and there is no declared length to show otherwise.
    #[test]
    fn cc_gap_inside_an_unbounded_unit_drops_it() {
        /// Bytes per TS payload.
        const PER_PACKET: usize = TS_PACKET_SIZE - 4;
        /// Four-packet unit, so a middle packet can be dropped.
        const PACKETS: usize = 4;
        /// Bytes of PES header [`unbounded_pes`] writes.
        const PES_HEADER_BYTES: usize = 9;

        let au: Vec<u8> = (0..PACKETS * PER_PACKET - PES_HEADER_BYTES)
            .map(|i| (i & 0xFF) as u8)
            .collect();
        let pes = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au);
        let packets = pes_packets(ES_PID_UNDER_TEST, 0, &pes);
        assert_eq!(packets.len(), PACKETS * TS_PACKET_SIZE);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));
        // Packet 0 starts the unit; packet 1 is lost; packets 2.. arrive.
        input.extend_from_slice(&packets[..TS_PACKET_SIZE]);
        input.extend_from_slice(&packets[2 * TS_PACKET_SIZE..]);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let samples = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::Sample { .. }))
            .count();
        assert_eq!(
            samples, 0,
            "a unit missing one of its own packets must not be delivered"
        );
    }

    /// A signalled discontinuity is **not** on its own a reason to drop a unit
    /// (r04-W49 review, round 3). The rule is stated in
    /// [`StreamingTsDemux::process_packet`]: a unit is damaged only by a
    /// continuity-counter gap on one of *its own* packets, or by a bounded PES
    /// arriving short of its declared length. The indicator only says the
    /// source's byte stream changes *here* — a normal HLS or splice seam has an
    /// intact last unit of the old segment immediately before it, and dropping
    /// that unit lost one access unit at every seam.
    ///
    /// The fixture is deliberately **unbounded** (`PES_packet_length == 0`, the
    /// ordinary video shape): a bounded PES carries its own completeness proof,
    /// so it cannot distinguish "the indicator dropped it" from "the length did
    /// not add up". Two whole units are followed by a third, with the indicator
    /// on the packet that ends unit 2 and starts unit 3.
    #[test]
    fn signalled_discontinuity_does_not_drop_the_unit_it_ends() {
        /// Continuity counter of the packet that carries the indicator: unit 2
        /// used counters 1 and 2, so the indicator continues at 3.
        const SIGNALLED_CC: u8 = 3;
        let au1 = data_au(0x20);
        let au2 = data_au(0xA0);
        let au3 = data_au(0xF0);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        // Unbounded units, two TS packets each, all present.
        let mut cc = 0u8;
        for au in [&au1, &au2] {
            let pes = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, au);
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            assert_eq!(
                packets.len(),
                2 * TS_PACKET_SIZE,
                "each unit spans two packets"
            );
            input.extend_from_slice(&packets);
            cc = cc.wrapping_add(2);
        }
        // The packet that starts unit 3 carries the indicator
        // (§2.4.3.5): `afc` '11', an 8-byte adaptation field, flags bit 7.
        let pes3 = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au3);
        input.extend_from_slice(&pes_packets_with_discontinuity(
            ES_PID_UNDER_TEST,
            SIGNALLED_CC,
            &pes3,
        ));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<Vec<u8>> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(
            got.len(),
            3,
            "every unit here is whole on the wire, so the indicator on the              packet starting unit 3 must not drop anything: {got:?}"
        );
        for (i, (got_au, want)) in got.iter().zip([&au1, &au2, &au3]).enumerate() {
            assert!(got_au.starts_with(want), "unit {i} must be delivered whole");
        }
    }

    /// The documented tradeoff at a seam, on an **unbounded** PES. A
    /// `payload_unit_start` ends the previous unit, so a counter restart there
    /// is the ordinary segment-concatenation shape and is *not* damage — which
    /// also means an unbounded unit that really did lose its tail is
    /// indistinguishable from one that ended cleanly, and is delivered
    /// (H.222.0 carries no length to tell them apart; §2.4.3.3/§2.4.3.7).
    ///
    /// This test pins that tradeoff explicitly, so the behaviour is a recorded
    /// decision rather than an accident, and so a future change that starts
    /// dropping here has to change this test deliberately. A **bounded** PES
    /// has no such tradeoff — its declared length settles it, which
    /// [`cc_jump_at_a_pes_start_keeps_the_previous_complete_access_unit`] and
    /// [`cc_gap_on_a_continuation_drops_only_that_access_unit`] cover.
    #[test]
    fn unbounded_unit_ended_by_a_counter_restart_is_delivered_by_design() {
        let au1 = data_au(0x20);
        let au2 = data_au(0xA0);

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        // Unit 1's packet 1 is lost; unit 2 starts on a counter that therefore
        // jumps. Unbounded units, so nothing proves unit 1 was short.
        let pes1 = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au1);
        let pkt1 = pes_packets(ES_PID_UNDER_TEST, 0, &pes1);
        input.extend_from_slice(&pkt1[..TS_PACKET_SIZE]);
        let pes2 = unbounded_pes(ES_STREAM_ID_PRIVATE_DATA, &au2);
        input.extend_from_slice(&pes_packets(ES_PID_UNDER_TEST, 2, &pes2));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let got: Vec<Vec<u8>> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(
            got.len(),
            2,
            "both the truncated-tail unit and the whole one are delivered: an              unbounded PES gives no way to tell them apart at a seam"
        );
    }

    // ── r04-W48: a PES with no PTS/DTS is interpolated, not re-stamped ─────

    /// `PTS_DTS_flags == '00'` is legal (ISO/IEC 13818-1 §2.4.3.7) and the
    /// 2.7.4 interval constraint only requires the stamps periodically, so a
    /// video PID's access units routinely alternate stamped / unstamped. The
    /// demux used to hand an unstamped access unit the *previous* one's
    /// stamps verbatim, so every consecutive pair carried an identical `dts`:
    /// the one-behind duration rule then gave the earlier of the pair
    /// `duration = 0` and made the next stamped access unit absorb the whole
    /// gap, producing zero-duration samples plus one long one.
    ///
    /// Real elementary-stream bytes: the H.264 access units are the real
    /// `Media` samples recovered from `fixtures/ts/h264-aac.ts` and re-emitted
    /// through the crate's own `TsMux` PES packetiser, with the timing flags
    /// of every second PES cleared. The frame period is a real one (the
    /// fixture's own 25 fps cadence, 3600 ticks of 90 kHz).
    #[test]
    fn unstamped_pes_access_unit_is_interpolated_not_restamped() {
        // Real H.264 access units from a committed capture.
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let source =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let media = TsDemux::new().demux(&source).expect("demux h264-aac.ts");

        /// Frame period of the fixture's video track, in 90 kHz ticks — the
        /// real cadence `TsMux` stamps its PES headers from.
        const FRAME_PERIOD: i64 = 3600;
        const UNSTAMPED_EVERY: usize = 2;

        let mut cc = 0u8;
        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_AVC),
        ));

        let video = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Avc { .. }))
            .expect("h264-aac.ts has an AVC track");
        let source_dts0 = video.samples[0]
            .dts
            .expect("the fixture's AVC track is stamped");
        let mut headers = 0usize;
        for (i, sample) in video.samples.iter().enumerate() {
            // The demux wants Annex B in each access unit; `TsMux` writes
            // length-prefixed samples, so rebuild the Annex B form from the
            // sample's own NALs.
            let mut au = Vec::new();
            let nals = crate::annexb::iter_length_prefixed_nals(&sample.data)
                .expect("TsMux writes valid 4-byte-length NAL prefixes");
            for nal in nals {
                au.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
                au.extend_from_slice(nal);
            }
            // A constant, decode-ordered 90 kHz clock: the fixture's real
            // cadence (3600 ticks per access unit), anchored at its own first
            // dts. Both stamps are present on a stamped PES and neither is on
            // an unstamped one — the exact `PTS_DTS_flags` '11' / '00'
            // alternation §2.4.3.7 permits.
            // The first two access units must be stamped: the period is only
            // measurable from a stamped pair, and an unstamped access unit
            // arriving before then has nothing to interpolate from (the
            // documented fallback, exercised separately below).
            let stamped = i < UNSTAMPED_EVERY || i % UNSTAMPED_EVERY == 0;
            let dts = source_dts0 + i as i64 * FRAME_PERIOD;
            let pes = if stamped {
                pes_packet(ES_STREAM_ID_VIDEO, dts, Some(dts), &au)
            } else {
                pes_packet_untimed(ES_STREAM_ID_VIDEO, &au)
            };
            headers += 1;
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            input.extend_from_slice(&packets);
        }
        assert!(
            video.samples.len() >= 20,
            "fixture too small for a meaningful interpolation test"
        );

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let samples: Vec<Sample> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample),
                _ => None,
            })
            .collect();
        assert_eq!(
            samples.len(),
            headers,
            "one sample per fed access unit (video is one AU per PES here)"
        );

        // The dts series must advance by exactly one frame period per access
        // unit. The pre-fix behaviour gave every unstamped access unit the
        // previous one's dts, so the series alternated 0 / 3600 steps.
        let dts: Vec<i64> = samples.iter().map(|s| s.dts.expect("video dts")).collect();
        let steps: Vec<i64> = dts.windows(2).map(|w| w[1] - w[0]).collect();
        assert!(
            steps.iter().all(|&d| d == FRAME_PERIOD),
            "every decode step must be one frame period ({FRAME_PERIOD} ticks); got {steps:?}"
        );
        assert!(
            samples
                .iter()
                .all(|s| s.duration == Some(FRAME_PERIOD as u32)),
            "no zero-duration sample may survive interpolation; durations: {:?}",
            samples.iter().map(|s| s.duration).collect::<Vec<_>>()
        );
    }

    // ── Audio re-anchor threshold (issue B5) ───────────────────────────────

    /// One 44.1 kHz stereo AAC-LC access unit: a real ADTS header (built by
    /// this crate's own `aac_asc::build_adts_header`, ISO/IEC 13818-7 §6.2,
    /// `sampling_frequency_index = 4` = 44100 Hz) plus filler payload. Content
    /// is irrelevant here — this test is about the timestamp anchor, and
    /// `emit_audio_au` only needs `split_adts_frames` to find the frame.
    fn aac_44100_access_unit() -> Vec<u8> {
        /// AAC-LC: `profile = audio_object_type - 1 = 1`.
        const ADTS_PROFILE_AAC_LC: u8 = 1;
        /// `sampling_frequency_index` for 44100 Hz (ISO/IEC 14496-3 Table 1.16).
        const SFI_44100: u8 = 4;
        /// `channel_configuration` = 2 (stereo).
        const CHANNELS_STEREO: u8 = 2;
        const PAYLOAD_BYTES: usize = 128;

        let frame_len = (ADTS_HEADER_SIZE + PAYLOAD_BYTES) as u16;
        let header = crate::aac_asc::build_adts_header(
            ADTS_PROFILE_AAC_LC,
            SFI_44100,
            CHANNELS_STEREO,
            frame_len,
        );
        let mut au = header.to_vec();
        au.resize(ADTS_HEADER_SIZE + PAYLOAD_BYTES, 0x21);
        au
    }

    /// PROVENANCE: synthesised, deliberately. The case under test is a
    /// **constant integer PES increment** at 44.1 kHz, and no committed
    /// capture here carries one — `fixtures/ts/h264-aac.ts` is 48 kHz, where
    /// 1024 samples is exactly 1920 ticks of 90 kHz and this class of drift
    /// cannot occur at all. The ADTS frames come from the crate's own
    /// spec-correct header builder, not hand-written bytes.
    ///
    /// The bug (issue B5 follow-up): the threshold was one intrinsic sample
    /// period — 3 ticks at 44.1 kHz — while `1024/44100 s` is `2089.795…`
    /// ticks, so a muxer stamping the rounded constant `2090` drifts `+0.204…`
    /// ticks per frame *on a perfectly continuous stream* and crossed the
    /// threshold roughly every 15 frames. `TimelineReanchored` was pure noise
    /// and the anchor was effectively inert.
    #[test]
    fn constant_increment_44100_aac_emits_no_timeline_reanchor() {
        /// What a muxer that rounds `1024 * 90000 / 44100` to an integer emits.
        const PES_INCREMENT_TICKS: i128 = 2090;
        const SAMPLE_RATE: u32 = 44_100;
        /// ~11.6 s of audio. Accumulated drift here is ~102 ticks: far past
        /// the old 3-tick threshold (which would have fired ~34 times), far
        /// short of the 1800-tick (20 ms) bound the fix derives.
        const FRAMES: i128 = 500;

        let au = aac_44100_access_unit();
        let mut anchor = AudioAnchor::default();
        let mut events: VecDeque<DemuxEvent> = VecDeque::new();
        for n in 0..FRAMES {
            let ts = n * PES_INCREMENT_TICKS;
            emit_audio_au(
                &AudioKind::Aac,
                SAMPLE_RATE,
                &mut anchor,
                &au,
                ts,
                ts,
                TrackId::new(1),
                &mut events,
            );
        }

        assert!(
            events
                .iter()
                .any(|e| matches!(e, DemuxEvent::Sample { .. })),
            "sanity: the synthesised ADTS frames must actually split into samples"
        );
        let reanchors = events
            .iter()
            .filter(|e| {
                matches!(
                    e,
                    DemuxEvent::Discontinuity {
                        kind: DiscontinuityKind::TimelineReanchored,
                        ..
                    }
                )
            })
            .count();
        assert_eq!(
            reanchors, 0,
            "a constant-increment 44.1 kHz stream is continuous — the \
             rounding drift a real muxer accrues by construction must never be \
             reported as a discontinuity"
        );
    }

    /// The other half of the threshold contract: a **genuine** timeline gap
    /// (an encoder restart / splice) must still be reported, exactly once.
    #[test]
    fn a_real_timeline_gap_emits_exactly_one_reanchor() {
        const PES_INCREMENT_TICKS: i128 = 2090;
        const SAMPLE_RATE: u32 = 44_100;
        const FRAMES_BEFORE: i128 = 50;
        const FRAMES_AFTER: i128 = 50;
        /// Two seconds of 90 kHz — orders of magnitude past any muxer drift.
        const GAP_TICKS: i128 = 180_000;

        let au = aac_44100_access_unit();
        let mut anchor = AudioAnchor::default();
        let mut events: VecDeque<DemuxEvent> = VecDeque::new();
        let emit = |ts: i128, anchor: &mut AudioAnchor, events: &mut VecDeque<DemuxEvent>| {
            emit_audio_au(
                &AudioKind::Aac,
                SAMPLE_RATE,
                anchor,
                &au,
                ts,
                ts,
                TrackId::new(1),
                events,
            );
        };
        for n in 0..FRAMES_BEFORE {
            emit(n * PES_INCREMENT_TICKS, &mut anchor, &mut events);
        }
        let resume = FRAMES_BEFORE * PES_INCREMENT_TICKS + GAP_TICKS;
        for n in 0..FRAMES_AFTER {
            emit(resume + n * PES_INCREMENT_TICKS, &mut anchor, &mut events);
        }

        let reanchors = events
            .iter()
            .filter(|e| {
                matches!(
                    e,
                    DemuxEvent::Discontinuity {
                        kind: DiscontinuityKind::TimelineReanchored,
                        ..
                    }
                )
            })
            .count();
        assert_eq!(
            reanchors, 1,
            "one genuine gap must produce exactly one TimelineReanchored — not \
             zero (the anchor silently absorbing a real splice) and not one \
             per following access unit"
        );
    }

    /// `split_adts_frames` must resync across PES payloads that don't start
    /// on a frame sync (issue #638 — the same defect reported for MP2, see
    /// `mpeg_legacy.rs`'s `mpeg_audio_resyncs_across_pes_boundaries`, applies
    /// identically to ADTS). Builds a real ADTS elementary stream from the
    /// real captured AAC frames in `fixtures/ts/h264-aac.ts` (re-synthesizing
    /// each frame's ADTS header from the track's real recovered config, the
    /// same way [`build_es_payload`] does for muxing), then re-chunks it at a
    /// fixed size that does not align to any real AAC frame length.
    #[test]
    fn adts_resyncs_across_pes_boundaries() {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let ts_bytes =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));

        let mut demux = TsDemux::new();
        let media = demux.demux(&ts_bytes).expect("demux h264-aac.ts");
        let audio = media
            .tracks
            .iter()
            .find(|t| matches!(t.config(), CodecConfig::Aac { .. }))
            .expect("h264-aac.ts has an AAC track");
        let esds = match audio.config() {
            CodecConfig::Aac { esds, .. } => esds,
            _ => unreachable!(),
        };
        let dsi = esds
            .es_descriptor
            .decoder_config
            .as_ref()
            .and_then(|dc| dc.decoder_specific_info.as_ref())
            .expect("AAC esds carries a DecoderSpecificInfo");
        let asc = AudioSpecificConfig::parse(&dsi.data).expect("parse real AudioSpecificConfig");

        // Real ADTS ES: real captured AAC frame bytes, each with a freshly
        // synthesized (but spec-correct, config-derived) ADTS header.
        let mut es: Vec<u8> = Vec::new();
        for s in &audio.samples {
            let frame_len = (ADTS_HEADER_SIZE + s.data.len()) as u16;
            let hdr = asc
                .to_adts_header(frame_len)
                .expect("build real ADTS header");
            es.extend_from_slice(&hdr);
            es.extend_from_slice(&s.data);
        }
        assert!(
            audio.samples.len() >= 10,
            "fixture too small to be a meaningful resync test"
        );

        // Re-chunk at a fixed size (a realistic broadcast audio PES payload
        // size, several frames' worth) with no relation to any real AAC
        // frame length (~292 bytes average here), so PES payload boundaries
        // land mid-frame (issue #638).
        const CHUNK: usize = 2000;
        let mut recovered = 0usize;
        let mut off = 0usize;
        while off < es.len() {
            let end = (off + CHUNK).min(es.len());
            recovered += split_adts_frames(&es[off..end]).len();
            off = end;
        }

        // Before the #638-style fix, `split_adts_frames` bails at the first
        // byte that isn't a syncword and never resyncs, so only the chunks
        // that happen to start exactly on a frame boundary by chance yield
        // anything -- effectively none, for a chunk size unrelated to frame
        // length. Resync must recover the large majority of the real frames.
        assert!(
            recovered * 2 >= audio.samples.len(),
            "resync must recover most real AAC frames across misaligned \
             chunks (got {recovered} of {} real frames)",
            audio.samples.len()
        );
    }

    /// Loads the real AudioSpecificConfig recovered from `fixtures/ts/h264-aac.ts`
    /// plus its real per-frame AAC payloads, for building real (but
    /// re-headered) ADTS test frames — same real source `adts_resyncs_across_pes_boundaries`
    /// uses.
    fn real_aac_asc_and_samples() -> (AudioSpecificConfig, Vec<Vec<u8>>) {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let ts_bytes =
            std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display()));
        let mut demux = TsDemux::new();
        let media = demux.demux(&ts_bytes).expect("demux h264-aac.ts");
        let audio = media
            .tracks
            .into_iter()
            .find(|t| matches!(t.config(), CodecConfig::Aac { .. }))
            .expect("h264-aac.ts has an AAC track");
        let esds = match audio.config() {
            CodecConfig::Aac { esds, .. } => esds.clone(),
            _ => unreachable!(),
        };
        let dsi = esds
            .es_descriptor
            .decoder_config
            .as_ref()
            .and_then(|dc| dc.decoder_specific_info.as_ref())
            .expect("AAC esds carries a DecoderSpecificInfo")
            .clone();
        let asc = AudioSpecificConfig::parse(&dsi.data).expect("parse real AudioSpecificConfig");
        let samples: Vec<Vec<u8>> = audio.samples.iter().map(|s| s.data.to_vec()).collect();
        (asc, samples)
    }

    /// C11 (#1012): a CRC-protected ADTS frame (`protection_absent == 0`) is
    /// 9 bytes of header (fixed+variable header, 7, plus `adts_error_check()`'s
    /// 16-bit `crc_check`, 2 — ISO/IEC 13818-7 §6.2) before the raw data
    /// block. No local tool can generate a real CRC-protected ADTS stream:
    /// ffmpeg's `adts` muxer has no CRC-write option (`ffmpeg -h muxer=adts`
    /// lists none) and always emits `protection_absent = 1`; TSDuck doesn't
    /// encode audio at all. Per the fixture-first rule, this is hand-built
    /// directly from that spec clause's field layout, using the crate's own
    /// spec-cited `build_adts_header`/`parse_adts_header` for every OTHER
    /// field (profile/sfi/channels/frame_length) and only overriding
    /// `protection_absent` — the real payload bytes are the genuine captured
    /// AAC frames from `fixtures/ts/h264-aac.ts`.
    ///
    /// Before the fix, `emit_audio_au` always stripped a fixed 7 bytes, so
    /// the emitted sample began with the 2 CRC bytes glued in front of the
    /// real payload — this test's oracle is the exact real payload bytes
    /// before they were wrapped, so that leak is directly visible as a
    /// length/content mismatch.
    #[test]
    fn adts_crc_protected_frame_strips_crc_not_sample_data() {
        let (asc, samples) = real_aac_asc_and_samples();
        assert!(samples.len() >= 2, "fixture must carry several AAC frames");

        let mut events: VecDeque<DemuxEvent> = VecDeque::new();
        let mut anchor = AudioAnchor::default();
        let mut dts_uw: i128 = 0;
        for payload in samples.iter().take(5) {
            // ADTS_CRC_SIZE(2) accounted in frame_length, per §6.2's
            // frame_length = "length of this ADTS frame including headers
            // and error_check in bytes".
            let frame_len = (ADTS_HEADER_SIZE + ADTS_CRC_SIZE + payload.len()) as u16;
            let mut header = asc.to_adts_header(frame_len).expect("build ADTS header");
            header[1] &= !0x01; // protection_absent = 0 (CRC present)
            let mut au = header.to_vec();
            au.extend_from_slice(&[0x00, 0x00]); // crc_check (value irrelevant here)
            au.extend_from_slice(payload);

            emit_audio_au(
                &AudioKind::Aac,
                44_100,
                &mut anchor,
                &au,
                dts_uw as u64 as i128,
                dts_uw,
                TrackId::new(1),
                &mut events,
            );
            dts_uw += AAC_SAMPLES_PER_FRAME as i128;
        }

        let emitted: Vec<Vec<u8>> = events
            .iter()
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample.data.to_vec()),
                _ => None,
            })
            .collect();
        assert_eq!(emitted.len(), 5, "one sample per CRC-protected ADTS frame");
        for (i, (got, want)) in emitted.iter().zip(samples.iter().take(5)).enumerate() {
            assert_eq!(
                got, want,
                "sample {i}: CRC bytes must not leak into (or truncate) the real payload"
            );
        }
    }

    /// C11 (#1012): `number_of_raw_data_blocks_in_frame > 0` (a legal,
    /// if rare, ADTS encoding — several AAC frames packed into one ADTS
    /// frame) must scale the emitted sample's duration by the number of
    /// raw data blocks, not always assume one. Same real-data provenance
    /// and same "no local tool" note as the CRC test above (ffmpeg's own
    /// AAC encoders never emit `number_of_raw_data_blocks_in_frame > 0`
    /// either); two real captured AAC frames are concatenated into a single
    /// ADTS frame's raw-data area to build a real (if hand-assembled at the
    /// framing level) 2-block frame.
    #[test]
    fn adts_multi_raw_data_block_duration_is_multiplied() {
        let (asc, samples) = real_aac_asc_and_samples();
        assert!(samples.len() >= 2, "fixture must carry several AAC frames");

        let mut combined = samples[0].clone();
        combined.extend_from_slice(&samples[1]);
        let frame_len = (ADTS_HEADER_SIZE + combined.len()) as u16;
        let mut header = asc.to_adts_header(frame_len).expect("build ADTS header");
        header[6] |= 0x01; // number_of_raw_data_blocks_in_frame = 1 (2 blocks)
        let mut au = header.to_vec();
        au.extend_from_slice(&combined);

        let mut events: VecDeque<DemuxEvent> = VecDeque::new();
        let mut anchor = AudioAnchor::default();
        emit_audio_au(
            &AudioKind::Aac,
            44_100,
            &mut anchor,
            &au,
            0,
            0,
            TrackId::new(1),
            &mut events,
        );

        let emitted: Vec<(Vec<u8>, Option<u32>)> = events
            .iter()
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some((sample.data.to_vec(), sample.duration)),
                _ => None,
            })
            .collect();
        assert_eq!(
            emitted.len(),
            1,
            "the whole 2-raw-data-block frame is one emitted sample"
        );
        assert_eq!(
            emitted[0].0, combined,
            "both raw data blocks' real bytes must be present, undamaged"
        );
        assert_eq!(
            emitted[0].1,
            Some(AAC_SAMPLES_PER_FRAME * 2),
            "duration must be (num_raw_data_blocks + 1) * AAC_SAMPLES_PER_FRAME, not just 1024"
        );
    }

    /// Build an ADTS frame per ISO/IEC 13818-7 Tables 5-9 from `blocks`
    /// (`blocks.len() - 1` = `number_of_raw_data_blocks_in_frame`), laying the
    /// bytes out independently of the demuxer (`adts_frame_payload`): header,
    /// then with `crc` the position table + header CRC + a per-block CRC word
    /// after every block. CRC words are non-zero junk so any leak shows.
    fn build_adts_frame(base: &[u8; 7], blocks: &[&[u8]], crc: bool) -> Vec<u8> {
        let n = blocks.len() - 1;
        let mut body = Vec::new();
        let mut positions = Vec::new();
        for (i, b) in blocks.iter().enumerate() {
            if i > 0 {
                positions.push(body.len() as u16); // offset from first block
            }
            body.extend_from_slice(b);
            if crc && n > 0 {
                body.extend_from_slice(&[0xC0 | i as u8, 0xDE]); // crc_check
            }
        }
        let mut tail = Vec::new();
        if crc {
            if n > 0 {
                for p in &positions {
                    tail.extend_from_slice(&p.to_be_bytes());
                }
            }
            tail.extend_from_slice(&[0xBE, 0xEF]); // header-level crc_check
        }
        tail.extend_from_slice(&body);
        let frame_length = 7 + tail.len();
        assert!(frame_length < (1 << 13));
        let mut h = *base;
        if crc {
            h[1] &= !0x01; // protection_absent = 0
        } else {
            h[1] |= 0x01;
        }
        // frame_length: bits 30..43 of the header = h[3][1:0], h[4], h[5][7:5].
        h[3] = (h[3] & !0x03) | ((frame_length >> 11) & 0x03) as u8;
        h[4] = ((frame_length >> 3) & 0xFF) as u8;
        h[5] = (h[5] & 0x1F) | (((frame_length & 0x07) as u8) << 5);
        h[6] = (h[6] & !0x03) | n as u8;
        let mut out = h.to_vec();
        out.extend_from_slice(&tail);
        out
    }

    fn demux_one_adts_frame(au: &[u8]) -> Vec<(Vec<u8>, Option<u32>)> {
        let mut events: VecDeque<DemuxEvent> = VecDeque::new();
        let mut anchor = AudioAnchor::default();
        emit_audio_au(
            &AudioKind::Aac,
            44_100,
            &mut anchor,
            au,
            0,
            0,
            TrackId::new(1),
            &mut events,
        );
        events
            .iter()
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some((sample.data.to_vec(), sample.duration)),
                _ => None,
            })
            .collect()
    }

    /// #1012: multi-raw-data-block ADTS frames, with and without CRC
    /// (ISO/IEC 13818-7 §6.2 Tables 5-7), spec-laid-out synthetic blocks of
    /// different lengths: the position table and every CRC word must be
    /// stripped, leaving only the concatenated raw_data_block payloads.
    #[test]
    fn adts_multi_block_with_crc_strips_positions_and_crcs() {
        let (asc, _) = real_aac_asc_and_samples();
        let base = asc.to_adts_header(7).expect("base header");
        let all: [&[u8]; 4] = [
            &[0x11; 5],
            &[0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28],
            &[0x33; 3],
            &[0x44; 9],
        ];
        for n_blocks in 1..=4usize {
            for crc in [false, true] {
                let blocks = &all[..n_blocks];
                let au = build_adts_frame(&base, blocks, crc);
                let got = demux_one_adts_frame(&au);
                assert_eq!(got.len(), 1, "n_blocks={n_blocks} crc={crc}");
                let want: Vec<u8> = blocks.concat();
                assert_eq!(got[0].0, want, "n_blocks={n_blocks} crc={crc}");
                assert_eq!(
                    got[0].1,
                    Some(AAC_SAMPLES_PER_FRAME * n_blocks as u32),
                    "n_blocks={n_blocks} crc={crc}"
                );
            }
        }
    }

    /// #1012: real AAC frames from `h264-aac.ts` re-framed as multi-block
    /// CRC-protected ADTS frames must demux to exactly the same bytes as the
    /// original single-block frames, concatenated.
    #[test]
    fn adts_multi_block_crc_reframed_real_aac_is_byte_identical() {
        let (asc, samples) = real_aac_asc_and_samples();
        let base = asc.to_adts_header(7).expect("base header");
        for n_blocks in 2..=4usize {
            let mut checked = 0;
            for chunk in samples.chunks_exact(n_blocks).take(20) {
                let blocks: Vec<&[u8]> = chunk.iter().map(|v| v.as_slice()).collect();
                let au = build_adts_frame(&base, &blocks, true);
                let got = demux_one_adts_frame(&au);
                assert_eq!(got.len(), 1);
                assert_eq!(got[0].0, chunk.concat(), "n_blocks={n_blocks}");
                checked += 1;
            }
            assert!(checked >= 5, "fixture too small ({checked} groups)");
        }
    }

    /// #1012: a malformed position table never rejects the frame; it degrades
    /// to stripping only the header-level CRC and position table.
    #[test]
    fn adts_multi_block_crc_bad_position_table_degrades_not_rejects() {
        let (asc, _) = real_aac_asc_and_samples();
        let base = asc.to_adts_header(7).expect("base header");
        let mut au = build_adts_frame(&base, &[&[0x11; 6], &[0x22; 6]], true);
        // position[1] (bytes 7..9) -> out of range
        au[7] = 0x7F;
        au[8] = 0xFF;
        let got = demux_one_adts_frame(&au);
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].0.len(), au.len() - (7 + 2 + 2));
    }

    /// Every DVB descriptor-disambiguated `stream_type` (`0x06`/`0x15`) with
    /// a recognised Dolby/DTS descriptor reclassifies from opaque data to the
    /// matching audio codec (issue #641). The end-to-end E-AC-3 case (real
    /// captured syncframes, full PMT-parse-through-sample-recovery path) is
    /// covered by `transmux/tests/it/dolby.rs`'s
    /// `dvb_0x06_enhanced_ac3_descriptor_classifies_as_eac3`; this covers the
    /// other two descriptor tags at the classification-function level.
    #[test]
    fn refine_with_descriptors_recognises_every_dolby_dts_tag() {
        let ac3_desc = [DESC_TAG_AC3, 1, 0x40];
        assert_eq!(
            Codec::Data(STREAM_TYPE_PES_PRIVATE)
                .refine_with_descriptors(STREAM_TYPE_PES_PRIVATE, &ac3_desc),
            Codec::Ac3
        );

        let dts_desc = [DESC_TAG_DTS, 1, 0x00];
        assert_eq!(
            Codec::Data(STREAM_TYPE_METADATA_PES)
                .refine_with_descriptors(STREAM_TYPE_METADATA_PES, &dts_desc),
            Codec::Dts,
            "0x15 (metadata in PES) is also descriptor-disambiguated"
        );

        let eac3_desc = [DESC_TAG_ENHANCED_AC3, 1, 0x00];
        assert_eq!(
            Codec::Data(STREAM_TYPE_PES_PRIVATE)
                .refine_with_descriptors(STREAM_TYPE_PES_PRIVATE, &eac3_desc),
            Codec::Eac3
        );
    }

    /// A `0x06`/`0x15` stream with no Dolby/DTS descriptor (e.g. DVB
    /// subtitles, tag `0x59`) must stay opaque data, not be misclassified as
    /// audio.
    #[test]
    fn refine_with_descriptors_leaves_non_audio_0x06_as_data() {
        const DESC_TAG_SUBTITLING: u8 = 0x59;
        let subtitle_desc = [DESC_TAG_SUBTITLING, 3, 0x65, 0x6E, 0x67];
        assert_eq!(
            Codec::Data(STREAM_TYPE_PES_PRIVATE)
                .refine_with_descriptors(STREAM_TYPE_PES_PRIVATE, &subtitle_desc),
            Codec::Data(STREAM_TYPE_PES_PRIVATE)
        );
    }

    fn dovi_es_info(profile_word: u16, flags: u16, dependency: Option<u16>) -> Vec<u8> {
        let mut es = vec![0x05, 4, b'D', b'O', b'V', b'I'];
        let mut body = vec![1u8, 0];
        body.extend_from_slice(&((profile_word << 9) | flags).to_be_bytes());
        if let Some(pid) = dependency {
            body.extend_from_slice(&(pid << 3).to_be_bytes());
        }
        body.push(0x10);
        es.push(crate::dovi::DOVI_VIDEO_STREAM_DESCRIPTOR_TAG);
        es.push(body.len() as u8);
        es.extend_from_slice(&body);
        es
    }

    #[test]
    fn dovi_hevc_reclassification_needs_base_layer_and_hevc_profile() {
        let classify = |es: &[u8]| {
            Codec::Data(STREAM_TYPE_PES_PRIVATE)
                .refine_with_descriptors(STREAM_TYPE_PES_PRIVATE, es)
        };
        let bl_rpu = 0b101;
        assert_eq!(classify(&dovi_es_info(8, bl_rpu, None)), Codec::Hevc);
        assert_eq!(
            classify(&dovi_es_info(10, bl_rpu, None)),
            Codec::Data(STREAM_TYPE_PES_PRIVATE),
            "profile 10 is not HEVC"
        );
        let el_rpu_only = 0b110;
        assert_eq!(
            classify(&dovi_es_info(7, el_rpu_only, Some(0x101))),
            Codec::Data(STREAM_TYPE_PES_PRIVATE),
            "an EL-only PID is not a standalone HEVC track"
        );
    }

    /// A `stream_type` outside the descriptor-disambiguated set (`0x06`/
    /// `0x15`) must never be reclassified, even if its ES_info descriptor
    /// loop happens to contain a Dolby/DTS tag byte -- the descriptor scan
    /// only applies to the two `stream_type`s DVB actually disambiguates this
    /// way.
    #[test]
    fn refine_with_descriptors_ignores_other_stream_types() {
        let eac3_desc = [DESC_TAG_ENHANCED_AC3, 1, 0x00];
        assert_eq!(
            Codec::H264.refine_with_descriptors(STREAM_TYPE_AVC, &eac3_desc),
            Codec::H264
        );
    }

    /// F1: a PID declared by two PMTs (an ordinary shared audio/subtitle
    /// component across programs in a DVB multiplex) must not be torn down
    /// just because *one* declaring PMT reclassifies its codec while the
    /// other program's declaration is unchanged — `apply_pmt_diff`'s
    /// codec-changed branch must consult the same `es_declarers` refcount the
    /// "removed" branch already does. Must fail before the fix: without the
    /// check, `remove_track` ran unconditionally on a codec change,
    /// destroying the shared track (new `track_id`, spurious
    /// `TrackRemoved`/`TrackAdded`) even though the other program's
    /// `applied_es` still lists it.
    ///
    /// Also exercises the decided conflict policy for the two-programs/
    /// different-codecs case (documented on the fix): reclassification is
    /// refused while any other declarer remains, and only proceeds once this
    /// PMT is the *last* declarer.
    #[test]
    fn codec_change_on_shared_pid_does_not_tear_down_other_program_track() {
        const PMT_A: u16 = 0x1000;
        const PMT_B: u16 = 0x1001;
        const SHARED_PID: Pid = Pid::new(0x0050);
        const STREAM_TYPE: u8 = 0x7F; // opaque data, PES-carried (see `data_carriage`)

        let mut demux = StreamingTsDemux::new();

        // PMT A declares the shared PID; PMT B declares it too (same codec).
        demux.apply_pmt_diff(
            Pid::new(PMT_A),
            &BTreeSet::new(),
            alloc::vec![(SHARED_PID, Codec::Data(STREAM_TYPE), Vec::new())],
        );
        demux.apply_pmt_diff(
            Pid::new(PMT_B),
            &BTreeSet::new(),
            alloc::vec![(SHARED_PID, Codec::Data(STREAM_TYPE), Vec::new())],
        );
        assert_eq!(
            demux.es_declarers.get(&SHARED_PID).map(|d| d.len()),
            Some(2),
            "both PMTs must be recorded as declarers of the shared PID"
        );

        // Promote it straight to `Live`, mirroring what real config recovery
        // would do: `ConfigProbe::Data` resolves on the very first access
        // unit (it needs no in-band header at all), so this is a faithful
        // shortcut, not a fabricated state.
        let carriage = data_carriage(STREAM_TYPE);
        assert_eq!(carriage, DataCarriage::Pes);
        demux.streams.get_mut(&SHARED_PID).unwrap().track = Some(TrackState::Parked {
            config: CodecConfig::Data {
                stream_type: STREAM_TYPE,
                descriptors: Vec::new(),
                carriage,
            },
            timescale: VIDEO_TIMESCALE,
            kind: LiveKind::Data {
                pending: None,
                last_duration: 0,
            },
            backlog: Vec::new(),
        });
        demux.try_promote_ready();
        let track_id_before = match demux.streams.get(&SHARED_PID).unwrap().track.as_ref() {
            Some(TrackState::Live(live)) => live.track_id,
            _ => panic!("expected the shared PID to be Live after promotion"),
        };
        while demux.poll_event().is_some() {} // drain TrackAdded — not under test here

        // PMT A reclassifies the PID's codec. PMT B's `applied_es` (the
        // diff baseline passed in on its own behalf) still lists the PID
        // unchanged — this call only ever represents PMT A's own view.
        let mut pmt_a_applied = BTreeSet::new();
        pmt_a_applied.insert(SHARED_PID);
        demux.apply_pmt_diff(
            Pid::new(PMT_A),
            &pmt_a_applied,
            alloc::vec![(SHARED_PID, Codec::Ac3, Vec::new())],
        );

        // The shared track must survive, unchanged, with its original
        // track_id — PMT B still declares it, so PMT A's reclassification
        // alone must not tear it down.
        match demux
            .streams
            .get(&SHARED_PID)
            .and_then(|s| s.track.as_ref())
        {
            Some(TrackState::Live(live)) => assert_eq!(
                live.track_id, track_id_before,
                "shared track must keep its original track_id"
            ),
            _ => {
                panic!("expected the shared track to survive PMT A's reclassification, still Live")
            }
        }
        assert!(
            !demux
                .events
                .iter()
                .any(|ev| matches!(ev, DemuxEvent::TrackRemoved { .. })),
            "PMT A's reclassification must not remove a track PMT B still declares"
        );
        assert_eq!(
            demux.streams.get(&SHARED_PID).unwrap().codec,
            Codec::Data(STREAM_TYPE),
            "the existing classification wins while another declarer disagrees"
        );

        // Now PMT B drops its declaration entirely — PMT A becomes the sole
        // (last) declarer.
        let mut pmt_b_applied = BTreeSet::new();
        pmt_b_applied.insert(SHARED_PID);
        demux.apply_pmt_diff(Pid::new(PMT_B), &pmt_b_applied, Vec::new());
        assert_eq!(
            demux.es_declarers.get(&SHARED_PID).map(|d| d.len()),
            Some(1),
            "PMT A must be the sole remaining declarer"
        );

        // PMT A reclassifies again: as the *last* declarer, the
        // teardown-and-rebuild now proceeds.
        demux.apply_pmt_diff(
            Pid::new(PMT_A),
            &pmt_a_applied,
            alloc::vec![(SHARED_PID, Codec::Aac, Vec::new())],
        );
        assert!(
            demux
                .events
                .iter()
                .any(|ev| matches!(ev, DemuxEvent::TrackRemoved { .. })),
            "once PMT A is the last declarer, its reclassification must actually tear down \
             the old track"
        );
        assert_eq!(demux.streams.get(&SHARED_PID).unwrap().codec, Codec::Aac);
    }

    /// F3: re-registering a PID after a codec-changed teardown (issue F1's
    /// `remove_track` + `register_new_es_at` pair) must preserve its original
    /// PMT-declaration-order slot, not lose it to the back of `codec_order`/
    /// `data_order` — the order backs `TrackAdded` emission order and gates
    /// promotion (`try_promote_ready`), so losing the slot reorders both.
    /// Must fail before the fix (the old `register_new_es` always appended).
    #[test]
    fn codec_change_reregistration_preserves_declaration_order_slot() {
        const PMT: u16 = 0x1000;
        const PID_X: Pid = Pid::new(0x0050);
        const PID_Y: Pid = Pid::new(0x0051);

        let mut demux = StreamingTsDemux::new();
        demux.apply_pmt_diff(
            Pid::new(PMT),
            &BTreeSet::new(),
            alloc::vec![
                (PID_X, Codec::Data(0x06), Vec::new()),
                (PID_Y, Codec::Data(0x07), Vec::new()),
            ],
        );
        assert_eq!(demux.data_order, alloc::vec![PID_X, PID_Y]);

        // PID X's stream_type changes (still opaque `Codec::Data`, so the
        // codec-changed teardown path runs) while PID Y is untouched.
        let mut old_applied = BTreeSet::new();
        old_applied.insert(PID_X);
        old_applied.insert(PID_Y);
        demux.apply_pmt_diff(
            Pid::new(PMT),
            &old_applied,
            alloc::vec![
                (PID_X, Codec::Data(0x08), Vec::new()),
                (PID_Y, Codec::Data(0x07), Vec::new()),
            ],
        );

        assert_eq!(
            demux.data_order,
            alloc::vec![PID_X, PID_Y],
            "PID X must keep its original (first) declaration-order slot, not move to the back"
        );
        assert_eq!(demux.streams.get(&PID_X).unwrap().codec, Codec::Data(0x08));
    }

    // ── InputDegradation tests (issue #778) ─────────────────────────────────

    /// A valid TS null packet (PID 0x1FFF, AFC=01, CC=0).
    pub(crate) fn null_packet() -> [u8; TS_PACKET_SIZE] {
        let mut p = [0xFFu8; TS_PACKET_SIZE];
        p[0] = 0x47;
        p[1] = 0x1F;
        p[2] = 0xFF;
        p[3] = 0x10;
        p
    }

    /// Helper: build a TS packet with explicit tei, pusi, pid, cc, adaptation
    /// field, and payload.
    fn ts_packet_degradation(
        tei: bool,
        pid: Pid,
        cc: u8,
        afc: u8,
        adaptation: Option<&[u8]>,
        payload: &[u8],
    ) -> [u8; TS_PACKET_SIZE] {
        let mut p = [0xFFu8; TS_PACKET_SIZE];
        p[0] = 0x47;
        p[1] = (if tei { 0x80 } else { 0x00 }) | ((pid.value() >> 8) as u8 & PID_HI_MASK);
        p[2] = (pid.value() & 0xFF) as u8;
        p[3] = afc | (cc & 0x0F);

        let mut off = 4usize;
        if let Some(af) = adaptation {
            let af_len = af.len() as u8;
            p[off] = af_len;
            off += 1;
            p[off..off + af.len()].copy_from_slice(af);
            off += af.len();
        }
        // Copy payload into remaining space.
        let payload_end = off + payload.len().min(TS_PACKET_SIZE - off);
        p[off..payload_end].copy_from_slice(&payload[..payload_end - off]);
        p
    }

    // ── TEI test ────────────────────────────────────────────────────────────

    #[test]
    fn tei_set_packet_emits_transport_error() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock with enough null packets.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let pkt = ts_packet_degradation(
            true, // tei
            Pid::new(0x0100),
            0,
            0x10, // AFC=01 (payload only)
            None,
            b"some payload",
        );
        demux.feed(&pkt);
        let events: Vec<_> = std::iter::from_fn(|| demux.poll_event()).collect();
        let degraded: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                DemuxEvent::InputDegraded {
                    kind, provenance, ..
                } => Some((*kind, *provenance)),
                _ => None,
            })
            .collect();
        assert_eq!(degraded.len(), 1, "expected exactly one InputDegraded");
        assert_eq!(degraded[0].0, InputDegradation::TransportError);
        assert_eq!(degraded[0].1.pid, Some(Pid::new(0x0100)));
        // packet_index includes the bootstrap null packets.
        assert_eq!(
            degraded[0].1.packet_index,
            Some(mpeg_ts::resync::LOCK_CONFIRMATIONS as u64 + 1)
        );
    }

    // ── Clean fixture: h264-aac.ts produces zero InputDegraded ───────────────

    #[test]
    fn h264_aac_clean_fixture_produces_zero_input_degraded() {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264-aac.ts");
        let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&data);
        demux.finish();
        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::InputDegraded { .. }))
            .collect();
        assert!(
            degraded.is_empty(),
            "h264-aac.ts must produce zero InputDegraded events, got {degraded:?}"
        );
    }

    // ── m6-discontinuity.ts smoke ───────────────────────────────────────────

    /// The m6-discontinuity fixture is a real, lossy capture — it has genuine
    /// CC gaps AND signalled discontinuities. This test asserts the gap count
    /// matches media-doctor's CcAnomalyCheck (877) — the two must agree.
    #[test]
    fn m6_discontinuity_fixture_gap_count_matches_media_doctor() {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("m6-discontinuity.ts");
        let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&data);
        demux.finish();

        let gap_count = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| {
                matches!(
                    e,
                    DemuxEvent::InputDegraded {
                        kind: InputDegradation::ContinuityGap { .. },
                        ..
                    }
                )
            })
            .count();
        assert_eq!(
            gap_count, 877,
            "m6-discontinuity.ts must produce exactly 877 ContinuityGap events \
             (matching media-doctor CcAnomalyCheck); any divergence means the \
             exclusion rules disagree with the two in-repo reference \
             implementations"
        );
    }

    /// The same fixture — CC gaps AND signalled discontinuities. This test
    /// just confirms the fixture plays through without panicking and that
    /// signalled discontinuities are still observed as `Discontinuity` events.
    #[test]
    fn m6_discontinuity_fixture_plays_through() {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("m6-discontinuity.ts");
        let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));

        let mut demux = StreamingTsDemux::new();
        demux.feed(&data);
        demux.finish();

        let mut saw_discontinuity = false;
        while let Some(event) = demux.poll_event() {
            if matches!(event, DemuxEvent::Discontinuity { .. }) {
                saw_discontinuity = true;
            }
        }
        assert!(
            saw_discontinuity,
            "m6-discontinuity.ts must produce at least one Discontinuity event"
        );
    }

    // ── Legal duplicate: same CC + identical payload emits nothing ──────────

    #[test]
    fn legal_duplicate_same_cc_and_identical_payload_emits_nothing() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let payload = b"duplicate payload bytes";
        let pkt = |cc: u8| -> [u8; TS_PACKET_SIZE] {
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = 0x00; // PID=0
            p[2] = 0x31; // PID=0x0031
            p[3] = 0x10 | (cc & 0x0F); // AFC=01
            let end = 4 + payload.len().min(TS_PACKET_SIZE - 4);
            p[4..end].copy_from_slice(&payload[..end - 4]);
            p
        };

        // First packet: CC=0.
        demux.feed(&pkt(0));
        // Second packet: legal duplicate — same CC=0, identical payload.
        demux.feed(&pkt(0));

        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::InputDegraded { .. }))
            .collect();
        assert!(
            degraded.is_empty(),
            "legal duplicate must not emit InputDegraded, got {degraded:?}"
        );
    }

    // ── r04-W49: duplicates are not reassembled; gap AUs are dropped ────────

    /// ITU-T H.222.0 §2.4.3.3: "In transport streams, duplicate packets may be
    /// sent as two, and only two, consecutive transport stream packets of the
    /// same PID… In duplicate packets each byte of the original packet shall be
    /// duplicated, with the exception that in the program clock reference
    /// fields, if present, a valid value shall be encoded." The decoder shall
    /// discard the duplicate — the demux used to detect it for the CC check and
    /// then feed it to the reassembler anyway, so the PES contained those 184
    /// bytes twice and every access unit was corrupt.
    ///
    /// Real packet layout: a PES header + `PES_packet_length` spanning two TS
    /// packets on one PID, each sent twice (the second copy re-encoding its PCR
    /// so the pair is a legal duplicate only under the byte-compare-except-PCR
    /// rule the shared `ts_dup` helper implements). The delivered sample must be
    /// one whole PES payload, with no byte repeated.
    #[test]
    fn legal_duplicate_packets_are_not_reassembled_twice() {
        /// A private-PES data stream (`stream_type` 0x06) carried as one
        /// `Sample` per PES — the simplest carrier for a byte-exact check.
        const DATA_BYTES: usize = 1000;

        // Two TS payloads' worth of PES: 4-byte start code + length + flags +
        // `PES_header_data_length` 0, then the payload — long enough to span
        // two packets so a duplicated continuation really would append twice.
        let body: Vec<u8> = (0..DATA_BYTES).map(|i| (i & 0xFF) as u8).collect();
        let pes_len = (3 + body.len()) as u16;
        let mut pes = Vec::new();
        pes.extend_from_slice(&[0x00, 0x00, 0x01, 0xBD]);
        pes.extend_from_slice(&pes_len.to_be_bytes());
        pes.push(0x80); // '10' marker, not scrambled
        pes.push(0x00); // PTS_DTS_flags = '00'
        pes.push(0x00); // PES_header_data_length = 0
        pes.extend_from_slice(&body);
        assert!(
            pes.len() > TS_MAX_PAYLOAD_BYTES,
            "the PES must span more than one TS packet for this test to mean anything"
        );

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        // Every packet of the PES is followed by its legal §2.4.3.3 duplicate
        // (same CC, same bytes). The duplicate of the *first* packet is the
        // decisive one: it must not be appended to the access unit in
        // progress, or the payload gains 184 spurious bytes in the middle.
        let mut cc = 0u8;
        let mut sent = 0usize;
        let mut dups = 0usize;
        while sent < pes.len() {
            let take = (pes.len() - sent).min(TS_MAX_PAYLOAD_BYTES);
            let mut pkt = [0xFFu8; TS_PACKET_SIZE];
            pkt[0] = 0x47;
            pkt[1] = ((ES_PID_UNDER_TEST.value() >> 8) as u8 & PID_HI_MASK)
                | if sent == 0 { 0x40 } else { 0x00 };
            pkt[2] = (ES_PID_UNDER_TEST.value() & 0xFF) as u8;
            pkt[3] = 0x10 | (cc & 0x0F);
            pkt[4..4 + take].copy_from_slice(&pes[sent..sent + take]);
            input.extend_from_slice(&pkt);
            // The legal duplicate: same CC, byte-identical (a re-encoded PCR
            // would also be legal, but this PES carries no PCR).
            input.extend_from_slice(&pkt);
            dups += 1;
            sent += take;
            cc = cc.wrapping_add(1);
        }
        assert!(
            dups >= 3,
            "the PES must span several packets for a duplicate append to be observable ({dups} packets)"
        );

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.finish();
        let samples: Vec<Sample> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample),
                _ => None,
            })
            .collect();
        assert!(
            dups >= 2,
            "the fixture must really contain duplicates ({dups} emitted)"
        );
        assert_eq!(samples.len(), 1, "one PES => one Data sample");
        assert_eq!(
            samples[0].data.as_ref(),
            body.as_slice(),
            "the delivered sample must be the PES *payload* exactly once — a reassembled duplicate appends its 184 bytes a second time"
        );
    }

    /// A continuity-counter gap loses at least one 184-byte payload, so the
    /// access unit being reassembled is missing bytes. The demux must drop it,
    /// not deliver it truncated — the IR cannot tell a complete PES from a
    /// truncated one, so every downstream muxer would write the corruption out.
    ///
    /// The *next* access unit, which begins with its own `payload_unit_start`,
    /// is intact from its first byte and must still be delivered.
    #[test]
    fn cc_gap_drops_the_access_unit_it_truncated_but_not_the_next_one() {
        let au1 = long_data_au();
        let au2 = long_data_au_alt();
        let pes1 = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, &au1);
        let pes2 = untimed_pes(ES_STREAM_ID_PRIVATE_DATA, &au2);
        assert!(
            pes1.len() > TS_MAX_PAYLOAD_BYTES && pes2.len() > TS_MAX_PAYLOAD_BYTES,
            "both access units must span more than one TS packet"
        );

        let mut input = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            input.extend_from_slice(&null_packet());
        }
        input.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        input.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_PES_PRIVATE),
        ));

        // AU 1: only its first packet survives; the continuation is lost, so
        // the next packet on the PID jumps the CC by two. AU 2 follows with
        // its own `payload_unit_start`, whole.
        let pkt1 = pes_packets(ES_PID_UNDER_TEST, 0, &pes1);
        assert_eq!(pkt1.len(), 2 * TS_PACKET_SIZE, "AU 1 must span two packets");
        input.extend_from_slice(&pkt1[..TS_PACKET_SIZE]);
        let pkt2 = pes_packets(ES_PID_UNDER_TEST, 2, &pes2);

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.feed(&pkt2);
        demux.finish();

        let degraded = std::iter::from_fn(|| demux.poll_event()).any(|e| {
            matches!(
                e,
                DemuxEvent::InputDegraded {
                    kind: InputDegradation::ContinuityGap { .. },
                    ..
                }
            )
        });
        assert!(
            degraded,
            "the lost continuation must be reported as a CC gap"
        );

        let mut demux = StreamingTsDemux::new();
        demux.feed(&input);
        demux.feed(&pkt2);
        demux.finish();
        let samples: Vec<Sample> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::Sample { sample, .. } => Some(sample),
                _ => None,
            })
            .collect();
        assert_eq!(
            samples.len(),
            1,
            "only the intact access unit may be delivered, got {} samples",
            samples.len()
        );
        assert_eq!(
            samples[0].data.as_ref(),
            au2.as_slice(),
            "the delivered sample must be the second, whole access unit"
        );
    }

    // ── CC gap (synthetic) ──────────────────────────────────────────────────

    #[test]
    fn cc_gap_emits_continuity_gap() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let payload_a = b"first packet";
        let payload_b = b"second different";
        let pkt = |cc: u8, payload: &[u8]| -> [u8; TS_PACKET_SIZE] {
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = 0x00;
            p[2] = 0x42; // PID=0x0042
            p[3] = 0x10 | (cc & 0x0F); // AFC=01
            let end = 4 + payload.len().min(TS_PACKET_SIZE - 4);
            p[4..end].copy_from_slice(&payload[..end - 4]);
            p
        };

        // First packet: CC=0.
        demux.feed(&pkt(0, payload_a));
        // Second packet: CC=5 (gap: expected=1, got=5), different payload.
        demux.feed(&pkt(5, payload_b));

        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::InputDegraded {
                    kind, provenance, ..
                } => Some((kind, provenance)),
                _ => None,
            })
            .collect();
        assert_eq!(
            degraded.len(),
            1,
            "expected exactly one InputDegraded on CC gap"
        );
        assert_eq!(
            degraded[0].0,
            InputDegradation::ContinuityGap {
                expected: 1,
                got: 5
            }
        );
        assert_eq!(degraded[0].1.pid, Some(Pid::new(0x0042)));
        // packet_index of the second packet (the gap), offset by bootstrap nulls.
        assert_eq!(
            degraded[0].1.packet_index,
            Some(mpeg_ts::resync::LOCK_CONFIRMATIONS as u64 + 2)
        );
    }

    // ── Mutation proof: disabling duplicate check produces false positives ──

    /// Confirms that the duplicate-detection exclusion is load-bearing: if we
    /// craft a synthetic scenario where a legal duplicate would appear and
    /// assert that the *undecorated* CC gap fires, the test must PASS (the
    /// real implementation skips duplicates correctly, so this test documents
    /// that duplicates are NOT reported). The mutation proof is the inverse:
    /// if an engineer removes the duplicate check, the CC=0 duplicate packet
    /// WOULD fire a ContinuityGap — but since we're testing the actual code
    /// (not a mutated copy), we assert the gap is absent.
    #[test]
    fn mutation_proof_duplicate_exclusion_is_load_bearing() {
        // This test exercises the duplicate path: two packets on same PID,
        // same CC, identical payload. If duplicate detection were removed,
        // the second packet would trigger a ContinuityGap { expected: 1, got: 0 }.
        // Since the real code skips it, we expect zero InputDegraded.
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let payload = b"identical";
        let pkt = |cc: u8| -> [u8; TS_PACKET_SIZE] {
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = 0x00;
            p[2] = 0x55;
            p[3] = 0x10 | (cc & 0x0F);
            let end = 4 + payload.len().min(TS_PACKET_SIZE - 4);
            p[4..end].copy_from_slice(&payload[..end - 4]);
            p
        };
        demux.feed(&pkt(0));
        demux.feed(&pkt(0)); // legal duplicate — same CC, same payload

        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::InputDegraded { .. }))
            .collect();
        assert!(
            degraded.is_empty(),
            "legal duplicate must not fire InputDegraded; \
             would produce ContinuityGap {{ expected: 1, got: 0 }} if exclusion were removed"
        );
    }

    // ── Mutation proof: change duplicate payload, confirm gap fires ─────────

    /// If the payload changes but CC is the same, it is NOT a legal duplicate
    /// — it's a genuine gap (or at minimum, it's not the spec-blessed
    /// duplicate case). This test confirms the code does NOT treat it as a
    /// duplicate.
    #[test]
    fn mutation_proof_changed_payload_same_cc_is_not_a_duplicate() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let pkt = |cc: u8, payload: &[u8]| -> [u8; TS_PACKET_SIZE] {
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = 0x00;
            p[2] = 0x66;
            p[3] = 0x10 | (cc & 0x0F);
            let end = 4 + payload.len().min(TS_PACKET_SIZE - 4);
            p[4..end].copy_from_slice(&payload[..end - 4]);
            p
        };
        demux.feed(&pkt(0, b"first"));
        demux.feed(&pkt(0, b"second")); // same CC, DIFFERENT payload — NOT a duplicate

        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter_map(|e| match e {
                DemuxEvent::InputDegraded { kind, .. } => Some(kind),
                _ => None,
            })
            .collect();
        assert_eq!(
            degraded.len(),
            1,
            "same CC + different payload must fire InputDegraded"
        );
        assert!(matches!(
            degraded[0],
            InputDegradation::ContinuityGap { .. }
        ));
    }

    // ── Mutation proof: signalled discontinuity skips CC gap ────────────────

    /// A packet whose adaptation field sets `discontinuity_indicator` must
    /// emit `Discontinuity`, not `InputDegraded::ContinuityGap`, even if its
    /// CC is a gap. This confirms the exclusion rule: if an engineer removes
    /// the `discontinuity_signalled` check, this test's assertion that no
    /// ContinuityGap appeared would fail.
    #[test]
    fn mutation_proof_signalled_discontinuity_suppresses_cc_gap() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let payload = b"payload";

        // First packet: CC=0, no adaptation, PID=0x0077.
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0077),
            0,
            0x10,
            None,
            payload,
        ));
        // Second packet: CC=5 (gap), BUT adaptation field with
        // discontinuity_indicator=1. Should emit Discontinuity, NOT
        // InputDegraded::ContinuityGap.
        let af = [
            0x80u8, // discontinuity_indicator=1, no other flags
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // stuffing
        ];
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0077),
            5,
            0x30,
            Some(&af),
            payload, // AFC=11
        ));

        let mut saw_discontinuity = false;
        let mut saw_cc_gap = false;
        while let Some(event) = demux.poll_event() {
            match event {
                DemuxEvent::Discontinuity { .. } => saw_discontinuity = true,
                DemuxEvent::InputDegraded {
                    kind: InputDegradation::ContinuityGap { .. },
                    ..
                } => saw_cc_gap = true,
                _ => {}
            }
        }
        assert!(
            saw_discontinuity,
            "packet with discontinuity_indicator must emit Discontinuity"
        );
        assert!(
            !saw_cc_gap,
            "packet with discontinuity_indicator must NOT emit ContinuityGap — \
             the exclusion rule was removed or broken"
        );
    }

    // ── Mutation proof: CC wraps correctly ──────────────────────────────────

    #[test]
    fn cc_wraps_at_15_to_0_without_false_gap() {
        let mut demux = StreamingTsDemux::new();
        // Bootstrap TsResync lock.
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }
        let pkt = |cc: u8| -> [u8; TS_PACKET_SIZE] {
            let mut p = [0xFFu8; TS_PACKET_SIZE];
            p[0] = 0x47;
            p[1] = 0x00;
            p[2] = 0x88;
            p[3] = 0x10 | (cc & 0x0F);
            p[4..11].copy_from_slice(b"payload");
            p
        };

        // CC 14, 15, 0 — no gap, normal wrap.
        demux.feed(&pkt(14));
        demux.feed(&pkt(15));
        demux.feed(&pkt(0));

        let degraded: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| matches!(e, DemuxEvent::InputDegraded { .. }))
            .collect();
        assert!(
            degraded.is_empty(),
            "normal CC wrap 15→0 must not emit InputDegraded, got {degraded:?}"
        );
    }

    // ── Regression: post-discontinuity legal CC is not a false gap (defect 1) ─

    /// Regression test for the review-found false positive: a payload-bearing
    /// signalled discontinuity must NOT prevent `last_cc` from being updated.
    /// The next legal CC (discontinuity's CC + 1) must emit nothing.
    ///
    /// Derived from the real pid 0x0083 sequence in m6-discontinuity.ts:
    /// packet N carries discontinuity_indicator + CC=X; packet N+1 is the
    /// next legal payload-bearing packet with CC=(X+1) & 0x0F.
    #[test]
    fn post_discontinuity_legal_cc_emits_nothing() {
        let mut demux = StreamingTsDemux::new();
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }

        let payload = b"payload";
        // First: normal packet, CC=0, PID=0x0083.
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0083),
            0,
            0x10,
            None,
            payload,
        ));
        // Second: discontinuity_indicator=1, CC=5 (gap — suppressed event, but state updated).
        let af = [0x80u8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0083),
            5,
            0x30,
            Some(&af),
            payload,
        ));
        // Third: legal follow-up, CC=6 ((5+1) & 0x0F). Must NOT fire ContinuityGap.
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0083),
            6,
            0x10,
            None,
            payload,
        ));

        let gaps: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| {
                matches!(
                    e,
                    DemuxEvent::InputDegraded {
                        kind: InputDegradation::ContinuityGap { .. },
                        ..
                    }
                )
            })
            .collect();
        assert!(
            gaps.is_empty(),
            "post-discontinuity legal CC must not fire ContinuityGap; \
             discontinuity_indicator suppresses the event but updates last_cc. \
             Got {gaps:?}"
        );
    }

    // ── Regression: PCR-only adaptation-field change is NOT a false duplicate mismatch (defect 2) ─

    /// Regression test for the review-found false positive: a legal duplicate
    /// whose only difference is a re-encoded PCR in the adaptation field must
    /// still be recognised as a duplicate. The duplicate check compares
    /// `pkt.payload`, not `raw[4..]` (which includes the adaptation field).
    ///
    /// Derived from the real PCR-bearing PID behaviour in broadcast streams.
    #[test]
    fn pcr_variation_in_adaptation_field_is_still_a_legal_duplicate() {
        let mut demux = StreamingTsDemux::new();
        let null = null_packet();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            demux.feed(&null);
        }

        let payload = b"identical payload for duplicate test";

        // First: CC=0, PID=0x0100, adaptation field with PCR=100.
        let af_pcr_100 = [
            0x10u8, // PCR flag only
            0x00, 0x00, 0x00, 0x00, 0x7E, 0x64, // PCR = 100 (encoded as 6-byte PCR field)
        ];
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0100),
            0,
            0x30, // AFC=11: adaptation + payload
            Some(&af_pcr_100),
            payload,
        ));

        // Second: CC=0 (legal duplicate), same payload, adaptation field with
        // PCR=200 (different PCR encoding — NOT a different payload).
        let af_pcr_200 = [
            0x10u8, // PCR flag only
            0x00, 0x00, 0x00, 0x00, 0x7E, 0xC8, // PCR = 200
        ];
        demux.feed(&ts_packet_degradation(
            false,
            Pid::new(0x0100),
            0, // same CC
            0x30,
            Some(&af_pcr_200),
            payload, // same payload
        ));

        let gaps: Vec<_> = std::iter::from_fn(|| demux.poll_event())
            .filter(|e| {
                matches!(
                    e,
                    DemuxEvent::InputDegraded {
                        kind: InputDegradation::ContinuityGap { .. },
                        ..
                    }
                )
            })
            .collect();
        assert!(
            gaps.is_empty(),
            "PCR-only adaptation-field change must not break duplicate detection; \
             duplicate check uses pkt.payload, not raw[4..]. Got {gaps:?}"
        );
    }

    // ── Cross-PES audio frame carry (issue #1160) ──────────────────────────
    //
    // PROVENANCE: synthetic, deliberately and necessarily. The defect needs a
    // muxer that does not align PES to audio frames at *known* offsets
    // (including a split inside the 4-byte header), so the byte positions are
    // the test input; no broadcast capture may be committed (licence rule).
    // Frames are spec-valid: MPEG-1 Layer II headers per ISO/IEC 11172-3
    // §2.4.1.3 (48 kHz, 192 kbit/s, with a padding bit on every third frame so
    // frame lengths vary 576/577), ADTS headers per ISO/IEC 13818-7 §6.2 built
    // by the crate's own `build_adts_header` (48 kHz AAC-LC stereo, variable
    // length). Bodies never contain `0xFF`, so there is no false syncword to
    // confuse the *test oracle* (the false-sync behaviour has its own tests).
    // The one real-capture run is `tests/it/mpeg_legacy.rs`'s
    // `mpeg_audio_resyncs_across_pes_boundaries` over the committed
    // `mpeg2-mp2-pes-misaligned.ts`.

    /// PES `stream_id` of the first MPEG audio stream (ISO/IEC 13818-1
    /// Table 2-22, `110x xxxx`).
    const ES_STREAM_ID_MPEG_AUDIO: u8 = 0xC0;
    /// Track timescale of the 48 kHz test streams.
    const CARRY_SAMPLE_RATE: i64 = 48_000;
    /// PTS (90 kHz) of the first frame.
    const CARRY_BASE_PTS_90K: i64 = 90_000;
    /// The same instant in 48 kHz track ticks.
    const CARRY_BASE_TRACK: i64 = CARRY_BASE_PTS_90K * CARRY_SAMPLE_RATE / 90_000;
    /// MP2 Layer II frame: 1152 samples (ISO/IEC 11172-3 §2.4.1.3) = 2160 ticks
    /// of 90 kHz at 48 kHz.
    const MP2_SAMPLES: i64 = 1152;
    /// AAC frame: 1024 samples = 1920 ticks of 90 kHz at 48 kHz.
    const AAC_SAMPLES: i64 = 1024;
    /// Frames per synthetic elementary stream.
    const CARRY_FRAMES: usize = 16;

    /// Deterministic filler, never `0xFF`.
    fn body_bytes(seed: usize, len: usize) -> Vec<u8> {
        let mut x = (seed as u32)
            .wrapping_mul(2_654_435_761)
            .wrapping_add(12_345);
        (0..len)
            .map(|_| {
                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                ((x >> 24) as u8) % 0xFE
            })
            .collect()
    }

    /// MPEG-1 Layer II, 192 kbit/s, 48 kHz, stereo, no CRC; padded when
    /// `n % 3 == 0` (ISO/IEC 11172-3 §2.4.1.3: `144 * 192000 / 48000 + pad`).
    fn mp2_frame(n: usize) -> Vec<u8> {
        let pad = n.is_multiple_of(3);
        let len = 576 + usize::from(pad);
        // sync(8) | sync(3) id=1 layer=II protection_bit=1 | bitrate_idx 10,
        // sampling_frequency 48k, padding | mode=stereo.
        let mut f = alloc::vec![0xFF, 0xFD, 0xA4 | (u8::from(pad) << 1), 0x00];
        f.extend_from_slice(&body_bytes(n, len - 4));
        let hdr = MpegAudioFrameHeader::parse(&f).expect("valid MP2 header");
        assert_eq!(hdr.frame_length, len);
        assert_eq!(hdr.samples_per_frame as i64, MP2_SAMPLES);
        assert_eq!(hdr.sample_rate, 48_000);
        f
    }

    /// 48 kHz AAC-LC stereo ADTS frame, 100..300 body bytes.
    fn adts_frame(n: usize) -> Vec<u8> {
        /// AAC-LC `profile` = audio_object_type - 1.
        const PROFILE_AAC_LC: u8 = 1;
        /// `sampling_frequency_index` of 48 kHz (ISO/IEC 14496-3 Table 1.16).
        const SFI_48000: u8 = 3;
        const CHANNELS_STEREO: u8 = 2;
        let body = 100 + (n * 37) % 200;
        let len = ADTS_HEADER_SIZE + body;
        let mut f = crate::aac_asc::build_adts_header(
            PROFILE_AAC_LC,
            SFI_48000,
            CHANNELS_STEREO,
            len as u16,
        )
        .to_vec();
        f.extend_from_slice(&body_bytes(n, body));
        assert_eq!(
            parse_adts_header(&f).expect("ADTS").frame_length as usize,
            len
        );
        f
    }

    /// A synthetic elementary stream: the frames, their concatenation and each
    /// frame's start offset in it.
    struct AudioEs {
        frames: Vec<Vec<u8>>,
        es: Vec<u8>,
        starts: Vec<usize>,
    }

    fn audio_es(frames: Vec<Vec<u8>>) -> AudioEs {
        let mut es = Vec::new();
        let mut starts = Vec::new();
        for f in &frames {
            starts.push(es.len());
            es.extend_from_slice(f);
        }
        AudioEs { frames, es, starts }
    }

    /// Packetise `es` into PES packets of the repeating `chunk_sizes` — cut
    /// wherever those land, ignoring frame boundaries — each PES stamped, per
    /// ISO/IEC 13818-1 §2.4.3.7, with the PTS of the first frame that
    /// *commences* in it (and unstamped when none does).
    fn audio_ts(
        stream_type: u8,
        es: &AudioEs,
        chunk_sizes: &[usize],
        frame_ticks_90k: i64,
    ) -> Vec<u8> {
        let mut out = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            out.extend_from_slice(&null_packet());
        }
        out.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        out.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, stream_type),
        ));
        let (mut off, mut i, mut cc) = (0usize, 0usize, 0u8);
        while off < es.es.len() {
            let end = (off + chunk_sizes[i % chunk_sizes.len()]).min(es.es.len());
            i += 1;
            let first = es.starts.iter().position(|&s| s >= off && s < end);
            let pes = match first {
                Some(k) => pes_packet(
                    ES_STREAM_ID_MPEG_AUDIO,
                    CARRY_BASE_PTS_90K + k as i64 * frame_ticks_90k,
                    None,
                    &es.es[off..end],
                ),
                None => pes_packet_untimed(ES_STREAM_ID_MPEG_AUDIO, &es.es[off..end]),
            };
            let packets = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            cc = cc.wrapping_add((packets.len() / TS_PACKET_SIZE) as u8);
            out.extend_from_slice(&packets);
            off = end;
        }
        out
    }

    /// Does some PES boundary of `chunk_sizes` fall 1..`hdr_len` bytes after a
    /// frame start, i.e. inside a frame header?
    fn splits_inside_a_header(es: &AudioEs, chunk_sizes: &[usize], hdr_len: usize) -> bool {
        let (mut off, mut i) = (0usize, 0usize);
        while off < es.es.len() {
            off += chunk_sizes[i % chunk_sizes.len()];
            i += 1;
            if es.starts.iter().any(|&s| off > s && off < s + hdr_len) {
                return true;
            }
        }
        false
    }

    /// `(data, dts, pts, duration)` of every emitted sample plus the number of
    /// `Discontinuity` events, driving [`StreamingTsDemux`] in `chunk`-byte feeds.
    type Observed = (Vec<(Vec<u8>, Option<i64>, Option<i64>, Option<u32>)>, usize);

    fn observe(ts: &[u8], chunk: usize) -> Observed {
        let mut d = StreamingTsDemux::new();
        let mut samples = Vec::new();
        let mut disc = 0usize;
        let mut drain = |d: &mut StreamingTsDemux| {
            while let Some(e) = d.poll_event() {
                match e {
                    DemuxEvent::Sample { sample, .. } => samples.push((
                        sample.data.to_vec(),
                        sample.dts,
                        sample.pts,
                        sample.duration,
                    )),
                    DemuxEvent::Discontinuity { .. } => disc += 1,
                    _ => {}
                }
            }
        };
        for c in ts.chunks(chunk) {
            d.feed(c);
            drain(&mut d);
        }
        d.finish();
        drain(&mut d);
        (samples, disc)
    }

    /// The whole contract for one stream: every frame byte-exact, count equal,
    /// PTS == the frame-exact rule, no `Discontinuity`, identical through the
    /// batch demuxer and the streaming one fed in arbitrary chunk splits, and
    /// zero gaps after a `TsMux` round trip.
    fn assert_carry_contract(
        label: &str,
        stream_type: u8,
        es: &AudioEs,
        strip: usize,
        samples_per_frame: i64,
        chunk_sizes: &[usize],
    ) {
        let frame_ticks_90k = samples_per_frame * 90_000 / CARRY_SAMPLE_RATE;
        let ts = audio_ts(stream_type, es, chunk_sizes, frame_ticks_90k);

        let (whole, disc) = observe(&ts, ts.len());
        assert_eq!(
            disc, 0,
            "{label}: a continuous stream raises no Discontinuity"
        );
        let missing: Vec<usize> = (0..es.frames.len())
            .filter(|&n| !whole.iter().any(|w| w.0 == es.frames[n][strip..]))
            .collect();
        assert_eq!(
            whole.len(),
            es.frames.len(),
            "{label}: every frame recovered, none dropped, none invented (missing {missing:?})"
        );
        for (n, (data, dts, pts, dur)) in whole.iter().enumerate() {
            assert_eq!(
                data,
                &es.frames[n][strip..],
                "{label}: frame {n} byte-exact"
            );
            // THE PTS RULE: a frame — a carried one included — sits at the
            // frame-exact cursor, i.e. the PTS of the PES in which its first
            // byte arrived plus the intrinsic durations of the frames before it.
            let want = CARRY_BASE_TRACK + n as i64 * samples_per_frame;
            assert_eq!(*dts, Some(want), "{label}: frame {n} dts");
            assert_eq!(*pts, Some(want), "{label}: frame {n} pts");
            assert_eq!(
                *dur,
                Some(samples_per_frame as u32),
                "{label}: frame {n} duration"
            );
        }

        // Batch entry point.
        let media = TsDemux::new().demux(&ts).expect("batch demux");
        let batch: Vec<_> = media.tracks[0]
            .samples
            .iter()
            .map(|s| (s.data.to_vec(), s.dts, s.pts, s.duration))
            .collect();
        assert_eq!(batch, whole, "{label}: batch == streaming");

        // Streaming, arbitrary feed splits: identical sample sequence.
        for chunk in [1usize, 7, 187, 188, 189, 1000] {
            let (got, d) = observe(&ts, chunk);
            assert_eq!((got, d), (whole.clone(), 0), "{label}: feed chunk {chunk}");
        }

        // TsMux round trip: zero gaps.
        let ts2 = TsMux::new().package(&media).expect("remux to TS");
        let (again, disc2) = observe(&ts2, ts2.len());
        assert_eq!(disc2, 0, "{label}: remux has no Discontinuity");
        assert_eq!(again.len(), whole.len(), "{label}: remux frame count");
        for (n, (a, w)) in again.iter().zip(&whole).enumerate() {
            assert_eq!(a.0, w.0, "{label}: remux frame {n} bytes");
        }
        for pair in again.windows(2) {
            assert_eq!(
                pair[1].1.unwrap() - pair[0].1.unwrap(),
                samples_per_frame,
                "{label}: remux has no timeline gap"
            );
        }
    }

    #[test]
    fn mp2_frames_straddling_pes_boundaries_are_all_recovered() {
        let es = audio_es((0..CARRY_FRAMES).map(mp2_frame).collect());
        let patterns: &[&[usize]] = &[
            &[2000], // multi-frame PES, misaligned
            &[577],  // each cut 1, 2, 3 ... bytes into the next header
            &[575],  // each cut 1, 2, 3 ... bytes before the next header
            &[574],
            &[573],
            &[576],      // frame-aligned (regression: nothing to carry)
            &[1000, 13], // irregular
            &[3],        // every PES, the first included, shorter than a header
            &[1],        // one byte per PES
        ];
        assert!(
            splits_inside_a_header(&es, &[577], 4),
            "the matrix must cut inside the 4-byte header"
        );
        for p in patterns {
            assert_carry_contract(
                &alloc::format!("mp2 {p:?}"),
                STREAM_TYPE_MPEG1_AUDIO,
                &es,
                0,
                MP2_SAMPLES,
                p,
            );
        }
    }

    #[test]
    fn adts_frames_straddling_pes_boundaries_are_all_recovered() {
        let es = audio_es((0..CARRY_FRAMES).map(adts_frame).collect());
        let patterns: &[&[usize]] = &[
            &[2000],
            &[301],
            &[299],
            &[7],
            // PES shorter than a header, first PES included (config recovery
            // must join the header across PES boundaries):
            &[6],
            &[3],
            &[1],
            &[900, 17],
        ];
        assert!(
            splits_inside_a_header(&es, &[7], ADTS_HEADER_SIZE),
            "the matrix must cut inside the 7-byte header"
        );
        for p in patterns {
            assert_carry_contract(
                &alloc::format!("adts {p:?}"),
                STREAM_TYPE_AAC_ADTS,
                &es,
                ADTS_HEADER_SIZE,
                AAC_SAMPLES,
                p,
            );
        }
    }

    /// The tail reported for carry: a whole header whose frame overruns, or a
    /// 1..HEADER_LEN byte prefix of one; nothing when the buffer ends on a
    /// frame boundary or in non-sync bytes.
    #[test]
    fn split_reports_the_unfinished_tail() {
        let (f0, f1) = (mp2_frame(1), mp2_frame(2));
        let mut buf = f0.clone();
        buf.extend_from_slice(&f1[..100]);
        let s = split_frames_with_tail::<MpegAudioSync>(&buf);
        assert_eq!(s.frames.len(), 1);
        assert_eq!(s.tail_start, f0.len(), "valid header, frame overruns");

        for k in 1..4 {
            let mut buf = f0.clone();
            buf.extend_from_slice(&f1[..k]);
            let s = split_frames_with_tail::<MpegAudioSync>(&buf);
            assert_eq!(s.frames.len(), 1);
            assert_eq!(s.tail_start, f0.len(), "{k}-byte header prefix is held");
        }
        let s = split_frames_with_tail::<MpegAudioSync>(&f0);
        assert_eq!(s.tail_start, f0.len(), "exact end: nothing to carry");
        let mut buf = f0.clone();
        buf.extend_from_slice(&[0x12, 0x34, 0x56]);
        let s = split_frames_with_tail::<MpegAudioSync>(&buf);
        assert_eq!(
            s.tail_start,
            buf.len(),
            "non-sync trailing bytes are not held"
        );
    }

    /// A false sync at the end of a PES must not swallow the real frames of the
    /// next one: the carried "frame" is only accepted if a valid header follows
    /// it.
    #[test]
    fn false_sync_tail_does_not_swallow_the_next_pes() {
        let frames: Vec<Vec<u8>> = (0..6).map(mp2_frame).collect();
        // PES 1: F0 F1 then a *valid-looking* header (claims 576 bytes) that is
        // really junk; PES 2: F2..F5, frame-aligned.
        let mut p1 = frames[0].clone();
        p1.extend_from_slice(&frames[1]);
        let mut junk = alloc::vec![0xFF, 0xFD, 0xA4, 0x00];
        junk.extend_from_slice(&body_bytes(99, 100));
        p1.extend_from_slice(&junk);
        let p2: Vec<u8> = frames[2..].concat();

        let mut ts = Vec::new();
        for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
            ts.extend_from_slice(&null_packet());
        }
        ts.extend_from_slice(&psi_section_packets(
            PAT_PID_UNDER_TEST,
            0,
            TABLE_ID_PAT,
            &pat_body(),
        ));
        ts.extend_from_slice(&psi_section_packets(
            PMT_PID_UNDER_TEST,
            0,
            TABLE_ID_PMT,
            &pmt_body(ES_PID_UNDER_TEST, STREAM_TYPE_MPEG1_AUDIO),
        ));
        let mut cc = 0u8;
        for (k, p) in [(0i64, &p1), (2, &p2)] {
            let pes = pes_packet(
                ES_STREAM_ID_MPEG_AUDIO,
                CARRY_BASE_PTS_90K + k * 2160,
                None,
                p,
            );
            let pk = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
            cc = cc.wrapping_add((pk.len() / TS_PACKET_SIZE) as u8);
            ts.extend_from_slice(&pk);
        }
        let (got, _) = observe(&ts, ts.len());
        let want: Vec<&Vec<u8>> = frames.iter().collect();
        assert_eq!(got.len(), want.len(), "all six real frames, junk discarded");
        for (g, w) in got.iter().zip(&want) {
            assert_eq!(&g.0, *w);
        }
    }

    /// End of stream with a dangling partial frame: nothing is emitted for it.
    #[test]
    fn dangling_partial_frame_at_flush_emits_nothing() {
        let mut frames: Vec<Vec<u8>> = (0..5).map(mp2_frame).collect();
        let last = frames.pop().unwrap();
        let mut es = audio_es(frames.clone());
        es.es.extend_from_slice(&last[..300]); // truncated mid-frame
        let ts = audio_ts(STREAM_TYPE_MPEG1_AUDIO, &es, &[700], 2160);
        let (got, _) = observe(&ts, ts.len());
        assert_eq!(got.len(), 4, "the four complete frames only");
        for (g, w) in got.iter().zip(&frames) {
            assert_eq!(&g.0, w);
        }
    }

    /// Bytes lost to a continuity gap must not be welded onto the held tail:
    /// whatever is emitted is a genuine frame, and the loss is bounded to the
    /// damaged PES plus the one frame straddling into it.
    #[test]
    fn continuity_gap_drops_the_carry_and_emits_only_genuine_frames() {
        let es = audio_es((0..CARRY_FRAMES).map(mp2_frame).collect());
        let ts = audio_ts(STREAM_TYPE_MPEG1_AUDIO, &es, &[1000], 2160);
        // Remove one non-start ES packet from the middle of the stream.
        let mut kept = Vec::new();
        let mut removed = false;
        for (i, p) in ts.chunks_exact(TS_PACKET_SIZE).enumerate() {
            let pid = (u16::from(p[1] & 0x1F) << 8) | u16::from(p[2]);
            if !removed && i > 12 && pid == ES_PID_UNDER_TEST.value() && p[1] & 0x40 == 0 {
                removed = true;
                continue;
            }
            kept.extend_from_slice(p);
        }
        assert!(removed);
        let (got, _) = observe(&kept, kept.len());
        let genuine: std::collections::HashSet<&Vec<u8>> = es.frames.iter().collect();
        for (i, g) in got.iter().enumerate() {
            assert!(genuine.contains(&g.0), "sample {i} is not a genuine frame");
        }
        assert!(
            got.len() < es.frames.len() && got.len() + 5 >= es.frames.len(),
            "loss bounded to the damaged PES (got {} of {})",
            got.len(),
            es.frames.len()
        );
    }

    /// Append `value` as `bits` bits MSB-first (ETSI TS 102 114 / 366 syntax
    /// tables are all MSB-first bit fields).
    fn put_bits(out: &mut Vec<u8>, nbits: &mut usize, value: u64, bits: usize) {
        for i in (0..bits).rev() {
            if (*nbits).is_multiple_of(8) {
                out.push(0);
            }
            let bit = ((value >> i) & 1) as u8;
            *out.last_mut().unwrap() |= bit << (7 - (*nbits % 8));
            *nbits += 1;
        }
    }

    /// AC-3 syncframe header + `body` filler bytes (ETSI TS 102 366 §4.3):
    /// `syncword | crc1 | fscod(2) frmsizecod(6) | bsid=8 bsmod=0 acmod=2
    /// dsurmod lfeon`. `fscod_frmsizecod` is the combined byte.
    fn ac3_header(fscod_frmsizecod: u8, body: usize) -> Vec<u8> {
        let mut h = alloc::vec![0x0B, 0x77, 0x00, 0x00, fscod_frmsizecod];
        let mut n = h.len() * 8;
        put_bits(&mut h, &mut n, 8, 5); // bsid
        put_bits(&mut h, &mut n, 0, 3); // bsmod
        put_bits(&mut h, &mut n, 2, 3); // acmod = 2/0
        put_bits(&mut h, &mut n, 0, 2); // dsurmod
        put_bits(&mut h, &mut n, 0, 1); // lfeon
        h.extend_from_slice(&body_bytes(3, body));
        h
    }

    /// A whole AC-3 syncframe: `fscod 0` (48 kHz), `frmsizecod 0` (32 kbit/s,
    /// 64 words = 128 bytes, Table 4.13), body made distinct by `n`.
    fn ac3_frame(n: usize) -> Vec<u8> {
        let mut f = ac3_header(0x00, 0);
        let hdr = f.len();
        f.extend_from_slice(&body_bytes(n, 128 - hdr));
        assert_eq!(f.len(), 128);
        assert_eq!(
            Ac3SyncframeInfo::parse_at(&f, 0).unwrap().frame_len_bytes(),
            Some(128)
        );
        f
    }

    /// E-AC-3 independent-substream header (ETSI TS 102 366 Annex E §E.1.2.2):
    /// `syncword | strmtyp=0 substreamid=0 frmsiz | fscod=0 numblkscod=3
    /// acmod=2 lfeon=0 | bsid=16`, then `body` filler. Frame = `(frmsiz+1)*2` B.
    fn eac3_header(frmsiz: u16, body: usize) -> Vec<u8> {
        let mut h = alloc::vec![0x0B, 0x77];
        let mut n = 16;
        put_bits(&mut h, &mut n, 0, 2); // strmtyp
        put_bits(&mut h, &mut n, 0, 3); // substreamid
        put_bits(&mut h, &mut n, frmsiz as u64, 11);
        put_bits(&mut h, &mut n, 0, 2); // fscod = 48 kHz
        put_bits(&mut h, &mut n, 3, 2); // numblkscod = 6 blocks
        put_bits(&mut h, &mut n, 2, 3); // acmod = 2/0
        put_bits(&mut h, &mut n, 0, 1); // lfeon
        put_bits(&mut h, &mut n, 16, 5); // bsid
        h.extend_from_slice(&body_bytes(4, body));
        h
    }

    /// A whole E-AC-3 syncframe of 128 bytes (`frmsiz = 63`), body varies by `n`.
    fn eac3_frame(n: usize) -> Vec<u8> {
        let mut f = eac3_header(63, 0);
        let hdr = f.len();
        f.extend_from_slice(&body_bytes(n, 128 - hdr));
        assert_eq!(f.len(), 128);
        let info = Ec3SyncframeInfo::parse_at(&f, 0).unwrap();
        assert_eq!((info.frmsiz as usize + 1) * 2, 128);
        assert_eq!(info.samples_per_frame(), 1536);
        f
    }

    /// DTS core frame header (ETSI TS 102 114 Table 5-1; private/specs-verified/mpeg/transmux/codec/
    /// dts-core-frame.md): `SYNC | FTYPE=1 SHORT=31 CPF=0 NBLKS=15 FSIZE |
    /// AMODE=2 SFREQ=13 RATE=15 | FixedBit..HFLAG=0`, then `body` filler.
    /// A frame is `FSIZE + 1` bytes and decodes `32 * (NBLKS + 1)` = 512 samples.
    fn dts_header(fsize: u16, body: usize) -> Vec<u8> {
        let mut h = DTS_CORE_SYNC_WORD.to_be_bytes().to_vec();
        let mut n = 32;
        put_bits(&mut h, &mut n, 1, 1); // FTYPE: normal frame
        put_bits(&mut h, &mut n, 31, 5); // SHORT
        put_bits(&mut h, &mut n, 0, 1); // CPF
        put_bits(&mut h, &mut n, 15, 7); // NBLKS
        put_bits(&mut h, &mut n, fsize as u64, 14);
        put_bits(&mut h, &mut n, 2, 6); // AMODE: 2 channels (A + B)
        put_bits(&mut h, &mut n, 13, 4); // SFREQ: 48 kHz
        put_bits(&mut h, &mut n, 15, 5); // RATE
        put_bits(&mut h, &mut n, 0, 1); // FixedBit
        put_bits(&mut h, &mut n, 0, 1); // DYNF
        put_bits(&mut h, &mut n, 0, 1); // TIMEF
        put_bits(&mut h, &mut n, 0, 1); // AUXF
        put_bits(&mut h, &mut n, 0, 1); // HDCD
        put_bits(&mut h, &mut n, 0, 3); // EXT_AUDIO_ID
        put_bits(&mut h, &mut n, 0, 1); // EXT_AUDIO
        put_bits(&mut h, &mut n, 0, 1); // ASPF
        put_bits(&mut h, &mut n, 0, 2); // LFF: no LFE
        put_bits(&mut h, &mut n, 0, 1); // HFLAG
        h.extend_from_slice(&body_bytes(5, body));
        h
    }

    /// A whole DTS core frame of 512 bytes (`FSIZE = 511`).
    fn dts_frame(n: usize) -> Vec<u8> {
        let mut f = dts_header(511, 0);
        let hdr = f.len();
        f.extend_from_slice(&body_bytes(n, 512 - hdr));
        assert_eq!(f.len(), 512);
        let info = DtsCoreFrameInfo::parse_at(&f, 0).unwrap();
        assert_eq!(
            (info.frame_size, info.samples_per_frame, info.sample_rate),
            (512, 512, 48_000)
        );
        f
    }

    #[test]
    fn ac3_frames_straddling_pes_boundaries_are_all_recovered() {
        let es = audio_es((0..CARRY_FRAMES).map(ac3_frame).collect());
        for p in [
            &[2000][..],
            &[129],
            &[127],
            &[7],
            &[4],
            &[3],
            &[1],
            &[300, 13],
        ] {
            assert_carry_contract(
                &alloc::format!("ac3 {p:?}"),
                STREAM_TYPE_AC3,
                &es,
                0,
                1536,
                p,
            );
        }
    }

    #[test]
    fn eac3_frames_straddling_pes_boundaries_are_all_recovered() {
        let es = audio_es((0..CARRY_FRAMES).map(eac3_frame).collect());
        for p in [
            &[2000][..],
            &[129],
            &[127],
            &[7],
            &[4],
            &[3],
            &[1],
            &[300, 13],
        ] {
            assert_carry_contract(
                &alloc::format!("eac3 {p:?}"),
                STREAM_TYPE_EAC3,
                &es,
                0,
                1536,
                p,
            );
        }
    }

    // ── E-AC-3 dependent substreams across PES boundaries (issue #1186) ────
    //
    // PROVENANCE: no real E-AC-3 capture with dependent substreams exists on
    // this machine or in the repo (`ac3.rs::seven_one_eac3_es` documents that
    // the bundled Dolby captures are 5.1 and ffmpeg's `eac3` encoder cannot
    // emit above 5.1). The independent frames below are therefore REAL (the
    // committed `fixtures/ts/dolby/eac3.ts` capture's own frames) where
    // marked; the dependent frame is built from the ETSI TS 102 366 §E.1.2.2
    // `bsi()` syntax (strmtyp 1, `chanmap` Lrs/Rrs + Cs per Table E.1.4), and
    // §E.1.3.1.2 ("Dependent substreams shall immediately follow the
    // independent substream with which they are associated") is the rule
    // under test.

    /// Dependent-substream syncframe of 64 bytes (`frmsiz = 31`): `syncword |
    /// strmtyp=1 substreamid=0 frmsiz | fscod=0 numblkscod=3 acmod=2 lfeon=0 |
    /// bsid=16 | dialnorm compre chanmape=1 chanmap | mixmdate=0 infomdate=0`
    /// (§E.1.2.2), filler body varying by `n`.
    fn eac3_dependent_frame(n: usize) -> Vec<u8> {
        eac3_dependent_frame_sized(n, 64)
    }

    /// [`eac3_dependent_frame`] of `len` bytes (`frmsiz = len / 2 - 1`).
    fn eac3_dependent_frame_sized(n: usize, len: usize) -> Vec<u8> {
        let mut h = alloc::vec![0x0B, 0x77];
        let mut nb = 16;
        put_bits(&mut h, &mut nb, 1, 2); // strmtyp = dependent
        put_bits(&mut h, &mut nb, 0, 3); // substreamid (dependent substreams are numbered from 0)
        put_bits(&mut h, &mut nb, (len / 2 - 1) as u64, 11); // frmsiz
        put_bits(&mut h, &mut nb, 0, 2); // fscod
        put_bits(&mut h, &mut nb, 3, 2); // numblkscod
        put_bits(&mut h, &mut nb, 2, 3); // acmod
        put_bits(&mut h, &mut nb, 0, 1); // lfeon
        put_bits(&mut h, &mut nb, 16, 5); // bsid
        put_bits(&mut h, &mut nb, 31, 5); // dialnorm
        put_bits(&mut h, &mut nb, 0, 1); // compre
        put_bits(&mut h, &mut nb, 1, 1); // chanmape
        // Table E.1.4 bits 6 (Lrs/Rrs) and 7 (Cs), bit 0 = MSB.
        put_bits(&mut h, &mut nb, (1 << 9) | (1 << 8), 16); // chanmap
        put_bits(&mut h, &mut nb, 0, 1); // mixmdate
        put_bits(&mut h, &mut nb, 0, 1); // infomdate
        let hdr = h.len();
        h.extend_from_slice(&body_bytes(n + 1000, len - hdr));
        assert_eq!(h.len(), len);
        // Every real frame carries a valid `crc2` (§E.2.2), and the probe
        // chooses frames by it.
        crate::ac3::tests::stamp_crc2(&mut h);
        let info = Ec3SyncframeInfo::parse_at(&h, 0).unwrap();
        assert_eq!(info.strmtyp, EAC3_STRMTYP_DEPENDENT);
        h
    }

    /// `n` access units of `independent(i) ++ eac3_dependent_frame(i)`.
    fn eac3_aus(independent: impl Fn(usize) -> Vec<u8>, n: usize) -> AudioEs {
        audio_es(
            (0..n)
                .map(|i| [independent(i), eac3_dependent_frame(i)].concat())
                .collect(),
        )
    }

    /// The real independent frames of the committed Dolby E-AC-3 capture.
    fn real_eac3_independent_frames() -> Vec<Vec<u8>> {
        let path = test_fixtures::path("ts/dolby/eac3.ts");
        let ts = std::fs::read(path).expect("committed Dolby E-AC-3 capture");
        let media = TsDemux::new().demux(&ts).expect("demux real E-AC-3");
        media.tracks[0]
            .samples
            .iter()
            .map(|s| s.data.to_vec())
            .collect()
    }

    /// PES sizes that put a boundary at every `split` bytes into an access unit
    /// of `au_len`: first PES = `split` bytes, then whole-AU strides.
    fn boundary_sizes(split: usize, au_len: usize) -> Vec<usize> {
        let mut v = alloc::vec![split];
        v.extend(core::iter::repeat_n(au_len, 64));
        v
    }

    /// Config of the first track of `ts`.
    fn first_track_config(ts: &[u8]) -> CodecConfig {
        let media = TsDemux::new().demux(ts).expect("demux");
        media.tracks[0].spec.config.clone()
    }

    #[test]
    fn eac3_dependent_substream_starting_a_pes_joins_its_access_unit() {
        let es = eac3_aus(eac3_frame, 12);
        let au_len = es.frames[0].len();
        // 128 = the boundary falls exactly between the independent frame and
        // its dependent frame, so the dependent frame STARTS a PES — the
        // reported defect. The others cut inside the dependent frame's header
        // and body, or at the access-unit boundary itself.
        for split in [128usize, 129, 131, 133, 140, 190, 192, 100, 5, au_len] {
            assert_carry_contract(
                &alloc::format!("eac3+dep split {split}"),
                STREAM_TYPE_EAC3,
                &es,
                0,
                1536,
                &boundary_sizes(split, au_len),
            );
        }
        // Boundaries everywhere, not aligned to anything.
        for p in [&[1usize][..], &[7], &[300, 13], &[1000]] {
            assert_carry_contract(
                &alloc::format!("eac3+dep {p:?}"),
                STREAM_TYPE_EAC3,
                &es,
                0,
                1536,
                p,
            );
        }
    }

    /// A dependent substream whose independent frame never arrived (the
    /// stream, or the PES after a gap, starts on it) is dropped instead of
    /// being emitted as a sample of its own with an independent frame's
    /// duration - which also shifted every following timestamp by one frame.
    #[test]
    fn eac3_orphan_dependent_at_stream_start_is_dropped() {
        let real = real_eac3_independent_frames();
        const REAL_RATE: i64 = 44_100;
        let aus = eac3_aus(|i| real[i % real.len()].clone(), 8);
        // The ES starts with a dependent frame (its independent frame is lost).
        let mut frames = alloc::vec![eac3_dependent_frame(99)];
        frames.extend(aus.frames.iter().cloned());
        let es = audio_es(frames);
        let ts = audio_ts(
            STREAM_TYPE_EAC3,
            &es,
            &[usize::MAX],
            1536 * 90_000 / REAL_RATE,
        );
        let (samples, disc) = observe(&ts, ts.len());
        assert_eq!(disc, 0);
        assert_eq!(
            samples.len(),
            aus.frames.len(),
            "the orphan must not be a sample of its own"
        );
        for (n, (data, dts, _, dur)) in samples.iter().enumerate() {
            assert_eq!(data, &aus.frames[n], "AU {n} byte-exact");
            assert_eq!(*dur, Some(1536));
            assert_eq!(*dts, Some(samples[0].1.unwrap() + n as i64 * 1536));
        }
    }

    #[test]
    fn eac3_real_independent_frames_with_dependents_join_across_pes() {
        let real = real_eac3_independent_frames();
        assert!(real.len() >= 12, "the real capture carries many frames");
        // The capture is 44.1 kHz (fscod 1), 1536 samples per frame.
        const REAL_RATE: i64 = 44_100;
        let es = eac3_aus(|i| real[i % real.len()].clone(), 12);
        let ind_len = real[0].len();
        for split in [ind_len, ind_len + 3, ind_len + 40] {
            let ts = audio_ts(
                STREAM_TYPE_EAC3,
                &es,
                &boundary_sizes(split, es.frames[0].len()),
                1536 * 90_000 / REAL_RATE,
            );
            let (samples, disc) = observe(&ts, ts.len());
            assert_eq!(disc, 0, "split {split}: no Discontinuity");
            assert_eq!(
                samples.len(),
                es.frames.len(),
                "split {split}: one sample per access unit — the dependent frame that starts a PES is NOT its own sample"
            );
            for (n, (data, dts, _, dur)) in samples.iter().enumerate() {
                assert_eq!(data, &es.frames[n], "split {split}: AU {n} byte-exact");
                assert_eq!(*dur, Some(1536));
                assert_eq!(*dts, Some(samples[0].1.unwrap() + n as i64 * 1536));
            }
            let CodecConfig::Eac3 { config, .. } = first_track_config(&ts) else {
                panic!("E-AC-3 track expected");
            };
            assert!(
                config.substreams[0].chan_loc.is_some(),
                "dec3 carries the dependent substream"
            );
        }
    }

    /// Config recovery needs the WHOLE first access unit: a PES that ends right
    /// after the independent frame must not yield a `dec3` without the
    /// dependent substream (it signalled 5.1 for a 7.1 stream).
    #[test]
    fn eac3_config_recovery_waits_for_the_dependent_substream() {
        let es = eac3_aus(eac3_frame, 8);
        let au_len = es.frames[0].len();
        for split in [128usize, 131, 190] {
            let ts = audio_ts(
                STREAM_TYPE_EAC3,
                &es,
                &boundary_sizes(split, au_len),
                1536 * 90_000 / CARRY_SAMPLE_RATE,
            );
            let CodecConfig::Eac3 { config, .. } = first_track_config(&ts) else {
                panic!("E-AC-3 track expected");
            };
            let s0 = &config.substreams[0];
            assert!(
                s0.chan_loc.is_some() && s0.num_dep_sub == 1,
                "split {split}: dec3 must describe the dependent substream, got {config:?}"
            );
            assert_eq!(s0.chan_loc, Some(0b110), "Lrs/Rrs + Cs");
        }
    }

    /// End of input is the only thing that completes a one-access-unit stream:
    /// it must still resolve (with its dependent substream) and its sample must
    /// be emitted (it is held back for a dependent that never comes).
    #[test]
    fn eac3_single_access_unit_stream_resolves_at_end_of_input() {
        let es = eac3_aus(eac3_frame, 1);
        let au_len = es.frames[0].len();
        let ts = audio_ts(
            STREAM_TYPE_EAC3,
            &es,
            &boundary_sizes(128, au_len),
            1536 * 90_000 / CARRY_SAMPLE_RATE,
        );
        let media = TsDemux::new().demux(&ts).expect("demux");
        let CodecConfig::Eac3 { config, .. } = &media.tracks[0].spec.config else {
            panic!("E-AC-3 track expected");
        };
        assert!(config.substreams[0].chan_loc.is_some());
        assert_eq!(media.tracks[0].samples.len(), 1);
        assert_eq!(&media.tracks[0].samples[0].data[..], &es.frames[0][..]);
    }

    /// Streams with NO dependent substreams are untouched: nothing is held
    /// back, so every sample is emitted as the PES arrives (real capture).
    #[test]
    fn eac3_without_dependents_emits_each_access_unit_immediately() {
        let real = real_eac3_independent_frames();
        let ts = std::fs::read(test_fixtures::path("ts/dolby/eac3.ts")).unwrap();
        let mut d = StreamingTsDemux::new();
        let mut got = 0usize;
        for c in ts.chunks(188) {
            d.feed(c);
            while let Some(e) = d.poll_event() {
                got += usize::from(matches!(e, DemuxEvent::Sample { .. }));
            }
        }
        // Before finish(): all but the last PES's frames are out already, and
        // the count is within one PES of the total (no frame withheld).
        assert!(
            got + 8 >= real.len(),
            "no per-PES hold-back without dependents: {got} of {}",
            real.len()
        );
    }

    #[test]
    fn dts_frames_straddling_pes_boundaries_are_all_recovered() {
        let es = audio_es((0..CARRY_FRAMES).map(dts_frame).collect());
        for p in [
            &[3000][..],
            &[513],
            &[511],
            &[11],
            &[7],
            &[4],
            &[3],
            &[1],
            &[600, 13],
        ] {
            assert_carry_contract(
                &alloc::format!("dts {p:?}"),
                STREAM_TYPE_DTS_82,
                &es,
                0,
                512,
                p,
            );
        }
    }

    /// Current carry length of the audio PID, if it is a live audio track.
    fn carry_len(d: &StreamingTsDemux) -> Option<usize> {
        match d.streams.get(&ES_PID_UNDER_TEST)?.track.as_ref()? {
            TrackState::Live(LiveTrack {
                kind: LiveKind::Audio { anchor, .. },
                ..
            }) => Some(anchor.carry.len()),
            _ => None,
        }
    }

    /// Hostile input must not grow the carry: a header claiming the largest
    /// frame, then PES after PES of junk that never completes it, keeps the
    /// held bytes under one frame's worth ([`AUDIO_CARRY_MAX_BYTES`]) at every
    /// step — while proving the carry was genuinely exercised.
    #[test]
    fn carry_is_bounded_under_hostile_input() {
        // (label, stream type, valid warm-up frames, header claiming the
        // maximum frame, claimed length)
        let adts_max = {
            let mut h = crate::aac_asc::build_adts_header(1, 3, 2, 8191).to_vec();
            h.extend_from_slice(&body_bytes(7, 40));
            h
        };
        // Layer II 384 kbit/s @ 32 kHz: the largest MPEG audio frame, 1728 B.
        let mp2_max = {
            let mut h = alloc::vec![0xFF, 0xFD, 0xE8, 0x00];
            h.extend_from_slice(&body_bytes(8, 40));
            h
        };
        type HostileCase<'a> = (&'a str, u8, Vec<Vec<u8>>, Vec<u8>, usize);
        let cases: [HostileCase; 5] = [
            (
                "ac3",
                STREAM_TYPE_AC3,
                (0..4).map(ac3_frame).collect(),
                ac3_header(0xA5, 40),
                3840,
            ),
            (
                "eac3",
                STREAM_TYPE_EAC3,
                (0..4).map(eac3_frame).collect(),
                eac3_header(2047, 40),
                4096,
            ),
            (
                "dts",
                STREAM_TYPE_DTS_82,
                (0..4).map(dts_frame).collect(),
                dts_header(16_383, 40),
                16_384,
            ),
            (
                "adts",
                STREAM_TYPE_AAC_ADTS,
                (0..4).map(adts_frame).collect(),
                adts_max,
                8191,
            ),
            (
                "mp2",
                STREAM_TYPE_MPEG1_AUDIO,
                (0..4).map(mp2_frame).collect(),
                mp2_max,
                1728,
            ),
        ];
        for (label, stream_type, warm, header, claimed) in cases {
            assert!(claimed <= AUDIO_CARRY_MAX_BYTES);
            let mut ts = Vec::new();
            for _ in 0..mpeg_ts::resync::LOCK_CONFIRMATIONS + 1 {
                ts.extend_from_slice(&null_packet());
            }
            ts.extend_from_slice(&psi_section_packets(
                PAT_PID_UNDER_TEST,
                0,
                TABLE_ID_PAT,
                &pat_body(),
            ));
            ts.extend_from_slice(&psi_section_packets(
                PMT_PID_UNDER_TEST,
                0,
                TABLE_ID_PMT,
                &pmt_body(ES_PID_UNDER_TEST, stream_type),
            ));
            let mut cc = 0u8;
            let mut push = |ts: &mut Vec<u8>, payload: &[u8]| {
                let pes = pes_packet_untimed(ES_STREAM_ID_MPEG_AUDIO, payload);
                let pk = pes_packets(ES_PID_UNDER_TEST, cc, &pes);
                cc = cc.wrapping_add((pk.len() / TS_PACKET_SIZE) as u8);
                ts.extend_from_slice(&pk);
            };
            push(&mut ts, &warm.concat());
            push(&mut ts, &header);
            for i in 0..4000 {
                push(&mut ts, &body_bytes(1000 + i, 60));
            }

            let mut d = StreamingTsDemux::new();
            let mut max_carry = 0usize;
            for c in ts.chunks(TS_PACKET_SIZE) {
                d.feed(c);
                let n = carry_len(&d).unwrap_or(0);
                assert!(
                    n <= AUDIO_CARRY_MAX_BYTES,
                    "{label}: carry {n} exceeds the one-frame bound"
                );
                assert!(
                    n < claimed.max(4),
                    "{label}: carry {n} >= claimed frame {claimed}"
                );
                max_carry = max_carry.max(n);
            }
            d.finish();
            assert!(
                max_carry > 40,
                "{label}: the hostile tail must have actually been carried (max {max_carry})"
            );
        }
    }
}