mediadecode-ffmpeg 0.15.0

FFmpeg adapter for the `mediadecode` abstraction layer — implements its `VideoAdapter` / `AudioAdapter` / `SubtitleAdapter` traits and the matching push-style decoder traits, with hardware-acceleration auto-probe across VideoToolbox / VAAPI / NVDEC / D3D11VA and software fallback via ffmpeg-next.
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
//! [`mediadecode::demuxer::Demuxer`] impl backed by `libavformat`.
//!
//! Opens a container — from a path, or from any `Read + Seek` reader
//! through a custom `AVIOContext` — builds its track table once, and
//! then hands packets out one at a time in interleaved file order.
//!
//! The table is built at open and **kept for the life of the session**:
//! it is what every packet is classified against, so reading it takes
//! nothing away and may happen at any point. Rows are handed out as
//! `triomphe::Arc<TrackInfo<Ffmpeg>>` handles — see
//! [`Demuxer::TrackHandle`](mediadecode::demuxer::Demuxer::TrackHandle).
//!
//! A container's **table of contents** is read at that same moment and
//! kept the same way: `AVFormatContext.chapters`, mirrored into
//! [`Chapter`] rows and answered by
//! [`Demuxer::chapters`](mediadecode::demuxer::Demuxer::chapters). See
//! [`build_chapters`] for what is read, what is bounded before it is
//! allocated, and what is deliberately left as the container wrote it.
//!
//! # What normalization this layer does
//!
//! libavformat's track table is not quite the one the demux tier
//! promises, and the gap is entirely about attachments:
//!
//! - **Cover art is an attachment, not video.** A still image in an
//!   MP3, FLAC or MP4 arrives as a video stream carrying
//!   `AV_DISPOSITION_ATTACHED_PIC`. This layer maps it to
//!   [`TrackKind::Attachment`], so the `Video` arm carries true motion
//!   video and nothing else.
//! - **A font's bytes are not in the packet stream at all.** An
//!   `AVMEDIA_TYPE_ATTACHMENT` stream never produces a packet; its
//!   payload lives in `AVCodecParameters.extradata`. This layer
//!   synthesizes the packet at open time.
//! - **Cover art's packet is hoisted.** libavformat parks the real
//!   packet in `AVStream.attached_pic`; some demuxers also emit it in
//!   the packet stream, some do not. This layer takes it from
//!   `attached_pic` at open time and drops the duplicate if it ever
//!   arrives, so the count is exactly one either way.
//!
//! Both kinds are queued at open — every attachment track, without
//! exception, or the open fails. That is what makes the face's "exactly
//! one packet, before any timed packet" true *by construction* here:
//! the queue is complete and drains before the first `av_read_frame`
//! call ever runs, so no packet on an attachment track can be anything
//! but a duplicate, and no seek can move a packet that was never on the
//! timeline.
//!
//! # Seeking
//!
//! `seek` converts the target to `AV_TIME_BASE` units and calls
//! `avformat_seek_file` over the window `[i64::MIN, target]`, which is
//! FFmpeg's backward convention: the landing point is the nearest
//! keyframe at or before the target, never after. `avformat_seek_file`
//! flushes libavformat's own buffers; this layer clears the EOF latch
//! it set itself, and deliberately does **not** touch the attachment
//! bookkeeping — an attachment already handed out is never handed out
//! again, and one not yet handed out is still owed.

use std::collections::{TryReserveError, VecDeque};
use std::{
  ffi::{CStr, c_int},
  io::{Read, Seek},
  num::NonZeroI32,
  path::Path,
  ptr::{addr_of, read_unaligned},
  sync::Arc,
};

// **The track handle's refcount is triomphe's, not `std`'s**, for the
// reason [`crate::buffer`] gives at length: `std::sync::Arc::new`
// aborts when the allocator declines, and the number of these headers
// is the container's stream count. `triomphe::Arc::try_new` reports
// it. `std::sync::Arc` stays for the reader-panic latch, whose one
// allocation is per session rather than per stream.
use triomphe::Arc as TrackArc;

use derive_more::{IsVariant, TryUnwrap, Unwrap};
use ffmpeg_next::{
  Packet, Rational,
  ffi::{
    AV_DISPOSITION_ATTACHED_PIC, AV_DISPOSITION_TIMED_THUMBNAILS, AV_NOPTS_VALUE, AVDictionary,
    AVStream, av_dict_get,
  },
  format::{self, context::Input},
};
use mediadecode::{
  Timebase, Timestamp,
  demuxer::{
    AttachmentPacket, AttachmentTrackPacket, AttachmentTrackParams, AudioTrackPacket,
    AudioTrackParams, Chapter, DataTrackPacket, DataTrackParams, DemuxedPacket, Demuxer,
    SubtitleTrackPacket, SubtitleTrackParams, TrackIndex, TrackInfo, TrackKind, TrackParams,
    UnknownTrackParams, VideoTrackPacket, VideoTrackParams,
  },
};
use smol_bytes::Utf8Bytes;

use crate::{
  Ffmpeg, boundary,
  buffer::PacketBufferError,
  codec_id::CodecId,
  extras::{AttachmentPacketExtra, TrackExtra},
  limits::DemuxLimits,
  reader_guard::{GuardedReader, PanicLatch},
  sample_format::SampleFormat,
};

/// One microsecond — the timebase `avformat_seek_file` expects when no
/// reference stream is named (`stream_index == -1`).
fn av_time_base_q() -> Timebase {
  Timebase::new(1, NonZeroI32::new(1_000_000).expect("1e6 is non-zero"))
}

/// `mediadecode::demuxer::Demuxer` impl wrapping `ffmpeg::format::context::Input`.
///
/// Construction is deliberately not on the trait — see [`Self::open`]
/// and [`Self::open_reader`].
pub struct CarrierDemuxer<C: crate::FfmpegCarrier> {
  input: Input,
  /// The track table, built once at open and held for the life of the
  /// session — **this is the table `next_packet` classifies against**,
  /// so nothing may take it away.
  ///
  /// Rows are `Arc`-wrapped at the door rather than by each consumer:
  /// [`TrackInfo`] is not `Clone` (the message-carrier law), so a
  /// consumer that needs a row past a borrow of this session needs a
  /// shared handle, and one allocation per track at open is the whole
  /// cost of every fan-out afterwards. `Arc` and not `Rc` because
  /// [`CodecTicket`](crate::ticket::CodecTicket) made these rows
  /// `Send + Sync` by construction precisely so a track table could
  /// cross tasks.
  tracks: Vec<TrackArc<TrackInfo<Ffmpeg>>>,
  /// The container's table of contents, mirrored once at open and held
  /// for the life of the session — see [`build_chapters`].
  ///
  /// Not `Arc`-wrapped, unlike the track rows above, and for the
  /// reason [`Chapter`] gives: a chapter is four scalars and a title,
  /// so a consumer that wants one past a borrow of this session clones
  /// the row itself and there is no carrier choice worth making.
  ///
  /// Empty for the overwhelming majority of files — nothing allocates
  /// where a container declares no chapters.
  chapters: Vec<Chapter<Ffmpeg>>,
  /// What libavformat decided the bytes are wrapped in, read once at
  /// open — see [`CarrierDemuxer::format`].
  ///
  /// Held rather than re-derived because it is a property of the
  /// session: `avformat_open_input` picks the demuxer and never changes
  /// it, so the answer cannot move and a second read could only cost
  /// more. `None` only where libavformat left `iformat` null or its
  /// name is not readable text — neither of which a successful open
  /// produces.
  format: Option<crate::ContainerFormat>,
  pending: VecDeque<(
    TrackIndex,
    AttachmentPacket<AttachmentPacketExtra, C::Buffer>,
  )>,
  /// `true` once this session has answered `Ok(None)`. Only then does
  /// [`Self::seek`] clear the `AVIOContext`'s EOF latch — clearing it
  /// unconditionally would also erase a genuine sticky I/O error, which
  /// `Input::seek` goes out of its way to preserve.
  eof: bool,
  /// `true` once this session has reported a packet whose stream the
  /// track table does not describe.
  ///
  /// The diagnostic is **once per session, not once per packet**. A
  /// format that adds an `AVStream` mid-read (`AVFMTCTX_NOHEADER`:
  /// MPEG-TS, RTP) then delivers packets on it at the wire's own rate,
  /// and a line each would be an unbounded log on healthy input — a
  /// live stream could fill a disk with it. One line names the
  /// condition; the rest of the session stays quiet. Never cleared,
  /// including across a seek: it records that this session has said
  /// its piece, which a seek does not undo.
  unplaceable_reported: bool,
  /// Set for a session opened over a caller's reader: where a panic
  /// raised inside that reader is recorded. `None` for a path-opened
  /// session, which runs no caller code.
  reader_panic: Option<Arc<PanicLatch>>,
  /// The budgets this session spends: on any one timed packet, and —
  /// already spent, at open — on the file's attachments.
  limits: DemuxLimits,
  /// A packet `av_read_frame` has already handed over and whose
  /// conversion has **not committed**, with the provenance that was
  /// observed for it.
  ///
  /// `av_read_frame` advances the container: once it returns, that
  /// packet is off the wire and nothing brings it back. A conversion
  /// that then fails on an *allocation* — a refcount the view lane
  /// could not take, a copy the middle row could not make — used to
  /// drop it, leaving a live session that answered the next pull with
  /// the **following** packet. Compressed data and subtitle cues went
  /// missing under memory pressure, quietly.
  ///
  /// So the read and the conversion are one transaction with a seat
  /// between them: a transient refusal parks the packet here and the
  /// next pull re-attempts *this* packet before reading another. It is
  /// the same park-then-replay the decode household already runs —
  /// `CarrierVideoStreamDecoder` holds `sw_replay_frames`, and the
  /// probe holds its rescue history — for the same reason: a byte C
  /// has already given up is not re-askable.
  ///
  /// The provenance is parked **with** the packet rather than re-probed
  /// on replay. It is an observation about the moment of delivery, and
  /// a queue that has moved on could answer it differently.
  unconverted: Option<(Packet, crate::buffer::PayloadProvenance)>,
}

// The generic bodies. Crate-private, because their bound is: they are
// the implementation, and the public faces below are written per lane
// so that no signature a consumer reads names a trait they cannot.
impl<C: crate::FfmpegCarrier + crate::CarrierOps> CarrierDemuxer<C> {
  /// Opens a container from a filesystem path.
  ///
  /// Runs `avformat_open_input` followed by
  /// `avformat_find_stream_info`, then builds the track table and
  /// captures every attachment payload.
  ///
  /// Call [`ffmpeg_next::init`] once before the first open if you want
  /// FFmpeg's logging and network protocols configured; probing a local
  /// container does not require it.
  pub(crate) fn open_impl<P: AsRef<Path> + ?Sized>(path: &P) -> Result<Self, DemuxError> {
    Self::open_with_impl(path, DemuxLimits::default())
  }

  /// [`Self::open`], with the session's resource budgets named.
  ///
  /// The budgets are taken **at open** rather than through a `with_*`
  /// builder because the attachment half of them is spent here: every
  /// attachment payload in the file is captured before this call
  /// returns, which is what makes the demux tier's "exactly one packet,
  /// before any timed packet" contract true by construction. A budget
  /// set afterwards would arrive after the spending.
  ///
  /// A file whose attachments exceed the budget **fails to open**, with
  /// [`DemuxError::AttachmentTooLarge`] or
  /// [`DemuxError::AttachmentBudgetExhausted`] naming the track that
  /// crossed the line.
  pub(crate) fn open_with_impl<P: AsRef<Path> + ?Sized>(
    path: &P,
    limits: DemuxLimits,
  ) -> Result<Self, DemuxError> {
    // **The probe knobs, set before libavformat reads a byte.** See
    // [`DemuxLimits::max_probe_bytes`]: `avformat_open_input` and
    // `avformat_find_stream_info` build the attachment, extradata and
    // coded-side-data buffers themselves, so every budget that measures
    // *this crate's* copies arrives after the original allocation. The
    // instrument that reaches behind that is the one bounding what the
    // parser is handed in the first place.
    //
    // On this entrypoint that is `probesize` / `formatprobesize` /
    // `max_streams` only: the hard byte meter needs an `AVIOContext`
    // this crate owns, and a path is opened by libavformat's own
    // protocol layer. The reader entrypoint gets both.
    Self::from_input(
      format::input_with_dictionary(path, probe_options(limits))?,
      limits,
    )
  }

  /// Opens a container from any `Read + Seek` byte source, through a
  /// custom `AVIOContext`.
  ///
  /// `Seek` is mandatory and not negotiable: MP4 files routinely put
  /// `moov` at the end, so a reader that cannot go backwards cannot be
  /// probed at all — and the seek law on the face would be
  /// unimplementable.
  ///
  /// `filename` is a probe hint, not a path: libavformat uses its
  /// extension to break ties between formats whose byte signatures are
  /// ambiguous. Pass `None` when there is nothing to hint with.
  ///
  /// # A panicking reader
  ///
  /// libavformat drives the reader from `extern "C"` callbacks, where a
  /// panic would abort the process rather than unwind. Every call into
  /// `reader` therefore runs under `catch_unwind`: a panic becomes an
  /// I/O error for libavformat and surfaces here — or from the next
  /// [`next_packet`](Demuxer::next_packet) / [`seek`](Demuxer::seek) —
  /// as [`DemuxError::ReaderPanic`], carrying the panic's message. The
  /// session is terminal from that point: the `AVIOContext`'s error
  /// state is sticky and the reader's own state is unknown.
  pub(crate) fn open_reader_impl<R: Read + Seek + Send + 'static>(
    reader: R,
    filename: Option<&str>,
  ) -> Result<Self, DemuxError> {
    Self::open_reader_with_impl(reader, filename, DemuxLimits::default())
  }

  /// [`Self::open_reader`], with the session's resource budgets named.
  /// See [`Self::open_with`] for why they are taken at open.
  pub(crate) fn open_reader_with_impl<R: Read + Seek + Send + 'static>(
    reader: R,
    filename: Option<&str>,
    limits: DemuxLimits,
  ) -> Result<Self, DemuxError> {
    let (guarded, latch, meter) = GuardedReader::new(reader, limits.max_probe_bytes());
    let io = format::context::StreamIo::from_read_seek(guarded)?;
    let input =
      format::input_from_stream(io, filename, Some(probe_options(limits))).map_err(|e| {
        // Three ways this can fail, and they must not be confused: a
        // panicked reader, a probe budget reached, or libavformat's own
        // verdict. The meter is consulted before the errno because
        // libavformat folds the reader's I/O error into whatever it was
        // doing at the time — usually "invalid data" — which would
        // report a refusal this crate made as a malformed file.
        reader_panic(&latch)
          .or_else(|| {
            meter.tripped().then(|| {
              DemuxError::ProbeBudgetExhausted(ProbeBudgetExhausted::new(
                meter.read(),
                meter.budget(),
              ))
            })
          })
          .unwrap_or(DemuxError::Ffmpeg(e))
      })?;
    if meter.tripped() {
      return Err(DemuxError::ProbeBudgetExhausted(ProbeBudgetExhausted::new(
        meter.read(),
        meter.budget(),
      )));
    }
    // Open and analysed: the seat bounds *probing*, and reading the
    // media itself afterwards is the caller's business, packet by
    // packet, already bounded by the packet seats.
    meter.release();
    // A panic libavformat tolerated (a failed probe it recovered from)
    // still poisoned the reader; the session must not open over it.
    if let Some(panicked) = reader_panic(&latch) {
      return Err(panicked);
    }
    let mut demuxer = Self::from_input(input, limits)?;
    demuxer.reader_panic = Some(latch);
    Ok(demuxer)
  }

  /// Borrows the wrapped `ffmpeg::format::context::Input` — for
  /// `av_dump_format`, container-level metadata, and anything else the
  /// portable track and chapter tables have no seat for.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(crate) const fn input_impl(&self) -> &Input {
    &self.input
  }

  /// The budgets this session was opened with.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(crate) const fn limits_impl(&self) -> DemuxLimits {
    self.limits
  }

  /// What libavformat decided this session's bytes are wrapped in.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(crate) const fn format_impl(&self) -> Option<&crate::ContainerFormat> {
    self.format.as_ref()
  }

  fn from_input(input: Input, limits: DemuxLimits) -> Result<Self, DemuxError> {
    // **Everything the container declares is judged before anything it
    // declares is paid for**, and that is a property of the *whole*
    // open rather than of either table.
    //
    // The order is: [`admit_chapters`] here, then [`admit_streams`] as
    // `build_tracks`' first statement, and only then a reservation. Both
    // passes allocate nothing — they read integers, and price metadata
    // through a borrow of libavutil's own buffer — so every budgeted
    // quantity this open can refuse is refused while the process has
    // spent nothing on the file.
    //
    // The class, stated once so it can be checked rather than
    // rediscovered: probe bytes are metered during the read;
    // `max_streams` is libavformat's own option, set before the header
    // is parsed; per-stream and whole-file codec parameters — which
    // includes extradata, every coded-side-data payload and a custom
    // channel map, all through
    // [`measure_parameters`](crate::extras::measure_parameters) — the
    // per-attachment and whole-file attachment payloads, and the
    // whole-file stream metadata are charged by `admit_streams`; the
    // chapter count and the chapter titles by `admit_chapters`; and a
    // single metadata value is bounded by [`metadata_value`]'s own
    // walk, which stops at [`METADATA_VALUE_MAX_BYTES`] rather than
    // reading past it. Three rounds of review found three instances of
    // one defect here — a correct check placed after the memory it was
    // meant to protect — which is why the list is written down.
    admit_chapters(&input, limits)?;
    let (tracks, pending) = build_tracks::<C>(&input, limits)?;
    // One allocation per track, here and never again: the session
    // keeps these handles and hands out clones of them.
    //
    // The table is reserved fallibly and so is each row's handle:
    // `triomphe::Arc::try_new` reports an allocator refusal where
    // `std::sync::Arc::new` would abort, and the count is the
    // container's. See [`crate::buffer`] for why this crate's
    // refcount is triomphe's.
    let count = tracks.len();
    let mut handles: Vec<TrackArc<TrackInfo<Ffmpeg>>> = Vec::new();
    handles
      .try_reserve_exact(count)
      .map_err(|_| DemuxError::TrackTableAlloc(TrackTableAlloc::new(count)))?;
    for row in tracks {
      handles.push(
        TrackArc::try_new(row)
          .map_err(|_| DemuxError::TrackTableAlloc(TrackTableAlloc::new(count)))?,
      );
    }
    let tracks = handles;
    // The chapter table is read here for the same reason the track
    // table is: `avformat_find_stream_info` has run, so the container's
    // answer is final and a session that holds it can be asked at any
    // point without touching the file again.
    let chapters = build_chapters(&input, limits)?;
    // SAFETY: `input` owns a live `AVFormatContext` for the whole of
    // this call, and the read takes copies of the two static-table
    // strings rather than borrowing from it.
    let format = unsafe { crate::ContainerFormat::from_context(input.as_ptr()) };
    Ok(Self {
      input,
      tracks,
      chapters,
      format,
      pending,
      unconverted: None,
      eof: false,
      unplaceable_reported: false,
      reader_panic: None,
      limits,
    })
  }

  /// The error a panicked reader owes this session, if one panicked.
  fn panicked(&self) -> Option<DemuxError> {
    self.reader_panic.as_deref().and_then(reader_panic)
  }
}

/// The libavformat options this crate sets before a container is
/// opened.
///
/// Passed as an `AVDictionary` because that is the only route to these
/// fields that works for both entrypoints: `avformat_open_input`
/// applies the dictionary to the context it allocates itself, and the
/// same names reach the context behind a custom `AVIOContext`.
///
/// * `probesize` / `formatprobesize` bound what the format probe and
///   the stream analysis are allowed to consume;
/// * `max_streams` bounds the `AVStream` array a header can conjure —
///   a container claiming a hundred thousand streams is an allocation
///   this crate's per-track budgets are downstream of.
fn probe_options(limits: DemuxLimits) -> ffmpeg_next::Dictionary<'static> {
  let mut options = ffmpeg_next::Dictionary::new();
  let probe = limits.max_probe_bytes().to_string();
  options.set("probesize", &probe);
  options.set("formatprobesize", &probe);
  options.set("max_streams", &limits.max_streams().to_string());
  options
}

/// Payload for [`DemuxError::ProbeBudgetExhausted`].
///
/// libavformat wanted more of the file than the probe budget allows.
///
/// # What this bounds
///
/// This is the only seat in the crate that reaches *behind*
/// libavformat: `avformat_open_input` and `avformat_find_stream_info`
/// build the attached picture, the extradata and the coded side data
/// out of the file themselves, so every budget measuring this crate's
/// own copies necessarily arrives after those allocations happened.
///
/// A parser cannot allocate from bytes it was never handed, so the
/// input is bounded instead. What is **not** bounded is amplification
/// inside a parser — a container can describe, in a few bytes, a
/// structure whose in-memory form is far larger, and nothing outside
/// libavformat can observe that. Bounding the output of that is the
/// substrate's own hardening territory; FFmpeg keeps `max_streams`,
/// `max_index_size` and `max_picture_buffer` for it, and this crate
/// sets the first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("libavformat read {read} bytes probing the container, over a budget of {budget}")]
pub struct ProbeBudgetExhausted {
  read: u64,
  budget: u64,
}

impl ProbeBudgetExhausted {
  /// Constructs a `ProbeBudgetExhausted` payload.
  #[inline]
  pub const fn new(read: u64, budget: u64) -> Self {
    Self { read, budget }
  }
  /// Bytes libavformat was handed before the budget was reached.
  #[inline]
  pub const fn read(&self) -> u64 {
    self.read
  }
  /// The budget in force.
  #[inline]
  pub const fn budget(&self) -> u64 {
    self.budget
  }
}

/// Turns a latched reader panic into the error that names it.
fn reader_panic(latch: &PanicLatch) -> Option<DemuxError> {
  latch
    .message()
    .map(|message| DemuxError::ReaderPanic(ReaderPanic::new(message)))
}

impl<C: crate::FfmpegCarrier + crate::CarrierOps> CarrierDemuxer<C> {
  pub(crate) fn tracks_impl(&self) -> &[TrackArc<TrackInfo<Ffmpeg>>] {
    &self.tracks
  }

  pub(crate) fn chapters_impl(&self) -> &[Chapter<Ffmpeg>] {
    &self.chapters
  }

  pub(crate) fn next_packet_impl(
    &mut self,
  ) -> Result<Option<DemuxedPacket<Ffmpeg, C::Buffer>>, DemuxError> {
    // A latched reader panic is terminal, and terminal starts here. The
    // queue is filled at open and owes nothing to the reader, so a pull
    // that drained it would answer `Ok` to a caller the session has
    // already told the truth to — `seek` can latch a panic while
    // attachments are still queued.
    if let Some(panicked) = self.panicked() {
      return Err(panicked);
    }

    // The attachment queue drains first and drains completely, which is
    // the whole of "exactly one packet, before any timed packet": no
    // `av_read_frame` has run yet when the last one leaves.
    if let Some((track, packet)) = self.pending.pop_front() {
      return Ok(Some(DemuxedPacket::Attachment(AttachmentTrackPacket::new(
        track, packet,
      ))));
    }

    loop {
      // **A parked packet is re-attempted before another is read.**
      // See [`Self::unconverted`]: `av_read_frame` has already given
      // this one up, so reading past it would lose it.
      let (packet, parked_provenance) = match self.unconverted.take() {
        Some((packet, provenance)) => (packet, Some(provenance)),
        None => {
          let mut packet = Packet::empty();
          let read = packet.read(&mut self.input);
          // A panicking reader reported an ordinary I/O error to C, and
          // libavformat may answer that with the error, with EOF (a
          // stream it cannot read looks finished), or with a packet it
          // had already buffered. None of those are the file's word, so
          // the latch is consulted whatever the outcome was.
          if let Some(panicked) = self.panicked() {
            return Err(panicked);
          }
          match read {
            Ok(()) => {}
            Err(ffmpeg_next::Error::Eof) => {
              self.eof = true;
              return Ok(None);
            }
            // A demuxer can resync past a corrupt packet, and
            // `AVERROR_INVALIDDATA` is not latched into the
            // `AVIOContext`, so reading again makes progress. Every
            // other error is sticky and is surfaced.
            Err(ffmpeg_next::Error::InvalidData) => continue,
            Err(e) => return Err(DemuxError::Ffmpeg(e)),
          }
          (packet, None)
        }
      };

      let index = packet.stream();
      // A packet for a stream the table does not describe cannot be
      // placed, so it is passed by — the same answer the `Unknown` arm
      // below gives a track nothing can name.
      //
      // **Neither an assertion nor an error.** The arm is reachable on
      // healthy input: a format flagged `AVFMTCTX_NOHEADER` — MPEG-TS,
      // RTP and the rest that carry no up-front stream list — may add
      // an `AVStream` in the middle of `av_read_frame`, and this
      // session's table was fixed at open, which is the contract
      // `TrackIndex` needs (position in `tracks()`, dense and stable
      // for the life of the session). A `debug_assert` would fire on a
      // transport stream, and an `Err` would end a session over a
      // stream the caller never asked about.
      //
      // It is no longer the *every* packet path. It was, for one
      // release: the take-the-table door emptied this very `Vec`, so
      // every index fell out of range at once and a healthy file
      // demuxed to nothing (issue #51). The table cannot be taken
      // away any more; what is left here is the genuinely
      // out-of-range index the arm was written for. Reported rather
      // than silent, because silence is what made the old failure
      // invisible — and reported **once**, because the very case that
      // makes the arm reachable is a live stream that would otherwise
      // log a line per packet for as long as it runs. See
      // [`Self::unplaceable_reported`].
      let Some(info) = self.tracks.get(index) else {
        if !self.unplaceable_reported {
          self.unplaceable_reported = true;
          tracing::debug!(
            stream = index,
            tracks = self.tracks.len(),
            "demux: no track row describes this packet's stream; passing it and any further \
             such packet by, without repeating this line",
          );
        }
        continue;
      };
      let track = TrackIndex::new(index);
      let time_base = info.timebase();

      // A payload that is there and cannot be referenced is an error,
      // never a silently dropped packet: `Ok(None)` below means the
      // packet carried nothing, and that is the only thing that reads
      // the next one.
      // **Everything this loop delivers is demux-delivered**, whatever
      // its refcount: libavformat just handed it over, so any other
      // reference to its buffer is libavformat's own and no
      // `ffmpeg_next::Packet` wraps one. That is not the hazard a
      // caller's second handle is — see
      // [`crate::buffer::PayloadProvenance`].
      //
      // Sharing is ordinary here. A queue-backed demuxer — SubRip,
      // SubViewer and the rest of the `FFDemuxSubtitlesQueue` family —
      // keeps its parsed cues and delivers `av_packet_ref`s of them,
      // so *every* packet it produces arrives with two references.
      //
      // The one sub-case that is stronger still is the container's
      // parked picture, which a stream carrying
      // `ATTACHED_PIC | TIMED_THUMBNAILS` delivers as its first packet:
      // written once while the container opened, so the view lane may
      // window it rather than copy. See [`is_streams_attached_pic`] for
      // the identity proof.
      //
      // SAFETY: both the session's `AVFormatContext` and `packet` are
      // live here.
      let provenance = match parked_provenance {
        // Observed when this packet was delivered, and kept with it.
        Some(provenance) => provenance,
        None if unsafe { is_streams_attached_pic(&self.input, index, &packet) } => {
          crate::buffer::PayloadProvenance::AttachedPicture
        }
        None => crate::buffer::PayloadProvenance::DemuxDelivered,
      };

      // The packet this loop just read is **handed over**, not lent: the
      // view lane's carrier is a window into its buffer, and a source
      // that survived the conversion would be a mutable alias of it.
      // Exactly one arm runs, so exactly one move happens.
      // **The conversion borrows what this session owns.** The packet
      // stays in hand until the carrier exists, which is what lets a
      // failure park it instead of dropping it; on success it falls out
      // of scope at the end of the iteration and the carrier keeps its
      // buffer alive by refcount, exactly as when the conversion
      // consumed it. Nothing outside this loop ever sees the packet, so
      // the borrow cannot become the aliasing shape the public faces
      // refuse.
      let converted = match info.kind() {
        TrackKind::Video => boundary::video_packet_from_borrowed::<C>(
          &packet,
          time_base,
          self.limits.packet(),
          provenance,
        )
        .map(|built| built.map(|p| DemuxedPacket::Video(VideoTrackPacket::new(track, p)))),
        TrackKind::Audio => boundary::audio_packet_from_borrowed::<C>(
          &packet,
          time_base,
          self.limits.packet(),
          provenance,
        )
        .map(|built| built.map(|p| DemuxedPacket::Audio(AudioTrackPacket::new(track, p)))),
        TrackKind::Subtitle => boundary::subtitle_packet_from_borrowed::<C>(
          &packet,
          time_base,
          self.limits.packet(),
          provenance,
        )
        .map(|built| built.map(|p| DemuxedPacket::Subtitle(SubtitleTrackPacket::new(track, p)))),
        TrackKind::Data => boundary::data_packet_from_borrowed::<C>(
          &packet,
          time_base,
          self.limits.packet(),
          provenance,
        )
        .map(|built| built.map(|p| DemuxedPacket::Data(DataTrackPacket::new(track, p)))),
        // Every attachment track's one packet was queued at open time,
        // so anything arriving on one now is the duplicate some
        // demuxers emit for cover art. Drop it — the contract is
        // exactly one, and the one has already left. Nothing is
        // converted here, so there is nothing to park.
        TrackKind::Attachment => continue,
        // The roster of arms is five; a track nothing can name has no
        // arm and its packets are not delivered.
        TrackKind::Unknown => continue,
      };

      let built = match converted {
        Ok(built) => built,
        Err(source) => {
          // **Park a refusal that another attempt could survive.** An
          // allocation that failed says nothing about the packet, and
          // the packet is off the wire either way. Anything else is a
          // fact about the packet itself — a malformed one is not made
          // well-formed by retrying, and parking it would answer every
          // later pull with the same error instead of letting the
          // session make progress.
          if source.parks_in_demux() {
            self.unconverted = Some((packet, provenance));
          }
          return Err(DemuxError::PacketBuffer(PacketBuffer::new(index, source)));
        }
      };

      // `None` here means the packet carried no payload — an empty
      // packet, which some demuxers emit as a marker. Nothing to
      // deliver; read the next one.
      if let Some(out) = built {
        return Ok(Some(out));
      }
    }
  }

  pub(crate) fn seek_impl(&mut self, target: Timestamp) -> Result<(), DemuxError> {
    let ts = target.rescale_to(av_time_base_q()).pts();
    // Only our own EOF latch is cleared, and only before the seek —
    // the seek machinery gates on `eof_reached`, so clearing it
    // afterwards would be too late.
    if self.eof {
      self.input.clear_eof();
      self.eof = false;
    }
    // `..ts` is how ffmpeg-next spells the seek window: it reads only
    // the endpoint, and `avformat_seek_file`'s `max_ts` is inclusive,
    // so the window is `[i64::MIN, ts]`. FFmpeg picks the closest seek
    // point inside it — the nearest keyframe at or before the target.
    // Never after: a decoder started past the target has no reference
    // frame.
    let sought = self.input.seek(ts, ..ts);
    if let Some(panicked) = self.panicked() {
      return Err(panicked);
    }
    sought?;
    // **The seat is cleared by a seek that happened, not by one that
    // was attempted.** A parked packet belongs to the position the
    // session is leaving, so a successful seek discards it. A *failed*
    // one leaves the session where it was — and that packet is off the
    // wire, so dropping it here would be the same silent loss the seat
    // exists to prevent, with no re-read able to recover it.
    //
    // FFmpeg does not specify where a container sits after a seek that
    // returned an error, and this crate does not guess: it keeps a
    // packet the container really did deliver, and a caller who saw the
    // seek fail already knows the position is not the one they asked
    // for. Every timestamp needed to tell is on the packet.
    self.unconverted = None;
    Ok(())
  }
}

macro_rules! demuxer_lane_face {
  ($($lane:ty),+ $(,)?) => { $(
    impl CarrierDemuxer<$lane> {
      /// Opens a container from a filesystem path.
      ///
      /// Runs `avformat_open_input` followed by
      /// `avformat_find_stream_info`, then builds the track table and
      /// captures every attachment payload.
      ///
      /// Call [`ffmpeg_next::init`] once before the first open if you
      /// want FFmpeg's logging and network protocols configured;
      /// probing a local container does not require it.
      pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> Result<Self, DemuxError> {
        Self::open_impl(path)
      }

      /// [`Self::open`], with the session's resource budgets named.
      ///
      /// The budgets are taken **at open** rather than through a
      /// `with_*` builder because the attachment half of them is spent
      /// here: every attachment payload is captured during this call.
      pub fn open_with<P: AsRef<Path> + ?Sized>(
        path: &P,
        limits: DemuxLimits,
      ) -> Result<Self, DemuxError> {
        Self::open_with_impl(path, limits)
      }

      /// Opens a container from any `Read + Seek` source.
      pub fn open_reader<R: Read + Seek + Send + 'static>(
        reader: R,
        url: Option<&str>,
      ) -> Result<Self, DemuxError> {
        Self::open_reader_impl(reader, url)
      }

      /// [`Self::open_reader`], with the session's budgets named.
      pub fn open_reader_with<R: Read + Seek + Send + 'static>(
        reader: R,
        url: Option<&str>,
        limits: DemuxLimits,
      ) -> Result<Self, DemuxError> {
        Self::open_reader_with_impl(reader, url, limits)
      }

      /// The wrapped `AVFormatContext`.
      pub const fn input(&self) -> &Input {
        self.input_impl()
      }

      /// The budgets this session was opened with.
      pub const fn limits(&self) -> DemuxLimits {
        self.limits_impl()
      }

      /// **What the container IS**, as libavformat identified it from
      /// the bytes — the demuxer it chose, with the short names that
      /// demuxer handles and its description.
      ///
      /// Decided during the open and fixed for the life of the
      /// session, so this answers the same thing at any point and
      /// costs nothing to ask.
      ///
      /// `None` only where libavformat left `iformat` null or its name
      /// is not readable text; neither happens on a session that
      /// opened successfully.
      ///
      /// **Nothing here looked at a path.** A file's extension is a
      /// claim about its bytes, and this is a reading of them — which
      /// is what makes the answer usable on a content-addressed row,
      /// where the same bytes under two names are one content. See
      /// [`ContainerFormat`](crate::ContainerFormat) for what the
      /// demuxer's name does and does not narrow to.
      pub const fn format(&self) -> Option<&crate::ContainerFormat> {
        self.format_impl()
      }
    }

    impl Demuxer for CarrierDemuxer<$lane> {
      type Adapter = Ffmpeg;
      type Buffer = <$lane as crate::FfmpegCarrier>::Buffer;
      type TrackHandle = TrackArc<TrackInfo<Ffmpeg>>;
      type Error = DemuxError;

      /// The track table, held for the life of the session.
      ///
      /// Reading it takes nothing away — clone the handles worth
      /// keeping. `Arc` is the carrier because
      /// [`CodecTicket`](crate::ticket::CodecTicket) mirrors an
      /// `AVCodecParameters` into owned Rust, which is what makes a
      /// row `Send + Sync` and a table shareable across tasks.
      fn tracks(&self) -> &[TrackArc<TrackInfo<Ffmpeg>>] {
        self.tracks_impl()
      }

      /// The container's chapter table, in the order
      /// `AVFormatContext.chapters` holds it, mirrored at open and
      /// held for the life of the session.
      ///
      /// Empty where the file declares no chapters — which is the
      /// provided answer too, so the override changes nothing for a
      /// container that has none.
      ///
      /// **Nothing is repaired.** A chapter whose `end` precedes its
      /// `start`, and one whose end libavformat left at its
      /// no-timestamp sentinel because the file declared none, are
      /// mirrored exactly as written; see [`Chapter`] for why this
      /// layer reports rather than clamps.
      fn chapters(&self) -> &[Chapter<Ffmpeg>] {
        self.chapters_impl()
      }

      /// Pulls the next packet.
      ///
      /// **A refusal that another attempt could survive costs no
      /// packet.** `av_read_frame` advances the container, so a
      /// conversion that then fails on an allocation would otherwise
      /// drop bytes nothing can ask for again. Such a packet is parked
      /// instead, and this method re-attempts *it* before reading
      /// another — so a caller who pulls again loses nothing. A refusal
      /// about the packet itself is not parked: retrying a malformed
      /// packet forever would be worse than passing it by.
      fn next_packet(
        &mut self,
      ) -> Result<Option<DemuxedPacket<Ffmpeg, Self::Buffer>>, DemuxError> {
        self.next_packet_impl()
      }

      fn seek(&mut self, target: Timestamp) -> Result<(), DemuxError> {
        self.seek_impl(target)
      }
    }
  )+ };
}

demuxer_lane_face!(crate::View, crate::Owned);

/// Payload for [`DemuxError::AttachmentTooLarge`].
///
/// One attachment's payload exceeds
/// [`DemuxLimits::max_attachment_bytes`].
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the attachment on stream {stream_index} is {bytes} bytes, over the {limit}-byte per-attachment budget"
)]
pub struct AttachmentTooLarge {
  stream_index: usize,
  bytes: usize,
  limit: usize,
}

impl AttachmentTooLarge {
  /// Constructs an `AttachmentTooLarge` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, bytes: usize, limit: usize) -> Self {
    Self {
      stream_index,
      bytes,
      limit,
    }
  }
  /// The `AVStream.index` carrying the oversized attachment.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The attachment's payload length.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
  /// The per-attachment budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::AttachmentBudgetExhausted`].
///
/// The file's attachments, together, exceed
/// [`DemuxLimits::max_total_attachment_bytes`].
///
/// Separate from [`AttachmentTooLarge`] because it is a different
/// attack: every attachment can be modest and there can still be four
/// hundred of them. This arm names the track that ran the total past
/// the line, not the track that was individually at fault — there
/// need not be one.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the attachment on stream {stream_index} brings the file's attachments to {total} bytes, over the {limit}-byte budget"
)]
pub struct AttachmentBudgetExhausted {
  stream_index: usize,
  total: usize,
  limit: usize,
}

impl AttachmentBudgetExhausted {
  /// Constructs an `AttachmentBudgetExhausted` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, total: usize, limit: usize) -> Self {
    Self {
      stream_index,
      total,
      limit,
    }
  }
  /// The `AVStream.index` whose attachment crossed the line.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The running total, including this attachment.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn total(&self) -> usize {
    self.total
  }
  /// The whole-file budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::ParametersTooLarge`].
///
/// One stream's codec parameters hold more heap bytes than
/// [`DemuxLimits::max_codec_parameter_bytes`] allows.
///
/// The bytes are `extradata` plus every `coded_side_data` entry plus a
/// custom channel map — the three seats `AVCodecParameters` reaches the
/// heap through. A MOV `prof` atom lands in the second of those as an
/// ICC profile, which is where the honest large values live and where
/// the forged ones do too.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the codec parameters on stream {stream_index} hold {bytes} heap bytes, over the {limit}-byte budget"
)]
pub struct ParametersTooLarge {
  stream_index: usize,
  bytes: usize,
  limit: usize,
}

impl ParametersTooLarge {
  /// Constructs a `ParametersTooLarge` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, bytes: usize, limit: usize) -> Self {
    Self {
      stream_index,
      bytes,
      limit,
    }
  }
  /// The `AVStream.index` whose parameters were refused.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The heap bytes the parameters declared.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
  /// The budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::ParametersBudgetExhausted`].
///
/// Every stream's codec parameters, together, hold more heap bytes than
/// [`DemuxLimits::max_total_codec_parameter_bytes`] allows.
///
/// A separate attack from [`ParametersTooLarge`], and separate for the
/// same reason the attachment pair are: each stream's parameters can be
/// individually modest and a container can still declare two hundred
/// streams. The arm names the stream that ran the total past the line,
/// which need not be one that was individually at fault.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the codec parameters on stream {stream_index} bring the file's to {total} heap bytes, over the {limit}-byte budget"
)]
pub struct ParametersBudgetExhausted {
  stream_index: usize,
  total: usize,
  limit: usize,
}

impl ParametersBudgetExhausted {
  /// Constructs a `ParametersBudgetExhausted` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, total: usize, limit: usize) -> Self {
    Self {
      stream_index,
      total,
      limit,
    }
  }
  /// The `AVStream.index` whose parameters crossed the line.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The running total, including this stream.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn total(&self) -> usize {
    self.total
  }
  /// The whole-file budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::ParametersMissing`].
///
/// Codec parameters arrived that were never allocated.
///
/// `ffmpeg_next::codec::Parameters` has safe constructors that hand
/// back a null-backed value when FFmpeg's allocation failed, and they
/// report nothing. Copying from one dereferences null, so it is
/// refused where it arrives — at construction, and again in the
/// copier — rather than crashing later somewhere that has forgotten
/// the allocator ever failed.
#[derive(thiserror::Error, Debug, Clone)]
#[error("the codec parameters for stream {stream_index} were never allocated")]
pub struct ParametersMissing {
  stream_index: usize,
}

impl ParametersMissing {
  /// Constructs a `ParametersMissing` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize) -> Self {
    Self { stream_index }
  }
  /// The `AVStream.index` the parameters were offered for.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
}

/// Payload for [`DemuxError::ParametersAlloc`].
///
/// Codec parameters for a track could not be allocated.
#[derive(thiserror::Error, Debug, Clone)]
#[error("out of memory allocating the codec parameters for stream {stream_index}")]
pub struct ParametersAlloc {
  stream_index: usize,
}

impl ParametersAlloc {
  /// Constructs a `ParametersAlloc` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize) -> Self {
    Self { stream_index }
  }
  /// The `AVStream.index` whose parameters could not be copied.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
}

/// Payload for [`DemuxError::TrackTimebaseInvalid`].
///
/// A stream declares an `AVRational` timebase that is not a
/// [`Timebase`]: a zero or negative denominator, or a negative
/// numerator.
///
/// **Refused rather than repaired.** The value is what every timestamp
/// on that track would be measured against, and there is no honest
/// substitute — a ruler invented here is indistinguishable downstream
/// from one the file declared. `0/1`, libavformat's own "not set yet"
/// default, is **not** this error: see
/// [`TrackInfo::timebase`](mediadecode::demuxer::TrackInfo::timebase).
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("stream {stream_index} declares the timebase {num}/{den}, which is not a usable one")]
pub struct TrackTimebaseInvalid {
  stream_index: usize,
  num: i32,
  den: i32,
}

impl TrackTimebaseInvalid {
  /// Constructs a `TrackTimebaseInvalid` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, num: i32, den: i32) -> Self {
    Self {
      stream_index,
      num,
      den,
    }
  }
  /// The `AVStream.index` that declared it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The numerator the container wrote.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn num(&self) -> i32 {
    self.num
  }
  /// The denominator the container wrote.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn den(&self) -> i32 {
    self.den
  }
}

/// Payload for [`DemuxError::ChapterTimebaseInvalid`].
///
/// A chapter declares an `AVRational` timebase that cannot rule its
/// span: a zero or negative denominator, a negative numerator, or a
/// **zero** numerator.
///
/// Stricter than [`TrackTimebaseInvalid`] by that last case, and
/// deliberately: a chapter's ruler is written by whatever wrote the
/// chapter, so `0/den` there is not an absence but a claim that every
/// boundary in the table falls on one instant.
///
/// **The whole open fails, rather than the row being dropped.** A
/// chapter table is a table: a reader that quietly returned the other
/// eleven rows would be handing a consumer something that disagrees
/// with the file and says nothing about it. This names the row, its
/// container id and the rational, so a caller learns exactly what the
/// file wrote — and repairing a container is a job for something that
/// rewrites containers, not for a reader that would have to invent the
/// number it repaired with.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "chapter {index} (container id {id}) declares the timebase {num}/{den}, which cannot rule its span"
)]
pub struct ChapterTimebaseInvalid {
  index: usize,
  id: i64,
  num: i32,
  den: i32,
}

impl ChapterTimebaseInvalid {
  /// Constructs a `ChapterTimebaseInvalid` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(index: usize, id: i64, num: i32, den: i32) -> Self {
    Self {
      index,
      id,
      num,
      den,
    }
  }
  /// The chapter's position in `AVFormatContext.chapters`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn index(&self) -> usize {
    self.index
  }
  /// The id the container assigned that chapter.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn id(&self) -> i64 {
    self.id
  }
  /// The numerator the container wrote.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn num(&self) -> i32 {
    self.num
  }
  /// The denominator the container wrote.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn den(&self) -> i32 {
    self.den
  }
}

/// Payload for [`DemuxError::TooManyChapters`].
///
/// The container declares more chapters than
/// [`DemuxLimits::max_chapters`] allows. Refused at open, before the
/// table is reserved.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("the container declares {declared} chapters, over the ceiling of {limit}")]
pub struct TooManyChapters {
  declared: usize,
  limit: u32,
}

impl TooManyChapters {
  /// Constructs a `TooManyChapters` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(declared: usize, limit: u32) -> Self {
    Self { declared, limit }
  }
  /// `AVFormatContext.nb_chapters`, as the container declared it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn declared(&self) -> usize {
    self.declared
  }
  /// The ceiling in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> u32 {
    self.limit
  }
}

/// Payload for [`DemuxError::ChapterTitleBudgetExhausted`].
///
/// The file's chapter titles, together, are over
/// [`DemuxLimits::max_total_chapter_title_bytes`].
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the chapter titles reach {bytes} bytes at chapter {index}, over the {limit}-byte whole-file budget"
)]
pub struct ChapterTitleBudgetExhausted {
  index: usize,
  bytes: usize,
  limit: usize,
}

impl ChapterTitleBudgetExhausted {
  /// Constructs a `ChapterTitleBudgetExhausted` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(index: usize, bytes: usize, limit: usize) -> Self {
    Self {
      index,
      bytes,
      limit,
    }
  }
  /// The chapter whose title ran the total past the line.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn index(&self) -> usize {
    self.index
  }
  /// The running total at that chapter.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
  /// The whole-file budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::ChapterTitleTooLong`].
///
/// A chapter's `title` has no terminator inside
/// [`METADATA_VALUE_MAX_BYTES`].
///
/// **Distinct from the budget error, and deliberately so.**
/// [`ChapterTitleBudgetExhausted`] means the file's titles together
/// exceed what the caller allowed, and a caller answers it by raising
/// [`DemuxLimits::max_total_chapter_title_bytes`](crate::DemuxLimits::max_total_chapter_title_bytes).
/// This one means a single value runs past a structural cap this crate
/// owns and no seat can move — folding the two together would offer a
/// knob that cannot fix it.
///
/// Refused rather than truncated (a truncated title is a different
/// title), and refused *visibly*: reporting it as an absent title, as
/// this road used to, made the mirrored table silently disagree with
/// the container and slipped the value past the budget entirely.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("the title on chapter {index} runs past the {limit}-byte cap on one metadata value")]
pub struct ChapterTitleTooLong {
  index: usize,
  limit: usize,
}

impl ChapterTitleTooLong {
  /// Constructs a `ChapterTitleTooLong` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(index: usize, limit: usize) -> Self {
    Self { index, limit }
  }
  /// The chapter's position in `AVFormatContext.chapters`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn index(&self) -> usize {
    self.index
  }
  /// The per-value cap in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::ChapterTitleAlloc`].
///
/// A chapter title that passed the budget could not be decoded into
/// owned text. The size had already been charged, so this is the
/// allocator refusing rather than the file asking for too much.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("out of memory decoding the {bytes}-byte title on chapter {index}")]
pub struct ChapterTitleAlloc {
  index: usize,
  bytes: usize,
}

impl ChapterTitleAlloc {
  /// Constructs a `ChapterTitleAlloc` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(index: usize, bytes: usize) -> Self {
    Self { index, bytes }
  }
  /// The chapter's position in `AVFormatContext.chapters`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn index(&self) -> usize {
    self.index
  }
  /// The decoded size that could not be reserved.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
}

/// Payload for [`DemuxError::TrackMetadataTooLong`].
///
/// One of a stream's retained metadata values — `filename`,
/// `mimetype` or `language` — has no terminator inside
/// [`METADATA_VALUE_MAX_BYTES`]. `key` says which.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("the {key} on stream {stream_index} runs past the {limit}-byte cap on one metadata value")]
pub struct TrackMetadataTooLong {
  stream_index: usize,
  key: &'static str,
  limit: usize,
}

impl TrackMetadataTooLong {
  /// Constructs a `TrackMetadataTooLong` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, key: &'static str, limit: usize) -> Self {
    Self {
      stream_index,
      key,
      limit,
    }
  }
  /// The `AVStream.index` carrying it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The dictionary key that was being read.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn key(&self) -> &'static str {
    self.key
  }
  /// The per-value cap in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::TrackMetadataBudgetExhausted`].
///
/// The file's stream metadata, together, is over
/// [`DemuxLimits::max_total_stream_metadata_bytes`].
///
/// The budget is whole-file rather than per-stream because the
/// exposure is: `max_streams` bounds how many streams a header may
/// declare and says nothing about what each may carry, and every
/// admitted stream's three values are mirrored eagerly at open.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the stream metadata reaches {bytes} bytes at the {key} on stream {stream_index}, over the {limit}-byte whole-file budget"
)]
pub struct TrackMetadataBudgetExhausted {
  stream_index: usize,
  key: &'static str,
  bytes: usize,
  limit: usize,
}

impl TrackMetadataBudgetExhausted {
  /// Constructs a `TrackMetadataBudgetExhausted` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, key: &'static str, bytes: usize, limit: usize) -> Self {
    Self {
      stream_index,
      key,
      bytes,
      limit,
    }
  }
  /// The `AVStream.index` whose value ran the total past the line.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The dictionary key that was being read.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn key(&self) -> &'static str {
    self.key
  }
  /// The running total at that value.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
  /// The whole-file budget in force.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn limit(&self) -> usize {
    self.limit
  }
}

/// Payload for [`DemuxError::TrackMetadataAlloc`].
///
/// A stream metadata value that passed the budget could not be decoded
/// into owned text.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("out of memory decoding the {bytes}-byte {key} on stream {stream_index}")]
pub struct TrackMetadataAlloc {
  stream_index: usize,
  key: &'static str,
  bytes: usize,
}

impl TrackMetadataAlloc {
  /// Constructs a `TrackMetadataAlloc` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, key: &'static str, bytes: usize) -> Self {
    Self {
      stream_index,
      key,
      bytes,
    }
  }
  /// The `AVStream.index` carrying it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The dictionary key that was being read.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn key(&self) -> &'static str {
    self.key
  }
  /// The decoded size that could not be reserved.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn bytes(&self) -> usize {
    self.bytes
  }
}

/// Payload for [`DemuxError::TrackTableAlloc`].
///
/// The track table, or the attachment queue built beside it, could not
/// be reserved. The stream count had already passed
/// [`DemuxLimits::max_streams`](crate::DemuxLimits::max_streams), so
/// this is the allocator declining rather than the file asking for too
/// much — reported instead of aborting, which is what an infallible
/// reservation would have done.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("out of memory reserving the table of {streams} streams")]
pub struct TrackTableAlloc {
  streams: usize,
}

impl TrackTableAlloc {
  /// Constructs a `TrackTableAlloc` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(streams: usize) -> Self {
    Self { streams }
  }
  /// The stream count the reservation was for.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn streams(&self) -> usize {
    self.streams
  }
}

/// Payload for [`DemuxError::ChapterAlloc`].
///
/// The chapter table could not be reserved. The count had already
/// passed [`DemuxLimits::max_chapters`], so this is the allocator
/// refusing rather than the file asking for too much — reported
/// instead of aborting, which is what an infallible reservation would
/// have done.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("out of memory reserving the table of {declared} chapters")]
pub struct ChapterAlloc {
  declared: usize,
}

impl ChapterAlloc {
  /// Constructs a `ChapterAlloc` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(declared: usize) -> Self {
    Self { declared }
  }
  /// The chapter count the reservation was for.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn declared(&self) -> usize {
    self.declared
  }
}

/// Payload for [`DemuxError::ParametersCopy`].
///
/// Copying a track's codec parameters failed part way.
#[derive(thiserror::Error, Debug, Clone)]
#[error("the codec parameters for stream {stream_index} could not be copied: {source}")]
pub struct ParametersCopy {
  stream_index: usize,
  #[source]
  source: ffmpeg_next::Error,
}

impl ParametersCopy {
  /// Constructs a `ParametersCopy` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, source: ffmpeg_next::Error) -> Self {
    Self {
      stream_index,
      source,
    }
  }
  /// The `AVStream.index` whose parameters could not be copied.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// What FFmpeg said.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn source(&self) -> &ffmpeg_next::Error {
    &self.source
  }
}

/// Payload for [`DemuxError::ParametersOpaque`].
///
/// A channel layout arrived carrying `opaque` — a raw pointer FFmpeg
/// documents as "private data of the user".
///
/// [`CodecTicket`](crate::ticket::CodecTicket) is an **owned** mirror:
/// it outlives the `AVCodecParameters` it was read from, and it may
/// cross threads, so a pointer into somebody else's data is exactly
/// what it cannot carry. libavformat sets neither
/// `AVChannelLayout::opaque` nor `AVChannelCustom::opaque`, so no
/// demuxed stream reaches the mirror with one; if one ever does, the
/// mirror refuses rather than dropping the pointer in silence. That is
/// the same fail-closed answer `extras::measure_parameters` gives a
/// channel order it has never heard of, and for the same reason:
/// carrying on would be a guess about memory nobody here owns.
#[derive(thiserror::Error, Debug, Clone)]
#[error(
  "the channel layout for stream {stream_index} carries user-private data \
   ({}) that an owned codec ticket cannot mirror",
  match channel { Some(i) => format!("custom channel {i}"), None => "the layout".to_owned() },
)]
pub struct ParametersOpaque {
  stream_index: usize,
  channel: Option<usize>,
}

impl ParametersOpaque {
  /// Constructs a `ParametersOpaque` payload. `channel` names the
  /// custom-map entry when the pointer was on one, and is `None` when
  /// it was on the layout itself.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, channel: Option<usize>) -> Self {
    Self {
      stream_index,
      channel,
    }
  }
  /// The `AVStream.index` whose layout carried the pointer.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The custom-map entry the pointer was on, or `None` when it was on
  /// the layout itself.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channel(&self) -> Option<usize> {
    self.channel
  }
}

/// Payload for [`DemuxError::ParametersChannelMap`].
///
/// A channel layout declared `AV_CHANNEL_ORDER_CUSTOM` without the map
/// that order requires.
///
/// **This one is a crash, not a curiosity.** For a custom order,
/// `av_channel_layout_copy` — which is how
/// `avcodec_parameters_to_context` moves a layout into a decoder's
/// context — does
///
/// ```c
/// dst->u.map = av_malloc_array(src->nb_channels, sizeof(*dst->u.map));
/// if (!dst->u.map)
///     return AVERROR(ENOMEM);
/// memcpy(dst->u.map, src->u.map, src->nb_channels * sizeof(*src->u.map));
/// ```
///
/// with **no null check on `src->u.map`** — verified against FFmpeg
/// n9.0. A layout that names channels it has no map for therefore makes
/// libavcodec `memcpy` from a null pointer the moment a decoder opens
/// from it.
///
/// So the mirror refuses such a layout at the door rather than
/// reproducing it. An earlier draft carried it through, on the argument
/// that a malformed layout in should be a malformed layout out — the
/// round trip is faithful either way, and the parity comparator agreed.
/// That symmetry was the wrong test: faithfully reproducing a shape
/// whose only consumer dereferences null is not fidelity, it is
/// forwarding a crash. Refusing is the same fail-closed answer
/// `extras::measure_parameters` gives a channel order it has never
/// heard of.
#[derive(thiserror::Error, Debug, Clone)]
#[error(
  "the custom channel layout for stream {stream_index} declares {channels} channels \
   and carries no usable map for them"
)]
pub struct ParametersChannelMap {
  stream_index: usize,
  channels: i32,
}

impl ParametersChannelMap {
  /// Constructs a `ParametersChannelMap` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, channels: i32) -> Self {
    Self {
      stream_index,
      channels,
    }
  }
  /// The `AVStream.index` whose layout was malformed.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// The `nb_channels` the layout declared with no map to describe them.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channels(&self) -> i32 {
    self.channels
  }
}

/// Payload for [`DemuxError::ParametersLayoutShape`].
///
/// The non-custom half of what a channel layout can be wrong about, and
/// the half that went unchecked for eleven rounds of review on the
/// argument that an order describing its channels through a `uint64_t`
/// mask cannot be malformed. The mask is not the only field:
/// `nb_channels` is an `int` a caller writes, and FFmpeg's helpers
/// compute `nb_channels - popcount(mask)` and take an integer square
/// root of it without checking either.
///
/// See
/// [`layout_preflight`](crate::channel_layout::layout_preflight) for
/// the complete rule and why it is one function.
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error(
  "the channel layout for stream {stream_index} declares order {order} with {channels} \
   channels, which is not a shape FFmpeg's own helpers can be given"
)]
pub struct ParametersLayoutShape {
  stream_index: usize,
  order: i32,
  channels: i32,
}

impl ParametersLayoutShape {
  /// Constructs a `ParametersLayoutShape` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, order: i32, channels: i32) -> Self {
    Self {
      stream_index,
      order,
      channels,
    }
  }
  /// The `AVStream.index` whose layout declared it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// `AVChannelLayout.order`, as the raw `c_int` it is on the wire.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn order(&self) -> i32 {
    self.order
  }
  /// `nb_channels`, as the layout declared it.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channels(&self) -> i32 {
    self.channels
  }
}

/// Names a channel-layout fault for a demux caller — **one mapper, so
/// the roads that share the preflight also share its report**.
///
/// `Alloc` is the only arm that is not a statement about the container:
/// it is the allocator declining a rendering buffer, and it keeps the
/// name every other allocator refusal on this road has.
pub(crate) fn layout_fault_to_demux(
  stream_index: usize,
  fault: crate::channel_layout::ChannelLayoutFault,
) -> DemuxError {
  use crate::channel_layout::ChannelLayoutFault as Fault;
  match fault {
    // The second cannot arrive from a pointer road — it is how the
    // *safe* conversion refuses a custom layout whose extent it cannot
    // establish — but both say the same thing about this stream.
    Fault::MalformedCustomMap { channels } | Fault::UnverifiableCustomMap { channels } => {
      DemuxError::ParametersChannelMap(ParametersChannelMap::new(stream_index, channels))
    }
    Fault::MalformedLayout { order, channels } => {
      DemuxError::ParametersLayoutShape(ParametersLayoutShape::new(stream_index, order, channels))
    }
    Fault::Alloc => DemuxError::ParametersAlloc(ParametersAlloc::new(stream_index)),
  }
}

/// Payload for [`DemuxError::PacketBuffer`].
///
/// A packet's payload could not be referenced — the bytes are there
/// and this layer could not carry them.
///
/// Never raised for a packet that simply has no payload: an empty
/// packet is a marker some demuxers emit, and it is skipped in
/// silence. Distinguishing the two is what keeps a refcount failure
/// under memory pressure from looking like the file's own word and
/// dropping real compressed bytes.
#[derive(thiserror::Error, Debug, Clone)]
#[error("stream {stream_index}: {source}")]
pub struct PacketBuffer {
  stream_index: usize,
  #[source]
  source: PacketBufferError,
}

impl PacketBuffer {
  /// Constructs a `PacketBuffer` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(stream_index: usize, source: PacketBufferError) -> Self {
    Self {
      stream_index,
      source,
    }
  }
  /// The `AVStream.index` the packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn stream_index(&self) -> usize {
    self.stream_index
  }
  /// What went wrong.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn source(&self) -> &PacketBufferError {
    &self.source
  }
}

/// Payload for [`DemuxError::ReaderPanic`].
///
/// The `Read + Seek` source given to [`FfmpegDemuxer::open_reader`]
/// panicked inside a libavformat callback.
///
/// The panic was caught before it could cross the `extern "C"`
/// boundary and abort the process; this is what it said. The session
/// is terminal — every later call reports the same panic.
#[derive(thiserror::Error, Debug, Clone)]
#[error("the reader panicked: {message}")]
pub struct ReaderPanic {
  message: Utf8Bytes,
}

impl ReaderPanic {
  /// Constructs a `ReaderPanic` payload.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(message: Utf8Bytes) -> Self {
    Self { message }
  }
  /// What the panic payload said.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn message(&self) -> &str {
    self.message.as_str()
  }
}

/// Errors from [`FfmpegDemuxer`].
///
/// **Open fault taxonomy, so it is `#[non_exhaustive]`.** New ways to
/// fail are discovered — a backend, a ceiling, a corruption a codec
/// learns to report — and a consumer that meets one it has never heard
/// of should take its generic-fault path. That is exactly what the
/// wildcard arm this attribute forces is for. The two status
/// vocabularies opposite it,
/// [`Sent`](mediadecode::Sent) and [`Received`](mediadecode::Received),
/// are exhaustive for the mirror-image reason: their arms are the
/// substrate's fixed state set, and there the wildcard would be dead
/// weight hiding a state a consumer forgot.
#[derive(thiserror::Error, Debug, Clone, IsVariant, Unwrap, TryUnwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
#[non_exhaustive]
pub enum DemuxError {
  /// The wrapped libavformat call reported an error — open, read or
  /// seek.
  #[error(transparent)]
  Ffmpeg(#[from] ffmpeg_next::Error),

  /// libavformat asked for more bytes than the probe budget allows
  /// while opening and analysing the container. See
  /// [`ProbeBudgetExhausted`].
  #[error(transparent)]
  ProbeBudgetExhausted(#[from] ProbeBudgetExhausted),

  /// One attachment's payload is over the per-attachment budget.
  /// Refused at open, before the copy.
  #[error(transparent)]
  AttachmentTooLarge(#[from] AttachmentTooLarge),

  /// The file's attachments, together, are over the whole-file budget.
  /// Refused at open, before the copy that would have crossed it.
  #[error(transparent)]
  AttachmentBudgetExhausted(#[from] AttachmentBudgetExhausted),

  /// One stream's codec parameters hold more heap bytes than the
  /// budget allows. Refused at open, before the clone.
  #[error(transparent)]
  ParametersTooLarge(#[from] ParametersTooLarge),

  /// Every stream's codec parameters together are over the whole-file
  /// budget. Refused at open, before the clone that would have crossed
  /// it.
  #[error(transparent)]
  ParametersBudgetExhausted(#[from] ParametersBudgetExhausted),

  /// Codec parameters arrived that were never allocated.
  #[error(transparent)]
  ParametersMissing(#[from] ParametersMissing),

  /// Codec parameters for a track could not be allocated.
  #[error(transparent)]
  ParametersAlloc(#[from] ParametersAlloc),

  /// Copying a track's codec parameters failed part way.
  #[error(transparent)]
  ParametersCopy(#[from] ParametersCopy),

  /// A channel layout arrived carrying user-private data an owned
  /// codec ticket cannot mirror.
  #[error(transparent)]
  ParametersOpaque(#[from] ParametersOpaque),

  /// A channel layout declared a custom order without the map that
  /// order requires — a shape `av_channel_layout_copy` would `memcpy`
  /// from null.
  #[error(transparent)]
  ParametersChannelMap(#[from] ParametersChannelMap),

  /// A stream's channel layout declares a shape FFmpeg's own helpers
  /// cannot be given — see [`ParametersLayoutShape`].
  #[error(transparent)]
  ParametersLayoutShape(#[from] ParametersLayoutShape),

  /// A stream declares a timebase that is not one. Refused at open,
  /// rather than repaired with a number this crate would have had to
  /// invent.
  #[error(transparent)]
  TrackTimebaseInvalid(#[from] TrackTimebaseInvalid),

  /// A chapter declares a timebase that cannot rule its span. Refused
  /// at open, for the reason [`ChapterTimebaseInvalid`] gives.
  #[error(transparent)]
  ChapterTimebaseInvalid(#[from] ChapterTimebaseInvalid),

  /// The container declares more chapters than the ceiling allows.
  /// Refused at open, before the table is reserved.
  #[error(transparent)]
  TooManyChapters(#[from] TooManyChapters),

  /// The file's chapter titles, together, are over the whole-file
  /// budget. Refused at the title that crossed it, before it was
  /// copied.
  #[error(transparent)]
  ChapterTitleBudgetExhausted(#[from] ChapterTitleBudgetExhausted),

  /// One chapter title runs past the cap on a single metadata value —
  /// refused, rather than reported as an absent title.
  #[error(transparent)]
  ChapterTitleTooLong(#[from] ChapterTitleTooLong),

  /// A chapter title the budget admitted could not be decoded.
  #[error(transparent)]
  ChapterTitleAlloc(#[from] ChapterTitleAlloc),

  /// One of a stream's retained metadata values runs past the cap on a
  /// single metadata value.
  #[error(transparent)]
  TrackMetadataTooLong(#[from] TrackMetadataTooLong),

  /// The file's stream metadata, together, is over the whole-file
  /// budget. Refused at the value that crossed it, before it was
  /// copied.
  #[error(transparent)]
  TrackMetadataBudgetExhausted(#[from] TrackMetadataBudgetExhausted),

  /// A stream metadata value the budget admitted could not be decoded.
  #[error(transparent)]
  TrackMetadataAlloc(#[from] TrackMetadataAlloc),

  /// The chapter table could not be reserved.
  #[error(transparent)]
  ChapterAlloc(#[from] ChapterAlloc),

  /// The track table, or the attachment queue beside it, could not be
  /// reserved.
  #[error(transparent)]
  TrackTableAlloc(#[from] TrackTableAlloc),

  /// A packet's payload could not be referenced — the bytes are there
  /// and this layer could not carry them.
  #[error(transparent)]
  PacketBuffer(#[from] PacketBuffer),

  /// The `Read + Seek` source given to
  /// [`FfmpegDemuxer::open_reader`] panicked inside a libavformat
  /// callback.
  #[error(transparent)]
  ReaderPanic(#[from] ReaderPanic),
}

// ---------------------------------------------------------------------------
//  Track-table construction.
// ---------------------------------------------------------------------------

type BuiltTracks<C> = (
  Vec<TrackInfo<Ffmpeg>>,
  VecDeque<(
    TrackIndex,
    AttachmentPacket<AttachmentPacketExtra, <C as crate::FfmpegCarrier>::Buffer>,
  )>,
);

fn build_tracks<C: crate::FfmpegCarrier + crate::CarrierOps>(
  input: &Input,
  limits: DemuxLimits,
) -> Result<BuiltTracks<C>, DemuxError> {
  // **Admission before allocation.** Every attachment in the file is
  // judged here, in full, before the loop below allocates anything at
  // all — see [`admit_streams`] for why the charge cannot live
  // inside the capture.
  admit_streams(input, limits)?;

  let count = input.streams().len();
  // **Reserved fallibly, both of them.** The stream count is the
  // container's; `max_streams` bounds it, and a bound the caller chose
  // is exactly the number that must come back as an error rather than
  // an abort when the allocator declines it.
  let mut tracks = Vec::new();
  tracks
    .try_reserve_exact(count)
    .map_err(|_| DemuxError::TrackTableAlloc(TrackTableAlloc::new(count)))?;
  let mut pending = VecDeque::new();
  pending
    .try_reserve(count)
    .map_err(|_| DemuxError::TrackTableAlloc(TrackTableAlloc::new(count)))?;
  // The whole file's stream-metadata budget, spent across every
  // admitted stream rather than per stream: `max_streams` bounds how
  // many streams a header may declare, and nothing bounded what each
  // could carry.
  let mut metadata_spent: usize = 0;

  for stream in input.streams() {
    let index = stream.index();
    // `AVStream.index` is the stream's position in `ic->streams[]` and
    // libavformat keeps the two identical. The demux tier makes
    // `TrackIndex` mean "position in `tracks()`", so the two agree by
    // construction — but only if they really are dense and in order,
    // which is cheap to insist on rather than assume.
    debug_assert_eq!(
      index,
      tracks.len(),
      "AVStream indices are dense and ordered"
    );

    let parameters = stream.parameters();
    let par = unsafe { parameters.as_ptr() };
    // Never read `AVCodecParameters.codec_type` / `.codec_id` as their
    // bindgen enums: a value outside this build's discriminant set is
    // UB the moment it exists. Both are read as the raw integers they
    // are on the wire — the medium through [`boundary::media_kind_of`],
    // which folds anything unnamed into `Unknown`.
    //
    // The medium used to go through `Parameters::medium()` on the
    // argument that `AVMediaType`'s set is tiny and stable. It is; that
    // made the read unlikely to bite, not sound. The exception is gone
    // rather than defended, so no attacker-reachable path in this crate
    // forms a bindgen enum out of FFmpeg memory.
    let medium = boundary::media_kind_of(&parameters);
    let codec =
      CodecId::from_raw(unsafe { read_unaligned(addr_of!((*par).codec_id).cast::<i32>()) });

    let disposition = unsafe { (*stream.as_ptr()).disposition };
    let attached_pic = is_attachment_disposition(disposition);

    // Already judged by [`admit_streams`], which refuses a malformed
    // ruler before this loop allocates anything; the same function is
    // called here because this is where the value is actually needed,
    // and one function is how the two passes are kept from becoming
    // two rules.
    let time_base = stream_timebase(index, stream.time_base())?;
    let raw_duration = stream.duration();
    let duration = (raw_duration != AV_NOPTS_VALUE && raw_duration > 0)
      .then(|| Timestamp::new(raw_duration, time_base));
    let raw_start = stream.start_time();
    let frames = stream.frames();

    let params = if attached_pic {
      // Cover art. A still image in a video-shaped slot is an
      // attachment by every property that matters, and the `Video` arm
      // is reserved for motion video.
      TrackParams::Attachment(AttachmentTrackParams::new(codec))
    } else {
      match medium {
        boundary::MediaKind::Video => TrackParams::Video(VideoTrackParams::new(
          codec,
          unsafe { (*par).width }.max(0) as u32,
          unsafe { (*par).height }.max(0) as u32,
          boundary::from_av_pixel_format(unsafe { (*par).format }),
          rate_to_timebase(stream.avg_frame_rate()),
        )),
        boundary::MediaKind::Audio => {
          let ch_layout = unsafe { std::ptr::addr_of!((*par).ch_layout) };
          // **This is the trusted road, and here is why it is trusted.**
          //
          // The `unsafe` form is the only one that reads a custom
          // channel map, because its contract asks the caller for the
          // map's extent — the one thing a pointer cannot be asked.
          // This call site can supply it: `par` is the
          // `AVCodecParameters` libavformat itself built for this
          // stream, and libavformat fills `ch_layout` through
          // `av_channel_layout_copy`, which allocates the map and sizes
          // it to `nb_channels` in the same operation. The layout is
          // never handed in by a caller of this crate, so there is no
          // road by which `nb_channels` and the map can disagree.
          //
          // SAFETY: (1) `par` is a live `*const AVCodecParameters` for
          // the life of `parameters`, so `ch_layout` is a live, aligned
          // `*const AVChannelLayout`. (2) For a `CUSTOM` order, `u.map`
          // is FFmpeg's own allocation of exactly `nb_channels`
          // `AVChannelCustom` entries, per the paragraph above. The
          // helper validates `order` as an `i32` before constructing any
          // `AVChannelOrder`, and refuses a null map or an
          // unterminated name before FFmpeg is allowed to render the
          // layout — a precondition, not a courtesy.
          let channel_layout =
            unsafe { crate::channel_layout::channel_layout_description_from_raw_ptr(ch_layout) }
              .map_err(|fault| layout_fault_to_demux(index, fault))?;
          TrackParams::Audio(AudioTrackParams::new(
            codec,
            unsafe { (*par).sample_rate }.max(0) as u32,
            channel_layout.channels().min(255) as u8,
            SampleFormat::from_raw(unsafe { (*par).format }),
            channel_layout,
          ))
        }
        boundary::MediaKind::Subtitle => TrackParams::Subtitle(SubtitleTrackParams::new(codec)),
        boundary::MediaKind::Data => TrackParams::Data(DataTrackParams::new(codec)),
        boundary::MediaKind::Attachment => {
          TrackParams::Attachment(AttachmentTrackParams::new(codec))
        }
        boundary::MediaKind::Unknown => TrackParams::Unknown(UnknownTrackParams::new(codec)),
      }
    };

    // The parameter mirror. For an `AVMEDIA_TYPE_ATTACHMENT` stream its
    // `extradata` **is** the attachment's payload — the same bytes the
    // carrier below already holds — so it is left behind rather than
    // copied. Censused before it was: nothing can use it. libavcodec
    // has no decoder for a font (`avcodec_find_decoder` answers null
    // for `AV_CODEC_ID_TTF` and its siblings), so no road in this crate
    // or downstream of it opens a codec context from these parameters;
    // the payload reaches a consumer as the attachment packet, which is
    // the delivery the demux tier promises.
    //
    // **Omitted, not stripped.** An earlier shape copied the extradata
    // and freed it immediately afterwards, which allocated the payload
    // for no reason and — worse — charged it against the *parameter*
    // ceiling on the way past. A font between the two ceilings passed
    // the admission pass and then failed inside the clone. See
    // [`ExtradataPolicy`](crate::extras::ExtradataPolicy).
    //
    // Cover art keeps its extradata: there the payload is the parked
    // `AVPacket`, extradata is *not* a copy of it, and a still codec
    // can legitimately need it (MJPEG with an external Huffman table).
    // Measured on this build: a cover-art stream carries none anyway.
    let extradata_policy = if medium.is_attachment() {
      crate::extras::ExtradataPolicy::Omit
    } else {
      crate::extras::ExtradataPolicy::Copy
    };
    // Straight from the stream's own parameters into the owned ticket.
    // The row used to reach here through an intermediate
    // `avcodec_parameters_copy` — one ffmpeg-native deep copy per
    // track, whose only purpose was to sever the tie to the format
    // context. The mirror severs it by being owned Rust, so that copy
    // is gone rather than moved.
    let ticket = crate::ticket::CodecTicket::mirror_with(
      &parameters,
      index,
      limits.max_codec_parameter_bytes(),
      extradata_policy,
    )?;
    let extra = TrackExtra::new(index as i32, ticket)
      .with_disposition(disposition)
      .with_start_time((raw_start != AV_NOPTS_VALUE).then_some(raw_start))
      .with_frame_count((frames > 0).then_some(frames));

    // SAFETY: `stream` keeps the `AVStream` — and so its metadata
    // dictionary — live across every read below. The dictionary is
    // read through `av_dict_get` rather than through
    // `DictionaryRef::get`: see [`metadata_value`].
    let metadata = unsafe { (*stream.as_ptr()).metadata };
    // **Every retained value is measured, charged and only then
    // built**, against one whole-file budget. Three values a stream
    // apiece, mirrored eagerly for every admitted stream, is an
    // open-time allocation a container controls the size of — and
    // `max_streams` bounds the count of streams, not the bytes each
    // one can carry.
    let mut text = |key: &'static CStr| -> Result<Option<Utf8Bytes>, DemuxError> {
      // SAFETY: as above — `stream` keeps the dictionary live, and the
      // borrow does not outlive this call.
      let raw = unsafe { metadata_value(metadata, key) };
      retain_metadata(
        raw,
        &mut metadata_spent,
        limits.max_total_stream_metadata_bytes(),
      )
      .map_err(|fault| stream_metadata_error(index, key, fault, limits))
    };
    let info = TrackInfo::new(time_base, params, extra)
      .with_duration(duration)
      // The same three keys `RETAINED_STREAM_METADATA` names, in the
      // same order — `admit_streams` has already charged every one of
      // them across the whole file, so nothing here can refuse a value
      // the pre-pass admitted. The charge stays as defence in depth:
      // it is what makes `metadata_spent` real rather than notional,
      // and it is the arm that reports an allocator refusal, which no
      // measurement can foresee.
      .with_filename(text(c"filename")?)
      .with_mime_type(text(c"mimetype")?)
      // **`language` is where every container's tag lands.** libavformat
      // normalises the *key*, not the value: Matroska's `Language`
      // element, MP4's `mdhd` language code and an `elng`/ISO 639-2
      // atom, Matroska's BCP 47 `LanguageBCP47`, an ASF descriptor and
      // an ID3 `TLAN` frame all arrive on this one entry. What each
      // wrote is what is read — see
      // [`TrackInfo::language`](mediadecode::demuxer::TrackInfo::language)
      // for why nothing folds it here.
      .with_language(text(c"language")?);

    // Capture the attachment payload now, so the queue is complete
    // before a single timed packet has been read. Every attachment
    // track leaves this loop with exactly one packet queued, or the
    // open fails: that is what makes "exactly one packet, before any
    // timed packet" a property of the construction rather than a
    // promise the pull loop has to keep.
    if info.kind() == TrackKind::Attachment {
      let packet = if attached_pic {
        // SAFETY: `stream` keeps the format context (and so the
        // `AVStream`) live; `attached_pic` is an `AVPacket` embedded by
        // value, and `addr_of!` reaches it without forming a reference
        // to the stream.
        let pkt = unsafe { std::ptr::addr_of!((*stream.as_ptr()).attached_pic) };
        unsafe { attached_pic_payload::<C>(pkt, index, limits) }?
      } else {
        extradata_payload::<C>(&stream, limits)?
      };
      pending.push_back((TrackIndex::new(index), packet));
    }

    tracks.push(info);
  }

  Ok((tracks, pending))
}

// ---------------------------------------------------------------------------
//  Chapter-table construction.
// ---------------------------------------------------------------------------

/// Mirrors `AVFormatContext.chapters` into owned rows.
///
/// libavformat fills the array while it parses the header — the MOV
/// `chpl`/chapter track, Matroska's `Chapters` element, an Ogg
/// `CHAPTER` comment — and `avformat_find_stream_info` has returned by
/// the time this runs, so the answer is final. That is what lets the
/// session hold the mirror beside the track table and answer
/// [`Demuxer::chapters`] at any point without touching the file again.
///
/// # Read raw, for the reasons the rest of this file is
///
/// The fields come off the `AVChapter` directly rather than through
/// `ffmpeg_next`'s own chapter wrapper. Two reasons, both already
/// standing here: that wrapper reads the metadata dictionary through
/// `DictionaryRef`, whose `&str` is built with `from_utf8_unchecked`
/// over bytes no container validates — see [`metadata_value`], the
/// measured road every metadata value in this file takes — and its
/// `as_ptr` dereferences the array entry without checking it, where
/// this walk answers a null entry by skipping it.
///
/// Nothing read here is a bindgen enum: an id, an `AVRational`, two
/// tick counts and a dictionary pointer.
///
/// # Nothing is repaired
///
/// A chapter whose `end` precedes its `start`, and one whose end
/// libavformat left at `AV_NOPTS_VALUE` because the file declared
/// none, are both mirrored exactly as written. This layer reports what
/// the container says; see [`Chapter`]'s own doc for why a clamp here
/// would be worse than the inverted row it replaced.
///
/// # Admission before allocation
///
/// The judging happens twice, and the first time is
/// [`admit_chapters`] — which runs before the *track* table is built,
/// because that table is where an open spends its memory and a file
/// certain to be refused should not pay for it. What follows here is
/// the same judgement repeated on the way to a row it has to build
/// anyway; see that function for why repeating it is how the two
/// passes stay one rule.
///
/// `nb_chapters` is file-controlled and libavformat has no
/// `max_chapters` knob to bound it with, so this crate judges the count
/// itself before reserving anything —
/// [`DemuxLimits::max_chapters`](crate::DemuxLimits::max_chapters), the
/// same posture [`admit_streams`] takes for the track table. Past the
/// ceiling the open fails with [`TooManyChapters`]; the reservation
/// that follows is **fallible** (`try_reserve_exact`), so an allocator
/// that refuses a count inside the ceiling is a named error rather than
/// an abort.
///
/// Titles are charged as they are read, against
/// [`DemuxLimits::max_total_chapter_title_bytes`](crate::DemuxLimits::max_total_chapter_title_bytes),
/// and the charge is made after each single title rather than before —
/// exactly as [`charge_attachment`] does. What bounds the overshoot is
/// [`METADATA_VALUE_MAX_BYTES`], which [`metadata_value`] refuses any
/// one dictionary value past: the worst this can hold before refusing
/// is the budget plus one 64 KiB title.
///
/// Note that libavformat having already built its own chapter array
/// does **not** bound this one. That array is four scalars and a
/// pointer per entry; a row here owns a title as well, so the mirror is
/// the larger of the two and a table that parsed successfully can still
/// be one this process should not pay for.
/// Reads the chapter array's shape and **allocates nothing**.
///
/// Shared by [`admit_chapters`] and [`build_chapters`] so the two
/// passes cannot come to disagree about what the container declared.
/// Returns `None` when there is no table to walk at all.
///
/// Safe because the borrow is the whole precondition: `input` owns the
/// `AVFormatContext` these two fields belong to, and it is live for as
/// long as the reference is.
fn chapter_array(input: &Input) -> Option<(usize, *mut *mut ffmpeg_next::ffi::AVChapter)> {
  // SAFETY: `input` owns a live `AVFormatContext` for the whole of
  // this call; `nb_chapters` and `chapters` are public fields of it.
  let (count, array) = unsafe {
    let context = input.as_ptr();
    ((*context).nb_chapters as usize, (*context).chapters)
  };
  if array.is_null() || count == 0 {
    None
  } else {
    Some((count, array))
  }
}

/// Judges the whole chapter table **before anything is materialised**,
/// allocating not one byte.
///
/// # Why this is a pass of its own
///
/// The judgement used to live inside [`build_chapters`], which runs
/// after the track table — and the track table is where this open
/// spends its memory: attachment carriers up to
/// [`DemuxLimits::max_total_attachment_bytes`](crate::DemuxLimits::max_total_attachment_bytes),
/// codec-parameter mirrors, retained stream metadata, and one `Arc` per
/// row. A file whose chapter count is a hundred times the ceiling was
/// therefore *certain* to be refused, and paid for hundreds of
/// megabytes of track material first. Repeating the open repeats the
/// bill, which is a resource-exhaustion road built out of two correct
/// checks in the wrong order.
///
/// So the cheap, allocation-free judgement runs beside stream
/// admission, before either table exists. What it judges is exactly
/// what [`build_chapters`] would have: the declared count against
/// [`DemuxLimits::max_chapters`](crate::DemuxLimits::max_chapters),
/// every chapter's timebase, and every title's decoded length against
/// the aggregate title budget.
///
/// # Why the second pass still judges
///
/// [`build_chapters`] repeats these checks rather than trusting this
/// one. It needs the timebase and the title anyway to build a row, and
/// re-deriving them is how the two passes stay one rule: nothing
/// between the two can change the container's answer —
/// `avformat_find_stream_info` has long returned — so a divergence
/// would be a bug in this file rather than a state to handle. The
/// repeat costs a pointer walk and a `strlen`; it allocates nothing.
fn admit_chapters(input: &Input, limits: DemuxLimits) -> Result<(), DemuxError> {
  let Some((count, array)) = chapter_array(input) else {
    return Ok(());
  };
  if count > limits.max_chapters() as usize {
    return Err(DemuxError::TooManyChapters(TooManyChapters::new(
      count,
      limits.max_chapters(),
    )));
  }

  let mut title_spent: usize = 0;
  for index in 0..count {
    // SAFETY: `array` is the context's own array of `count` chapter
    // pointers and `index` is below `count`.
    let chapter = unsafe { *array.add(index) };
    if chapter.is_null() {
      continue;
    }
    // SAFETY: a non-null entry is an `AVChapter` the context owns for
    // its whole life. Every field read is a plain scalar, an
    // `AVRational` or a dictionary pointer — never a bindgen enum.
    let (id, time_base, metadata) = unsafe {
      (
        (*chapter).id,
        Rational::from((*chapter).time_base),
        (*chapter).metadata,
      )
    };
    if positive_rational_to_timebase(time_base).is_none() {
      return Err(DemuxError::ChapterTimebaseInvalid(
        ChapterTimebaseInvalid::new(index, id, time_base.numerator(), time_base.denominator()),
      ));
    }
    // The title is **measured, not built**: `metadata_value` returns a
    // borrow of libavutil's own buffer and `lossy_len` prices the
    // decoding without producing it, so an over-budget table is
    // refused having touched no heap at all.
    //
    // SAFETY: `metadata` is the chapter's own dictionary, owned by the
    // context and live for the whole of this call.
    let raw_title = unsafe { metadata_value(metadata, c"title") };
    // Measured and charged; the row itself is built by
    // [`build_chapters`], which is where the bytes are actually spent.
    let _admitted = charge_metadata(
      raw_title,
      &mut title_spent,
      limits.max_total_chapter_title_bytes(),
    )
    .map_err(|fault| chapter_title_error(index, fault, limits))?;
  }
  Ok(())
}

fn build_chapters(input: &Input, limits: DemuxLimits) -> Result<Vec<Chapter<Ffmpeg>>, DemuxError> {
  let Some((count, array)) = chapter_array(input) else {
    return Ok(Vec::new());
  };
  if count > limits.max_chapters() as usize {
    return Err(DemuxError::TooManyChapters(TooManyChapters::new(
      count,
      limits.max_chapters(),
    )));
  }

  let mut out = Vec::new();
  out
    .try_reserve_exact(count)
    .map_err(|_| DemuxError::ChapterAlloc(ChapterAlloc::new(count)))?;
  let mut title_spent: usize = 0;

  for index in 0..count {
    // SAFETY: `array` is the context's own array of `count` chapter
    // pointers and `index` is below `count`.
    let chapter = unsafe { *array.add(index) };
    if chapter.is_null() {
      continue;
    }
    // SAFETY: a non-null entry is an `AVChapter` the context owns for
    // its whole life. Every field below is a plain scalar, an
    // `AVRational` or a dictionary pointer — never a bindgen enum.
    let (id, time_base, start, end, metadata) = unsafe {
      (
        (*chapter).id,
        Rational::from((*chapter).time_base),
        (*chapter).start,
        (*chapter).end,
        (*chapter).metadata,
      )
    };
    // **The ruler is judged before the row is built.** A chapter's
    // timebase is file-controlled and libavformat does not validate it
    // — the FFMETADATA parser stores `TIMEBASE=-1/1000` as written —
    // so this is where a container's malformed rational becomes a
    // refusal instead of a fabricated ruler or a panic.
    let timebase =
      positive_rational_to_timebase(time_base).ok_or(DemuxError::ChapterTimebaseInvalid(
        ChapterTimebaseInvalid::new(index, id, time_base.numerator(), time_base.denominator()),
      ))?;

    // **`title` is where every container's chapter name lands.**
    // libavformat normalises the key, not the value: a Matroska
    // `ChapterDisplay`'s `ChapString`, a MOV chapter track's text
    // sample and an FFMETADATA `title=` all arrive on this one entry,
    // and what each wrote is what is read.
    //
    // **Measured and charged before a byte of it is copied.** The
    // reading below borrows libavutil's buffer, so a title the budget
    // refuses costs no heap at all — see [`retain_metadata`].
    //
    // SAFETY: `metadata` is the chapter's own dictionary, owned by the
    // context and live for the whole of this call.
    let raw_title = unsafe { metadata_value(metadata, c"title") };
    let title = retain_metadata(
      raw_title,
      &mut title_spent,
      limits.max_total_chapter_title_bytes(),
    )
    .map_err(|fault| chapter_title_error(index, fault, limits))?;

    // Inside the reservation above, which was for `count` rows and is
    // never pushed past — so no growth, fallible or otherwise, happens
    // here.
    out.push(
      Chapter::new(
        id,
        timebase,
        Timestamp::new(start, timebase),
        Timestamp::new(end, timebase),
      )
      .with_title(title),
    );
  }
  Ok(out)
}

/// Whether `packet`'s payload is the very allocation the container has
/// parked in `AVStream.attached_pic` for stream `index`.
///
/// # Why this exists
///
/// libavformat queues a stream's attached picture as its **first
/// packet** — `read_frame_internal` does `av_packet_ref(pkt,
/// &st->attached_pic)` and keeps its own reference — so that packet
/// arrives with two references through nobody's fault. A pure cover-art
/// stream never reaches this road (it is an attachment, hoisted at
/// open), but a stream carrying `ATTACHED_PIC | TIMED_THUMBNAILS` is
/// deliberately classified as **video** by
/// [`is_attachment_disposition`], so its first pull comes through here
/// and would be refused as a shared payload. Every packet after it is
/// an ordinary timed one with a buffer of its own.
///
/// # The probe, and why it is a proof rather than a guess
///
/// `av_buffer_ref` sets the new reference's `buffer` field to the
/// source's, so two `AVBufferRef`s name one allocation **iff** their
/// `buffer` pointers are equal — the same identity
/// [`crate::FfmpegBuffer::ptr_eq`] rests on. Comparing them therefore
/// establishes the fact the carve-out needs: this payload's allocation
/// *is* `AVStream.attached_pic`'s, so one of its outstanding references
/// is the container's own.
///
/// The alternatives were heuristics and are not used: the disposition
/// bits say a stream *has* an attached picture, not that this packet is
/// it; "the first packet on the stream" is an ordering assumption that
/// nothing in libavformat's contract fixes.
///
/// # The soundness argument, restated for this packet
///
/// It is the same one the hoisted-attachment road rests on, and it
/// holds here for the same reason. `AVStream.attached_pic` is written
/// once, while the container is being opened, and never again; the
/// reference this crate is looking at is the container's, held for the
/// lifetime of the `AVFormatContext`, and there is no
/// `ffmpeg_next::Packet` wrapping it for anyone to call `data_mut` on.
/// What the uniqueness rule guards against is a *safe Rust* handle that
/// may write while this crate reads, and the container's reference is
/// not one.
///
/// # Safety
///
/// `input` and `packet` must both be live for the duration of the call.
unsafe fn is_streams_attached_pic(input: &Input, index: usize, packet: &Packet) -> bool {
  // SAFETY: `input` owns a live `AVFormatContext`; `streams` is an
  // array of `nb_streams` pointers, and `index` is checked against it.
  let stream = unsafe {
    let context = input.as_ptr();
    if index >= (*context).nb_streams as usize {
      return false;
    }
    *(*context).streams.add(index)
  };
  if stream.is_null() {
    return false;
  }
  // SAFETY: `stream` is one of the context's own live `AVStream`s and
  // `packet` is live per this function's contract.
  unsafe { packet_is_parked_picture(stream, packet) }
}

/// The identity itself: whether `packet`'s payload allocation is the
/// one `stream` has parked in `attached_pic`.
///
/// Split out from [`is_streams_attached_pic`] so the comparison can be
/// tested against a hand-built pair without forging an
/// `AVFormatContext` — see `a_queued_attached_picture_is_recognised`.
///
/// # Safety
///
/// `stream` must be a live `AVStream` and `packet` a live `AVPacket`.
unsafe fn packet_is_parked_picture(stream: *const AVStream, packet: &Packet) -> bool {
  use ffmpeg_next::packet::Ref;

  // SAFETY: both are live per the contract; `attached_pic` is an inline
  // `AVPacket` and both `buf` fields may be null, which is answered
  // before either is read through.
  unsafe {
    let parked = (*stream).attached_pic.buf;
    let carried = (*packet.as_ptr()).buf;
    if parked.is_null() || carried.is_null() {
      return false;
    }
    // The shared `AVBuffer`, not the `AVBufferRef`: `av_packet_ref`
    // mints a new reference struct around the same allocation, so
    // comparing the references themselves would answer "no" to exactly
    // the case this is for.
    (*parked).buffer == (*carried).buffer
  }
}

/// Whether a stream's disposition makes it an **attachment** — a
/// payload with no place on the timeline — rather than a timed track.
///
/// `AV_DISPOSITION_ATTACHED_PIC` alone says "cover art": one still
/// image, parked in `AVStream.attached_pic`, no timeline. But FFmpeg
/// pairs it with `AV_DISPOSITION_TIMED_THUMBNAILS` for a different
/// thing entirely — "the stream is sparse, and contains thumbnail
/// images, often corresponding to chapter markers", a flag its own
/// header documents as *only ever* used together with `ATTACHED_PIC`.
/// Such a stream has many images and every one of them has a
/// timestamp.
///
/// Classifying that as an attachment loses all but the first: the
/// attachment contract is exactly one packet, so the queue takes the
/// parked copy and the delivery loop drops every timed packet on the
/// track. It goes to the **`Video`** arm instead. That does not
/// contradict "cover art is an attachment, not video" — the reason
/// behind that ruling is that a single still with no timeline must not
/// look like a motion track, and a timed-thumbnail stream *is* on the
/// timeline. It is sparse video: a codec id, a frame size, a pixel
/// format and packets with timestamps, which is everything a consumer
/// needs to decode the images. The `Data` arm was the alternative and
/// is worse: it would strand encoded pictures in an arm that names no
/// decoder.
///
/// The bits are tested against the raw `AVStream.disposition` rather
/// than through `ffmpeg_next`'s `Disposition`, which mints no
/// `TIMED_THUMBNAILS` constant at all — its `from_bits_truncate` drops
/// every bit this build of the wrapper has no name for, which is how
/// the distinction went missing in the first place.
const fn is_attachment_disposition(disposition: c_int) -> bool {
  disposition & AV_DISPOSITION_ATTACHED_PIC != 0
    && disposition & AV_DISPOSITION_TIMED_THUMBNAILS == 0
}

/// Upper bound on the NUL search in [`metadata_value`].
///
/// Generous by four orders of magnitude for a filename or a MIME type,
/// and there only so that a value libavutil did not terminate cannot
/// turn the walk into an unbounded read — the same discipline
/// [`crate::channel_layout`] and the pixel-format namer follow. A value
/// longer than this is refused rather than truncated: a truncated
/// filename is a different filename.
const METADATA_VALUE_MAX_BYTES: usize = 64 * 1024;

/// What a metadata dictionary holds for one key — **measured, and not
/// yet copied**.
///
/// Three outcomes rather than an `Option`, because the answer that
/// used to go missing is the third one: a value with no terminator
/// inside [`METADATA_VALUE_MAX_BYTES`] is not an absent value, and
/// reporting it as one made a container's declaration vanish silently
/// *and* escape every budget charged against it.
///
/// `Present` borrows libavutil's own buffer. That is the load-bearing
/// property of this function and the reason it exists at all: a borrow
/// allocates nothing, so a caller can learn a value's size and refuse
/// it **before** any owning conversion exists.
enum MetadataValue<'a> {
  /// The dictionary has no such key, or the entry's value is null.
  Absent,
  /// The value, borrowed from the dictionary. Not NUL-terminated here:
  /// the terminator is what bounded the walk.
  Present(&'a [u8]),
  /// No terminator below [`METADATA_VALUE_MAX_BYTES`]. Refused rather
  /// than truncated — a truncated filename is a different filename —
  /// and now refused *visibly*, unlike an absent one.
  NotTerminated,
}

/// Measures one dictionary entry without copying it.
///
/// # Safety
///
/// `dict` must be null or a live `*const AVDictionary` for the
/// duration of this call, and the returned borrow is valid only while
/// that dictionary is neither modified nor freed.
unsafe fn metadata_value<'a>(dict: *const AVDictionary, key: &CStr) -> MetadataValue<'a> {
  if dict.is_null() {
    return MetadataValue::Absent;
  }
  // SAFETY: `dict` is live per the contract above and `key` is a
  // NUL-terminated C string by construction; `av_dict_get` reads both
  // and returns a borrowed entry owned by the dictionary.
  let entry = unsafe { av_dict_get(dict, key.as_ptr(), std::ptr::null(), 0) };
  if entry.is_null() {
    return MetadataValue::Absent;
  }
  // SAFETY: a non-null entry is a live `AVDictionaryEntry` for as long
  // as the dictionary is not modified, which it is not here.
  let value = unsafe { (*entry).value };
  if value.is_null() {
    return MetadataValue::Absent;
  }
  for len in 0..METADATA_VALUE_MAX_BYTES {
    // SAFETY: `value` is a NUL-terminated string libavutil allocated
    // with `av_strdup`; the walk reads at most one byte past the last
    // value byte and stops at the terminator.
    if unsafe { *value.add(len).cast::<u8>() } == 0 {
      // SAFETY: the `len` bytes below the terminator were just walked,
      // so the slice is in bounds and initialised. The borrow lives as
      // long as the dictionary does, which this function's contract
      // requires of its caller.
      return MetadataValue::Present(unsafe {
        std::slice::from_raw_parts(value.cast::<u8>(), len)
      });
    }
  }
  MetadataValue::NotTerminated
}

/// The length `String::from_utf8_lossy` would produce for `bytes`,
/// **without producing it**.
///
/// The charge has to be the decoded size rather than the raw one:
/// lossy decoding replaces each invalid sequence with `U+FFFD`, three
/// bytes, so a value of invalid single bytes triples on the way in. It
/// also has to be knowable before anything is allocated, which rules
/// out decoding first and measuring afterwards.
///
/// Exactness is not decorative — an approximation would either
/// under-charge the budget or refuse ordinary text — so agreement with
/// `from_utf8_lossy` is asserted directly in the unit lanes rather
/// than argued here.
pub(crate) fn lossy_len(bytes: &[u8]) -> usize {
  const REPLACEMENT: usize = char::REPLACEMENT_CHARACTER.len_utf8();

  let mut rest = bytes;
  let mut total = 0usize;
  loop {
    match std::str::from_utf8(rest) {
      Ok(valid) => return total + valid.len(),
      Err(fault) => {
        total += fault.valid_up_to() + REPLACEMENT;
        match fault.error_len() {
          // An invalid sequence of `skip` bytes becomes one `U+FFFD`.
          Some(skip) => rest = &rest[fault.valid_up_to() + skip..],
          // A truncated trailing sequence: one `U+FFFD`, and the end.
          None => return total,
        }
      }
    }
  }
}

/// Decodes measured bytes into owned text, through a buffer reserved
/// **fallibly**.
///
/// `decoded` is [`lossy_len`]'s answer for the same bytes, so the one
/// reservation here is exact and the pushes that follow cannot grow
/// it.
///
/// # Nothing is copied, and nothing allocates after the charge
///
/// The buffer is reserved once, fallibly, at the exact decoded size,
/// and then **moved** into the carrier: `Utf8Bytes::from(String)`
/// keeps a short value inline (`smol_bytes::INLINE_CAP`, no allocation
/// at all) and hands a longer one to `bytes::Bytes::from(Vec<u8>)`,
/// which takes the vector's own allocation over. The `Utf8Bytes` this
/// replaced copied into a fresh `Arc<str>` instead — a second
/// allocation, infallible, of an attacker-sized value, made while the
/// first was still live, so failing it aborted the process that the
/// budget above existed to keep alive.
///
/// **The one residue, stated exactly.** `Bytes::from(Vec<u8>)` moves
/// the buffer outright when the vector's length equals its capacity,
/// which `try_reserve_exact` followed by exactly `decoded` bytes is
/// what produces; should an allocator hand back more capacity than was
/// asked for, `bytes` allocates a fixed-size reference-count header —
/// thirty-two bytes, the same for a ten-byte title and a sixty-four
/// kibibyte one. What is gone is the part an attacker could scale.
pub(crate) fn lossy_text(bytes: &[u8], decoded: usize) -> Result<Utf8Bytes, TryReserveError> {
  let mut buffer = std::string::String::new();
  buffer.try_reserve_exact(decoded)?;

  let mut rest = bytes;
  loop {
    match std::str::from_utf8(rest) {
      Ok(valid) => {
        buffer.push_str(valid);
        break;
      }
      Err(fault) => {
        let (valid, after) = rest.split_at(fault.valid_up_to());
        buffer.push_str(
          std::str::from_utf8(valid).expect("valid_up_to bounds a valid prefix by definition"),
        );
        buffer.push(char::REPLACEMENT_CHARACTER);
        match fault.error_len() {
          Some(skip) => rest = &after[skip..],
          None => break,
        }
      }
    }
  }
  debug_assert_eq!(
    buffer.len(),
    decoded,
    "lossy_len must price exactly what lossy_text builds",
  );
  // The move. Nothing past this point copies the value.
  Ok(Utf8Bytes::from(buffer))
}

/// Names the fault a stream's metadata ran into, for the key it was
/// reading.
///
/// One mapper rather than three copies of the same `match`: the three
/// values a track row retains — `filename`, `mimetype` and `language`
/// — share one budget and one road, and differ only in which key is
/// reported.
/// Names the fault a chapter's title ran into, the way
/// [`stream_metadata_error`] does for a stream's — one mapper so the
/// admission pass and the materialisation cannot report the same fault
/// two different ways.
fn chapter_title_error(index: usize, fault: MetadataFault, limits: DemuxLimits) -> DemuxError {
  match fault {
    MetadataFault::TooLong => {
      DemuxError::ChapterTitleTooLong(ChapterTitleTooLong::new(index, METADATA_VALUE_MAX_BYTES))
    }
    MetadataFault::BudgetExhausted(total) => DemuxError::ChapterTitleBudgetExhausted(
      ChapterTitleBudgetExhausted::new(index, total, limits.max_total_chapter_title_bytes()),
    ),
    MetadataFault::Alloc(bytes) => {
      DemuxError::ChapterTitleAlloc(ChapterTitleAlloc::new(index, bytes))
    }
  }
}

fn stream_metadata_error(
  index: usize,
  key: &'static CStr,
  fault: MetadataFault,
  limits: DemuxLimits,
) -> DemuxError {
  let key = key.to_str().unwrap_or("<non-utf8 key>");
  match fault {
    MetadataFault::TooLong => DemuxError::TrackMetadataTooLong(TrackMetadataTooLong::new(
      index,
      key,
      METADATA_VALUE_MAX_BYTES,
    )),
    MetadataFault::BudgetExhausted(total) => {
      DemuxError::TrackMetadataBudgetExhausted(TrackMetadataBudgetExhausted::new(
        index,
        key,
        total,
        limits.max_total_stream_metadata_bytes(),
      ))
    }
    MetadataFault::Alloc(bytes) => {
      DemuxError::TrackMetadataAlloc(TrackMetadataAlloc::new(index, key, bytes))
    }
  }
}

/// Why a metadata value this crate meant to retain was not retained.
///
/// Crate-private on purpose: each call site maps it to an error that
/// names *what* was being read, because "the chapter titles are over
/// budget" and "this stream's language is over budget" are different
/// things to a caller even though the mechanism is one.
#[derive(Debug)]
enum MetadataFault {
  /// [`MetadataValue::NotTerminated`].
  TooLong,
  /// The running total, which is over the budget.
  BudgetExhausted(usize),
  /// The decoded size that could not be reserved.
  Alloc(usize),
}

/// **Measure, charge, then materialise — in that order.**
///
/// The order is the whole of it. Reading the size is a borrow of
/// libavutil's buffer and allocates nothing, so a value the budget
/// refuses costs no heap at all; only a value already admitted is
/// built, and it is built through [`lossy_text`]'s fallible
/// reservation.
///
/// `spent` advances only for a value actually retained.
fn retain_metadata(
  value: MetadataValue<'_>,
  spent: &mut usize,
  limit: usize,
) -> Result<Option<Utf8Bytes>, MetadataFault> {
  let Some((bytes, decoded)) = charge_metadata(value, spent, limit)? else {
    return Ok(None);
  };
  lossy_text(bytes, decoded)
    .map(Some)
    .map_err(|_| MetadataFault::Alloc(decoded))
}

/// **The judging half of [`retain_metadata`], on its own** — measure
/// and charge, build nothing.
///
/// It is separate because the judging has to happen in a place the
/// building cannot: an admission pass that runs before any table is
/// materialised. Sharing one function is what stops the two passes
/// from drifting into two rules, which for a budget would mean a file
/// admitted by one and refused by the other after the memory was
/// already spent.
///
/// Returns the admitted bytes with [`lossy_len`]'s price for them, so a
/// caller that *is* going to build can hand both straight to
/// [`lossy_text`] without measuring twice. `spent` advances only for a
/// value that was admitted.
fn charge_metadata<'a>(
  value: MetadataValue<'a>,
  spent: &mut usize,
  limit: usize,
) -> Result<Option<(&'a [u8], usize)>, MetadataFault> {
  let bytes = match value {
    MetadataValue::Absent => return Ok(None),
    MetadataValue::NotTerminated => return Err(MetadataFault::TooLong),
    MetadataValue::Present(bytes) => bytes,
  };
  let decoded = lossy_len(bytes);
  let total = spent.saturating_add(decoded);
  if total > limit {
    return Err(MetadataFault::BudgetExhausted(total));
  }
  *spent = total;
  Ok(Some((bytes, decoded)))
}

/// The three metadata keys a track row retains, in the order
/// [`build_tracks`] reads them — so the admission pass and the
/// materialisation refuse on the *same* value and name the same key.
const RETAINED_STREAM_METADATA: [&CStr; 3] = [c"filename", c"mimetype", c"language"];

/// Wraps `AVStream.attached_pic` — the real packet libavformat parsed
/// for a cover-art stream — as this track's one attachment packet.
///
/// A stream that declares cover art but parks no payload still gets a
/// packet: an empty one, marked `synthesized`, because the contract is
/// one packet per attachment track and a consumer that sees an empty
/// payload learns something true about the file. The alternative shipped
/// once — waiting for the payload to arrive as a packet later — and it
/// cannot hold: nothing stops a timed packet, or a seek, from coming
/// first, so the track's packet would arrive out of order or never.
///
/// Measured before it was written: across MP3 (ID3 APIC), M4A (`covr`),
/// FLAC (`METADATA_BLOCK_PICTURE`) and Matroska (an `image/*`
/// attachment), every stream libavformat gives
/// `AV_DISPOSITION_ATTACHED_PIC` also carries the parked packet —
/// `ff_add_attached_pic` sets the disposition and fills
/// `attached_pic` in the same breath. The empty case is the honest
/// answer to a state this build's demuxers do not produce, not a
/// fallback anything relies on.
///
/// # Safety
///
/// `pkt` must be a live `*const AVPacket` — in practice the
/// `attached_pic` embedded in the `AVStream` at `index` — for the
/// duration of this call.
unsafe fn attached_pic_payload<C: crate::FfmpegCarrier + crate::CarrierOps>(
  pkt: *const ffmpeg_next::ffi::AVPacket,
  index: usize,
  limits: DemuxLimits,
) -> Result<AttachmentPacket<AttachmentPacketExtra, C::Buffer>, DemuxError> {
  // Already admitted: [`admit_streams`] charged this payload — and
  // every other attachment in the file — before `build_tracks`
  // allocated anything. The per-attachment budget is passed down as
  // this packet's own ceiling anyway, so the funnel is guarded even if
  // a future caller reaches it without the admission pass.
  //
  // SAFETY: `pkt` is live per the contract above.
  // **The container's own cover art**, whose buffer libavformat also
  // holds — see [`crate::buffer::PayloadProvenance`] for why that
  // second reference is not the hazard a caller's second `Packet` is.
  let captured = unsafe {
    crate::buffer::payload_of::<C>(
      pkt,
      limits.max_attachment_bytes(),
      crate::buffer::PayloadProvenance::AttachedPicture,
    )
  }
  .map_err(|source| DemuxError::PacketBuffer(PacketBuffer::new(index, source)))?;
  let extra = AttachmentPacketExtra::new(index as i32);
  Ok(match captured {
    Some(payload) => {
      // The hoisted packet's own flags, through the same raw reader the
      // five boundary conversions use. FFmpeg marks an attached picture
      // `AV_PKT_FLAG_KEY` — a still image is a keyframe if anything is
      // — and building this one with empty flags dropped that, along
      // with `CORRUPT` and every other bit the packet really carried.
      // SAFETY: `pkt` points at the live embedded `AVPacket`.
      let flags = unsafe { boundary::md_flags_from_av_packet(pkt) }
        .map_err(|source| DemuxError::PacketBuffer(PacketBuffer::new(index, source)))?;
      AttachmentPacket::new(payload, extra).with_flags(flags)
    }
    // Nothing was parked, so there are no flags to read: an empty set
    // is the honest answer for a packet this layer invented.
    None => AttachmentPacket::new(C::empty(), extra.with_synthesized(true)),
  })
}

/// Builds an attachment payload out of a track's codec extradata — the
/// only place a font's bytes ever live, since an
/// `AVMEDIA_TYPE_ATTACHMENT` stream produces no packets at all.
///
/// A track with no extradata still gets a packet, with an empty
/// payload: the contract is one packet per attachment track, and a
/// consumer that sees an empty one learns something true about the
/// file. Only an allocation failure is an error.
fn extradata_payload<C: crate::FfmpegCarrier + crate::CarrierOps>(
  stream: &ffmpeg_next::format::stream::Stream<'_>,
  limits: DemuxLimits,
) -> Result<AttachmentPacket<AttachmentPacketExtra, C::Buffer>, DemuxError> {
  let index = stream.index();
  let parameters = stream.parameters();
  // SAFETY: `parameters` keeps the `AVCodecParameters` live;
  // `extradata` / `extradata_size` are public fields.
  let par = unsafe { parameters.as_ptr() };
  let ptr = unsafe { (*par).extradata };
  let len = unsafe { (*par).extradata_size }.max(0) as usize;
  // Already admitted, exactly as on the hoisted cover-art path — see
  // [`admit_streams`]. Re-judged here against the per-attachment
  // ceiling alone, so the helper is safe to call on its own.
  if len > limits.max_attachment_bytes() {
    return Err(DemuxError::AttachmentTooLarge(AttachmentTooLarge::new(
      index,
      len,
      limits.max_attachment_bytes(),
    )));
  }
  let bytes: &[u8] = if ptr.is_null() || len == 0 {
    &[]
  } else {
    // SAFETY: libavformat guarantees `extradata` is readable for
    // `extradata_size` bytes (plus its padding) while the parameters
    // live, and the slice is consumed before this function returns.
    unsafe { std::slice::from_raw_parts(ptr, len) }
  };
  // Extradata is a plain allocation with no `AVBufferRef` behind it —
  // an `AVMEDIA_TYPE_ATTACHMENT` stream produces no packets, so a
  // font's bytes never live in a refcounted buffer. **Both** lanes copy
  // here, which is what `from_bytes` is for.
  Ok(AttachmentPacket::new(
    C::from_bytes(bytes).ok_or_else(|| {
      DemuxError::PacketBuffer(PacketBuffer::new(
        index,
        crate::buffer::PacketBufferError::CaptureFailed(crate::buffer::CaptureFailed::new(len)),
      ))
    })?,
    AttachmentPacketExtra::new(index as i32).with_synthesized(true),
  ))
}

/// **The admission pass**: judges every stream in the file before the
/// track table allocates anything at all.
///
/// # Why this cannot live inside the capture
///
/// It used to, and that was a bypass. `build_tracks` deep-copies each
/// stream's `AVCodecParameters` on its way to building a `TrackExtra`,
/// and for an `AVMEDIA_TYPE_ATTACHMENT` stream **the extradata inside
/// those parameters is the attachment's payload**. So the loop paid for
/// the payload — a full `avcodec_parameters_copy` — one statement
/// before asking whether it was allowed to. A file declaring a gigabyte
/// of "font" allocated the gigabyte and then reported that a gigabyte
/// was too much.
///
/// The fix is not a check moved a few lines earlier: any per-track
/// interleaving of judging and paying has the same shape, because the
/// aggregate budget is only knowable once every track has been *seen*.
/// So the whole file is admitted here, in a pass that allocates
/// nothing — it reads two integers per stream — and only a container
/// that passes in full reaches the loop that builds carriers and
/// parameter copies.
///
/// # Why it is every stream, not every attachment
///
/// Because the track table copies **every** stream's codec parameters,
/// and `AVCodecParameters` reaches the heap three ways — `extradata`,
/// every `coded_side_data` entry, a custom channel map — all of them
/// sized by the file. A pass that walked only attachment streams left
/// the other road wide open: a MOV puts an ICC profile in
/// `coded_side_data`, on an ordinary video track, and the wholesale
/// copy took it before anything asked how big it was. That was the same
/// class of defect three review rounds running, which is why the copy
/// itself is gone (see
/// [`bounded_clone_parameters`](crate::extras::bounded_clone_parameters))
/// and why this pass sees everything.
///
/// # What is charged
///
/// The bytes this session will **retain**, which is not always the
/// declared size:
///
/// - every stream is charged its parameter clone's footprint against
///   the per-stream and whole-file codec-parameter budgets;
/// - a synthesized attachment's `extradata` is charged to the
///   *attachment* budget and left out of the parameter one, because the
///   clone strips it and the carrier holds it — one set of bytes, one
///   charge;
/// - the attachment budgets then see:
///
/// - a hoisted cover-art track retains its parked `AVPacket`'s payload
///   *and* the extradata in its parameter copy, which the still decoder
///   may need and which is not a duplicate of the payload;
/// - a synthesized `AVMEDIA_TYPE_ATTACHMENT` track retains only the
///   carrier, because `build_tracks` strips the duplicate extradata out
///   of the parameter copy (see the comment there for the census).
///
/// Charging residency rather than payload is what keeps the budget an
/// honest statement about memory instead of about file structure.
///
/// The per-attachment ceiling is judged first for each track: when a
/// single payload is itself over the line, that is the more specific
/// fact, and naming the aggregate instead would send a reader looking
/// for four hundred attachments that are not there.
fn admit_streams(input: &Input, limits: DemuxLimits) -> Result<(), DemuxError> {
  let mut attachment_spent: usize = 0;
  let mut parameter_spent: usize = 0;
  let mut metadata_spent: usize = 0;

  for stream in input.streams() {
    let index = stream.index();
    let parameters = stream.parameters();
    // SAFETY: `parameters` keeps the `AVCodecParameters` live for this
    // measurement, which allocates nothing and dereferences only what
    // it counts.
    let par = unsafe { parameters.as_ptr() };
    if par.is_null() {
      return Err(DemuxError::ParametersMissing(ParametersMissing::new(index)));
    }

    // **The ruler, judged here rather than during materialisation.**
    //
    // This is the judge-before-pay invariant for a refusal that is not
    // a budget, and it was the third place the invariant failed. A
    // malformed `AVStream.time_base` is a permanent, deterministic fact
    // about the container — it does not depend on how much memory the
    // machine has — so it can and must be decided while nothing has
    // been spent. It used to be decided inside `build_tracks`' loop,
    // which meant a malformed ruler on the *last* stream was refused
    // only after every earlier stream's codec ticket, metadata and
    // attachment carrier had been materialised.
    //
    // Structure before budget, deliberately: a stream that is malformed
    // is a more specific thing to say than a file that is too large,
    // and the two can be true of one container at once.
    let _ruler = stream_timebase(index, stream.time_base())?;

    // **And the layout's structure, for the same reason.** A non-null
    // `ch_layout.opaque`, a custom order with no map or a non-positive
    // count, and a non-null `opaque` on any map entry are all
    // permanent facts about the container that the codec ticket would
    // otherwise discover mid-materialisation — after every earlier
    // stream had been paid for. Deciding them costs a pointer walk and
    // no allocation; see
    // [`validate_channel_layout`](crate::ticket::validate_channel_layout),
    // which the ticket builder calls again as its own first statement.
    //
    // SAFETY: `par` is the live `AVCodecParameters` checked non-null
    // above, owned by `parameters` for this iteration, and for a custom
    // order libavformat filled its map with `nb_channels` entries
    // through `av_channel_layout_copy` — the same argument the demux
    // road's own channel-layout read makes.
    unsafe { crate::ticket::validate_channel_layout(par, index) }?;

    let footprint =
      unsafe { crate::extras::measure_parameters(par) }.ok_or(DemuxError::ParametersTooLarge(
        ParametersTooLarge::new(index, usize::MAX, limits.max_codec_parameter_bytes()),
      ))?;

    // SAFETY: `stream` keeps the `AVStream` live; `disposition` is a
    // public field.
    let disposition = unsafe { (*stream.as_ptr()).disposition };
    let cover_art = is_attachment_disposition(disposition);
    let synthesized = !cover_art && boundary::media_kind_of(&parameters).is_attachment();

    // What the *parameter clone* will retain for this stream. The
    // synthesized-attachment road strips `extradata` — the font's
    // payload rides the carrier instead — so counting it here would
    // charge the same bytes twice and make the budget a statement about
    // the file rather than about memory.
    let retained_parameters = if synthesized {
      footprint.total_without_extradata()
    } else {
      footprint.total()
    }
    .ok_or(DemuxError::ParametersTooLarge(ParametersTooLarge::new(
      index,
      usize::MAX,
      limits.max_codec_parameter_bytes(),
    )))?;

    if retained_parameters > limits.max_codec_parameter_bytes() {
      return Err(DemuxError::ParametersTooLarge(ParametersTooLarge::new(
        index,
        retained_parameters,
        limits.max_codec_parameter_bytes(),
      )));
    }
    parameter_spent = parameter_spent.saturating_add(retained_parameters);
    if parameter_spent > limits.max_total_codec_parameter_bytes() {
      return Err(DemuxError::ParametersBudgetExhausted(
        ParametersBudgetExhausted::new(
          index,
          parameter_spent,
          limits.max_total_codec_parameter_bytes(),
        ),
      ));
    }

    // **And the three metadata values this row will retain**, measured
    // here for the same reason everything else in this pass is: a
    // budget checked during materialisation is a budget that has
    // already been paid. The charge used to live in `build_tracks`'s
    // loop, which meant an over-budget value on the *last* stream was
    // refused only after every earlier stream's parameter clone and
    // attachment carrier had been retained and this stream's ticket
    // copied — so a file certain to be refused could first be made to
    // cost the whole aggregate, on every open.
    //
    // Nothing here allocates: `metadata_value` hands back a borrow of
    // libavutil's own buffer and `lossy_len` prices the decoding
    // without producing it. The keys are read in `build_tracks`' own
    // order so both passes refuse on the same value and name the same
    // key, and both call `charge_metadata`, so there is one rule
    // rather than two.
    //
    // SAFETY: `stream` keeps the `AVStream` — and so its metadata
    // dictionary — live across the reads below, and no borrow outlives
    // this loop iteration.
    let metadata = unsafe { (*stream.as_ptr()).metadata };
    for key in RETAINED_STREAM_METADATA {
      // SAFETY: as above.
      let raw = unsafe { metadata_value(metadata, key) };
      let _admitted = charge_metadata(
        raw,
        &mut metadata_spent,
        limits.max_total_stream_metadata_bytes(),
      )
      .map_err(|fault| stream_metadata_error(index, key, fault, limits))?;
    }

    // And what the *carrier* will hold, for the two attachment roads.
    let carrier = if cover_art {
      // SAFETY: `attached_pic` is an `AVPacket` embedded in the
      // `AVStream` by value; `addr_of!` reaches it without forming a
      // reference to the stream.
      let pkt = unsafe { std::ptr::addr_of!((*stream.as_ptr()).attached_pic) };

      // **The parked packet's own structure, judged here.**
      //
      // `PacketBuffer` is not one fault: it carries a `TRUSTED` payload
      // this crate must not copy, a `data`/`size` pair that does not lie
      // inside the buffer it claims, a buffer somebody else holds a
      // reference to, flags outside the portable set — **and** the
      // allocator declining the carrier. Only the last of those is
      // unforeseeable; the rest are permanent facts about an `AVPacket`
      // that is already parked and already readable. Deciding them in
      // the capture meant a bad final attachment was refused after every
      // earlier stream's ticket, metadata and carrier had been retained.
      //
      // The budget passed here is deliberately `usize::MAX`: the size
      // question belongs to `charge_attachment` below, which answers it
      // as `AttachmentTooLarge` against the attachment seats rather than
      // as a packet's own ceiling. This call is asked only for the
      // structural answers.
      //
      // SAFETY: `pkt` points at the live embedded `AVPacket` for the
      // whole of this call, and no plan outlives it — it is discarded
      // here, the capture happens later against the same packet.
      let _plan = unsafe {
        crate::buffer::preflight_payload(
          pkt,
          usize::MAX,
          crate::buffer::PayloadProvenance::AttachedPicture,
        )
      }
      .map_err(|source| DemuxError::PacketBuffer(PacketBuffer::new(index, source)))?;
      // And the flags the packet will be rebuilt with, which is the one
      // remaining deterministic `PacketBuffer` arm.
      //
      // SAFETY: as above.
      unsafe { boundary::md_flags_from_av_packet(pkt) }
        .map_err(|source| DemuxError::PacketBuffer(PacketBuffer::new(index, source)))?;

      // SAFETY: a plain `int` field of the live embedded packet.
      unsafe { (*pkt).size }.max(0) as usize
    } else if synthesized {
      // The **payload**, not the padded clone figure. The carrier is
      // an `FfmpegBytes` over exactly these bytes and the clone omits
      // extradata entirely on this road, so nothing here allocates the
      // padding — charging it would bill sixty-four bytes that are
      // never spent, reject a payload in the last sixty-four below the
      // ceiling, and disagree with the image road about the same file
      // at exactly the cap.
      footprint.extradata_payload()
    } else {
      // Not an attachment: nothing is captured eagerly for it, so
      // nothing more is charged.
      continue;
    };

    charge_attachment(index, carrier, limits, &mut attachment_spent)?;
  }
  Ok(())
}

/// Charges `declared` bytes against both attachment budgets, refusing
/// before anything is copied. The one place a file's attachment
/// spending is decided; see [`admit_streams`] for when it runs.
fn charge_attachment(
  index: usize,
  declared: usize,
  limits: DemuxLimits,
  spent: &mut usize,
) -> Result<(), DemuxError> {
  if declared > limits.max_attachment_bytes() {
    return Err(DemuxError::AttachmentTooLarge(AttachmentTooLarge::new(
      index,
      declared,
      limits.max_attachment_bytes(),
    )));
  }
  let total = spent.saturating_add(declared);
  if total > limits.max_total_attachment_bytes() {
    return Err(DemuxError::AttachmentBudgetExhausted(
      AttachmentBudgetExhausted::new(index, total, limits.max_total_attachment_bytes()),
    ));
  }
  *spent = total;
  Ok(())
}

/// A stream's own ruler, refused rather than repaired — **one
/// conversion and one error, for the two passes that need it**.
///
/// A timebase is file-controlled and there is no honest substitute for
/// it: it is what every timestamp on the track is measured against, so
/// a malformed one makes the track's whole timeline a fabrication
/// rather than a detail. `0/1` — libavformat's own "not set" — is not
/// malformed and is admitted; see [`rational_to_timebase`].
///
/// This exists as a function because the judgement has to happen twice
/// and must not become two judgements. [`admit_streams`] calls it while
/// nothing has been allocated, which is what makes a malformed ruler on
/// the *last* stream refuse the open before the first stream's codec
/// ticket is copied; [`build_tracks`] calls it again where the value is
/// actually used. Two call sites, one rule, and no way for the pass
/// that pays to refuse something the pass that judges admitted.
fn stream_timebase(index: usize, declared: Rational) -> Result<Timebase, DemuxError> {
  rational_to_timebase(declared).ok_or(DemuxError::TrackTimebaseInvalid(TrackTimebaseInvalid::new(
    index,
    declared.numerator(),
    declared.denominator(),
  )))
}

/// A file-controlled `AVRational` as a [`Timebase`], or `None` where it
/// is not one.
///
/// **Nothing is clamped and nothing is invented.** `None` means exactly
/// that [`Timebase`] has no such value: a denominator that is zero or
/// negative, or a negative numerator. A zero numerator *is* admitted,
/// because it is not malformed — `0/1` is libavformat's own "this
/// stream has no timebase yet" default, which ordinary containers carry
/// on untimed streams, and passing it through is reporting rather than
/// guessing. See [`positive_rational_to_timebase`] for the stricter
/// rule the seats that cannot mean *absent* take.
///
/// # Why this is fallible now
///
/// It used to clamp the denominator up to 1 and hand the numerator to
/// `Timebase::new` unexamined, on the argument that a malformed
/// timebase makes one track's timestamps meaningless rather than the
/// file unreadable. The first half of that was a fabrication — a `1/1`
/// invented here is indistinguishable downstream from a `1/1` the file
/// really declared — and the second half was a **panic**:
/// `Timebase::new` asserts a non-negative numerator, and an
/// `AVRational` out of a container can be negative. libavformat's
/// FFMETADATA parser stores `TIMEBASE=-1/1000` verbatim, so sixty bytes
/// of text were enough to abort a safe `open`. Every caller now answers
/// a `None` with a named error instead.
fn rational_to_timebase(value: Rational) -> Option<Timebase> {
  Timebase::try_new(value.numerator(), NonZeroI32::new(value.denominator())?)
}

/// [`rational_to_timebase`], and the numerator must be positive too.
///
/// The rule for a seat where a zero numerator cannot mean "absent".
///
/// A chapter's `time_base` is one such seat: `avpriv_new_chapter` takes
/// it as an argument, so whatever wrote the chapter wrote its ruler
/// too, and `0/den` there is not an unset default but a declaration
/// that every boundary in the table is the same instant — which is the
/// whole content of the row, malformed. A declared frame *rate* is the
/// other: zero frames per second is not a rate.
fn positive_rational_to_timebase(value: Rational) -> Option<Timebase> {
  (value.numerator() > 0)
    .then(|| rational_to_timebase(value))
    .flatten()
}

/// A frame *rate* as a rate-shaped [`Timebase`] (`30000/1001` for
/// 29.97 fps), or `None` when the container declares none.
fn rate_to_timebase(value: Rational) -> Option<Timebase> {
  positive_rational_to_timebase(value)
}

#[cfg(test)]
mod tests {
  use ffmpeg_next::ffi::{av_dict_free, av_dict_set};

  use ffmpeg_next::codec::Parameters;

  use super::*;
  use crate::extras::TrackExtra;

  /// Builds a dictionary holding one entry whose *value* is the given
  /// raw bytes. The bytes go in as a C string, which is all
  /// `av_dict_set` promises to copy — FFmpeg never asks whether they
  /// are UTF-8, which is the whole point of the lane below.
  fn dict_with(key: &CStr, value: &[u8]) -> *mut AVDictionary {
    let mut dict: *mut AVDictionary = std::ptr::null_mut();
    let mut terminated = value.to_vec();
    terminated.push(0);
    let rc = unsafe {
      av_dict_set(
        &mut dict,
        key.as_ptr(),
        terminated.as_ptr().cast::<std::ffi::c_char>(),
        0,
      )
    };
    assert!(rc >= 0, "av_dict_set failed: {rc}");
    dict
  }

  #[test]
  fn metadata_that_is_not_utf8_is_read_lossily_not_unsoundly() {
    // The bytes a real container can hold: a Latin-1 "café.ttf" whose
    // 0xE9 is not valid UTF-8 on its own. Read through
    // `DictionaryRef::get` this produced a `&str` that violates the
    // type's invariant — undefined behaviour before anything ever
    // copied it.
    let raw = b"caf\xE9.ttf".to_vec();
    assert!(
      std::str::from_utf8(&raw).is_err(),
      "the source bytes really are not UTF-8",
    );
    let dict = dict_with(c"filename", &raw);
    let mut spent = 0usize;
    let text = retain_metadata(
      unsafe { metadata_value(dict, c"filename") },
      &mut spent,
      usize::MAX,
    )
    .expect("a readable value")
    .expect("the entry exists");
    assert_eq!(text.as_str(), "caf\u{FFFD}.ttf");
    assert_eq!(
      spent,
      "caf\u{FFFD}.ttf".len(),
      "the charge is the decoded size, which the replacement made longer than the raw bytes",
    );
    // A key the dictionary does not hold, and a null dictionary, are
    // both simply absent.
    assert!(matches!(
      unsafe { metadata_value(dict, c"mimetype") },
      MetadataValue::Absent,
    ));
    assert!(matches!(
      unsafe { metadata_value(std::ptr::null(), c"filename") },
      MetadataValue::Absent,
    ));
    unsafe { av_dict_free(&mut { dict }) };
  }

  #[test]
  fn valid_metadata_survives_unchanged() {
    let dict = dict_with(c"mimetype", b"application/x-truetype-font");
    let mut spent = 0usize;
    assert_eq!(
      retain_metadata(
        unsafe { metadata_value(dict, c"mimetype") },
        &mut spent,
        usize::MAX,
      )
      .expect("a readable value")
      .as_deref(),
      Some("application/x-truetype-font"),
    );
    unsafe { av_dict_free(&mut { dict }) };
  }

  #[test]
  fn an_unterminated_length_is_refused_rather_than_truncated() {
    // Nothing libavutil produces is this long; the cap exists so a
    // value it did not terminate cannot walk off the end. A value that
    // reaches the cap is refused — and, since this shape was fixed,
    // refused *visibly*: it is no longer the same answer as absent.
    let long = vec![b'a'; METADATA_VALUE_MAX_BYTES + 1];
    let dict = dict_with(c"filename", &long);
    assert!(matches!(
      unsafe { metadata_value(dict, c"filename") },
      MetadataValue::NotTerminated,
    ));
    unsafe { av_dict_free(&mut { dict }) };
  }

  /// A reader that panics with a payload whose destructor panics in
  /// turn. Both panics are safe code; the second one is what used to
  /// leave the guard and enter the `extern "C"` AVIO callback.
  struct PanicsWithAHostilePayload;

  struct PanicOnDrop;

  impl Drop for PanicOnDrop {
    fn drop(&mut self) {
      panic!("and the payload went too");
    }
  }

  impl std::io::Read for PanicsWithAHostilePayload {
    fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
      std::panic::panic_any(PanicOnDrop);
    }
  }

  impl std::io::Seek for PanicsWithAHostilePayload {
    fn seek(&mut self, _pos: std::io::SeekFrom) -> std::io::Result<u64> {
      std::panic::panic_any(PanicOnDrop);
    }
  }

  #[test]
  fn a_reader_panic_with_a_hostile_payload_does_not_abort_the_process() {
    // In its own process, because the assertion *is* the process: a
    // parent that sees the child exit cleanly has seen the abort not
    // happen. The guard caught the reader's panic and then dropped its
    // payload outside `catch_unwind`, so a payload whose `Drop` panics
    // sent that second panic straight out of `read` and into C —
    // through the very guard that exists to stop it.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::a_reader_panic_with_a_hostile_payload_does_not_abort_the_process",
      || {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let opened =
          CarrierDemuxer::<crate::Owned>::open_reader(PanicsWithAHostilePayload, Some("x.mkv"));
        std::panic::set_hook(previous);
        match opened {
          Err(DemuxError::ReaderPanic(_)) => {}
          Err(other) => panic!("expected ReaderPanic, got {other:?}"),
          Ok(_) => panic!("a reader that only panics cannot open a container"),
        }
      },
    );
  }

  #[test]
  fn codec_parameters_that_cannot_be_allocated_are_named() {
    // `Parameters::new` does not check `avcodec_parameters_alloc`, and
    // `clone_from` dereferences the result immediately: under a failed
    // allocation the shipped clone would write through null.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::codec_parameters_that_cannot_be_allocated_are_named",
      || {
        let source = Parameters::new();
        assert!(
          !unsafe { source.as_ptr() }.is_null(),
          "the source allocates before the cap goes on",
        );
        crate::fault_subprocess::cap_ffmpeg_allocations(1);
        let refused = crate::extras::bounded_clone_parameters(&source, 4, usize::MAX);
        crate::fault_subprocess::uncap_ffmpeg_allocations();
        assert!(
          matches!(
            refused,
            Err(DemuxError::ParametersAlloc(ref p)) if p.stream_index() == 4
          ),
          "expected ParametersAlloc, got {:?}",
          refused.map(|_| ()),
        );
        // And with the cap lifted the same copy succeeds, so the
        // refusal was the allocator's answer and not a broken helper.
        crate::extras::bounded_clone_parameters(&source, 4, usize::MAX).expect("an uncapped copy");
      },
    );
  }

  #[test]
  fn the_public_track_extra_handoffs_still_answer_the_allocator() {
    // The lane this replaces guarded a hazard that no longer exists:
    // `TrackExtra` derived `Clone` over `ffmpeg_next`'s `Parameters`,
    // whose clone dereferences an unchecked allocation, so safe public
    // code reached a SIGSEGV by copying a track row. The row holds no
    // `Parameters` at all now, and the two public handoffs have split
    // in kind because of it:
    //
    // * `Clone` allocates **nothing from FFmpeg** — it copies an
    //   owned mirror, which is a `Vec` spine and a refcount bump — so
    //   it survives a capped allocator rather than reporting through
    //   one. That is what makes the derive honest under the carrier
    //   law, and a capped allocator is the only way to pin it.
    // * `clone_parameters` is the rebuild, and it is where FFmpeg
    //   allocation moved to. It still answers.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::the_public_track_extra_handoffs_still_answer_the_allocator",
      || {
        let source = Parameters::new();
        assert!(!unsafe { source.as_ptr() }.is_null(), "allocated uncapped");
        let extra = TrackExtra::new(
          6,
          crate::ticket::CodecTicket::mirror(&source, 6, usize::MAX).expect("uncapped"),
        );

        crate::fault_subprocess::cap_ffmpeg_allocations(1);
        let cloned = extra.clone();
        let handed = extra.clone_parameters().map(|_| ());
        crate::fault_subprocess::uncap_ffmpeg_allocations();

        assert_eq!(
          cloned.parameter_bytes(),
          extra.parameter_bytes(),
          "the row cloned under an allocator that refuses everything",
        );
        assert!(
          matches!(handed, Err(DemuxError::ParametersAlloc(ref p)) if p.stream_index() == 6),
          "TrackExtra::clone_parameters: {handed:?}",
        );

        // And the rebuild works once the allocator does.
        extra.clone_parameters().expect("an uncapped handoff");
      },
    );
  }

  #[test]
  fn parameters_that_never_allocated_are_refused_at_the_door() {
    // The route the destination check could not see. A safe
    // `Parameters::new()` under a failed allocation hands back a
    // null-backed value and says nothing; the copier then allocated its
    // own destination happily — the allocator having recovered by
    // then — and called `avcodec_parameters_copy(out, NULL)`, which
    // dereferences its source. Same crash, one recovery later, still
    // from safe public code.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::parameters_that_never_allocated_are_refused_at_the_door",
      || {
        // The cap is on *while the source is built* — that is the whole
        // difference from the destination lane.
        crate::fault_subprocess::cap_ffmpeg_allocations(1);
        let never_allocated = Parameters::new();
        crate::fault_subprocess::uncap_ffmpeg_allocations();
        assert!(
          unsafe { never_allocated.as_ptr() }.is_null(),
          "the safe constructor really does hand back a null-backed value",
        );

        // The door moved with the handle. `TrackExtra::new` no longer
        // takes a `Parameters` at all, so the only way a null-backed
        // one reaches a track row is through the mirror — which is
        // where the check now lives, and where it belongs: beside the
        // raw pointer rather than one type downstream of it.
        let refused = crate::ticket::CodecTicket::mirror(&never_allocated, 9, usize::MAX);
        let Err(DemuxError::ParametersMissing(p)) = refused.map(|_| ()) else {
          panic!("a null-backed source must not become a codec ticket");
        };
        assert_eq!(p.stream_index(), 9);

        // And the copier refuses it too, so the invariant is not the
        // only thing standing between this and a null dereference.
        let never_allocated = {
          crate::fault_subprocess::cap_ffmpeg_allocations(1);
          let p = Parameters::new();
          crate::fault_subprocess::uncap_ffmpeg_allocations();
          p
        };
        assert!(matches!(
          crate::extras::bounded_clone_parameters(&never_allocated, 9, usize::MAX).map(|_| ()),
          Err(DemuxError::ParametersMissing(p)) if p.stream_index() == 9,
        ));

        // A row built over real parameters still hands off both ways,
        // so the refusal is about the null and nothing else.
        let real = Parameters::new();
        let extra = TrackExtra::new(
          9,
          crate::ticket::CodecTicket::mirror(&real, 9, usize::MAX).expect("real parameters"),
        );
        let _ = extra.clone();
        extra.clone_parameters().expect("handoff");
      },
    );
  }

  #[cfg(feature = "resample")]
  #[test]
  fn a_spec_read_from_parameters_that_never_allocated_is_absent() {
    // The same trap at another public door, found by the sweep:
    // `ResampleSpec::from_parameters` asks `parameters.medium()`
    // first, and *that* dereferences the pointer inside ffmpeg-next
    // before any code of ours runs.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::a_spec_read_from_parameters_that_never_allocated_is_absent",
      || {
        crate::fault_subprocess::cap_ffmpeg_allocations(1);
        let never_allocated = Parameters::new();
        crate::fault_subprocess::uncap_ffmpeg_allocations();
        assert!(unsafe { never_allocated.as_ptr() }.is_null());
        assert_eq!(
          crate::ResampleSpec::from_parameters(&never_allocated),
          None,
          "parameters that do not exist describe no audio",
        );
      },
    );
  }

  #[test]
  fn codec_parameters_whose_copy_fails_are_named() {
    // The other leg: the destination allocates, and the deep copy of
    // the extradata does not. `clone_from` discards that return value,
    // so the shipped clone handed back parameters missing the very
    // bytes a decoder needs to open — and said nothing.
    crate::fault_subprocess::in_subprocess(
      "demuxer::tests::codec_parameters_whose_copy_fails_are_named",
      || {
        const EXTRADATA: usize = 8 * 1024 * 1024;
        let mut source = Parameters::new();
        // SAFETY: `source` owns a live `AVCodecParameters`; the buffer
        // comes from FFmpeg's allocator and is handed to it, so
        // `avcodec_parameters_free` releases it with the rest.
        unsafe {
          let par = source.as_mut_ptr();
          let extradata = ffmpeg_next::ffi::av_mallocz(EXTRADATA) as *mut u8;
          assert!(!extradata.is_null(), "av_mallocz");
          (*par).extradata = extradata;
          (*par).extradata_size = EXTRADATA as i32;
        }

        // Big enough for the destination `AVCodecParameters`, far too
        // small for its extradata.
        crate::fault_subprocess::cap_ffmpeg_allocations(64 * 1024);
        let refused = crate::extras::bounded_clone_parameters(&source, 2, usize::MAX);
        crate::fault_subprocess::uncap_ffmpeg_allocations();
        match refused {
          Err(DemuxError::ParametersCopy(p)) => assert_eq!(p.stream_index(), 2),
          Err(other) => panic!("expected ParametersCopy, got {other:?}"),
          Ok(_) => panic!("a copy that could not copy the extradata must not succeed"),
        }
        crate::extras::bounded_clone_parameters(&source, 2, usize::MAX).expect("an uncapped copy");
      },
    );
  }

  /// A stream whose `attached_pic` is `parked`, and the packet
  /// libavformat would queue for it.
  ///
  /// # On the fixture road
  ///
  /// The container shape this guards — a stream carrying
  /// `ATTACHED_PIC | TIMED_THUMBNAILS` — **cannot be minted by the
  /// ffmpeg CLI**, and that was censused rather than assumed: no muxer
  /// has a field for those bits (`-disposition:v
  /// attached_pic+timed_thumbnails` round-trips to nothing through
  /// mp4, mov and matroska alike), because the mov *demuxer* derives
  /// them from a chapter-track reference its own muxer does not write
  /// in that direction.
  ///
  /// What is reproducible, and what actually matters, is the **packet
  /// shape**: `read_frame_internal` queues a stream's parked picture
  /// with `av_packet_ref` while keeping its own reference, which is
  /// exactly what `av_packet_ref` builds here. The classification half
  /// — that such a stream is video rather than an attachment — is
  /// pinned separately by
  /// [`a_timed_thumbnail_stream_is_not_an_attachment`].
  fn parked_picture_stream(parked: &Packet) -> (Box<AVStream>, Packet) {
    use ffmpeg_next::packet::{Mut, Ref};

    let mut stream: Box<AVStream> = Box::new(unsafe { std::mem::zeroed() });
    let mut queued = Packet::empty();
    // SAFETY: `parked` is a live refcounted packet; `av_packet_ref`
    // takes a reference to its buffer, which is precisely what
    // libavformat does when it queues an attached picture. The stream
    // is zeroed apart from the one field the probe reads.
    unsafe {
      assert_eq!(
        ffmpeg_next::ffi::av_packet_ref(queued.as_mut_ptr(), parked.as_ptr()),
        0,
      );
      stream.attached_pic.buf = (*parked.as_ptr()).buf;
      stream.attached_pic.data = (*parked.as_ptr()).data;
      stream.attached_pic.size = (*parked.as_ptr()).size;
    }
    (stream, queued)
  }

  #[test]
  fn a_queued_attached_picture_is_recognised() {
    use ffmpeg_next::packet::Ref;

    let parked = Packet::copy(&[9u8; 2048]);
    let (stream, queued) = parked_picture_stream(&parked);

    // The two references are different structs around one allocation —
    // which is the whole reason the probe compares `buffer` and not the
    // `AVBufferRef`. Asserting the difference is what makes this a test
    // of the right comparison rather than of a lucky one.
    // SAFETY: both packets are live.
    unsafe {
      assert_ne!(
        (*queued.as_ptr()).buf,
        (*parked.as_ptr()).buf,
        "av_packet_ref must mint a new reference struct",
      );
    }
    // SAFETY: the stream is a zeroed `AVStream` whose only populated
    // fields are the ones the probe reads, and `queued` is live.
    assert!(unsafe { packet_is_parked_picture(&*stream, &queued) });

    // An ordinary timed packet — the shape every pull after the first
    // one has — is not the parked picture.
    let ordinary = Packet::copy(&[1u8; 2048]);
    // SAFETY: as above.
    assert!(!unsafe { packet_is_parked_picture(&*stream, &ordinary) });

    // And a stream that parks nothing recognises nothing.
    let bare: Box<AVStream> = Box::new(unsafe { std::mem::zeroed() });
    // SAFETY: as above.
    assert!(!unsafe { packet_is_parked_picture(&*bare, &queued) });
  }

  #[test]
  fn the_queued_picture_is_admitted_and_later_packets_take_the_ordinary_road() {
    use crate::buffer::{PacketBufferError, PayloadProvenance, payload_of};
    use ffmpeg_next::packet::Ref;

    let parked = Packet::copy(&[9u8; 2048]);
    let (_stream, queued) = parked_picture_stream(&parked);
    // SAFETY: the packet is live; `buf` is a public field.
    let parked_buffer = unsafe { (*parked.as_ptr()).buf };

    // **The first pull.** Two references, one of them the container's.
    // From a *caller* that shape is refused, because a caller's second
    // reference may be a `Packet` with a safe `data_mut`.
    // SAFETY: `queued` is live for every call in this test.
    assert!(matches!(
      unsafe {
        payload_of::<crate::View>(
          queued.as_ptr(),
          usize::MAX,
          PayloadProvenance::CallerSupplied,
        )
      },
      Err(PacketBufferError::SharedPayload(_)),
    ));

    // Delivered by the demux loop, the same shape is carried — by copy,
    // because a window would outlive the exclusivity the read rests on.
    // SAFETY: as above.
    let copied = unsafe {
      payload_of::<crate::View>(
        queued.as_ptr(),
        usize::MAX,
        PayloadProvenance::DemuxDelivered,
      )
    }
    .expect("a demux-delivered shared payload is carriable")
    .expect("it has a payload");
    assert_eq!(copied.as_ref(), &[9u8; 2048][..]);
    // SAFETY: the packet is live; `data` is a public field.
    unsafe {
      assert_ne!(
        copied.as_ref().as_ptr() as usize,
        (*queued.as_ptr()).data as usize,
        "a shared demux-delivered payload is copied, not windowed",
      );
    }

    // With the provenance the probe establishes, both lanes carry it.
    // SAFETY: as above.
    let viewed = unsafe {
      payload_of::<crate::View>(
        queued.as_ptr(),
        usize::MAX,
        PayloadProvenance::AttachedPicture,
      )
    }
    .expect("the container's own picture is carriable")
    .expect("it has a payload");
    assert_eq!(viewed.as_ref(), &[9u8; 2048][..]);
    // And on the view lane it is a window into the parked allocation
    // rather than a copy of it.
    // SAFETY: both are live; `data`/`size` are public fields.
    unsafe {
      let start = (*parked_buffer).data as usize;
      let end = start + (*parked_buffer).size;
      let at = viewed.as_ref().as_ptr() as usize;
      assert!(
        at >= start && at + viewed.len() <= end,
        "the queued picture must be viewed, not copied",
      );
    }
    // SAFETY: as above.
    let owned = unsafe {
      payload_of::<crate::Owned>(
        queued.as_ptr(),
        usize::MAX,
        PayloadProvenance::AttachedPicture,
      )
    }
    .expect("the owned lane carries it too")
    .expect("it has a payload");
    assert_eq!(owned.as_ref(), &[9u8; 2048][..]);

    // **Every pull after it.** A timed packet has a buffer of its own,
    // so it stays on the `Delivered` road, is unique, and the view lane
    // shares it.
    let later = Packet::copy(&[4u8; 1024]);
    // SAFETY: `later` is live.
    let shared = unsafe {
      payload_of::<crate::View>(
        later.as_ptr(),
        usize::MAX,
        PayloadProvenance::DemuxDelivered,
      )
    }
    .expect("an ordinary packet is carriable")
    .expect("it has a payload");
    // SAFETY: as above.
    unsafe {
      assert_eq!(
        shared.as_ref().as_ptr() as usize,
        (*later.as_ptr()).data as usize,
        "a uniquely-referenced packet is still shared, not copied",
      );
    }
  }

  #[test]
  fn a_timed_thumbnail_stream_is_not_an_attachment() {
    // `TIMED_THUMBNAILS` is documented as only ever appearing beside
    // `ATTACHED_PIC`, so testing the picture bit alone reads a sparse
    // chapter-thumbnail track as cover art — and the attachment
    // contract then delivers exactly one of its images and drops the
    // rest, every one of which had a timestamp.
    assert!(
      is_attachment_disposition(AV_DISPOSITION_ATTACHED_PIC),
      "a plain attached picture is still an attachment",
    );
    assert!(
      !is_attachment_disposition(AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS),
      "a timed-thumbnail stream is a timed track, whatever else it is flagged",
    );
    // Neither bit, and the other bits that ride along, change nothing.
    assert!(!is_attachment_disposition(0));
    assert!(!is_attachment_disposition(AV_DISPOSITION_TIMED_THUMBNAILS));
    assert!(is_attachment_disposition(
      AV_DISPOSITION_ATTACHED_PIC | ffmpeg_next::ffi::AV_DISPOSITION_DEFAULT
    ));
    // And the reason the raw bits are read at all: the wrapper's own
    // flag set cannot express the distinction.
    assert!(
      ffmpeg_next::format::stream::Disposition::from_bits(AV_DISPOSITION_TIMED_THUMBNAILS)
        .is_none(),
      "ffmpeg_next mints no TIMED_THUMBNAILS bit — from_bits_truncate would drop it silently",
    );
  }

  #[test]
  fn an_uncapturable_cover_still_gets_its_one_packet() {
    // The state the shipped `AwaitingPacket` fallback existed for: a
    // stream that declares cover art and parks no payload. The fallback
    // waited for a packet that may never come, and let timed packets —
    // and seeks — go first, which the face forbids. The track now gets
    // its one packet at open like every other attachment track: empty,
    // and marked as this layer's own work.
    //
    // Not reachable from a file: across MP3, M4A, FLAC and Matroska,
    // every ATTACHED_PIC stream libavformat produces carries the parked
    // packet, because `ff_add_attached_pic` sets the disposition and
    // fills it in the same call. A zeroed `AVPacket` is exactly what
    // `attached_pic` would hold if one ever did not.
    let empty: ffmpeg_next::ffi::AVPacket = unsafe { std::mem::zeroed() };
    let packet = unsafe { attached_pic_payload::<crate::Owned>(&empty, 7, DemuxLimits::default()) }
      .expect("an unparked cover is a degenerate track, not an unreadable file");
    assert!(packet.data().as_ref().is_empty());
    assert!(
      packet.extra().synthesized(),
      "nothing in the container handed this payload over",
    );
    assert_eq!(packet.extra().stream_index(), 7);
  }

  /// **`lossy_len` prices exactly what `from_utf8_lossy` builds.**
  ///
  /// The budget charge is made from this number *before* anything is
  /// decoded, so a disagreement would either under-charge the budget —
  /// the hostile case, where bytes that are not UTF-8 triple on the way
  /// through — or refuse ordinary text. Asserted against the real
  /// decoder rather than argued, over the shapes that differ: valid
  /// ASCII and multi-byte text, a lone invalid byte, a run of them, an
  /// invalid sequence between valid text, and a truncated trailing
  /// sequence (which `error_len() == None` reports and which becomes
  /// exactly one replacement).
  #[test]
  fn lossy_len_prices_exactly_what_lossy_text_builds() {
    let cases: [&[u8]; 9] = [
      b"",
      b"Opening",
      "héllo wörld".as_bytes(),
      b"\xff",
      b"\xff\xfe\xfd",
      b"before\xffafter",
      b"\xe2\x82",           // truncated three-byte sequence
      b"ok\xe2\x82",         // ... after valid text
      b"\xf0\x9f\x92\xa9ok", // a real four-byte sequence, untouched
    ];
    for raw in cases {
      let built = std::string::String::from_utf8_lossy(raw);
      assert_eq!(
        lossy_len(raw),
        built.len(),
        "{raw:?} must be priced at what from_utf8_lossy produces",
      );
      let text = lossy_text(raw, lossy_len(raw)).expect("a small reservation");
      assert_eq!(
        text.as_str(),
        built.as_ref(),
        "{raw:?} must decode identically"
      );
    }
  }

  /// **Measure, charge, materialise — and a value the budget refuses is
  /// never materialised at all.**
  ///
  /// The ordering is a property of the types rather than of the
  /// control flow, which is what makes it hold: [`metadata_value`]
  /// hands back a **borrow** of libavutil's buffer, so the size is
  /// known before any owning conversion exists, and the refusal below
  /// happens with nothing on the heap. A zero budget therefore costs
  /// nothing however long the value is.
  #[test]
  fn a_refused_metadata_value_is_never_materialised() {
    let long = vec![b'x'; 4096];
    let mut spent = 0usize;
    match retain_metadata(MetadataValue::Present(&long), &mut spent, 0) {
      Err(MetadataFault::BudgetExhausted(total)) => assert_eq!(total, 4096),
      _ => panic!("a zero budget must refuse a 4096-byte value"),
    }
    assert_eq!(spent, 0, "a refused value does not advance the budget");

    // Under a budget that admits it, the same value is retained and
    // charged its decoded size — once.
    let mut spent = 0usize;
    let text = retain_metadata(MetadataValue::Present(&long), &mut spent, 8192)
      .expect("admitted")
      .expect("present");
    assert_eq!(text.len(), 4096);
    assert_eq!(spent, 4096);

    // And the three outcomes stay apart.
    let mut spent = 0usize;
    assert!(
      retain_metadata(MetadataValue::Absent, &mut spent, 0)
        .expect("absent is not a fault")
        .is_none(),
    );
    assert!(matches!(
      retain_metadata(MetadataValue::NotTerminated, &mut spent, usize::MAX),
      Err(MetadataFault::TooLong),
    ));
    assert_eq!(spent, 0);
  }

  /// **A value with no terminator is not an absent value.**
  ///
  /// The shape that used to erase it: the reader answered `None` for
  /// both, so a declared title of exactly 65,536 bytes reached a
  /// consumer as an untitled chapter, uncharged against any budget.
  #[test]
  fn the_unterminated_case_is_distinct_from_the_absent_one() {
    let mut spent = 0usize;
    assert!(matches!(
      retain_metadata(MetadataValue::NotTerminated, &mut spent, usize::MAX),
      Err(MetadataFault::TooLong),
    ));
    assert!(matches!(
      retain_metadata(MetadataValue::Absent, &mut spent, usize::MAX),
      Ok(None),
    ));
  }

  /// **A malformed rational is refused, never clamped and never a
  /// panic.**
  ///
  /// This replaces a lane that asserted the opposite — that `1/0` came
  /// back as `1/1`. That clamp was a fabrication a consumer could not
  /// tell from a declaration, and it did not cover the case that
  /// actually bites: `Timebase::new` asserts a non-negative numerator,
  /// so a negative one panicked a safe `open`. libavformat stores
  /// `TIMEBASE=-1/1000` out of an FFMETADATA sidecar verbatim, which
  /// made sixty bytes of text enough to abort the process.
  #[test]
  fn a_malformed_rational_is_refused_rather_than_clamped() {
    for (num, den) in [(1, 0), (1, -1000), (-1, 1000), (-1, -1000)] {
      assert_eq!(
        rational_to_timebase(Rational::new(num, den)),
        None,
        "{num}/{den} is not a timebase, and inventing one for it would be indistinguishable \
         downstream from a file that declared it",
      );
    }
  }

  /// **One rule for a stream's ruler, and both passes hold it.**
  ///
  /// The refusal used to live inside `build_tracks`' materialisation
  /// loop, so a malformed ruler on the *last* stream was decided only
  /// after every earlier stream's codec ticket, metadata and attachment
  /// carrier had been paid for. It is decided in `admit_streams` now,
  /// where nothing has been allocated — and by *this* function, which
  /// is the only place the conversion and the error are written, so the
  /// pass that pays cannot refuse something the pass that judges
  /// admitted.
  ///
  /// **On reachability, stated rather than implied.** Unlike
  /// `AVChapter.time_base` — which libavformat stores exactly as an
  /// FFMETADATA sidecar wrote it, `TIMEBASE=-1/1000` included, and
  /// which the lane above pins against a real container — a stream's
  /// timebase normally arrives through `avpriv_set_pts_info`, which
  /// refuses a non-positive value itself. No container was found that
  /// reaches this refusal, so it is a defensive one: demuxers that
  /// assign `st->time_base` directly are not obliged to go through that
  /// helper, and a check whose cost is one comparison is not worth
  /// trading for an assumption about every demuxer in libavformat. What
  /// this lane can pin is the rule and the report; what the ordering
  /// rests on is that the pass it now lives in allocates nothing at
  /// all.
  #[test]
  fn a_stream_ruler_is_refused_by_one_rule_that_names_what_was_declared() {
    for (num, den) in [(1, 0), (1, -1000), (-1, 1000), (-1, -1000)] {
      match stream_timebase(7, Rational::new(num, den)) {
        Err(DemuxError::TrackTimebaseInvalid(fault)) => {
          assert_eq!(fault.stream_index(), 7, "the refusal names the stream");
          assert_eq!(
            (fault.num(), fault.den()),
            (num, den),
            "{num}/{den} is reported as the container wrote it, not as a repair",
          );
        }
        // Split so nothing here relies on `Timebase` being `Debug`.
        Err(other) => panic!("{num}/{den} must be a timebase fault, got {other:?}"),
        Ok(_) => panic!("{num}/{den} must be refused, and it was admitted"),
      }
    }

    // And the two shapes a stream may legitimately carry are admitted:
    // an ordinary ruler, and libavformat's own "never set".
    assert_eq!(
      stream_timebase(0, Rational::new(1, 90_000))
        .map(|tb| (tb.num(), tb.den().get()))
        .ok(),
      Some((1, 90_000)),
    );
    assert_eq!(
      stream_timebase(0, Rational::new(0, 1))
        .map(|tb| (tb.num(), tb.den().get()))
        .ok(),
      Some((0, 1)),
      "`0/1` is not malformed for a track seat — see the lane below",
    );
  }

  /// A zero numerator is the one rational the two rules disagree on,
  /// and the disagreement is the point.
  ///
  /// `0/1` is libavformat's own default for a stream whose demuxer
  /// never set one, so a track seat reads it as the container declaring
  /// nothing. A chapter's ruler is written by whatever wrote the
  /// chapter, so the same value there is a claim that every boundary in
  /// the table falls on one instant — malformed, and refused.
  #[test]
  fn a_zero_numerator_is_absent_for_a_track_and_malformed_for_a_chapter() {
    let zero = Rational::new(0, 1);
    assert_eq!(
      rational_to_timebase(zero).map(|tb| (tb.num(), tb.den().get())),
      Some((0, 1)),
      "the track rule passes libavformat's own unset default through",
    );
    assert_eq!(
      positive_rational_to_timebase(zero),
      None,
      "the strict rule refuses it",
    );
  }

  #[test]
  fn a_declared_frame_rate_becomes_a_rate_shaped_timebase() {
    let ntsc = rate_to_timebase(Rational::new(30_000, 1001)).expect("declared");
    assert_eq!((ntsc.num(), ntsc.den().get()), (30_000, 1001));
    assert_eq!(
      rate_to_timebase(Rational::new(0, 1)),
      None,
      "0 fps is absent"
    );
    assert_eq!(
      rate_to_timebase(Rational::new(30, 0)),
      None,
      "no denominator"
    );
  }

  #[test]
  fn the_seek_timebase_is_microseconds() {
    // `avformat_seek_file` with `stream_index == -1` takes AV_TIME_BASE
    // units; a target expressed in anything else has to arrive there.
    let tb = av_time_base_q();
    assert_eq!((tb.num(), tb.den().get()), (1, 1_000_000));
    let target = Timestamp::new(1_500, Timebase::new(1, NonZeroI32::new(1000).expect("ms")));
    assert_eq!(target.rescale_to(tb).pts(), 1_500_000);
  }
}