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
use std::{collections::VecDeque, mem::ManuallyDrop, ptr};

use ffmpeg_next::{
  Codec, Packet, Rational,
  codec::{
    self,
    Context,
    // Bring the `Mut` / `Ref` traits into scope so `Packet::as_ptr` /
    // `Packet::as_mut_ptr` resolve. They are aliased to avoid shadowing
    // any future `Mut`/`Ref` types we might add — `cargo clippy` would
    // otherwise flag them as "unused" without the alias and the import
    // can mistakenly look unused. Confirmed in use by all `packet.as_ptr()`
    // / `packet.as_mut_ptr()` call sites in this module.
    packet::{Mut as PacketMut, Ref as PacketRef},
  },
  ffi::{
    AVBufferRef, AVCodec, AVFrame, AVHWFramesContext, AVMediaType, av_buffer_ref, av_buffer_unref,
    av_frame_move_ref, av_frame_unref, av_hwdevice_ctx_create, av_hwframe_transfer_data,
    av_packet_ref, avcodec_alloc_context3, avcodec_free_context, avcodec_parameters_to_context,
  },
  frame,
};

/// Local FFI shims: FFmpeg entry points re-declared with `c_int` where
/// the generated bindings use a closed Rust enum.
///
/// Constructing `AVCodecID` / `AVPixelFormat` / `AVSampleFormat` from a
/// runtime integer that is not in this build's discriminant set is UB —
/// and these are open C enums that FFmpeg extends in ABI-compatible
/// releases. Declaring the same C symbol with `c_int` sidesteps the
/// boundary entirely: both Rust declarations resolve to the same symbol
/// at link time, and the integer never becomes an enum on the Rust
/// side.
///
/// **This is the enum class inside this crate's own code.** The
/// dependency-API sweep closed every place *ffmpeg-next* formed an enum
/// out of FFmpeg memory; these three are places the crate's own new
/// code did the same thing. The census that walks the pixel-format
/// table to price the worst format is the sharpest instance: it exists
/// precisely to be correct about formats this build does not name, and
/// the binding it called returned those very ids as a closed
/// `AVPixelFormat`. Every id would have become an invalid enum value on
/// the way *into* the pricing that was supposed to handle it.
pub(crate) mod c_shims {
  use libc::c_int;

  use super::AVCodec;

  unsafe extern "C" {
    /// `AVCodecID` as `c_int`.
    pub fn avcodec_find_decoder(id: c_int) -> *const AVCodec;

    /// `AVCodecID` as `c_int`, answering the descriptor libavcodec keeps
    /// for that id — or null where this build names no codec for it.
    ///
    /// The pointer is into `codec_descriptors[]`, a `static const` table
    /// compiled into libavcodec, so the strings it names are live and
    /// unwritten for the process — the contract `crate::ffi`'s bounded
    /// reader is given. It is left **raw** at every call site: the
    /// struct embeds an `AVCodecID` and an `AVMediaType`, and forming a
    /// reference to it would assert two bindgen enums valid on a table
    /// that belongs to the linked library rather than to the bindings.
    /// See `crate::CodecId::descriptor`.
    ///
    /// Preferred over `avcodec_get_name`, which never answers null: for
    /// an id it cannot place it returns the string `"unknown_codec"`,
    /// a sentinel wearing a name's clothes. A descriptor that is absent
    /// is `None` here, and a consumer can tell the two apart.
    pub fn avcodec_descriptor_get(id: c_int) -> *const ffmpeg_next::ffi::AVCodecDescriptor;

    /// Returns `AVPixelFormat` as `c_int` — the id of a descriptor that
    /// may well name a format this build's bindings do not.
    pub fn av_pix_fmt_desc_get_id(desc: *const ffmpeg_next::ffi::AVPixFmtDescriptor) -> c_int;

    /// Takes `AVPixelFormat` as `c_int`, so an id straight out of
    /// [`av_pix_fmt_desc_get_id`] can be priced without ever being an
    /// enum.
    pub fn av_image_get_buffer_size(
      pix_fmt: c_int,
      width: c_int,
      height: c_int,
      align: c_int,
    ) -> c_int;

    /// Takes `AVSampleFormat` as `c_int`. Kept for the footprint
    /// sweep, which walks the format table to decide which cells
    /// exist; production pricing goes through
    /// `av_samples_get_buffer_size`, the allocator's own ruler.
    #[cfg(test)]
    pub fn av_get_bytes_per_sample(sample_fmt: c_int) -> c_int;

    /// The allocator's own audio ruler, with `AVSampleFormat` as
    /// `c_int`. `align = 0` asks for the alignment
    /// `av_frame_get_buffer` itself uses.
    pub fn av_samples_get_buffer_size(
      linesize: *mut c_int,
      nb_channels: c_int,
      nb_samples: c_int,
      sample_fmt: c_int,
      align: c_int,
    ) -> c_int;

    /// Writes an `AV_PIX_FMT_NONE`-terminated list of destination
    /// formats a transfer may produce. Declared `*mut *mut c_int` so
    /// the list is walked as integers — a driver may well offer a
    /// format this build's bindings do not name.
    pub fn av_hwframe_transfer_get_formats(
      hwframe_ctx: *mut ffmpeg_next::ffi::AVBufferRef,
      dir: c_int,
      formats: *mut *mut c_int,
      flags: c_int,
    ) -> c_int;
  }
}

use mediadecode::{Received, Sent, decoder::ScaledOutputCapability};

use crate::{
  backend::{self, Backend},
  error::{AllBackendsFailed, Error, HwDeviceInitFailed, Result},
  ffi::{CallbackState, codec_supports_hwaccel, get_hw_format},
  frame::Frame,
};

/// Hardware-accelerated video decoder.
///
/// Hardware-only — there is no software fallback inside this crate. If
/// every hardware backend in the platform's probe order fails to open,
/// `open` returns [`Error::AllBackendsFailed`] and the caller is
/// responsible for falling back to a software decoder of their choice
/// (e.g. `ffmpeg::decoder::Video`).
///
/// Mirrors `ffmpeg::decoder::Video`'s `send_packet`/`receive_frame` interface.
/// Decoded frames are returned through [`crate::Frame`], a CPU-side wrapper
/// whose accessors avoid the `AVPixelFormat`-enum UB that an unvalidated read
/// of FFmpeg's raw integer pixel formats can trigger.
///
/// `open` does a true probe: each backend opens with a strict `get_format`
/// callback. On the first non-transient error from a backend the decoder is
/// torn down and the next backend in probe order is tried, with all packets
/// seen so far replayed through it. The advance is *transactional* — the
/// candidate backend must successfully build and accept the replayed packets
/// before any probe state is consumed, so a failing backend in the middle of
/// the order does not strand the caller without history. Once the first frame
/// is delivered the probe collapses and subsequent calls go straight to the
/// active (committed) backend.
///
/// The committed backend can still fail at runtime — e.g. VideoToolbox can
/// decode a clip's first frames and then hit content its kernel can't handle
/// (H.264 High 4:2:2 10-bit), surfacing `AVERROR_EXTERNAL`. Post-commit a
/// non-transient, non-EOF error from the committed backend is reclassified to
/// [`Error::AllBackendsFailed`] (see the `is_hw_decode_failure` predicate), so
/// the [`crate::FfmpegVideoStreamDecoder`] wrapper still recognises it as a
/// HW-path exhaustion and falls back to software. The post-commit
/// `unconsumed_packets` is empty (the probe buffer is gone); the wrapper's
/// rolling since-last-keyframe buffer supplies the replay set.
pub struct VideoDecoder {
  /// Live FFmpeg state for the currently active backend.
  state: DecoderState,
  /// Reusable frame buffer used for hw-side decoding before transfer / move.
  /// Internal use only — never handed to callers.
  hw_frame: frame::Video,
  /// Probe state: present until the first frame is received from the active
  /// backend, then `None`. While `Some`, packets are buffered for replay and
  /// non-transient errors / decoder failures advance to the next backend.
  probe: Option<ProbeState>,
  /// CPU-side frames produced by a candidate decoder during probe replay
  /// (when its internal queue filled and we had to drain output before the
  /// next `send_packet`). Already transferred from the candidate's
  /// `AVHWFramesContext` to a CPU frame, so they remain valid after the
  /// candidate state is committed. [`Self::receive_frame`] dequeues these
  /// FIFO before reading from `state.inner`.
  pending_frames: VecDeque<frame::Video>,
  /// Per-decoder byte budget for [`Self::pending_frames`] during probe
  /// replay. Defaults to [`DEFAULT_MAX_PROBE_PENDING_BYTES`]; override via
  /// [`Self::with_max_probe_pending_bytes`].
  max_probe_pending_bytes: usize,
  /// Resource ceilings for the frames this decoder produces. Fixed at
  /// open, because [`FrameLimits::max_pixels`] is written into every
  /// `AVCodecContext` this decoder builds — including the ones a probe
  /// advance builds later — and a context's ceiling cannot be moved
  /// after `avcodec_open2`.
  frame_limits: crate::limits::DecoderLimits,
  /// The stream's packet timebase, written into every
  /// `AVCodecContext` this decoder opens — including the ones a probe
  /// advance opens later, which is why it is held rather than passed.
  ///
  /// `None` for a standalone decoder: [`Self::open`] and its siblings
  /// are handed codec parameters and no stream, so there is no ruler
  /// to declare. The stream decoder one tier up has one.
  pkt_timebase: Option<mediadecode::Timebase>,
  /// `true` once [`Self::send_eof`] has been accepted, until
  /// [`Self::flush`].
  ///
  /// **It lives here rather than in [`ProbeState`], and that move is
  /// the point.** It used to be a probe field, so it vanished the
  /// moment the probe collapsed — a committed decoder could not tell
  /// whether the caller had signalled the end, and therefore could not
  /// answer the one question [`SessionPhase`] exists to answer without
  /// guessing. The probe machinery still reads it for replay; it simply
  /// no longer owns it.
  eof_sent: bool,
  /// The GPU-side scaled-output stage — see [`crate::vtscale`]. Carries
  /// the caller's standing [`Self::request_scaled_output`] and, on the
  /// VideoToolbox road, the cached pixel-transfer session and fitted
  /// frames context the CPU download reads from.
  ///
  /// **It rides the decoder rather than the wrapper** because the seam
  /// it inserts itself into is here: between the decoded hardware frame
  /// and `av_hwframe_transfer_data`, the one point at which a picture is
  /// still a GPU surface and can still be resized without a
  /// full-resolution round-trip through main memory.
  ///
  /// Declared last, so it drops **after** the [`DecoderState`] holding
  /// the VideoToolbox device its fitted frames context was built over —
  /// and that order is safe by the FFmpeg contract rather than by luck:
  /// `av_hwframe_ctx_alloc` "will make a new reference for internal
  /// use", so the device outlives the decoder that opened it for exactly
  /// as long as this stage still holds a context over it.
  scaled_output: crate::vtscale::ScaledOutput,
}

/// Owned FFmpeg state for one open codec context. Has its own `Drop` so we
/// can swap it out cleanly during a probe advance via `mem::replace`.
struct DecoderState {
  /// Wrapped FFmpeg decoder. `ManuallyDrop` so we can sequence its drop
  /// before freeing the callback state.
  inner: ManuallyDrop<ffmpeg_next::decoder::Video>,
  /// Backend driving this state.
  backend: Backend,
  /// Owned reference produced by `av_hwdevice_ctx_create`.
  hw_device_ref: *mut AVBufferRef,
  /// Owned `Box<CallbackState>` raw pointer; `AVCodecContext::opaque`
  /// aliases it.
  callback_state: *mut CallbackState,
}

/// Maximum number of packets we are willing to buffer for probe replay
/// before abandoning the fallback safety net. Set high enough to absorb
/// long B-frame GOPs and codec setup latency, low enough to bound memory
/// against malicious / pathological streams that never produce a first
/// frame.
const MAX_PROBE_PACKETS: usize = 256;

/// Maximum total compressed-byte size of buffered probe packets. Each
/// `Packet` clone holds a refcounted reference to the demuxer's bitstream
/// data — even though the clone itself is shallow, the underlying buffers
/// stay alive until we drop them. 64 MiB is generous for normal video and
/// gives untrusted media a hard ceiling.
const MAX_PROBE_PACKET_BYTES: usize = 64 * 1024 * 1024;

/// Hard cap on the number of side-data entries we tolerate per buffered
/// packet. `av_packet_ref` allocates an `AVPacketSideData` descriptor and
/// an `AVBufferRef` per entry, so a packet stuffed with many tiny or
/// zero-sized entries can consume significant memory in descriptor /
/// allocator overhead even after [`packet_side_data_bytes`] charges
/// [`SIDE_DATA_ENTRY_OVERHEAD`] bytes per entry. Refusing to clone such
/// packets short-circuits the descriptor explosion path.
///
/// Sized for legitimate streams (typical video packets carry 0-5 side-
/// data entries; SEI-heavy HEVC/AV1 maybe a dozen) while comfortably
/// rejecting weaponised input.
///
/// Shared with the [`crate::FfmpegVideoStreamDecoder`] rolling GOP buffer,
/// which charges the same side-data budget so its byte cap is a true upper
/// bound on retained memory rather than counting bare payloads.
pub(crate) const MAX_PROBE_PACKET_SIDE_DATA_ENTRIES: usize = 64;

/// Conservative per-side-data-entry overhead estimate used by both
/// [`packet_side_data_bytes`] and the budget accounting in
/// [`VideoDecoder::send_packet`]. Counts the `AVPacketSideData`
/// descriptor (24 bytes per the FFmpeg 9.x bindings), the `AVBufferRef`
/// FFmpeg allocates per entry, and a margin for malloc bookkeeping
/// (header bytes, alignment slack). Setting it on the high side keeps
/// the byte cap a true upper bound on retained memory; under-charging
/// would let many tiny entries slip past the cap.
const SIDE_DATA_ENTRY_OVERHEAD: usize = 80;

/// Conservative upper-bound bytes-per-pixel multiplier used to estimate
/// the size of a CPU frame **before** `av_hwframe_transfer_data`
/// allocates its pixel buffers. Covers every HW download format this
/// crate produces (worst case is `P416LE` / `P412LE` at 6 bytes/pixel
/// for 16-bit 4:4:4 semi-planar) plus a margin for FFmpeg's per-row
/// stride alignment (typically 32-byte aligned, ~5% extra at HD widths
/// and below).
///
/// Used by [`drain_into_pending`] as a pre-transfer guard: if the
/// product `width * height * WORST_CASE_BYTES_PER_PIXEL` would already
/// push `pending_bytes` past `max_probe_pending_bytes`, the candidate
/// replay refuses the frame *before* allocating. Without this, FFmpeg
/// would perform the full HW→CPU download (potentially ~100 MiB for
/// 8K HDR) and we would only reject the frame after RSS had already
/// spiked. The post-transfer accounting via [`cpu_frame_bytes`] stays in
/// place as a backstop using the frame's actual stride/format.
///
/// Slightly over-charges true 4:2:0 NV12 / P010 frames (which dominate
/// real workloads) — that's the right side to err on. Callers feeding
/// 8K+ workloads through the probe path can tune
/// [`VideoDecoder::with_max_probe_pending_bytes`] upward to compensate.
const WORST_CASE_BYTES_PER_PIXEL: usize = 8;

/// Maximum number of CPU frames we are willing to queue from a candidate
/// during probe replay. Each frame is a fully-allocated CPU buffer
/// (~3 MiB for 1080p NV12, ~24 MiB for 4K P010, ~96 MiB for 8K P010), so
/// an unbounded queue would OOM on a candidate with a shallow internal
/// queue against a deep replay history. This cap, together with
/// [`DEFAULT_MAX_PROBE_PENDING_BYTES`], is enforced as a hard limit during
/// replay: once either limit is reached, probe buffering fails for the
/// candidate (returns `ENOMEM` from `drain_into_pending`) instead of
/// queueing additional drained frames. The probe loop then advances to
/// the next backend or returns `Error::AllBackendsFailed` if exhausted.
const MAX_PROBE_PENDING_FRAMES: usize = 16;

/// Default byte budget for probe-replay drained frames. 256 MiB is enough
/// for 16 frames at 4K P010 (~24 MiB each = 384 MiB worst case under the
/// count cap), and is the cap that fires first for very high-resolution
/// content (8K P010: ~96 MiB per frame → only ~2 frames fit).
///
/// Override per-decoder with [`VideoDecoder::with_max_probe_pending_bytes`]
/// when targeting 8K+ workloads or memory-constrained environments.
///
/// TODO: when frames significantly exceed typical sizes, consider
/// memmap-backed pending buffers (write transferred frames to a temp file
/// or shared-memory segment) so the resident set stays bounded even when
/// the byte cap is raised. Out of scope for now.
pub const DEFAULT_MAX_PROBE_PENDING_BYTES: usize = 256 * 1024 * 1024;

/// Where a decoding session is in its life — **the one derived fact the
/// classifiers read, and the only place the latches are interpreted.**
///
/// Every road that must decide what an errno *means* needs the same two
/// questions answered, and answering them ad hoc at each road is what
/// let them disagree. `EAGAIN` means "send me more" only where more can
/// come; `AVERROR_EOF` means "the stream is over" only where a backend
/// has committed to producing it. Read those wrong and a caller is
/// handed a state with no satisfying operation, or a candidate that
/// will never produce a frame is mistaken for a finished stream.
///
/// The two questions are exactly the two dimensions the machinery
/// already keeps latches for — whether an end has been recorded, and
/// whether a backend is still on trial — so this enum is a census of
/// those latches rather than a new idea. Deriving it lives in
/// [`VideoDecoder::phase`] and its siblings, one per session type;
/// nothing else reads a latch to answer a classification question.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum SessionPhase {
  /// A committed backend, and no end-of-stream recorded. Both flow
  /// signals mean what they say.
  Streaming,
  /// A committed backend draining its tail after a recorded end. "Send
  /// me more" is no longer satisfiable here — the caller has nothing
  /// left to send and the send gates refuse — so it reads as the end.
  Draining,
  /// A candidate backend on trial, no end recorded. It may legitimately
  /// want more input; what it may not do is quietly end the stream on
  /// the caller's behalf, which is the committed backend's privilege.
  Auditioning,
  /// A candidate on trial that has already been handed the whole
  /// history, **end-of-stream included**.
  ///
  /// The arm that had no name. A candidate here has been given
  /// everything there is and answers about a stream that is already
  /// over: if it has produced no frame, it never will. That is a
  /// candidate failing — the probe's business — and neither "send me
  /// more" (nothing left to send) nor "the stream ended" (this backend
  /// never decoded a thing) is a true reading of it.
  AuditioningPastEnd,
}

impl SessionPhase {
  /// Whether more input can still reach this session.
  ///
  /// The satisfiability question: [`Received::NeedsInput`] and
  /// [`Sent::MustDrain`] are both instructions, and both are honest
  /// only where the caller can carry them out.
  pub(crate) const fn accepts_input(self) -> bool {
    matches!(self, Self::Streaming | Self::Auditioning)
  }

  /// Whether a backend has committed, and so may speak for the stream.
  ///
  /// Only a committed backend's `AVERROR_EOF` is the stream's end. A
  /// candidate's is its own: it drained to nothing without ever proving
  /// it could decode this content.
  pub(crate) const fn is_committed(self) -> bool {
    matches!(self, Self::Streaming | Self::Draining)
  }
}

/// How a funnel verdict routes. See [`VideoDecoder::verdict_routing`].
enum VerdictRouting {
  /// The name says this backend cannot decode this content.
  CandidateFailed,
  /// The name says retrying a backend cannot help — report it as it is.
  Direct,
  /// Nothing was named; the road's own reading decides.
  Unnamed,
}

/// What an **unnamed** verdict means on the road that produced it — the
/// one thing the shared routing policy cannot know for itself.
enum BareVerdict {
  /// A flow signal's own fault: `avcodec_send_packet` answering
  /// `AVERROR_EOF` to a submission past the end. The probe must not
  /// advance on it — the candidate did nothing wrong, the caller did.
  Reported,
  /// A real failure. While a candidate is on trial, that is the
  /// candidate failing.
  CandidateFailure,
}

/// What the caller should do with a routed hardware failure.
enum HwRoute {
  /// Hand this to the caller.
  Report(Error),
  /// The active candidate failed: advance the probe and retry.
  Advance(Error),
}

/// State carried only during the probe window (before the first successful
/// frame). Holds enough information to tear down the current decoder and
/// retry with the next backend.
struct ProbeState {
  parameters: codec::Parameters,
  codec: Codec,
  /// Backends still to try, in order. Empty means "no more options after
  /// the active one fails" — `advance_probe` then surfaces
  /// [`Error::AllBackendsFailed`] so the contract is the same on
  /// single-backend platforms (e.g. macOS) as on multi-backend ones.
  remaining_backends: Vec<Backend>,
  /// Packets sent so far, kept for replay through any candidate backend.
  /// Preserved across failed candidates — only cleared when the probe
  /// collapses on a successful first frame, or when the probe is
  /// abandoned due to the size caps.
  buffered_packets: Vec<Packet>,
  /// Cumulative size (in compressed bytes) of `buffered_packets`. Tracked
  /// incrementally so we don't have to re-sum on every send.
  buffered_bytes: usize,
  /// Whether `send_eof` has been called; replayed alongside packets.
  /// Per-backend errors captured since the probe window opened. Pushed
  /// whenever a backend's failure triggers `advance_probe` (the active
  /// backend that just failed) or a candidate's build / replay rejects
  /// it. Drained into [`Error::AllBackendsFailed`] when the probe
  /// exhausts every option.
  attempts: Vec<(Backend, Box<Error>)>,
}

// SAFETY: All raw pointers are exclusively owned by `DecoderState` and never
// shared. `ffmpeg::decoder::Video` is itself `Send` (its `Context` carries an
// `unsafe impl Send`). The decoder is not safe for concurrent use, hence not
// `Sync`.
//
// `VideoDecoder`'s claim additionally covers what `crate::vtscale` holds on
// Apple targets: a `VTPixelTransferSessionRef` and an `AVBufferRef` to a
// fitted `AVHWFramesContext`. Both are exclusively owned by the stage — no
// `Clone`, no handing out — and every use of the session goes through
// `&mut ScaledOutput`, so the one-transfer-at-a-time protocol
// `VTPixelTransferSessionTransferImage` expects is serialized by the borrow
// rather than by a lock. VideoToolbox sessions are Core Foundation objects
// with no thread affinity (unlike the UI-framework types that have one), so
// moving one between threads is exactly as sound as moving the codec context
// beside it. Still not `Sync`, for the same reason nothing else here is.
unsafe impl Send for DecoderState {}
unsafe impl Send for VideoDecoder {}

impl Drop for DecoderState {
  fn drop(&mut self) {
    // Order matters:
    //  1. Drop the codec context first. While it lives, FFmpeg may invoke
    //     `get_format`, which dereferences `callback_state` via `opaque`.
    //  2. Free the callback state heap allocation.
    //  3. Release our hw device reference (FFmpeg released its own when
    //     the codec context was freed in step 1).
    unsafe {
      ManuallyDrop::drop(&mut self.inner);
      if !self.callback_state.is_null() {
        drop(Box::from_raw(self.callback_state));
        self.callback_state = ptr::null_mut();
      }
      if !self.hw_device_ref.is_null() {
        av_buffer_unref(&mut self.hw_device_ref);
      }
    }
  }
}

impl VideoDecoder {
  /// Auto-probe hardware backends in the platform's default order.
  ///
  /// Each backend opens with a strict `get_format` callback. The first
  /// backend whose `avcodec_open2` succeeds becomes active; if its first
  /// frame is unusable (decode error, transfer failure, or a CPU-format
  /// frame from a HW context) the decoder is torn down and the next backend
  /// is tried — packets sent so far are replayed through the new decoder
  /// transparently. The probe advance is transactional: the next backend
  /// must build *and* accept the replayed history before any probe state is
  /// consumed, so a misbehaving middle backend cannot strand the caller.
  ///
  /// [`Self::backend`] reflects whichever backend ultimately produced the
  /// first frame.
  ///
  /// [`Error::AllBackendsFailed`] surfaces in two places, with the same
  /// meaning ("no hardware backend can decode this stream — fall back to
  /// software yourself"):
  /// - From `open` itself, when no backend even opens.
  /// - From [`Self::send_packet`] / [`Self::send_eof`] /
  ///   [`Self::receive_frame`], when the initially-opened backend fails
  ///   at decode time and every remaining backend in the probe order
  ///   either also fails or doesn't exist. On single-backend platforms
  ///   (e.g. macOS, where the order is `[VideoToolbox]`), this is the
  ///   only place a HW-only failure surfaces.
  ///
  /// In both cases, `attempts` carries the per-backend error log. When
  /// the runtime path fires, `unconsumed_packets` also contains the
  /// packets the decoder consumed from the caller before the probe
  /// exhausted (refcounted shallow clones); for non-seekable inputs
  /// (live streams, pipes) the caller can replay these directly into
  /// a software decoder of their choice without re-demuxing. From the
  /// open-time path the vec is empty since no packets have been sent.
  ///
  /// On `Ok`, the returned decoder **always** has an active probe
  /// rescue safety net. If a parameters clone fails under memory
  /// pressure before the probe state can be set up, `open` returns
  /// `Err(Error::Ffmpeg(Other { errno: ENOMEM }))` rather than handing
  /// back a live decoder with no fallback contract. No packets have
  /// been sent yet, so the caller can retry or fall back to software
  /// with the original `parameters` directly.
  pub fn open(parameters: codec::Parameters) -> Result<Self> {
    Self::open_with_frame_limits(parameters, crate::limits::DecoderLimits::default())
  }

  /// [`Self::open`], with the stream's packet timebase declared.
  ///
  /// **Prefer this one whenever the caller knows the timebase**, which
  /// is nearly always: the packets fed to a decoder carry timestamps in
  /// their stream's units, and `AVCodecContext.pkt_timebase` is how
  /// libavcodec is told what those units are. Not owning the
  /// `AVStream` does not mean not knowing its ruler.
  ///
  /// The value reaches every `AVCodecContext` this decoder opens,
  /// including the ones a later hardware probe advance opens.
  pub fn open_timed(
    parameters: codec::Parameters,
    timebase: mediadecode::Timebase,
  ) -> Result<Self> {
    Self::open_with_frame_limits_timed(
      parameters,
      crate::limits::DecoderLimits::default(),
      timebase,
    )
  }

  /// [`Self::open`], with the frame ceilings named.
  ///
  /// Taken at open for the reason [`Self::open_with_limits`] gives:
  /// [`FrameLimits::max_pixels`] is written into every `AVCodecContext`
  /// this decoder opens — including the ones a later probe advance
  /// opens — and a context's ceiling cannot be moved after
  /// `avcodec_open2`.
  pub fn open_with_frame_limits(
    parameters: codec::Parameters,
    limits: crate::limits::DecoderLimits,
  ) -> Result<Self> {
    // **Explicitly untimed.** No packet timebase is declared, so
    // `AVCodecContext.pkt_timebase` is left at libavcodec's own
    // default and anything it derives from that field — a subtitle
    // cue's PTS, a packet-duration fallback — is unavailable. Reach
    // for [`Self::open_with_frame_limits_timed`] when the stream's
    // ruler is known, which is nearly always.
    Self::open_with_frame_limits_timed_in(parameters, limits, None)
  }

  /// [`Self::open_with_frame_limits`], with the stream's packet
  /// timebase declared — see [`Self::open_timed`].
  pub fn open_with_frame_limits_timed(
    parameters: codec::Parameters,
    limits: crate::limits::DecoderLimits,
    timebase: mediadecode::Timebase,
  ) -> Result<Self> {
    Self::open_with_frame_limits_timed_in(parameters, limits, Some(timebase))
  }

  fn open_with_frame_limits_timed_in(
    parameters: codec::Parameters,
    limits: crate::limits::DecoderLimits,
    pkt_timebase: Option<mediadecode::Timebase>,
  ) -> Result<Self> {
    let codec = find_decoder(&parameters)?;
    let order = backend::probe_order();

    let mut attempts: Vec<(Backend, Box<Error>)> = Vec::new();
    for (i, &backend) in order.iter().enumerate() {
      // Use the checked clone — ffmpeg-next's `Parameters::clone` does
      // `avcodec_parameters_alloc` without a null check and ignores the
      // return of `avcodec_parameters_copy`. Under OOM that path silently
      // produces a Parameters with a null inner pointer.
      let cloned_for_build =
        match try_clone_parameters(&parameters, limits.max_codec_parameter_bytes()) {
          Ok(p) => p,
          Err(e) => {
            tracing::warn!(?backend, error = %e, "hwdecode: parameters clone failed");
            attempts.push((backend, Box::new(e)));
            continue;
          }
        };
      match Self::build_state(cloned_for_build, codec, backend, limits, pkt_timebase) {
        Ok(state) => {
          tracing::info!(?backend, "hwdecode: opened video decoder (probing)");
          let remaining = order[(i + 1)..].to_vec();
          // Deep-copy the caller's `parameters` before storing in ProbeState.
          // `codec::Parameters` from `stream.parameters()` carries an Rc
          // owner pointing at the demuxer; moving that Rc to a worker
          // thread (when VideoDecoder is sent) would race with the demuxer's
          // Rc on the original thread. The checked clone copies the bytes
          // into a fresh allocation with `owner: None`, severing the link.
          //
          // We always create ProbeState — even when `remaining` is empty
          // (single-backend platforms like macOS) — so that a first-frame
          // failure on the only backend surfaces as
          // `Error::AllBackendsFailed` from `receive_frame` /
          // `send_packet` rather than as a raw FFmpeg error. That keeps
          // the API contract the same regardless of how many HW backends
          // the platform exposes.
          //
          // If the clone fails (ENOMEM), fail the **whole open call**
          // rather than returning a live decoder with `probe: None`.
          // Returning Ok here would let the caller send packets that the
          // active backend consumes, and a subsequent backend failure
          // would then surface as a raw FFmpeg error with no
          // `unconsumed_packets` — silently breaking the rescue contract
          // for non-seekable inputs (live streams, pipes). Dropping the
          // already-built `state` here runs its FFmpeg cleanup, and the
          // caller can retry / fall back to software with the original
          // parameters in their hand (no packets were consumed yet).
          // Seed the probe's attempt log with any backends that failed
          // to open earlier in this loop (including
          // `BackendUnsupportedByCodec` and parameters-clone errors).
          // Without this, a runtime exhaustion on the active backend
          // would surface an `AllBackendsFailed` containing only the
          // active backend's runtime failure — losing the original
          // open-time causes that, on multi-backend platforms (Linux,
          // Windows), are usually the more diagnostic signal. E.g. a
          // VAAPI-then-CUDA host where VAAPI fails to open and CUDA
          // later fails at first-frame must report both failures in
          // probe order, not just CUDA.
          let probe = match try_clone_parameters(&parameters, limits.max_codec_parameter_bytes()) {
            Ok(probe_params) => ProbeState {
              parameters: probe_params,
              codec,
              remaining_backends: remaining,
              buffered_packets: Vec::new(),
              buffered_bytes: 0,
              attempts: std::mem::take(&mut attempts),
            },
            Err(e) => {
              tracing::warn!(
                error = %e,
                "hwdecode: parameters clone failed for probe state at open; \
                 failing closed instead of returning a decoder without rescue"
              );
              return Err(e);
            }
          };
          return Ok(Self {
            state,
            hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
            probe: Some(probe),
            pending_frames: VecDeque::new(),
            max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
            frame_limits: limits,
            pkt_timebase,
            eof_sent: false,
            scaled_output: crate::vtscale::ScaledOutput::new(),
          });
        }
        Err(e) => {
          tracing::warn!(?backend, error = %e, "hwdecode: backend open failed");
          attempts.push((backend, Box::new(e)));
        }
      }
    }
    // No packets have been consumed at open time.
    Err(Error::AllBackendsFailed(AllBackendsFailed::new(
      attempts,
      Vec::new(),
    )))
  }

  /// Open the decoder with a specific backend. No probe, no fallback.
  ///
  /// If `backend` cannot actually decode this stream, the failure surfaces
  /// from [`Self::receive_frame`] (the strict `get_format` callback returns
  /// `AV_PIX_FMT_NONE`, the decoder errors out). The caller is responsible
  /// for retrying with another hardware backend or falling back to a
  /// software decoder of their choice (e.g. `ffmpeg::decoder::Video`).
  pub fn open_with(parameters: codec::Parameters, backend: Backend) -> Result<Self> {
    Self::open_with_limits(parameters, backend, crate::limits::DecoderLimits::default())
  }

  /// [`Self::open_with`], with the stream's packet timebase declared —
  /// see [`Self::open_timed`].
  pub fn open_with_timed(
    parameters: codec::Parameters,
    backend: Backend,
    timebase: mediadecode::Timebase,
  ) -> Result<Self> {
    Self::open_with_limits_timed(
      parameters,
      backend,
      crate::limits::DecoderLimits::default(),
      timebase,
    )
  }

  /// [`Self::open_with`], with the frame ceilings named.
  ///
  /// The limits are taken **at open**, not through a `with_*` builder,
  /// because [`FrameLimits::max_pixels`] is written straight into the
  /// `AVCodecContext` this call opens — that is the layer that makes
  /// libavcodec refuse an oversized picture before allocating it, and a
  /// context's ceiling cannot be moved after `avcodec_open2`. A builder
  /// would have silently applied to only half the enforcement.
  pub fn open_with_limits(
    parameters: codec::Parameters,
    backend: Backend,
    limits: crate::limits::DecoderLimits,
  ) -> Result<Self> {
    // Explicitly untimed — see [`Self::open_with_frame_limits`].
    Self::open_with_limits_timed_in(parameters, backend, limits, None)
  }

  /// [`Self::open_with_limits`], with the stream's packet timebase
  /// declared — see [`Self::open_timed`].
  pub fn open_with_limits_timed(
    parameters: codec::Parameters,
    backend: Backend,
    limits: crate::limits::DecoderLimits,
    timebase: mediadecode::Timebase,
  ) -> Result<Self> {
    Self::open_with_limits_timed_in(parameters, backend, limits, Some(timebase))
  }

  fn open_with_limits_timed_in(
    parameters: codec::Parameters,
    backend: Backend,
    limits: crate::limits::DecoderLimits,
    pkt_timebase: Option<mediadecode::Timebase>,
  ) -> Result<Self> {
    let codec = find_decoder(&parameters)?;
    let state = Self::build_state(parameters, codec, backend, limits, pkt_timebase)?;
    Ok(Self {
      state,
      hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
      probe: None,
      pending_frames: VecDeque::new(),
      max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
      frame_limits: limits,
      pkt_timebase,
      eof_sent: false,
      scaled_output: crate::vtscale::ScaledOutput::new(),
    })
  }

  /// Builds a decoder around a **software** `ffmpeg::decoder::Video`,
  /// for tests that need [`VideoDecoder`]'s own send/receive arms driven
  /// against real libavcodec.
  ///
  /// **Why this exists.** Those arms classify libavcodec's flow control
  /// themselves, and the only other way to reach them is
  /// [`VideoDecoder::open`], which needs a working hardware backend and
  /// a sample file — so every existing lane through them is
  /// `#[ignore]`-gated and runs nowhere. A regression that never runs is
  /// a claim, not a check. This keeps the arms, the probe state and the
  /// funnels exactly as production builds them and swaps only the
  /// backend behind `state.inner`, which is the one thing a test cannot
  /// otherwise supply.
  ///
  /// `auditioning` opens the probe window with **no backends left to
  /// try**, which is what makes the candidate-failure road observable:
  /// `advance_probe` has nowhere to advance to, so it surfaces
  /// [`Error::AllBackendsFailed`] and a lane can tell "the probe road
  /// was taken" from "a status was answered". Passing `false` leaves the
  /// probe collapsed, for lanes that mean to exercise a committed
  /// backend.
  ///
  /// The `backend` label is cosmetic here — it is read only for the
  /// attempt log and [`Self::backend`], neither of which a software
  /// decoder reaches — and `hw_device_ref` is null, which
  /// [`DecoderState`]'s `Drop` already handles.
  #[cfg(test)]
  pub(crate) fn from_software_for_test(
    parameters: codec::Parameters,
    limits: crate::limits::DecoderLimits,
    auditioning: bool,
  ) -> Result<Self> {
    let codec = find_decoder(&parameters)?;
    let (ctx, callback_state) = build_codec_context(&parameters, limits, None)?;
    let opened = ctx.decoder().open_as(codec).map_err(Error::Ffmpeg)?;
    ensure_video_codec_type(&opened)?;
    let state = DecoderState {
      inner: ManuallyDrop::new(ffmpeg_next::decoder::Video(opened)),
      backend: backend::probe_order()
        .first()
        .copied()
        .unwrap_or(Backend::VideoToolbox),
      hw_device_ref: ptr::null_mut(),
      callback_state: Box::into_raw(callback_state),
    };
    let probe = auditioning.then(|| ProbeState {
      parameters: try_clone_parameters(&parameters, limits.max_codec_parameter_bytes())
        .expect("a clonable parameter set"),
      codec,
      remaining_backends: Vec::new(),
      buffered_packets: Vec::new(),
      buffered_bytes: 0,
      attempts: Vec::new(),
    });
    Ok(Self {
      state,
      hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
      probe,
      pending_frames: VecDeque::new(),
      max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
      frame_limits: limits,
      pkt_timebase: None,
      eof_sent: false,
      scaled_output: crate::vtscale::ScaledOutput::new(),
    })
  }

  /// Override the byte budget for probe-replay queued frames. Defaults to
  /// [`DEFAULT_MAX_PROBE_PENDING_BYTES`]. Use a higher value when targeting
  /// 8K+ workloads where 16 frames at full size could exceed the default;
  /// use a lower value in memory-constrained services to bound peak
  /// allocation more tightly.
  ///
  /// Setting after the first frame has been delivered is harmless but has
  /// no observable effect — the probe has already collapsed and the cap
  /// only applies during replay drain.
  ///
  /// Returns `self` for builder-style chaining:
  /// ```ignore
  /// let decoder = VideoDecoder::open(params)?
  ///     .with_max_probe_pending_bytes(1024 * 1024 * 1024); // 1 GiB
  /// ```
  #[must_use]
  pub fn with_max_probe_pending_bytes(mut self, bytes: usize) -> Self {
    self.max_probe_pending_bytes = bytes;
    self
  }

  /// The backend currently producing frames. While the probe is still in
  /// progress (no frame received yet) this returns the optimistically
  /// selected backend; after the first frame, it is the backend that
  /// actually produced it. Once stable, never changes again.
  pub fn backend(&self) -> Backend {
    self.state.backend
  }

  /// Whether this decoder can emit pictures at a caller-requested size
  /// instead of full coded size.
  ///
  /// [`ScaledOutputCapability::Supported`] on exactly one road: the
  /// VideoToolbox backend on an Apple target, where
  /// [`crate::vtscale`]'s `VTPixelTransferSession` sits between the
  /// decoded hardware frame and the CPU download. Every other backend
  /// this crate wires — [`Backend::Vaapi`], [`Backend::Cuda`],
  /// [`Backend::D3d11va`] — answers `Unsupported`, each with its own
  /// filed native scaling seam.
  ///
  /// # And it stops saying `Supported` the moment the promise breaks
  ///
  /// The trait's contract is that a `Supported` answer lets a caller
  /// skip its own resampler, so a session that quietly went back to
  /// full-size pictures under that answer would hand the caller mixed
  /// extents with nothing to notice them by. The stage can stand down
  /// per frame — a padded pixel buffer, a crop rectangle, side data a
  /// resize would strand, a resolution change that turns the standing
  /// request into an upscale, a transfer that fails — and the **first**
  /// frame that goes out at anything other than the requested extent
  /// flips this answer to [`ScaledOutputCapability::Unsupported`]. That
  /// is the explicit transition a caller is told to look for: query
  /// again and learn that resampling is theirs once more. A fresh
  /// [`Self::request_scaled_output`] buys a fresh promise.
  ///
  /// A request the stream already satisfies is not a broken promise:
  /// the picture arrives at exactly the size asked for.
  ///
  /// A pure query: it neither requests anything nor changes what
  /// [`Self::receive_frame`] delivers.
  pub fn scaled_output_capability(&self) -> ScaledOutputCapability {
    if crate::vtscale::ScaledOutput::supported()
      && self.state.backend.is_video_toolbox()
      && self.scaled_output.promise_stands()
    {
      ScaledOutputCapability::Supported
    } else {
      ScaledOutputCapability::Unsupported
    }
  }

  /// Asks this decoder to emit pictures at `size` from the next frame
  /// on, and reports whether the request was recorded.
  ///
  /// # What "from the next frame on" means, exactly
  ///
  /// The stage is consulted per frame, on the way out of the decoder
  /// and before the GPU→CPU download. So a request placed mid-stream
  /// takes effect on the next picture `receive_frame` produces — never
  /// retroactively on one already decoded and queued, and never later
  /// than that.
  ///
  /// # Refusal is not an error
  ///
  /// [`ScaledOutputCapability::Unsupported`] comes back when this road
  /// has no stage at all (see [`Self::scaled_output_capability`]), when
  /// either requested extent is zero, or when the request is an
  /// **upscale** of the stream's coded size — the stage exists to move
  /// fewer bytes across the GPU→CPU bus, and enlarging a picture moves
  /// more. Nothing about [`Self::send_packet`] or
  /// [`Self::receive_frame`] can fail because of it.
  ///
  /// **A refusal returns the session to full coded size**, dropping any
  /// request already standing. That is what the trait says this answer
  /// means, and the only reading a caller can act on: told
  /// `Unsupported` it resamples for itself, and a session that went on
  /// quietly fitting to an older request would have it resample an
  /// already-fitted picture. Like an acceptance, it takes effect from
  /// the next picture; one already decoded keeps the extent it was
  /// decoded at.
  ///
  /// See [`ScaledOutputCapability`] for the determinism trade a caller
  /// takes on by acting on a `Supported` answer.
  pub fn request_scaled_output(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
    // **The road, not the standing promise.** A session whose promise
    // broke on an earlier request answers `Unsupported` from
    // [`Self::scaled_output_capability`] until somebody asks again —
    // and asking again is exactly this, so gating it on that answer
    // would make the break permanent and unrecoverable. What is checked
    // here is what cannot change: whether this build and this backend
    // have a stage at all.
    if !crate::vtscale::ScaledOutput::supported() || !self.state.backend.is_video_toolbox() {
      return ScaledOutputCapability::Unsupported;
    }
    let coded = (self.width(), self.height());
    self.scaled_output.request(size, coded)
  }

  /// Withdraws any standing scaled-output request, returning this
  /// decoder to full coded size from the next frame.
  ///
  /// The refusal road that does not go through
  /// [`Self::request_scaled_output`]: the wrapper refuses a request
  /// placed while a decoded picture is parked, and a refusal has to
  /// mean the same thing there as everywhere else — the session is
  /// returning to full coded size. Without this the old request would
  /// stay armed behind an `Unsupported` answer, and a caller acting on
  /// that answer would resample pictures that were already fitted.
  pub fn cancel_scaled_output(&mut self) {
    self.scaled_output.cancel();
  }

  /// Decoder width in pixels.
  pub fn width(&self) -> u32 {
    self.state.inner.width()
  }

  /// Decoder height in pixels.
  pub fn height(&self) -> u32 {
    self.state.inner.height()
  }

  /// Codec context time base.
  pub fn time_base(&self) -> Rational {
    self.state.inner.time_base()
  }

  /// Frame rate from the codec context, if known.
  pub fn frame_rate(&self) -> Option<Rational> {
    self.state.inner.frame_rate()
  }

  /// Reclassify a post-commit runtime error from the committed HW backend
  /// into [`Error::AllBackendsFailed`] so the [`crate::FfmpegVideoStreamDecoder`]
  /// wrapper recognises it as a HW-path exhaustion and falls back to
  /// software. The single attempt records the committed backend
  /// (`self.state.backend` is the live backend post-commit) paired with the
  /// underlying FFmpeg error. `unconsumed_packets` is empty: the probe
  /// buffer is gone after commit, so the wrapper's rolling
  /// since-last-keyframe buffer supplies the replay set.
  ///
  /// # `reason` is the funnel's verdict, and this does not mint another
  ///
  /// It used to call [`Self::hw_exit`] itself, which was right while it
  /// was the *first* funnel on its road and wrong the moment it was the
  /// second. On the receive road the verdict is minted at the top of the
  /// arm, and `hw_exit` **consumes** the latch it reads — so a second
  /// call finds nothing and records the raw errno libavcodec reported,
  /// throwing away the refusal that had already been collected. A
  /// caller's attempt log then blamed `InvalidData` for a coded surface
  /// this crate declined over a configured ceiling.
  ///
  /// So the verdict is minted once, by whichever funnel is first on the
  /// road, and threaded from there. See the doors' invariant on
  /// [`software_receive`].
  /// Mints a verdict for a road that holds none yet, then routes it.
  ///
  /// The funnel runs **exactly once** here, which is the law the doors
  /// carry: see the invariant on [`software_receive`]. Roads that have
  /// already minted (the receive arm) call [`Self::hw_route`] straight.
  fn hw_failure(&self, e: ffmpeg_next::Error, bare: BareVerdict) -> HwRoute {
    self.hw_route(self.hw_exit(Error::Ffmpeg(e)), e, bare)
  }

  /// How a funnel verdict routes, before the road's own reading of an
  /// unnamed one applies.
  ///
  /// **Exhaustive on purpose, and with no wildcard.** A `_ => false`
  /// stood here and was a hazard rather than a convenience: a future
  /// named verdict that *did* require a fallback would inherit the
  /// silence and be reported plain, which is a bug that compiles. The
  /// match is total over this crate's own error vocabulary, so adding an
  /// arm forces whoever adds it to say how it routes.
  fn verdict_routing(reason: &Error) -> VerdictRouting {
    match reason {
      // The hardware pool declined the coded surface. Software is not
      // subject to that ceiling, and neither is the next backend.
      Error::HwSurfaceTooLarge(_) => VerdictRouting::CandidateFailed,
      // Software would decode the same oversized frame and be refused
      // by the same ceiling; so would the next backend. A fallback here
      // invites an action that cannot succeed.
      Error::FrameBudgetExceeded(_) => VerdictRouting::Direct,
      // The funnel handed its fallback straight back: nothing was named,
      // so the errno is all there is and the road decides.
      Error::Ffmpeg(_) => VerdictRouting::Unnamed,
      // None of these can leave a funnel — `hw_exit` mints only the two
      // refusals above or returns its argument — and each is already a
      // decided fact that did not ask for a backend to be retried. They
      // are listed rather than swept up so a twelfth arm cannot join
      // them silently.
      Error::PacketBuild(_)
      | Error::ParametersTooLarge(_)
      // A malformed channel layout is a fact about the *stream*, not
      // about a backend: every backend would be handed the same
      // parameters and refuse them the same way, and the refusal
      // happens before any backend is chosen at all.
      | Error::MalformedChannelLayout(_)
      | Error::ChannelMapMissing(_)
      | Error::NoCodec(_)
      | Error::HwTransferTooLarge(_)
      | Error::BackendUnsupportedByCodec(_)
      | Error::HwDeviceInitFailed(_)
      | Error::AllBackendsFailed(_)
      | Error::FallbackFailed(_) => VerdictRouting::Direct,
    }
  }

  /// Whether a post-commit failure means the hardware backend cannot
  /// decode this content, so the wrapper must open a software decoder.
  ///
  /// A named verdict outranks the raw errno in **both** directions: a
  /// name that says no is as binding as one that says yes, and the errno
  /// is consulted only where nothing was named. See
  /// [`Self::verdict_routing`].
  fn fallback_required(reason: &Error, raw: ffmpeg_next::Error) -> bool {
    match Self::verdict_routing(reason) {
      VerdictRouting::CandidateFailed => true,
      VerdictRouting::Direct => false,
      VerdictRouting::Unnamed => is_hw_decode_failure(&raw),
    }
  }

  /// **One policy for what a funnelled hardware failure means, shared by
  /// every road that can produce one.**
  ///
  /// The send roads used to return their funnel's result the moment they
  /// had it. That was right for a flow signal and wrong for anything
  /// else: `hw_send` can mint [`Error::HwSurfaceTooLarge`], and returning
  /// it plain meant the wrapper — which opens software only on
  /// [`Error::AllBackendsFailed`] — simply stopped, and a probe still
  /// auditioning never advanced past the candidate that had just
  /// declined the surface.
  ///
  /// So minting and routing are one move now, and the receive road's
  /// policy is the policy. What differs between roads is only what an
  /// *unnamed* verdict means, which is why [`BareVerdict`] is a
  /// parameter rather than an assumption.
  fn hw_route(&self, reason: Error, raw: ffmpeg_next::Error, bare: BareVerdict) -> HwRoute {
    let candidate_failed = match Self::verdict_routing(&reason) {
      VerdictRouting::CandidateFailed => true,
      VerdictRouting::Direct => false,
      VerdictRouting::Unnamed => matches!(bare, BareVerdict::CandidateFailure),
    };
    if !candidate_failed {
      return HwRoute::Report(reason);
    }
    if self.probe.is_some() {
      return HwRoute::Advance(reason);
    }
    if Self::fallback_required(&reason, raw) {
      return HwRoute::Report(self.post_commit_hw_failure(reason));
    }
    HwRoute::Report(reason)
  }

  fn post_commit_hw_failure(&self, reason: Error) -> Error {
    // `new_post_commit` stamps `FallbackOrigin::PostCommit`: the wrapper
    // routes its replay on that explicit signal, not on the (here-empty)
    // `unconsumed_packets`, which a probe-era first-packet cap trip also
    // leaves empty.
    Error::AllBackendsFailed(AllBackendsFailed::new_post_commit(vec![(
      self.state.backend,
      Box::new(reason),
    )]))
  }

  /// Whether the probe rescue history is still being recorded.
  ///
  /// While this is true, [`Self::send_packet`] `av_packet_ref`s every
  /// accepted packet into `buffered_packets`, and a later
  /// [`Error::AllBackendsFailed`] hands those recordings to the caller
  /// as owned, mutable `Packet`s. A submission built to be dropped
  /// inside one call therefore does **not** stay inside that call on
  /// this road — which is what the view lane's send-side sharing
  /// assumed. The window closes at commit, when the first frame
  /// arrives and `probe` is taken.
  #[inline]
  pub(crate) const fn is_probing(&self) -> bool {
    self.probe.is_some()
  }

  /// **Where this session is, derived here and nowhere else.**
  ///
  /// The two latches this reads — whether a backend is still on trial,
  /// and whether an end has been recorded — are the only inputs any
  /// classification question has ever needed. Reading them at the point
  /// of a decision is what let the roads disagree; reading them once,
  /// here, is what stops it.
  pub(crate) const fn phase(&self) -> SessionPhase {
    match (self.probe.is_some(), self.eof_sent) {
      (false, false) => SessionPhase::Streaming,
      (false, true) => SessionPhase::Draining,
      (true, false) => SessionPhase::Auditioning,
      (true, true) => SessionPhase::AuditioningPastEnd,
    }
  }

  /// Submit a packet to the decoder.
  ///
  /// On success — and only on success — the packet is buffered for potential
  /// replay through a fallback backend while the probe is active. `EAGAIN`
  /// (the decoder needs `receive_frame` to drain output first) is
  /// [`Sent::MustDrain`]: nothing was consumed, so the caller drains and
  /// offers the same packet again. `AVERROR_EOF` is **not** back pressure
  /// on this face — it means this decoder was already told the stream
  /// ended — so it stays a fault. See [`send_status`].
  ///
  /// While the probe is active, a non-transient error (e.g. the active HW
  /// backend rejecting this stream's geometry on first packet) advances the
  /// probe to the next candidate and retries the packet there. The caller
  /// observes only the eventual success or, if the probe is exhausted, the
  /// final error.
  ///
  /// **Atomic probe rescue.** While the probe is active, the rescue
  /// invariant is that everything FFmpeg has consumed since open is
  /// reflected in `buffered_packets` (so a future
  /// [`Error::AllBackendsFailed`] can hand a complete replay history
  /// back to the caller for software fallback on a non-seekable input).
  /// If we cannot prove this packet is buffer-able — its side-data
  /// entry count exceeds [`MAX_PROBE_PACKET_SIDE_DATA_ENTRIES`], its
  /// bytes would push the probe past [`MAX_PROBE_PACKETS`] or
  /// [`MAX_PROBE_PACKET_BYTES`], or [`av_packet_ref`] fails ENOMEM —
  /// `send_packet` returns [`Error::AllBackendsFailed`] **without
  /// invoking** `state.inner.send_packet` on this packet. The caller's
  /// packet stays in their hand and `unconsumed_packets` carries the
  /// pre-existing buffered history, so they can replay
  /// `unconsumed_packets` plus the current packet through their
  /// software decoder of choice. The post-probe path (after the first
  /// frame, when `self.probe` is `None`) skips this pre-flight
  /// entirely.
  pub fn send_packet(&mut self, packet: &Packet) -> Result<Sent> {
    loop {
      // Re-read each iteration: a probe advance moves this session from
      // one phase to another underneath the loop.
      let phase = self.phase();
      // Pre-flight while probe is active: prove we can record this
      // packet for replay BEFORE the active decoder consumes it.
      // `staged_clone` carries the refcounted clone and the new
      // `buffered_bytes` value through the send below; we only commit
      // them to the probe state if FFmpeg accepts the packet.
      let staged_clone: Option<(Packet, usize)> = if let Some(probe) = self.probe.as_ref() {
        // Step 1: side-data entry count cap. Read just `side_data_elems`
        // (no array walk yet) so a corrupt or weaponised value cannot
        // drive an unbounded loop from the safe entry point.
        let side_count = packet_side_data_count(packet);
        if side_count > MAX_PROBE_PACKET_SIDE_DATA_ENTRIES {
          let probe = self.probe.take().expect("probe present");
          tracing::warn!(
            side_data_entries = side_count,
            max_side_data_entries = MAX_PROBE_PACKET_SIDE_DATA_ENTRIES,
            trigger = "side_data_entry_cap",
            "hwdecode: probe rescue exhausted before consuming packet; \
             returning AllBackendsFailed without invoking decoder"
          );
          return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
            probe.attempts,
            probe.buffered_packets,
          )));
        }
        // Step 2: byte / packet count cap. `packet_side_data_bytes`
        // clamps its walk to MAX_PROBE_PACKET_SIDE_DATA_ENTRIES as
        // defense-in-depth even though the count check above already
        // bounded the array length.
        let pkt_size = packet.size().saturating_add(packet_side_data_bytes(
          packet,
          MAX_PROBE_PACKET_SIDE_DATA_ENTRIES,
        ));
        let new_count = probe.buffered_packets.len() + 1;
        let new_bytes = probe.buffered_bytes.saturating_add(pkt_size);
        if new_count > MAX_PROBE_PACKETS || new_bytes > MAX_PROBE_PACKET_BYTES {
          let probe = self.probe.take().expect("probe present");
          tracing::warn!(
            packets = new_count,
            bytes = new_bytes,
            side_data_entries = side_count,
            max_packets = MAX_PROBE_PACKETS,
            max_bytes = MAX_PROBE_PACKET_BYTES,
            trigger = "byte_or_packet_cap",
            "hwdecode: probe rescue exhausted before consuming packet; \
             returning AllBackendsFailed without invoking decoder"
          );
          return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
            probe.attempts,
            probe.buffered_packets,
          )));
        }
        // Step 3: pre-clone before consuming. `av_packet_ref` is a
        // refcounted shallow clone (no payload deep-copy) but can still
        // ENOMEM on heavy side-data; if it does we bail rather than
        // consuming a packet we can't track.
        match try_clone_packet(packet) {
          Ok(c) => Some((c, new_bytes)),
          Err(e) => {
            let probe = self.probe.take().expect("probe present");
            tracing::warn!(
              error = %e,
              "hwdecode: packet clone failed before consuming; \
               returning AllBackendsFailed without invoking decoder"
            );
            return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
              probe.attempts,
              probe.buffered_packets,
            )));
          }
        }
      } else {
        None
      };

      match self.state.inner.send_packet(packet) {
        Ok(()) => {
          if let Some((cloned, new_bytes)) = staged_clone {
            // Probe is still Some here: the only paths that take it are
            // the bailouts above (which return) and `advance_probe`'s
            // exhaustion (which would have propagated via `?`). Commit
            // the clone now that FFmpeg has accepted the packet.
            if let Some(probe) = self.probe.as_mut() {
              probe.buffered_packets.push(cloned);
              probe.buffered_bytes = new_bytes;
            }
          }
          return Ok(Sent::Accepted);
        }
        // **libavcodec's send-side flow control, guarded here and read
        // through the funnel — the same door the software road uses.**
        //
        // The guard and the classification are two different questions
        // and they get two different answers. `is_transient` decides
        // *whether the probe may advance*: neither `EAGAIN` nor
        // `AVERROR_EOF` is a candidate failing, so both are taken here,
        // ahead of the failure road, exactly as this one guard always
        // took them. `send_status` then decides *which* of the two this
        // is — back pressure or the double-EOF fault — and that
        // decision is not written here at all, so this arm cannot drift
        // away from the road the software decoders take. The staged
        // clone drops; the caller drains and re-offers, and we re-clone
        // at the top of the loop.
        //
        // It reads the errno through [`Self::hw_send`] rather than
        // classifying it raw: a refusal this crate latched during the
        // submission — `get_format` declining a coded surface as the
        // decoder configures on its first packet — must be what the
        // caller is told, not the `EAGAIN` libavcodec reported over the
        // top of it.
        // **Mint, then route — not mint and return.** A flow signal
        // leaves immediately; anything else is a verdict, and a verdict
        // that names a declined surface has to reach the probe or the
        // fallback rather than exiting plain. `BareVerdict::Reported`
        // is the road's own reading of an *unnamed* verdict here: the
        // double-EOF is the caller's fault, not the candidate's, so the
        // probe must not advance on it.
        Err(e) if is_transient(&e) => match self.hw_send(e, phase) {
          Ok(status) => return Ok(status),
          Err(reason) => match self.hw_route(reason, e, BareVerdict::Reported) {
            HwRoute::Report(err) => return Err(err),
            HwRoute::Advance(err) => {
              self.advance_probe(err)?;
              continue;
            }
          },
        },
        // A real failure. Minted once and routed by the shared policy:
        // while a candidate is on trial this is that candidate failing,
        // so `advance_probe` consumes the reason into `attempts` and
        // either installs the next candidate or surfaces
        // `AllBackendsFailed`. Any staged clone drops without entering
        // history; the next iteration clones afresh.
        Err(e) => match self.hw_failure(e, BareVerdict::CandidateFailure) {
          HwRoute::Report(err) => return Err(err),
          HwRoute::Advance(err) => {
            self.advance_probe(err)?;
            continue;
          }
        },
      }
    }
  }

  /// Signal end-of-stream to the decoder.
  ///
  /// Recorded for replay only if the underlying `send_eof` succeeds. While
  /// the probe is active, non-transient errors trigger probe advance and
  /// retry, matching `send_packet`'s behaviour.
  ///
  /// Answers [`Sent::MustDrain`] on `EAGAIN` — the end-of-stream was
  /// **not** recorded, so drain and signal again. A second EOF is a
  /// caller fault and stays one; see [`send_status`].
  pub fn send_eof(&mut self) -> Result<Sent> {
    loop {
      // Re-read each iteration: a probe advance moves this session from
      // one phase to another underneath the loop.
      let phase = self.phase();
      match self.state.inner.send_eof() {
        Ok(()) => {
          self.eof_sent = true;
          return Ok(Sent::Accepted);
        }
        // The same guard, the same door and the same routing as
        // `send_packet`; see the note there.
        Err(e) if is_transient(&e) => match self.hw_send(e, phase) {
          Ok(status) => return Ok(status),
          Err(reason) => match self.hw_route(reason, e, BareVerdict::Reported) {
            HwRoute::Report(err) => return Err(err),
            HwRoute::Advance(err) => {
              self.advance_probe(err)?;
              continue;
            }
          },
        },
        // The same shared policy; see `send_packet`.
        Err(e) => match self.hw_failure(e, BareVerdict::CandidateFailure) {
          HwRoute::Report(err) => return Err(err),
          HwRoute::Advance(err) => {
            self.advance_probe(err)?;
            continue;
          }
        },
      }
    }
  }

  /// Receive a CPU-side decoded frame.
  ///
  /// The frame is downloaded with `av_hwframe_transfer_data` and metadata
  /// is copied via `av_frame_copy_props`. The caller's frame is always
  /// unref'd first, so reuse across resolution changes or different
  /// decoders is safe.
  ///
  /// While the probe window is open, *any* non-transient failure (decode
  /// error, transfer error, copy_props error, or a CPU-format frame from a
  /// HW-opened context) tears down the current decoder and advances to the
  /// next hardware backend in probe order, replaying buffered packets
  /// through it. Frames the candidate produced during replay (drained when
  /// `send_packet` returned EAGAIN) are queued and delivered FIFO via this
  /// method, so the caller never loses initial frames after a fallback.
  ///
  /// This crate is hardware-only: there is no software fallback inside the
  /// decoder. When every backend in the probe order has been exhausted —
  /// including the case of a single-backend platform whose only backend
  /// failed — this returns [`Error::AllBackendsFailed`] with the per-
  /// backend attempt log so the caller can branch into a software
  /// decoder of their choice.
  ///
  /// Answers the same three states `ffmpeg::decoder::Video` does, in
  /// the shape the trait tier publishes: [`Received::NeedsInput`] where
  /// libavcodec says `EAGAIN`, [`Received::Ended`] where it says `EOF`,
  /// and [`Received::Frame`] when `frame` was written. **The errno
  /// stops here** — the two flow signals never leave this crate as
  /// `Error::Ffmpeg`, so a caller has nothing to decode.
  pub fn receive_frame(&mut self, frame: &mut Frame) -> Result<Received> {
    // Pre-drain frames queued during probe replay. They are already CPU-side
    // (transferred at drain time, when the candidate's HW context was alive)
    // so we just move them into the caller's slot.
    if self.try_pop_pending(frame) {
      return Ok(Received::Frame);
    }

    loop {
      // Re-read each iteration: a probe advance moves this session from
      // one phase to another underneath the loop.
      let phase = self.phase();
      let res = self.state.inner.receive_frame(&mut self.hw_frame);
      match res {
        Err(e) => {
          // **The phase decides whether this errno is a protocol state
          // at all, and this arm holds no opinion of its own.**
          //
          // `EAGAIN` used to short-circuit here unconditionally, which
          // was right for three of the four phases and quietly wrong for
          // the fourth: a candidate that has been replayed the whole
          // history *including the end* and still answers "nothing yet"
          // has produced zero frames and never will. Answering the
          // caller `NeedsInput` there asked for input nothing could
          // supply; answering `Ended` would have credited a backend that
          // never decoded a thing. It is a candidate failing, and the
          // classifier says so by handing it back — straight into the
          // probe road below, which is where candidate failures have
          // always gone.
          //
          // **And it reads the errno through the funnel, which is the
          // law this road lost and got back.** A `get_format`
          // declination or an allocator-judge refusal sits in the
          // callback state waiting to be collected; classifying the raw
          // errno first answers `Ended` or `NeedsInput` for a frame this
          // crate itself declined, and the reason dies unread. The
          // funnel is no longer a step to remember — [`Self::hw_receive`]
          // is the only way in, and the classifiers are private to this
          // module so no road can take a shortcut past it.
          let reason = match self.hw_receive(e, phase) {
            Ok(status) => return Ok(status),
            // The funnel's verdict: the latched refusal when there was
            // one, the original error when there was not. It travels
            // onward as it is — rebuilding `Error::Ffmpeg(e)` here would
            // throw away the collection that just happened.
            Err(reason) => reason,
          };
          // **The same shared policy every hardware road uses.** This
          // road mints its own verdict (above), so it routes rather than
          // minting again. `CandidateFailure` is its reading of an
          // unnamed verdict: a candidate that drains to `EOF` without
          // ever producing a frame is a candidate failing, not a stream
          // ending — which is why this road hands `AVERROR_EOF` to the
          // probe while the send roads report it.
          match self.hw_route(reason, e, BareVerdict::CandidateFailure) {
            HwRoute::Report(err) => return Err(err),
            HwRoute::Advance(err) => {
              self.advance_probe(err)?;
              // Probe advance may have populated `pending_frames`;
              // deliver one of those before reading more from the new
              // candidate.
              if self.try_pop_pending(frame) {
                return Ok(Received::Frame);
              }
              continue;
            }
          }
        }
        Ok(()) => {
          // Always attempt the HW→CPU transfer. With strict `get_format`,
          // libavcodec can only deliver frames in the wired-up HW format
          // (or fail). If a misbehaving codec ever hands us a CPU-side
          // frame anyway, `av_hwframe_transfer_data` returns AVERROR(EINVAL)
          // (neither src nor dst has an AVHWFramesContext attached) and we
          // route through the same error path below.
          // **The transfer is priced before it is paid, and a refusal
          // here is final.** See [`judge_hw_transfer`]: neither ceiling
          // hook reaches this allocation — `hwaccel->alloc_frame`
          // bypasses `get_buffer2` entirely, and the CPU destination is
          // allocated by `av_hwframe_transfer_data` outside both — so
          // this is the seat that bounds what the hardware road hands
          // back.
          //
          // Judged out here rather than inside `transfer_hw_frame`
          // deliberately. Errors from that function are FFmpeg's, and
          // the arms below reclassify them into "the hardware failed,
          // fall back to software". A byte ceiling is not a hardware
          // failure: software would decode the same oversized frame and
          // be refused again, so retrying it silently is exactly the
          // wrong answer. The named refusal returns straight to the
          // caller.
          if let Err(e) =
            unsafe { judge_hw_transfer(self.hw_frame.as_ptr(), self.frame_limits.frame()) }
          {
            return Err(Error::HwTransferTooLarge(e));
          }
          // **The scaled-output stage, and the one place it sits.** A
          // standing request turns this into a GPU resize followed by a
          // download of the *fitted* surface; with no request, or on any
          // condition the stage cannot honor, `stage` answers `None` and
          // the full-size hardware frame is downloaded exactly as
          // before. It cannot fail — see [`crate::vtscale`].
          //
          // The byte ceiling above is deliberately **not** re-priced
          // against the fitted size. `judge_hw_transfer` bounds what
          // this road may allocate, and pricing the full-size frame is
          // the conservative reading of that bound: a stream refused
          // without scaled output is refused identically with it, so
          // turning the stage on can never widen what the ceiling lets
          // through. What it saves is the bus traffic and the CPU
          // allocation actually paid, which is the trade #55 is about.
          //
          // **And a fitted surface that will not download is the
          // stage's failure, not the backend's.** The scale can succeed
          // and the crossing still fail — an unsupported destination
          // pixel format, a metadata copy that runs out of memory — and
          // routing that into the arms below would let an optional
          // bandwidth optimisation reject a VideoToolbox decode that
          // was working, or degrade the session to software. So the
          // fitted attempt is made first and separately: if it fails,
          // the stage latches the key off, the destination is reset,
          // and the original full-size frame — still live in
          // `hw_frame`, still the path this crate took before any of
          // this existed — is downloaded instead. Only *that* failing
          // is a hardware failure.
          let scaled = self
            .scaled_output
            .stage(&self.hw_frame)
            .map(|fitted| unsafe { transfer_hw_frame(frame, fitted) });
          match scaled {
            Some(Ok(())) => {
              self.probe = None;
              return Ok(Received::Frame);
            }
            Some(Err(e)) => {
              tracing::warn!(
                error = %e,
                "hwdecode: the fitted surface would not download; retiring scaled output for \
                 this size and delivering the full-size frame instead"
              );
              self.scaled_output.latch_failure();
              // SAFETY: `frame` is the caller's slot; unreferencing it
              // discards whatever the failed transfer left behind
              // before the retry writes it again.
              unsafe { av_frame_unref(frame.as_inner_mut().as_mut_ptr()) };
            }
            None => {}
          }
          match unsafe { transfer_hw_frame(frame, &self.hw_frame) } {
            Ok(()) => {
              self.probe = None;
              return Ok(Received::Frame);
            }
            Err(e) => {
              // The same shared policy. A transfer failure is an
              // HW-output problem — an unsupported CPU pix_fmt surfaces
              // as `AVERROR(EINVAL)`, a context loss as Bug/Bug2/Unknown
              // — never input corruption, so while a candidate is on
              // trial it is that candidate failing.
              match self.hw_failure(e, BareVerdict::CandidateFailure) {
                HwRoute::Report(err) => return Err(err),
                HwRoute::Advance(err) => {
                  self.advance_probe(err)?;
                  unsafe { av_frame_unref(frame.as_inner_mut().as_mut_ptr()) };
                  if self.try_pop_pending(frame) {
                    return Ok(Received::Frame);
                  }
                  continue;
                }
              }
            }
          }
        }
      }
    }
  }

  /// Pop one queued frame (produced by a candidate decoder during probe
  /// replay) into the caller's slot. Returns `true` when a frame was
  /// delivered, `false` when the queue was empty.
  fn try_pop_pending(&mut self, frame: &mut Frame) -> bool {
    let Some(mut buffered) = self.pending_frames.pop_front() else {
      return false;
    };
    // SAFETY: `buffered` is a CPU-side AVFrame we previously transferred
    // and pushed into the queue; both pointers are valid.
    unsafe {
      av_frame_unref(frame.as_inner_mut().as_mut_ptr());
      av_frame_move_ref(frame.as_inner_mut().as_mut_ptr(), buffered.as_mut_ptr());
    }
    // Probe semantics: delivering a frame collapses the probe.
    self.probe = None;
    true
  }

  /// Flush internal buffers (e.g. after a seek).
  ///
  /// Discards every frame buffered by the decoder, every frame queued during
  /// probe replay (`pending_frames`), and the residual `hw_frame` scratch
  /// buffer. Probe-time replay state (buffered packets, EOF marker) is also
  /// cleared since post-seek packets do not align with the previously
  /// captured history. After a flush, the next `receive_frame` waits for new
  /// post-seek input.
  pub fn flush(&mut self) {
    self.state.inner.flush();
    // SAFETY: hw_frame is a valid AVFrame we own; av_frame_unref is a no-op
    // for an already-empty frame.
    unsafe { av_frame_unref(self.hw_frame.as_mut_ptr()) };
    self.pending_frames.clear();
    // The end belongs to the position being abandoned.
    self.eof_sent = false;
    if let Some(probe) = self.probe.as_mut() {
      probe.buffered_packets.clear();
      probe.buffered_bytes = 0;
    }
  }

  /// Takes the coded-surface refusal the `get_format` callback left
  /// behind, if it left one, clearing it for the next candidate.
  fn take_ceiling_declination(&self) -> Option<Error> {
    ceiling_declination_of(self.state.callback_state)
  }

  /// **The single hardware-exit funnel.** Every road that turns a
  /// hardware failure — or an end-of-stream that is really a refusal —
  /// into an `Error` goes through here, and it reads the callback's
  /// declination *before* anything wraps or tears down state.
  ///
  /// The reason there is a funnel at all: a `get_format` callback
  /// cannot return a reason, so it leaves one behind, and every exit
  /// that forgets to collect it hands the caller libavcodec's
  /// `Invalid data found when processing input` for a refusal this
  /// crate made — or, on the explicit-backend road, a stream that
  /// simply drains to EOF with nothing said at all.
  ///
  /// The lesson this encodes: R14 claimed four consumers of the
  /// declination and production had exactly one. Consumers added
  /// helper-by-helper are lost the next time the surrounding code is
  /// restructured; a single funnel that every exit *must* call is the
  /// only version of this that stays true. The per-road table in
  /// `decoder/tests.rs` is what checks that it did.
  /// The hardware road's funnel-and-classify entry — [`software_receive`]'s
  /// twin, and the same law: what a caller reads is what the funnel
  /// found, never the errno that reached it.
  ///
  /// Answers `Err` with the funnel's verdict, which is the latched
  /// refusal when there was one. Callers route *that* value onward
  /// rather than rebuilding the raw error, or the collection is undone
  /// the moment it is used.
  fn hw_receive(&self, e: ffmpeg_next::Error, phase: SessionPhase) -> Result<Received> {
    receive_status(self.hw_exit(Error::Ffmpeg(e)), phase)
  }

  /// The send road's half of [`Self::hw_receive`].
  fn hw_send(&self, e: ffmpeg_next::Error, phase: SessionPhase) -> Result<Sent> {
    send_status(self.hw_exit(Error::Ffmpeg(e)), phase)
  }

  fn hw_exit(&self, fallback: Error) -> Error {
    self
      .take_ceiling_declination()
      .or_else(|| frame_budget_declination_of(self.state.callback_state))
      .unwrap_or(fallback)
  }

  /// Try the next backend in `remaining_backends`. Transactional: a
  /// candidate must successfully build and accept the replayed history
  /// before any probe state is consumed. Backends that fail to build or
  /// reject the replay are recorded into `probe.attempts` and the loop
  /// continues to the next one.
  ///
  /// `last_error` is the error that triggered this advance — i.e. the
  /// failure of the currently active backend on `send_packet` /
  /// `send_eof` / `receive_frame`. It is recorded against the active
  /// backend before any candidate is tried so that a final
  /// `AllBackendsFailed` carries the full attempt log including the
  /// initially-opened backend's runtime failure.
  ///
  /// Returns:
  /// - `Ok(())` when a candidate is installed and replay completed —
  ///   caller should retry the operation.
  /// - `Err(Error::AllBackendsFailed(p))` when every remaining
  ///   backend has been exhausted (including the just-failed active one).
  ///   `p.attempts()` carries the per-backend failure log.
  ///   This is what the documented `open` contract promises, surfaced at
  ///   runtime so the caller can branch into a software fallback. On a
  ///   single-backend platform (e.g. macOS), this fires after the only
  ///   backend's first-frame failure; on multi-backend platforms it
  ///   fires after the last candidate's failure.
  /// - `Err(_)` for other fatal conditions surfaced by probe machinery
  ///   itself (e.g. `alloc_av_frame` ENOMEM during replay drain).
  fn advance_probe(&mut self, last_error: Error) -> Result<()> {
    // Record the failure that triggered this advance against the active
    // backend. If the probe was somehow already gone (shouldn't happen —
    // call sites guard with `self.probe.is_some()`), just propagate the
    // error so behaviour matches the pre-fix code path.
    let active_backend = self.state.backend;
    // **The reason the callback could not return.** Declining a format
    // in `get_format` surfaces from libavcodec as
    // `Invalid data found when processing input` — true about what it
    // saw, false about what happened, because the data was fine and
    // this crate declined it over the coded surface's size. The
    // callback leaves the real reason in its own state; this is where
    // it becomes the error the caller reads.
    // **Mint or no-op, and never a re-derivation.** Three of this
    // method's callers hand it a raw `Error::Ffmpeg` — no funnel has run
    // on their roads — so this is where their verdict is minted. The
    // receive road hands it one already minted, and this call then finds
    // the latch empty and returns its argument unchanged: `hw_exit`
    // answers with the recorded refusal when there is one and with its
    // fallback when there is not, so a verdict passed in comes back out.
    // Either way the caller's reason is what gets recorded. See the
    // invariant on [`software_receive`].
    let last_error = self.hw_exit(last_error);
    match self.probe.as_mut() {
      Some(probe) => probe.attempts.push((active_backend, Box::new(last_error))),
      None => return Err(last_error),
    }

    // Drop frames previously queued from the backend we're now abandoning.
    // They came from a candidate that just failed for cause and cannot be
    // trusted alongside frames we may queue from the next candidate. (If
    // this method is called repeatedly via chained probe advances, this
    // also keeps `pending_frames` from accumulating frames from multiple
    // rejected backends.)
    self.pending_frames.clear();
    // Read before any `probe` borrow: the end is the *decoder's* fact
    // now, not the probe's, and a candidate must be handed it along
    // with the replayed history or it will sit at `EAGAIN` forever on a
    // stream that is already over.
    let eof_sent = self.eof_sent;

    loop {
      // Snapshot inputs without mutating probe state. Use the checked
      // clone helper rather than `Parameters::clone` (which masks ENOMEM).
      let (next_backend, parameters, codec) = match self.probe.as_ref() {
        Some(probe) if !probe.remaining_backends.is_empty() => {
          let parameters = match try_clone_parameters(
            &probe.parameters,
            self.frame_limits.max_codec_parameter_bytes(),
          ) {
            Ok(p) => p,
            Err(e) => {
              tracing::warn!(
                error = %e,
                "hwdecode: parameters clone failed during probe advance; popping backend and trying next"
              );
              let popped = self
                .probe
                .as_mut()
                .expect("probe state present")
                .remaining_backends
                .remove(0);
              self
                .probe
                .as_mut()
                .expect("probe state present")
                .attempts
                .push((popped, Box::new(e)));
              continue;
            }
          };
          (probe.remaining_backends[0], parameters, probe.codec)
        }
        // No more candidates — surface the accumulated attempt log as
        // AllBackendsFailed so single- and multi-backend platforms have
        // the same contract for "every HW backend failed."
        //
        // Hand the buffered packet history back to the caller along
        // with the attempt log: those packets were consumed from the
        // caller's demuxer (and refcounted-cloned into `buffered_packets`)
        // before the probe exhausted, and for non-seekable inputs the
        // caller cannot re-demux them. Returning them here lets a
        // caller-side software fallback replay the same byte history
        // through `ffmpeg::decoder::Video` without losing initial frames.
        // Dropping `ProbeState` after the take frees the codec/params
        // refs we no longer need; only `attempts` and `buffered_packets`
        // are retained.
        _ => {
          let (attempts, unconsumed_packets) = self
            .probe
            .take()
            .map(|p| (p.attempts, p.buffered_packets))
            .unwrap_or_default();
          return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
            attempts,
            unconsumed_packets,
          )));
        }
      };

      let prev_backend = self.state.backend;
      tracing::warn!(from = ?prev_backend, to = ?next_backend, "hwdecode: advancing probe");

      // Build candidate. On failure, record into attempts and continue
      // without touching the packet buffer.
      let mut candidate_state = match Self::build_state(
        parameters,
        codec,
        next_backend,
        self.frame_limits,
        self.pkt_timebase,
      ) {
        Ok(s) => s,
        Err(e) => {
          tracing::warn!(?next_backend, error = %e, "hwdecode: candidate build failed");
          self
            .probe
            .as_mut()
            .expect("probe state present")
            .remaining_backends
            .remove(0);
          self
            .probe
            .as_mut()
            .expect("probe state present")
            .attempts
            .push((next_backend, Box::new(e)));
          continue;
        }
      };

      // Replay buffered history through the candidate WITHOUT installing it.
      // We borrow the buffer immutably; if replay fails the candidate's Drop
      // releases the FFmpeg state and the buffer is preserved for the next
      // attempt.
      //
      // EAGAIN handling: `avcodec_send_packet` may return EAGAIN when its
      // internal queue is full and the user is expected to drain output
      // first (B-frame buffering, candidate-specific queue depth, etc.).
      // This is normal flow — we drain frames out of the candidate, transfer
      // each one to a CPU frame, and stash them in `local_pending`. After
      // commit they move to `self.pending_frames` and are delivered FIFO
      // by `receive_frame`, so the caller never loses initial frames.
      let mut local_pending: VecDeque<frame::Video> = VecDeque::new();
      let mut local_pending_bytes: usize = 0;
      let max_pending_bytes = self.max_probe_pending_bytes;
      let replay_result: std::result::Result<(), ffmpeg_next::Error> = {
        let probe = self.probe.as_ref().expect("probe state present");
        let mut hw_buf = match alloc_av_frame() {
          Ok(f) => f,
          Err(e) => return Err(Error::Ffmpeg(e)),
        };
        let mut r: std::result::Result<(), ffmpeg_next::Error> = Ok(());

        'replay: for pkt in &probe.buffered_packets {
          loop {
            match candidate_state.inner.send_packet(pkt) {
              Ok(()) => break,
              Err(e) if is_eagain(&e) => {
                // Drain candidate output (transferring + queueing each frame)
                // and retry the same packet.
                if let Err(de) = drain_into_pending(
                  &mut candidate_state.inner,
                  &mut hw_buf,
                  &mut local_pending,
                  &mut local_pending_bytes,
                  max_pending_bytes,
                  self.frame_limits.frame(),
                ) {
                  r = Err(de);
                  break 'replay;
                }
              }
              Err(e) => {
                r = Err(e);
                break 'replay;
              }
            }
          }
        }
        if r.is_ok() && eof_sent {
          // `avcodec_send_packet(NULL)` (which `send_eof` becomes) can
          // return EAGAIN with the same drain-output-first semantics as
          // a regular send_packet. Loop drain+retry instead of failing
          // the candidate on backpressure.
          loop {
            match candidate_state.inner.send_eof() {
              Ok(()) => break,
              Err(e) if is_eagain(&e) => {
                if let Err(de) = drain_into_pending(
                  &mut candidate_state.inner,
                  &mut hw_buf,
                  &mut local_pending,
                  &mut local_pending_bytes,
                  max_pending_bytes,
                  self.frame_limits.frame(),
                ) {
                  r = Err(de);
                  break;
                }
              }
              Err(e) => {
                r = Err(e);
                break;
              }
            }
          }
        }
        r
      };

      if let Err(e) = replay_result {
        tracing::warn!(?next_backend, error = %e, "hwdecode: candidate replay failed");
        // **The candidate's own refusal, read before the candidate
        // dies.** `hw_exit` consults `self.state` — the backend that is
        // still active — but the error being recorded here belongs to
        // `candidate_state`, whose `get_format` callback is the one
        // that may have declined. Classifying through the wrong state
        // and then dropping the right one lost the reason entirely: the
        // attempt log recorded FFmpeg's `Invalid data found when
        // processing input` for a coded surface this crate refused.
        //
        // Order matters and is the whole fix — read, then drop.
        let recorded =
          ceiling_declination_of(candidate_state.callback_state).unwrap_or(Error::Ffmpeg(e));
        // Drop candidate explicitly so its FFI cleanup runs now. Discard any
        // frames we drained from this candidate — they're tied to a decoder
        // we're throwing away.
        drop(candidate_state);
        drop(local_pending);
        self
          .probe
          .as_mut()
          .expect("probe state present")
          .remaining_backends
          .remove(0);
        self
          .probe
          .as_mut()
          .expect("probe state present")
          .attempts
          .push((next_backend, Box::new(recorded)));
        continue;
      }

      // Commit: install the candidate, clear residual hw_frame, queue the
      // drained frames for the caller, and pop the now-active backend.
      self.state = candidate_state;
      // **The scaled-output stage's session belongs to the device that
      // just went away.** Its fitted frames context was built over the
      // outgoing backend's hardware device; the caller's standing
      // request outlives the advance, but nothing built for the old
      // device may. Unreachable on the one platform where the stage has
      // a body — `probe_order` names a single backend on Apple targets,
      // so this method never reaches a commit there — and written all
      // the same, because "unreachable today" is not a property a
      // resource-owning cache should depend on.
      self.scaled_output.retire();
      unsafe { av_frame_unref(self.hw_frame.as_mut_ptr()) };
      self.pending_frames.append(&mut local_pending);
      self
        .probe
        .as_mut()
        .expect("probe state present")
        .remaining_backends
        .remove(0);
      return Ok(());
    }
  }

  /// Build raw FFmpeg state for one hardware backend. Strict `get_format`
  /// (NONE on missing HW format); cross-backend fallback is the caller's job.
  fn build_state(
    parameters: codec::Parameters,
    codec: Codec,
    backend: Backend,
    limits: crate::limits::DecoderLimits,
    pkt_timebase: Option<mediadecode::Timebase>,
  ) -> Result<DecoderState> {
    // Use our checked allocator instead of Context::from_parameters, which
    // does not null-check avcodec_alloc_context3 and would feed a null
    // AVCodecContext into FFmpeg under OOM.
    let (mut ctx, mut state) = build_codec_context(&parameters, limits, pkt_timebase)?;
    let av_type = backend.av_hwdevice_type();

    // Verify the codec advertises this hwaccel **with the exact HW pix_fmt
    // we're about to wire up in `get_format`**. FFmpeg's HW config table
    // is keyed per (device_type, pix_fmt); a codec can advertise the same
    // device with several HW pix_fmts, so matching only on device_type
    // would let probing succeed for a backend whose pix_fmt the codec
    // never offers — the failure would then surface deep inside the
    // probe/decode loop. Matching the exact pix_fmt keeps the strict
    // `get_format` honest and gives `open_with` a clean rejection.
    let hw_pix_fmt = backend.hw_pixel_format();
    if !codec_supports_hwaccel(unsafe { codec.as_ptr() }, av_type, hw_pix_fmt as i32) {
      return Err(Error::BackendUnsupportedByCodec(backend));
    }

    // Create the device context.
    let mut hw_device_ref: *mut AVBufferRef = ptr::null_mut();
    // SAFETY: `hw_device_ref` is a stack ptr we hand FFmpeg to fill.
    let ret = unsafe {
      av_hwdevice_ctx_create(&mut hw_device_ref, av_type, ptr::null(), ptr::null_mut(), 0)
    };
    if ret < 0 {
      return Err(Error::HwDeviceInitFailed(HwDeviceInitFailed::new(
        backend,
        ffmpeg_next::Error::from(ret),
      )));
    }

    // The state `build_codec_context` already installed in `opaque`,
    // told which format this backend wants. One allocation, one seat:
    // the budget the judge reads and the declination the funnel reads
    // are the same object, and `Box::into_raw` hands its ownership to
    // the guard below without moving it — so the pointer the context
    // holds stays the one that is freed.
    state.wanted = hw_pix_fmt;
    state.wanted_int = hw_pix_fmt as i32;
    let callback_state = Box::into_raw(state);
    // RAII guard: from now until the end-of-function `into_owned()`, every
    // early return — `av_buffer_ref` failure, `open_as` failure, codec_type
    // mismatch, or any future error path added between here and the
    // `DecoderState` construction — frees `hw_device_ref` and
    // `callback_state` via the guard's Drop. Without it, each error site
    // had to remember to clean up these two FFI-owned resources by hand;
    // the codec_type-mismatch branch was missed and silently leaked one
    // device ref + one heap allocation per bad input.
    let guard = PartialBuildState {
      hw_device_ref,
      callback_state,
    };

    // SAFETY: ctx is a freshly-constructed AVCodecContext we own;
    // av_buffer_ref bumps the refcount of the device buffer for FFmpeg's
    // use (we keep our own ref in `hw_device_ref` for cleanup).
    // av_buffer_ref returns NULL on allocation failure; we must check it
    // before assigning, otherwise the codec context would be opened with a
    // HW-flagged setup but no actual device reference.
    let device_ref_for_ctx = unsafe { av_buffer_ref(hw_device_ref) };
    if device_ref_for_ctx.is_null() {
      // guard's Drop frees hw_device_ref (the first ref) and callback_state.
      return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
        errno: libc::ENOMEM,
      }));
    }
    // SAFETY: device_ref_for_ctx is a valid AVBufferRef* from av_buffer_ref;
    // ctx is freshly built and owned by us. After this point ctx aliases
    // `callback_state` via `opaque` (FFmpeg never frees opaque, so
    // `callback_state` ownership stays with us / the guard) and aliases
    // `device_ref_for_ctx` (the second ref) via `hw_device_ctx` (FFmpeg
    // unrefs that on codec context drop, independent of the guard's first
    // ref).
    unsafe {
      let raw = ctx.as_mut_ptr();
      (*raw).hw_device_ctx = device_ref_for_ctx;
      (*raw).opaque = callback_state.cast();
      (*raw).get_format = Some(get_hw_format);
    }

    // Open the decoder. On failure `ctx`/`opened` Drop releases the codec
    // context (and via that the second device ref); the guard releases the
    // first device ref and the callback state.
    //
    // We deliberately bypass `Opened::video()` because it calls
    // `Context::medium()`, which reads `AVCodecContext.codec_type` as the
    // bindgen `AVMediaType` enum — the same UB hazard we've been
    // systematically removing. Instead: validate `codec_type` as a raw
    // `c_int` ourselves, then construct the `decoder::Video` wrapper
    // directly via its public tuple field.
    // Through the funnel's free-standing half — there is no decoder yet
    // to ask, and the guard frees the callback state on the way out, so
    // the reason has to be collected here or not at all.
    let opened = match ctx.decoder().open_as(codec) {
      Ok(opened) => opened,
      Err(e) => return Err(ceiling_declination_of(callback_state).unwrap_or(Error::Ffmpeg(e))),
    };

    // Validate codec_type as a raw integer — never construct AVMediaType
    // from an unvalidated runtime value. On failure `opened`'s Drop
    // releases the codec context; the guard releases the first
    // hw_device_ref and the callback state.
    if let Err(e) = ensure_video_codec_type(&opened) {
      // Same exit, same collection: a declined format can leave the
      // context looking like the wrong medium.
      return Err(ceiling_declination_of(callback_state).unwrap_or(e));
    }
    // SAFETY of construction: `decoder::Video` is `pub struct Video(pub Opened)`.
    // We construct via the public field; this is the same wrapping
    // `Opened::video()` does on success, just without the enum read.
    let opened = ffmpeg_next::decoder::Video(opened);

    // Disarm the guard and transfer ownership of both resources into the
    // returned DecoderState (whose own Drop handles their lifetime).
    let (hw_device_ref, callback_state) = guard.into_owned();
    Ok(DecoderState {
      inner: ManuallyDrop::new(opened),
      backend,
      hw_device_ref,
      callback_state,
    })
  }
}

/// RAII guard for the partially-owned FFmpeg state that
/// [`VideoDecoder::build_state`] holds between the
/// `av_hwdevice_ctx_create` and `Box::into_raw(CallbackState)`
/// allocations and the final `DecoderState` construction.
///
/// If `build_state` returns `Err` for any reason in that window
/// (`av_buffer_ref` ENOMEM, `open_as` failure, codec_type mismatch, or
/// any future error path), this guard's `Drop` releases
/// `hw_device_ref` — the first ref returned by `av_hwdevice_ctx_create`,
/// distinct from the second ref FFmpeg unrefs when the codec context
/// drops — and the boxed `CallbackState`, which FFmpeg never touches
/// because `AVCodecContext::opaque` is purely user-owned.
///
/// Successful construction calls [`Self::into_owned`] to disarm the
/// guard and hand both pointers to the new `DecoderState`.
struct PartialBuildState {
  hw_device_ref: *mut AVBufferRef,
  callback_state: *mut CallbackState,
}

impl PartialBuildState {
  /// Disarm the guard: return the owned pointers and replace the guard's
  /// fields with null so its Drop is a no-op.
  fn into_owned(mut self) -> (*mut AVBufferRef, *mut CallbackState) {
    let hw = std::mem::replace(&mut self.hw_device_ref, ptr::null_mut());
    let cb = std::mem::replace(&mut self.callback_state, ptr::null_mut());
    (hw, cb)
  }
}

impl Drop for PartialBuildState {
  fn drop(&mut self) {
    // SAFETY: pointers are either freshly allocated by `build_state` (via
    // `av_hwdevice_ctx_create` and `Box::into_raw`) or null after
    // `into_owned`. Both `av_buffer_unref` and `Box::from_raw` need the
    // null check we apply here; both are otherwise sound on resources we
    // own.
    unsafe {
      if !self.hw_device_ref.is_null() {
        let mut hw = self.hw_device_ref;
        av_buffer_unref(&mut hw);
      }
      if !self.callback_state.is_null() {
        drop(Box::from_raw(self.callback_state));
      }
    }
  }
}

/// Download a HW frame into a CPU [`Frame`]. Always unrefs the destination
/// first so reuse across resolution changes is safe.
///
/// `src` is whichever surface the scaled-output stage nominated: the
/// decoder's own hardware frame in the ordinary case, or the fitted
/// surface [`crate::vtscale`] scaled it into when a request is standing.
/// Both are VideoToolbox frames carrying their own `AVHWFramesContext`,
/// and the fitted one already carries this frame's metadata — so this
/// function's contract is unchanged either way, and the CPU frame's
/// extent is the nominated surface's.
///
/// Deliberately does **not** call `av_frame_copy_props`. That FFmpeg
/// helper deep-copies AVFrame side data (SEI, mastering display, ICC
/// profiles, dynamic HDR, etc.), the metadata dict, and bumps both
/// `opaque_ref` and `private_ref` on every receive — none of which
/// `Frame` exposes via its public accessors. On a crafted stream with
/// megabytes of per-frame metadata that would mean an unbounded
/// allocation per receive, with no caller-visible benefit. We instead
/// copy only the scalar fields the public API can read (today: `pts`);
/// pixel layout (`width`, `height`, `format`, `linesize`, `data`) is
/// already set by `av_hwframe_transfer_data`. If `Frame` ever grows
/// accessors for timing extras (`duration`, `time_base`, `pkt_dts`) or
/// color metadata, add those to `copy_frame_props_minimal` at the same
/// time.
unsafe fn transfer_hw_frame(
  dst: &mut Frame,
  src: &frame::Video,
) -> std::result::Result<(), ffmpeg_next::Error> {
  unsafe {
    av_frame_unref(dst.as_inner_mut().as_mut_ptr());
    let ret = av_hwframe_transfer_data(dst.as_inner_mut().as_mut_ptr(), src.as_ptr(), 0);
    if ret < 0 {
      return Err(ffmpeg_next::Error::from(ret));
    }
    // Validate the post-transfer CPU pix_fmt against the safe `Frame`
    // accessor's supported set. FFmpeg picks the destination format
    // when `dst.format == AV_PIX_FMT_NONE` on entry (which it always is
    // here — `av_frame_unref` clears it) by walking the result of
    // `av_hwframe_transfer_get_formats`. Driver/version ordering can
    // pick a layout outside our NV*/P0xx/P2xx/P4xx set; the call would
    // return success while the resulting frame is unreadable through
    // `Frame::row` / `Frame::as_ptr` (those return `None` for
    // unsupported formats). Surface the unsupported result as a
    // transfer failure so `receive_frame`'s probe-active path advances
    // to the next backend rather than collapsing on an unusable frame;
    // post-probe, the caller gets an `Err` they can branch into a
    // software fallback.
    let dst_raw_fmt: i32 = (*dst.as_inner_mut().as_ptr()).format;
    let dst_pix_fmt = crate::boundary::from_av_pixel_format(dst_raw_fmt);
    if !crate::frame::is_supported_cpu_pix_fmt(&dst_pix_fmt) {
      tracing::warn!(
        pix_fmt = dst_raw_fmt,
        "hwdecode: hw->cpu transfer produced unsupported pix_fmt; \
         treating as backend failure"
      );
      av_frame_unref(dst.as_inner_mut().as_mut_ptr());
      return Err(ffmpeg_next::Error::Other {
        errno: libc::EINVAL,
      });
    }
    if let Err(e) = copy_frame_props_minimal(dst.as_inner_mut().as_mut_ptr(), src.as_ptr()) {
      // Failed to propagate metadata. Reset the destination so the
      // partial frame doesn't leak (its pixel buffers were attached
      // by `av_hwframe_transfer_data` above) and surface as a
      // backend failure — the probe path will advance to the next
      // candidate; post-probe, the caller branches into SW fallback.
      av_frame_unref(dst.as_inner_mut().as_mut_ptr());
      return Err(e);
    }
  }
  Ok(())
}

/// Copies AVFrame metadata (timestamps, color metadata, crop rect,
/// flags, side data, etc.) from the source HW frame to the destination
/// CPU frame so the post-transfer frame surfaces the same metadata a
/// SW-decoded frame would.
///
/// Defers to FFmpeg's `av_frame_copy_props`, which handles the per-
/// `side_data[i]` allocation, dict copy, and refcounted buffer
/// replacements internally. The cost is bounded by what the source
/// frame attaches — typical HDR streams carry 1–3 side-data entries
/// (mastering display, content light level, dolby/HDR10+ dynamic
/// metadata) totalling a few hundred bytes, so per-frame allocation
/// overhead stays negligible relative to the pixel data already
/// transferred via `av_hwframe_transfer_data`.
///
/// # Safety
/// Both pointers must be valid `AVFrame` pointers we own. We do not
/// form `&AVFrame` — `av_frame_copy_props` operates on raw pointers
/// directly.
/// Sum the byte sizes of every entry in `(*frame).side_data[]`.
/// Used by the probe replay queue's byte-cap accounting so a
/// frame's deep-copied side-data is charged against
/// `max_probe_pending_bytes` along with its pixel buffers.
///
/// # Safety
/// `frame` must be a live `*const AVFrame`. Reads only `nb_side_data`,
/// the `side_data` pointer array, and each `AVFrameSideData.size` —
/// no `&AVFrame` reference is formed.
unsafe fn sum_side_data_bytes(frame: *const AVFrame) -> usize {
  // Clamp `nb_side_data` to the same entry cap the copy path
  // enforces. Without the clamp, a decoder-controlled or
  // version-skew `nb_side_data` value (the bindgen field is
  // `c_int`, signed) could drive this walk arbitrarily long
  // before the cap downstream kicks in. Negative values are
  // pinned to zero before casting.
  let raw = unsafe { (*frame).nb_side_data };
  let arr = unsafe { (*frame).side_data };
  if raw <= 0 || arr.is_null() {
    return 0;
  }
  let count = (raw as usize).min(HW_COPY_SIDE_DATA_MAX_ENTRIES);
  let mut total: usize = 0;
  for i in 0..count {
    // SAFETY: `arr` points to `nb_side_data` valid `*mut AVFrameSideData`
    // entries per FFmpeg's contract; `i < count` is in-bounds.
    let entry = unsafe { *arr.add(i) };
    if entry.is_null() {
      continue;
    }
    let sz = unsafe { (*entry).size };
    total = total.saturating_add(sz);
    if total >= HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES {
      // Already at or above the byte cap — further entries can't
      // change the projected-vs-cap decision the caller makes.
      total = HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES;
      break;
    }
  }
  total
}

/// Hard cap on the number of `AVFrameSideData` entries we copy from
/// HW source frame to CPU destination frame on the HW transfer
/// path. Mirrors `convert::SIDE_DATA_MAX_ENTRIES`; the public
/// converter re-enforces the same cap so this is defense in depth.
pub(crate) const HW_COPY_SIDE_DATA_MAX_ENTRIES: usize = 64;
/// Hard cap on the total side-data byte budget per HW transfer.
/// Mirrors `convert::SIDE_DATA_MAX_TOTAL_BYTES`.
const HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES: usize = 256 * 1024;

/// Maps a raw `AV_FRAME_DATA_*` integer to the matching bindgen
/// `AVFrameSideDataType` enum value when (and only when) the integer
/// is a known discriminant in the linked FFmpeg's bindgen output.
/// Returns `None` for unknown / version-skew / corrupt values —
/// the caller drops those entries instead of `transmute`-ing an
/// arbitrary integer back into the enum (which would be immediate
/// UB if the discriminant isn't in the enum's set).
///
/// The whitelist covers the entries safe to preserve across HW
/// transfer:
/// - HDR10 / HDR10+ / Dolby Vision / Vivid / ambient HDR metadata
/// - SMPTE / GOP timecodes
/// - ICC color profile
/// - A53 closed captions
/// - Spherical / display matrix orientation
/// - Stereo3D layout
///
/// Other AV_FRAME_DATA_* constants exist (motion vectors, encoder
/// params, RPU buffers, …) but are either decoder-internal or
/// rarely useful through the public mediadecode API; dropping them
/// is the safe default.
pub(crate) fn whitelisted_side_data_kind(
  kind_raw: i32,
) -> Option<ffmpeg_next::ffi::AVFrameSideDataType> {
  use ffmpeg_next::ffi::AVFrameSideDataType;
  // Each match arm compares `kind_raw` against the i32 cast of a
  // known constant, then returns the constant itself — we never
  // construct the enum from arbitrary integer bytes.
  let kind = match kind_raw {
    x if x == AVFrameSideDataType::AV_FRAME_DATA_PANSCAN as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_PANSCAN
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_A53_CC as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_A53_CC
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_STEREO3D as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_STEREO3D
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_DISPLAYMATRIX as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_DISPLAYMATRIX
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_AFD as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_AFD
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_MASTERING_DISPLAY_METADATA as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_MASTERING_DISPLAY_METADATA
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_GOP_TIMECODE as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_GOP_TIMECODE
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_SPHERICAL as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_SPHERICAL
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_CONTENT_LIGHT_LEVEL as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_CONTENT_LIGHT_LEVEL
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_ICC_PROFILE as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_ICC_PROFILE
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_S12M_TIMECODE as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_S12M_TIMECODE
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_PLUS as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_PLUS
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_REGIONS_OF_INTEREST as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_REGIONS_OF_INTEREST
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_SEI_UNREGISTERED as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_SEI_UNREGISTERED
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_FILM_GRAIN_PARAMS as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_FILM_GRAIN_PARAMS
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_DOVI_RPU_BUFFER as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_DOVI_RPU_BUFFER
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_DOVI_METADATA as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_DOVI_METADATA
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_VIVID as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_VIVID
    }
    x if x == AVFrameSideDataType::AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT as i32 => {
      AVFrameSideDataType::AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT
    }
    _ => return None,
  };
  Some(kind)
}

pub(crate) unsafe fn copy_frame_props_minimal(
  dst: *mut AVFrame,
  src: *const AVFrame,
) -> std::result::Result<(), ffmpeg_next::Error> {
  // We deliberately do NOT use `av_frame_copy_props` here, despite
  // its convenience. Upstream `av_frame_copy_props` deep-copies
  // *every* `AVFrameSideData` entry, the metadata `AVDictionary`,
  // and refcounted `opaque_ref` / `private_ref` buffers — all from
  // attacker-controlled decoder output. A crafted stream with many
  // multi-MiB side-data entries could drive the per-frame
  // allocation cost arbitrarily high (one alloc per entry, with the
  // entry's bytes copied via `memcpy`). The downstream
  // `convert::collect_side_data` cap helps the *Rust* side but the
  // FFmpeg-side allocations have already happened.
  //
  // Instead we copy scalar fields manually (timestamps, color
  // metadata, picture type, flags) and copy side-data with a hard
  // cap matching the converter's. Metadata dict and opaque_ref /
  // private_ref are intentionally NOT copied — they're rarely
  // populated on decoded frames and represent unbounded surfaces.
  use core::ptr::{addr_of, addr_of_mut, read_unaligned, write_unaligned};
  use ffmpeg_next::ffi::av_frame_new_side_data;
  unsafe {
    // Scalar timestamps / flags / color / SAR / crop. None of
    // these allocate.
    (*dst).pts = (*src).pts;
    (*dst).pkt_dts = (*src).pkt_dts;
    (*dst).duration = (*src).duration;
    (*dst).best_effort_timestamp = (*src).best_effort_timestamp;
    (*dst).quality = (*src).quality;
    (*dst).repeat_pict = (*src).repeat_pict;
    (*dst).flags = (*src).flags;
    (*dst).sample_aspect_ratio = (*src).sample_aspect_ratio;
    (*dst).crop_left = (*src).crop_left;
    (*dst).crop_top = (*src).crop_top;
    (*dst).crop_right = (*src).crop_right;
    (*dst).crop_bottom = (*src).crop_bottom;
    (*dst).time_base = (*src).time_base;

    // Enum-typed fields: bit-copy raw to avoid materializing an
    // invalid `AVColorPrimaries` etc. on either side. `read_unaligned`
    // / `write_unaligned` on `i32` projections sidestep the bindgen
    // enum's discriminant-validity invariant.
    let pict_type_raw = read_unaligned(addr_of!((*src).pict_type) as *const i32);
    write_unaligned(addr_of_mut!((*dst).pict_type) as *mut i32, pict_type_raw);
    let cp_raw = read_unaligned(addr_of!((*src).color_primaries) as *const i32);
    write_unaligned(addr_of_mut!((*dst).color_primaries) as *mut i32, cp_raw);
    let trc_raw = read_unaligned(addr_of!((*src).color_trc) as *const i32);
    write_unaligned(addr_of_mut!((*dst).color_trc) as *mut i32, trc_raw);
    let cs_raw = read_unaligned(addr_of!((*src).colorspace) as *const i32);
    write_unaligned(addr_of_mut!((*dst).colorspace) as *mut i32, cs_raw);
    let cr_raw = read_unaligned(addr_of!((*src).color_range) as *const i32);
    write_unaligned(addr_of_mut!((*dst).color_range) as *mut i32, cr_raw);
    let cl_raw = read_unaligned(addr_of!((*src).chroma_location) as *const i32);
    write_unaligned(addr_of_mut!((*dst).chroma_location) as *mut i32, cl_raw);

    // Side-data: bounded copy. `av_frame_new_side_data(dst, type,
    // size)` allocates the entry and returns a pointer to write
    // the payload bytes into; a null return is the OOM signal.
    // Callers (`transfer_hw_frame`, `drain_into_pending`) hand us
    // freshly-unref'd `dst` frames, so any prior side-data has
    // already been freed by `av_frame_unref` — we don't need to
    // strip dst's existing side-data here.
    // Read `nb_side_data` as the bindgen `c_int` and clamp non-
    // positive values BEFORE casting to `usize`. A negative value
    // (corrupt / version-skew decoder output) cast directly to
    // `usize` becomes a huge positive count and would walk OOB
    // memory below; pinning to zero up front collapses that to a
    // no-op. Same signed-count guard `sum_side_data_bytes` applies.
    let nb_side_data_raw = (*src).nb_side_data;
    let src_arr = (*src).side_data;
    if nb_side_data_raw > 0 && !src_arr.is_null() {
      let count_raw = nb_side_data_raw as usize;
      let count = count_raw.min(HW_COPY_SIDE_DATA_MAX_ENTRIES);
      if count_raw > HW_COPY_SIDE_DATA_MAX_ENTRIES {
        tracing::warn!(
          cap = HW_COPY_SIDE_DATA_MAX_ENTRIES,
          requested = count_raw,
          "mediadecode-ffmpeg: HW->CPU transfer side-data entry cap reached; truncating",
        );
      }
      let mut total_bytes: usize = 0;
      for i in 0..count {
        let entry = *src_arr.add(i);
        if entry.is_null() {
          continue;
        }
        let kind_raw = read_unaligned(addr_of!((*entry).type_) as *const i32);
        let size = (*entry).size;
        let data_ptr = (*entry).data;
        if size == 0 || data_ptr.is_null() {
          continue;
        }
        // Whitelist gate: only proceed when `kind_raw` matches a
        // known `AV_FRAME_DATA_*` constant the linked FFmpeg's
        // bindgen output knows about. Without this gate, a
        // version-skew or hostile decoder could write a side-data
        // type integer outside our bindgen's discriminant set, and
        // constructing the `AVFrameSideDataType` enum value (so
        // we could pass it to `av_frame_new_side_data`) would be
        // immediate UB before the call. Unknown types are dropped
        // with a debug-level log — the public converter's
        // `collect_side_data` walks the destination raw and would
        // also surface them as bare integers in `SideDataEntry.kind`.
        let Some(kind_enum) = whitelisted_side_data_kind(kind_raw) else {
          tracing::debug!(
            kind_raw,
            "mediadecode-ffmpeg: unknown AV_FRAME_DATA type during HW->CPU transfer; dropping",
          );
          continue;
        };
        let projected = total_bytes.saturating_add(size);
        if projected > HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES {
          tracing::warn!(
            cap = HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES,
            projected,
            "mediadecode-ffmpeg: HW->CPU transfer side-data byte cap reached; dropping rest",
          );
          break;
        }
        let new_entry = av_frame_new_side_data(dst, kind_enum, size);
        if new_entry.is_null() {
          // **OOM is reported, not absorbed.** This used to `break` and
          // return `Ok(())`, which published a frame carrying whatever
          // side data happened to fit before the allocator gave out —
          // silently dropping the entries behind it. Those entries are
          // the HDR mastering metadata, the ICC profile and the display
          // matrix: a picture that comes back with its colours or its
          // orientation quietly missing is worse than one that does not
          // come back, because nothing downstream can tell.
          //
          // The caller already knows what to do with an error here: it
          // unrefs the partial destination and either advances to the
          // next backend or surfaces the failure for a software retry.
          tracing::warn!("mediadecode-ffmpeg: av_frame_new_side_data OOM during HW->CPU transfer",);
          return Err(ffmpeg_next::Error::Other {
            errno: libc::ENOMEM,
          });
        }
        // SAFETY: `(*new_entry).data` is allocated for `size` bytes
        // per av_frame_new_side_data's contract; `data_ptr` is
        // valid for `size` reads per AVFrameSideData's contract.
        core::ptr::copy_nonoverlapping(data_ptr, (*new_entry).data, size);
        total_bytes = projected;
      }
    }
  }
  Ok(())
}

/// `EAGAIN` and `EOF` together: "this decoder has no more output for
/// now", either because it wants input or because it is finished.
///
/// **What is left of a predicate that used to guard both roads.** Both
/// public faces classify at their boundary now — [`receive_status`] and
/// [`send_status`] — and the send face had to stop treating the two
/// alike, since `AVERROR_EOF` there is a caller fault rather than a
/// state. The one caller that still wants them together is
/// [`drain_into_pending`], the probe-replay drain: it reads a raw
/// `ffmpeg_next::decoder::Video` that never crosses a public seam, and
/// for it "wants input" and "finished" really are one answer — stop
/// draining, the candidate produced everything it is going to.
fn is_transient(e: &ffmpeg_next::Error) -> bool {
  is_eagain(e) || matches!(e, ffmpeg_next::Error::Eof)
}

/// **The receive road's single errno gate, and it cannot be spent
/// without saying where the session is.**
///
/// Turns what a funnel (`software_exit` / `hw_exit`) handed back into
/// the trait's status vocabulary, keeping the two flow signals inside
/// this crate.
///
/// Takes the funnel's *output*, never libavcodec's raw error, and that
/// ordering is the point: the funnels collect a `get_format` or
/// allocator-judge refusal that the callback state is holding, and a
/// classifier placed in front of them would answer "needs input" for a
/// road that had a named refusal waiting. So every receive site funnels
/// first and gates second.
///
/// # Why the phase is a parameter and not a guess
///
/// The same errno means different things at different points in a
/// session's life, and every road that guessed guessed differently:
///
/// * `EAGAIN` is [`Received::NeedsInput`] only where more input can
///   arrive. Past a recorded end it is an instruction the caller cannot
///   carry out — the send gates refuse — so it is the end instead. And
///   on a candidate that has already been handed the whole history
///   including the end, it is neither: that candidate has produced no
///   frame and never will, which is a candidate failing, so it goes
///   back as an error for the probe machinery to act on.
/// * `AVERROR_EOF` is [`Received::Ended`] only from a backend that has
///   committed. A candidate's is its own exhaustion, not the stream's.
///
/// Making the phase an argument is what stops a road from having an
/// opinion about this. A classification without it does not compile.
fn receive_status(e: Error, phase: SessionPhase) -> Result<Received> {
  match &e {
    Error::Ffmpeg(f) if is_eagain(f) => {
      if phase.accepts_input() {
        Ok(Received::NeedsInput)
      } else if phase.is_committed() {
        // Draining. A committed backend with nothing more to give has
        // ended, whichever errno it chose — libavcodec is not supposed
        // to answer `EAGAIN` after a flush packet, but this crate has
        // met a codec that does (see `ImageDecodeError::NoImage`), and
        // the alternative is handing back a state nothing can satisfy.
        Ok(Received::Ended)
      } else {
        // `AuditioningPastEnd`: a candidate that has been given
        // everything and produced nothing. The probe road owns it.
        Err(e)
      }
    }
    Error::Ffmpeg(ffmpeg_next::Error::Eof) if phase.is_committed() => Ok(Received::Ended),
    _ => Err(e),
  }
}

/// **The send road's gate, and it is deliberately narrower than its
/// sibling.** Only `EAGAIN` is back pressure here.
///
/// `avcodec_send_packet` answers `AVERROR_EOF` for a different fact than
/// `avcodec_receive_frame` does: not "the stream is over" but *"this
/// decoder has already been told the stream is over, and you sent
/// something anyway"* — a caller usage fault rather than a session
/// state, so it stays in `Err`. Reading it as `Accepted` would silently
/// drop the submission; reading it as `MustDrain` would send the caller
/// into a drain loop that can never make the next offer succeed.
///
/// The same line puts [`crate::ResampleError::AfterEof`] and the
/// WebCodecs adapter's `AfterEof` on the error side.
///
/// # The phase, here too
///
/// [`Sent::MustDrain`] is a promise — *drain, and this same offer
/// becomes acceptable* — and past a recorded end it is one no session
/// can keep. The send gates refuse there first, so this is the second
/// lock rather than the first; what it buys is that the classifier
/// itself becomes incapable of making the promise, which is the whole
/// point of moving the phase into the signature.
fn send_status(e: Error, phase: SessionPhase) -> Result<Sent> {
  match &e {
    Error::Ffmpeg(f) if is_eagain(f) && phase.accepts_input() => Ok(Sent::MustDrain),
    _ => Err(e),
  }
}

/// Post-commit, a HW-only decoder's non-transient, non-EOF error means the
/// committed HW backend can't decode this content → fall back to SW. VT's
/// "hardware accelerator failed" surfaces as AVERROR_EXTERNAL; some HW
/// backends report unsupported geometry as InvalidData; context loss as
/// Bug/Bug2/Unknown. Broad-by-design (decode-all-kinds); fixtures will let us
/// narrow if a real backend proves a code should NOT trigger fallback.
///
/// `EAGAIN`/`EOF` are deliberately excluded by the caller, which guards on
/// them first — on the send roads through [`is_transient`] into
/// [`send_status`], and on `receive_frame` through [`is_eagain`] into
/// [`receive_status`], plus the probe/`hw_exit` road for `EOF`. `EAGAIN` is back pressure and `EOF` is a
/// genuine end-of-stream that must reach the caller as
/// [`Received::Ended`], never be trapped in an infinite fallback-retry
/// loop. `Other { errno: EINVAL }` from the HW→CPU transfer path is also
/// covered — an unsupported CPU output pix_fmt is a HW-output problem,
/// never input corruption.
fn is_hw_decode_failure(e: &ffmpeg_next::Error) -> bool {
  matches!(
    e,
    ffmpeg_next::Error::External
      | ffmpeg_next::Error::Bug
      | ffmpeg_next::Error::Bug2
      | ffmpeg_next::Error::Unknown
      | ffmpeg_next::Error::InvalidData
      | ffmpeg_next::Error::Other {
        errno: libc::EINVAL
      }
  )
}

/// Reject a `codec::Parameters` whose inner `*mut AVCodecParameters` is
/// null. This guards the public trust boundary: ffmpeg-next can produce
/// such a `Parameters` under OOM (`Parameters::new()` does not check
/// `avcodec_parameters_alloc`), and a safe caller can legally hand one
/// in. Without this check, the very next `(*p.as_ptr()).field` read
/// would be a null deref.
fn ensure_parameters_non_null(parameters: &codec::Parameters) -> Result<()> {
  // SAFETY: as_ptr() returns the inner *const AVCodecParameters; we just
  // inspect the pointer value (no deref).
  if unsafe { parameters.as_ptr() }.is_null() {
    return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
      errno: libc::ENOMEM,
    }));
  }
  Ok(())
}

/// Allocate a fresh `frame::Video`, checking that `av_frame_alloc` did not
/// return NULL. ffmpeg-next's `frame::Video::empty()` does not surface that
/// failure and the resulting null pointer would be UB on the next field
/// access; this wrapper catches it and surfaces it as `ENOMEM`.
fn alloc_av_frame() -> std::result::Result<frame::Video, ffmpeg_next::Error> {
  let inner = frame::Video::empty();
  // SAFETY: as_ptr() just exposes the inner pointer for inspection.
  if unsafe { inner.as_ptr() }.is_null() {
    return Err(ffmpeg_next::Error::Other {
      errno: libc::ENOMEM,
    });
  }
  Ok(inner)
}

/// Build a fresh `Context` from `parameters`, checking the underlying
/// `avcodec_alloc_context3` for NULL before passing it to
/// `avcodec_parameters_to_context`. ffmpeg-next's `Context::from_parameters`
/// skips that check and would feed a null pointer into FFmpeg under OOM —
/// undefined behavior. This helper surfaces the failure as `ENOMEM` and
/// frees the context if `parameters_to_context` itself errors.
pub(crate) fn build_codec_context(
  parameters: &codec::Parameters,
  limits: crate::limits::DecoderLimits,
  pkt_timebase: Option<mediadecode::Timebase>,
) -> Result<(Context, Box<CallbackState>)> {
  ensure_parameters_non_null(parameters)?;
  // **The choke point.** `avcodec_parameters_to_context` below is a
  // wholesale copy *into* FFmpeg — it duplicates `extradata`, every
  // `coded_side_data` entry and the channel map into the context, at
  // whatever size the caller's parameters declare. Every road that
  // opens a decoder in this crate arrives here, so measuring and
  // admitting once, right here, is what stops a caller handing
  // libavcodec parameters nobody budgeted: the four session `open`s,
  // the HW probe's `build_state`, its per-backend advances, and the
  // software fallback all pass through this function and none of them
  // can reach `avcodec_parameters_to_context` any other way.
  //
  // The outbound clone (`extras::bounded_clone_parameters`) closed the
  // Rust-side copy; this closes the FFmpeg-side one. They are the same
  // budget.
  //
  // **Structure before size, and before FFmpeg is handed anything.**
  //
  // `measure_parameters` below prices a custom channel map from
  // `nb_channels` alone and never looks at `u.map`, so a layout with a
  // positive count and a null map passed this budget and went on to
  // `avcodec_parameters_to_context`, which reaches
  // `av_channel_layout_copy` — a `memcpy` from that null. The
  // non-custom orders were no better: nothing bounded `nb_channels` for
  // a `NATIVE` or `AMBISONIC` layout, and FFmpeg's own arithmetic over
  // it assumes invariants it does not check.
  //
  // Every decoder this crate opens arrives here, and the refusal is
  // structural rather than an allocation failure, so it carries its own
  // error rather than the ceiling's or the allocator's.
  //
  // SAFETY: `ensure_parameters_non_null` just proved the pointer is
  // live; for a custom order its map is FFmpeg's own allocation of
  // `nb_channels` entries, and the preflight allocates nothing.
  unsafe {
    crate::channel_layout::layout_preflight(ptr::addr_of!((*parameters.as_ptr()).ch_layout))
  }
  .map_err(
    |fault| match crate::demuxer::layout_fault_to_demux(0, fault) {
      crate::demuxer::DemuxError::ParametersLayoutShape(shape) => {
        Error::MalformedChannelLayout(shape)
      }
      crate::demuxer::DemuxError::ParametersChannelMap(map) => Error::ChannelMapMissing(map),
      // The preflight allocates nothing, so no other arm is reachable;
      // reporting the allocator keeps the match total without an
      // `unreachable!`.
      _ => Error::Ffmpeg(ffmpeg_next::Error::Other {
        errno: libc::ENOMEM,
      }),
    },
  )?;

  // SAFETY: `ensure_parameters_non_null` just proved the pointer is
  // live; the measurement allocates nothing.
  let footprint = unsafe { crate::extras::measure_parameters(parameters.as_ptr()) };
  let declared = footprint.and_then(|f| f.total()).unwrap_or(usize::MAX);
  if declared > limits.max_codec_parameter_bytes() {
    return Err(Error::ParametersTooLarge(
      crate::demuxer::ParametersTooLarge::new(0, declared, limits.max_codec_parameter_bytes()),
    ));
  }
  // SAFETY: avcodec_alloc_context3(NULL) returns a fresh AVCodecContext
  // or NULL on allocation failure.
  let ctx_ptr = unsafe { avcodec_alloc_context3(ptr::null()) };
  if ctx_ptr.is_null() {
    return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
      errno: libc::ENOMEM,
    }));
  }
  // SAFETY: ctx_ptr is non-null and freshly allocated; parameters.as_ptr()
  // returns a valid AVCodecParameters pointer; the function copies bytes
  // out of parameters into the context.
  let ret = unsafe { avcodec_parameters_to_context(ctx_ptr, parameters.as_ptr()) };
  if ret < 0 {
    // SAFETY: ctx_ptr was allocated by us and never handed to anyone else.
    let mut p = ctx_ptr;
    unsafe { avcodec_free_context(&mut p) };
    return Err(Error::Ffmpeg(ffmpeg_next::Error::from(ret)));
  }
  // **The push-down.** The same pixel ceiling this crate checks against
  // a decoded frame is written into the decoder itself, so libavcodec
  // refuses an oversized picture *before allocating it*. Checking only
  // on our side would mean FFmpeg had already paid for the frame by the
  // time we declined to copy it — two layers, one number, and this is
  // the layer that matters.
  //
  // FFmpeg's own default here is `INT_MAX`, i.e. no ceiling worth the
  // name. `max_pixels` is a plain `int64_t` field on `AVCodecContext`
  // (and has been since FFmpeg 4.0), so it is set directly rather than
  // through `av_opt_set_int` and a stringly-typed option name.
  //
  // **And the byte ceiling, pushed down through the same field.**
  //
  // The pixel ceiling alone does not bound bytes, because a pixel is not
  // a fixed price: 10000x10000 is 100 Mpx — comfortably under the 256
  // Mpx default — and in `rgba64` it is 800 MB, well over the 512 MiB
  // byte ceiling. A highly compressible frame of that shape is a few KB
  // on disk, so nothing upstream sees it coming.
  //
  // **`max_pixels` carries the caller's number, verbatim.** It used to
  // carry `min(that, max_frame_bytes / worst-bytes-per-pixel)`, so the
  // byte ceiling could be enforced before libavcodec allocated — and
  // that translation charged every stream the widest format in
  // existence, 16 bytes a pixel. A 1920x1080 `yuv420p` frame costs
  // 3.14 MiB and was refused under a 4 MiB budget, at
  // `ff_set_dimensions`, before anything accurate had a chance to look
  // at it. Over-refusing ordinary video is not a conservative failure;
  // it is a broken decoder.
  //
  // The translation is gone because it is no longer needed: the byte
  // ceiling is enforced by [`judge_buffer`], which is *also* a
  // pre-allocation seat — `get_buffer2` is the allocator, so it runs
  // before the allocation and prices the frame's real format at its
  // real aligned dimensions. Nothing is lost on the software road by
  // stating the pixel limit as what it is.
  //
  // SAFETY: `ctx_ptr` is the non-null context just allocated and
  // populated above; `max_pixels` is a public field.
  unsafe {
    (*ctx_ptr).max_pixels = i64::try_from(limits.frame().max_pixels()).unwrap_or(i64::MAX);
  }

  // **The byte ceiling's own seat, in the allocator itself.**
  // `max_pixels` bounds an extent; what an extent costs depends on its
  // format and on how the allocator aligns it — a `gray8` frame of
  // 65536x1 is 64 KiB by `w * h` and 2 MiB once its single row is
  // rounded up. No scalar compared against a pixel product can bound
  // that, so the byte question is asked where the answer is knowable:
  // in `get_buffer2`, which *is* the allocation, against the caller's
  // own `max_frame_bytes`.
  //
  // See [`judge_buffer`] for why this hook rather than `get_format`
  // (measured: `get_format` never fires for a one-shot `png` decode).
  //
  // SAFETY: `ctx_ptr` is the non-null context; `get_buffer2` is a
  // public function-pointer field, and `judge_buffer` delegates every
  // frame it accepts to the allocator libavcodec would have used.
  unsafe {
    (*ctx_ptr).get_buffer2 = Some(judge_buffer);
  }

  // **The packet timebase, for every decoder opened against a stream.**
  //
  // `AVCodecContext.pkt_timebase` is documented as caller-supplied, and
  // libavcodec reads it: its generic subtitle path derives
  // `AVSubtitle.pts` and the packet-duration fallback *only* when the
  // field is set, so a subtitle decoder opened without it returns
  // timestamped cues carrying neither. It was never written here, on
  // any road.
  //
  // **A zero numerator is deliberately not written.** Left alone the
  // field is `0/1`, and `0/1` is also exactly what a container that
  // declared no timebase hands this crate — the two are the same
  // statement, so writing it would be ceremony, and treating it as a
  // real ruler would claim one the file never gave. See
  // [`crate::demuxer`]'s own note on why that value is passed through
  // rather than refused on the track road.
  if let Some(timebase) = pkt_timebase.filter(|timebase| timebase.num() > 0) {
    // SAFETY: `ctx_ptr` is the non-null context allocated above and
    // `pkt_timebase` is a public field; the value is built from a
    // `Timebase`, which cannot be negative or zero-denominatored.
    unsafe {
      (*ctx_ptr).pkt_timebase =
        ffmpeg_next::Rational::new(timebase.num(), timebase.den().get()).into();
    }
  }

  // **`max_samples` is deliberately left alone.**
  //
  // It bounds `nb_samples * channels`, so bounding *bytes* with it
  // means dividing by a per-channel-sample cost — and the only sound
  // divisor is the widest sample format the build can emit, 8 bytes.
  // That charged every stream `f64` rates: a 6-channel `s16` frame
  // fitting a 64 KiB budget was refused, because the translation
  // priced it at four times its real cost.
  //
  // The audio pre-allocation story is now the same as the video one,
  // and it is stronger than the translation was: [`judge_buffer`] runs
  // in `get_buffer2`, before the planes are allocated, and prices the
  // frame's real sample format at its real channel count through
  // [`crate::footprint`] — which asks `av_samples_get_buffer_size`, the
  // allocator's own ruler. An exact judge at the allocation beats an
  // approximate one before it.

  // **The judge's budget seat.** `judge_buffer` runs as a C callback
  // with nothing but the context to read, and the byte ceiling is not
  // recoverable from any field on it — see
  // [`CallbackState::max_frame_bytes`]. So the state that already
  // carries the `get_format` declination carries the budget too, and
  // every road gets one: this is the single point every decoder in the
  // crate is built through.
  //
  // Ownership stays with the caller, which keeps the box alive for as
  // long as the context. `Box` contents do not move when the box does,
  // so the pointer installed here stays valid across the return.
  let mut state = Box::new(CallbackState {
    wanted: ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE,
    wanted_int: ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE as i32,
    ceiling_declined: core::sync::atomic::AtomicBool::new(false),
    declined_pixels: core::sync::atomic::AtomicI64::new(0),
    declined_limit: core::sync::atomic::AtomicI64::new(0),
    max_frame_bytes: limits.frame().max_frame_bytes() as u64,
    frame_budget_declined: core::sync::atomic::AtomicBool::new(false),
    declined_frame_bytes: core::sync::atomic::AtomicU64::new(0),
    declined_frame_audio: core::sync::atomic::AtomicBool::new(false),
  });
  // SAFETY: `ctx_ptr` is the non-null context; `opaque` is a public
  // field FFmpeg never reads or frees.
  unsafe {
    (*ctx_ptr).opaque = (&raw mut *state).cast();
  }

  // SAFETY: ctx_ptr is valid; passing `owner: None` means our wrapper owns
  // the allocation and `Context::drop` will run `avcodec_free_context`.
  Ok((unsafe { Context::wrap(ctx_ptr, None) }, state))
}

/// Checked deep-clone of `codec::Parameters`. ffmpeg-next's
/// `Parameters::clone` allocates via `avcodec_parameters_alloc` without
/// checking for NULL and runs `avcodec_parameters_copy` without checking
/// the return code. On `ENOMEM` the result is a `Parameters` with a null
/// inner pointer, which becomes UB when later passed to FFmpeg.
///
/// This helper performs both calls explicitly, frees a partial allocation
/// on failure, and surfaces the AVERROR. The returned `Parameters` has
/// `owner: None`, severing any Rc link to the caller's demuxer (the
/// reason we deep-clone in the first place — see Send safety in
/// `VideoDecoder::open`).
pub(crate) fn try_clone_parameters(
  src: &codec::Parameters,
  budget: usize,
) -> std::result::Result<codec::Parameters, Error> {
  // Through the bounded clone, like every other parameter copy in this
  // crate — see [`crate::extras::bounded_clone_parameters`] for the
  // rule and why the wholesale `avcodec_parameters_copy` this used to
  // call is gone. This path is attacker-facing: `VideoDecoder::open`
  // takes whatever `stream.parameters()` hands it, straight off a
  // container.
  //
  // `budget` is the **active** ceiling, threaded from the session's own
  // `DecoderLimits` — through the initial ownership clone, the probe
  // state's copy, every probe advance and the software fallback. It
  // used to be the crate default, so a lowered ceiling did not bind
  // here (the clone admitted 16 MiB whatever the caller configured,
  // and only `build_codec_context` downstream refused) and a raised one
  // could not be used at all.
  //
  // The stream index is reported as 0: this helper is handed
  // parameters, not a stream, and inventing a coordinate it cannot
  // know would be worse than admitting it has none.
  crate::extras::bounded_clone_parameters(src, 0, budget).map_err(|e| match e {
    crate::demuxer::DemuxError::ParametersTooLarge(p) => Error::ParametersTooLarge(p),
    crate::demuxer::DemuxError::ParametersCopy(p) => Error::Ffmpeg(*p.source()),
    // A missing or unallocatable destination is the out-of-memory this
    // helper has always reported.
    _ => Error::Ffmpeg(ffmpeg_next::Error::Other {
      errno: libc::ENOMEM,
    }),
  })
}

/// Checked counterpart to `Packet::clone()`. ffmpeg-next's `clone_from`
/// calls `av_packet_ref` and ignores the int return value; on `ENOMEM`
/// the destination is left empty while the caller assumes the clone
/// succeeded — corrupting any later replay history. This helper surfaces
/// the AVERROR. The result is a refcounted shallow clone — the payload
/// buffer is shared with `src` rather than deep-copied; the probe replay
/// only sends packets through `avcodec_send_packet`, which does not
/// require a writable buffer.
pub(crate) fn try_clone_packet(src: &Packet) -> std::result::Result<Packet, ffmpeg_next::Error> {
  let mut dst = Packet::empty();
  // SAFETY: dst is a freshly zero-initialized Packet (av_init_packet inside
  // Packet::empty); av_packet_ref initializes its data fields from src's
  // refcounted buffer or returns AVERROR(ENOMEM) on failure.
  let ret = unsafe { av_packet_ref(dst.as_mut_ptr(), src.as_ptr()) };
  if ret < 0 {
    return Err(ffmpeg_next::Error::from(ret));
  }
  Ok(dst)
}

/// Sum of `AVPacket.side_data[i].size` across every entry, plus
/// `nb_entries * SIDE_DATA_ENTRY_OVERHEAD` (descriptor + AVBufferRef +
/// allocator bookkeeping per entry). `av_packet_ref` performs a deep
/// copy of side data via `av_packet_copy_props`, so each probe-buffered
/// clone retains every one of these bytes. Charging both keeps
/// `MAX_PROBE_PACKET_BYTES` a true upper bound — without the overhead,
/// many zero-size entries slip past the cap on pure descriptor cost.
///
/// Walks at most `max_entries` entries even when `side_data_elems`
/// reports a larger count. Defense-in-depth against a corrupt or hostile
/// packet whose `side_data_elems` lies about the actual array length:
/// the caller is expected to also reject any packet whose count exceeds
/// the cap (so the inflated clone is never created), but bounding the
/// walk here means a stale or weaponised value can never trigger an
/// unbounded raw-pointer scan from the safe API.
///
/// Reads only the `size` field of each `AVPacketSideData` entry — never
/// touches the bindgen `AVPacketSideDataType` enum, so no UB even if a
/// future FFmpeg adds a side-data type discriminant our build doesn't
/// know.
pub(crate) fn packet_side_data_bytes(packet: &Packet, max_entries: usize) -> usize {
  // SAFETY: AVPacket.side_data is `*mut AVPacketSideData` and
  // side_data_elems is `c_int`; both are raw struct fields safe to read.
  // Field projection (`.size`) does not reconstruct the enum-typed `type_`
  // field, so the bindgen-enum UB hazard does not apply here.
  unsafe {
    let raw = packet.as_ptr();
    let nel = (*raw).side_data_elems;
    let arr = (*raw).side_data;
    if arr.is_null() || nel <= 0 || max_entries == 0 {
      return 0;
    }
    let count = (nel as usize).min(max_entries);
    let mut total = count.saturating_mul(SIDE_DATA_ENTRY_OVERHEAD);
    for i in 0..count {
      let entry = arr.add(i);
      total = total.saturating_add((*entry).size);
    }
    total
  }
}

/// Number of `AVPacketSideData` entries on `packet`. The probe buffer
/// uses this to enforce [`MAX_PROBE_PACKET_SIDE_DATA_ENTRIES`] before
/// cloning, so a packet whose entry count alone would dominate retained
/// memory is rejected up front.
pub(crate) fn packet_side_data_count(packet: &Packet) -> usize {
  // SAFETY: side_data_elems is `c_int`, safe to read; clamp negatives to 0.
  let nel = unsafe { (*packet.as_ptr()).side_data_elems };
  if nel <= 0 { 0 } else { nel as usize }
}

/// Just `EAGAIN` (separate from EOF — the FFmpeg send/receive state machine
/// distinguishes "drain output and retry" from "stream over").
fn is_eagain(e: &ffmpeg_next::Error) -> bool {
  matches!(e, ffmpeg_next::Error::Other { errno } if *errno == ffmpeg_next::error::EAGAIN)
}

/// The probe square the per-pixel cost is measured on.
///
/// 256 divides every chroma subsampling FFmpeg has **and** every
/// alignment libavcodec uses, so the measurement is exact: no plane is
/// rounded up to cover a half-sized dimension, and no row is padded to
/// an alignment boundary. Measured at 257 the same census reads 16.934
/// bytes per pixel instead of 16.000 — that 5.8% is per-*row* padding,
/// a term linear in height rather than in pixels, and it is not part of
/// the per-pixel rate.
pub(crate) const PROBE_PIXELS: usize = 256 * 256;

/// Bytes a [`PROBE_PIXELS`]-pixel picture costs in the **most expensive
/// pixel format this build of libavcodec can describe**.
///
/// # Why the worst case and not the declared one
///
/// The first cut of this ceiling charged the format the *container*
/// declared, and a container's declaration is not an upper bound on
/// anything. It may be unset, it may be wrong, and it may be narrower
/// than what the decoder actually emits — a stream declaring `yuv420p`
/// at 1.5 bytes per pixel whose decoder outputs `rgbaf32` at 16 got a
/// ceiling more than ten times too generous, which is the same hole one
/// layer down from the one it was added to close.
///
/// So the rate is not negotiated with the file at all. Every stream is
/// charged the worst case, and the worst case is **measured**, not
/// tabulated: this build's descriptor list is walked once and each
/// format priced through `av_image_get_buffer_size`, the same function
/// `avcodec_default_get_buffer2` sizes from. A future FFmpeg that adds
/// a wider format is priced correctly without this crate learning its
/// name.
///
/// # The census, at the time of writing
///
/// 267 descriptors, 251 of them CPU formats that price (the rest are
/// hardware surfaces, which carry no CPU bytes and return no size). The
/// maximum is **16.000 bytes per pixel**, reached by eight formats —
/// `gbrapf32be/le`, `rgbaf32be/le`, `rgba128be/le`, `gbrap32be/le`.
/// Next below are the 12-byte `gbrpf32`/`rgbf32` family.
///
/// # What this trades
///
/// Over-refusal for cheap formats, and it is deliberate. At the 512 MiB
/// default the effective ceiling becomes ~33.55 Mpx, so 8K (33.18 Mpx)
/// still decodes in *any* format — including the 16-byte ones, where it
/// really does cost 506 MiB — but a 16K `yuv420p` frame, which would
/// only have cost 199 MB, is refused too. That is the honest shape of a
/// bound that has to hold before the format is known: the deployment
/// answer is to raise `max_frame_bytes`, which is exactly the knob that
/// says how much memory one frame may cost.
///
/// # The residual, stated
///
/// Row alignment adds at most `align x planes x height` bytes on top of
/// this rate — about 1 MB on an 8K frame, 0.2%, and covered by the fact
/// that `max_frame_bytes` is a policy number rather than a hardware
/// limit. It is only significant for degenerate aspect ratios (a
/// one-pixel-wide frame is all padding), which the *pixel* ceiling has
/// always been the wrong shape to bound and which this change neither
/// introduces nor worsens.
pub(crate) fn worst_bytes_per_probe() -> usize {
  /// The census result, taken once. `av_pix_fmt_desc_next` walks a
  /// static table that cannot change during the process.
  static WORST: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  *WORST.get_or_init(|| {
    /// The measured maximum at the time of writing, and the floor this
    /// census may not fall below. A build whose census comes back
    /// *smaller* than the eight 16-byte formats has failed to walk the
    /// table, not discovered a cheaper world — take the known number
    /// rather than a ceiling built on a failed measurement.
    const KNOWN_WORST_BYTES_PER_PIXEL: usize = 16;

    let mut worst = 0usize;
    let mut desc: *const ffmpeg_next::ffi::AVPixFmtDescriptor = ptr::null();
    loop {
      // SAFETY: `av_pix_fmt_desc_next` walks libavutil's own static
      // descriptor table, taking the previous entry (or null to start)
      // and returning null at the end. It traffics in descriptor
      // pointers, not enums, so it needs no shim.
      desc = unsafe { ffmpeg_next::ffi::av_pix_fmt_desc_next(desc) };
      if desc.is_null() {
        break;
      }
      // **Both of these go through the `c_int` shims**, and this is the
      // place it matters most: the whole point of walking the table is
      // to price formats this build's bindings may not name, and the
      // generated `av_pix_fmt_desc_get_id` hands those ids back as a
      // closed `AVPixelFormat`. Every future format would have become
      // an invalid enum value on the way into the pricing meant to
      // handle it — the census would have been UB on exactly its reason
      // for existing.
      //
      // SAFETY: `desc` is a live entry from libavutil's static table;
      // the id is passed straight back to libavutil as the integer it
      // is, and `av_image_get_buffer_size` returns a negative AVERROR
      // for ids it cannot size rather than misbehaving.
      let id = unsafe { c_shims::av_pix_fmt_desc_get_id(desc) };
      let size = unsafe { c_shims::av_image_get_buffer_size(id, 256, 256, 1) };
      if size > 0 {
        worst = worst.max(size as usize);
      }
    }
    worst.max(KNOWN_WORST_BYTES_PER_PIXEL * PROBE_PIXELS)
  })
}
/// `AVCodecContext.get_buffer2`: the same pixel ceiling, applied where
/// the **aligned** dimensions are knowable.
///
/// # The hole this closes
///
/// `max_pixels` is checked by libavcodec against the frame's *raw*
/// `width * height`. What it then allocates is the **aligned** shape —
/// `avcodec_align_dimensions2` rounds both dimensions up to whatever
/// the codec and the CPU want — and for degenerate aspect ratios those
/// are not the same number at all. Measured on this build:
///
/// | shape | raw | aligned | inflation |
/// |---|---|---|---|
/// | `gray8` 65536x1 | 65,536 px / 64 KiB | 65536x32 = 2,097,152 px / 2 MiB | **32x** |
/// | `gray8` 1x65536 | 65,536 px / 64 KiB | 16x65536 = 1,048,576 px / 2 MiB | 16x |
/// | `yuv420p` 7680x4320 | 33,177,600 px | 7680x4320 | 1.00x |
/// | `gray8` 1024x1024 | 1,048,576 px | 1024x1024 | 1.00x |
///
/// So a one-pixel-tall frame slips 32 times its declared cost past a
/// scalar compared against `w * h`, and no value of that scalar can fix
/// it: bounding the product cannot bound a product whose factors are
/// then rounded up independently. Real pictures inflate by nothing at
/// all, which is why the ceiling looked sound.
///
/// # Why this hook and not `get_format`
///
/// `get_format` was measured first, because it needs no allocation
/// decision and receives the context. It **does not fire on every
/// road**: on this build a one-shot `mjpeg` decode calls it once and a
/// `png` decode calls it *zero* times. Cover art is overwhelmingly
/// mjpeg or png, so half the road this ceiling exists to guard would
/// have been unguarded.
///
/// `get_buffer2` fired on both — it is the allocator, so every frame
/// libavcodec hands back comes through it, and it sees the frame's
/// *real* format rather than a negotiated candidate.
///
/// # No state, so no lifetime to prove
///
/// The composed-`opaque` design was not needed. This callback reads the
/// ceiling from `AVCodecContext.max_pixels` — the field this crate set
/// itself, one number, already carrying the byte ceiling converted at
/// the worst per-pixel rate — and applies it to the aligned dimensions.
/// Same scalar, same meaning, applied where alignment is knowable.
/// `opaque` is untouched, so the hardware path keeps it and there is no
/// allocation whose lifetime has to outlive a C callback.
///
/// Panic discipline is likewise structural rather than asserted: the
/// body allocates nothing, indexes nothing, unwraps nothing, and calls
/// exactly three FFmpeg functions. There is no Rust operation in it
/// that can panic, and an `extern "C"` function aborts rather than
/// unwinding into C in any case.
///
/// # Safety
///
/// Called by libavcodec with a live context and a frame whose `format`,
/// `width` and `height` are set. Delegates every accepted frame to
/// `avcodec_default_get_buffer2`, which is what libavcodec would have
/// called had this hook not been installed.
unsafe extern "C" fn judge_buffer(
  ctx: *mut ffmpeg_next::ffi::AVCodecContext,
  frame: *mut ffmpeg_next::ffi::AVFrame,
  flags: libc::c_int,
) -> libc::c_int {
  // SAFETY: libavcodec passes a live context and frame; both fields are
  // plain integers.
  let (width, height) = unsafe { ((*frame).width, (*frame).height) };

  // **This seat judges cost, and only cost.**
  //
  // `max_pixels` is a *logical* limit on a picture's extent, and
  // libavcodec already enforces it — against the **raw** dimensions, in
  // `ff_set_dimensions` via `av_image_check_size2`, before any frame
  // exists. That is the semantics the caller asked for and the
  // semantics FFmpeg documents, and this callback does not restate it.
  //
  // It used to. R11 added an *aligned*-dimension comparison here
  // against `max_pixels`, because at the time the callback had no
  // accurate byte check and a degenerate shape could slip its real cost
  // past a raw-pixel gate — 65536x1 aligns to 65536x32, thirty-two
  // times the pixels. That instrument is now both **redundant** and
  // **wrong**:
  //
  // * redundant, because since the byte ceiling was threaded in the
  //   footprint below prices the aligned dimensions itself, so the
  //   degenerate shape is refused on its actual cost; and
  // * wrong, because `max_pixels` is `min(the caller's pixel limit,
  //   byte ceiling / worst-bytes-per-pixel)` — so when the caller's
  //   pixel limit was the tighter seat, alignment inflation alone
  //   refused frames satisfying *both* requested limits. A 65536x1
  //   `gray8` frame under `max_pixels = 65536` and a generous byte
  //   budget fits the pixel limit exactly and costs 2 MiB, and was
  //   refused anyway — for arithmetic the caller never asked about.
  //
  // Logical extent is libavcodec's gate on raw dimensions; allocation
  // cost is this one, against the caller's own `max_frame_bytes`. One
  // question each.
  //
  // Audio reaches here too, and used to pass unpriced entirely:
  // `max_samples` bounds the sample *count*, so one sample across eight
  // packed `f64` channels is 64 valid bytes under a 64-byte ceiling and
  // a 2,080-byte allocation — delivered, because the copy-out only ever
  // rechecks the valid bytes.
  //
  // SAFETY: `ctx` and `frame` are live; every field read is a plain
  // integer, and `format` stays an integer throughout.
  // SAFETY: `frame` is live; the field is a plain pointer.
  let hw_frames = unsafe { (*frame).hw_frames_ctx };

  // A hardware frame carries no CPU bytes for this seat to price — its
  // pool is judged where it is declared, in the `get_format` callback —
  // so it is delegated rather than failed closed on an unpriceable
  // format.
  if hw_frames.is_null() {
    // **The caller's own number, read from the seat that carries it.**
    // This used to recover a byte ceiling from `AVCodecContext.max_pixels`,
    // and the recovery was wrong in both directions:
    //
    // * `max_pixels` is `min(pixel ceiling, byte ceiling / worst)`, so
    //   when the *pixel* seat was the tighter of the two it stopped
    //   encoding the byte ceiling at all — and the recovery invented a
    //   smaller one. A 256x256 frame at 16 bytes a pixel under
    //   `max_pixels = 65536` with a 2 MiB byte budget satisfies both of
    //   the caller's limits, costs 1,050,624 bytes, and was judged
    //   against 1,048,576 and refused. The claim that the conflation
    //   was harmless in one direction was simply wrong: it omitted the
    //   footprint's own alignment and slack, which is exactly where
    //   those extra 2,048 bytes live.
    // * and for audio a pixel ceiling has no business being consulted
    //   at all.
    //
    // The audio road briefly recovered from `max_samples` instead,
    // which *is* exact — but two sources of truth for one number is how
    // the first one went wrong. Both media read the seat now.
    //
    // SAFETY: `opaque` holds the `CallbackState` that
    // `build_codec_context` installed and whose owner outlives the
    // context. A null one means a context this crate did not build, and
    // is refused rather than assumed generous.
    let state = unsafe { (*ctx).opaque } as *const CallbackState;
    if state.is_null() {
      return -(libc::EINVAL);
    }
    // SAFETY: non-null per the check above; the field is a plain `u64`.
    let byte_ceiling = u128::from(unsafe { (*state).max_frame_bytes });

    // SAFETY: `frame` is live; both are plain integer fields.
    let (format_raw, nb_samples) = unsafe { ((*frame).format, (*frame).nb_samples) };
    let priced = if width > 0 && height > 0 {
      crate::footprint::video_frame_bytes(format_raw, width, height)
    } else if nb_samples > 0 {
      // **The frame's layout, not the context's.** FFmpeg's
      // `get_buffer2` contract says the callback reads the values on
      // the *frame*, and `avcodec_default_get_buffer2` sizes from them
      // — the context's layout is whatever was last negotiated and can
      // differ outright. A context claiming mono against a frame
      // carrying 255 `dblp` channels at 130,000 samples prices about a
      // megabyte and allocates about 265 MB.
      //
      // Read raw and signed, per the house discipline, and refused
      // rather than floored: a negative count is malformed, and
      // flooring it to zero would price an allocation that is about to
      // happen at nothing.
      // SAFETY: `frame` is live; `ch_layout.nb_channels` is a plain
      // `c_int`.
      let channels = unsafe { (*frame).ch_layout.nb_channels };
      if channels <= 0 {
        return -(libc::EINVAL);
      }
      crate::footprint::audio_frame_bytes(format_raw, nb_samples as usize, channels as usize)
    } else {
      // Neither geometry nor samples: nothing is being allocated that
      // this seat can price, and nothing is claimed.
      Some(0)
    };

    // **The refusal leaves its reason behind.** A `get_buffer2`
    // callback can only answer libavcodec with an errno, and
    // `AVERROR(EINVAL)` is also what libavcodec reports for corrupt
    // input — so a bare refusal here was indistinguishable from a
    // broken file, and only one of those is worth retrying with a
    // larger ceiling. The decoder funnels collect this the same way
    // they collect the `get_format` declination.
    let record = |bytes: u64| {
      use core::sync::atomic::Ordering;
      // SAFETY: `state` was proved non-null above.
      unsafe {
        (*state)
          .declined_frame_bytes
          .store(bytes, Ordering::Relaxed);
        (*state)
          .declined_frame_audio
          .store(width <= 0 && height <= 0, Ordering::Relaxed);
        (*state)
          .frame_budget_declined
          .store(true, Ordering::Release);
      }
      -(libc::EINVAL)
    };
    match priced {
      // Fail closed. An allocation whose size cannot be established is
      // not a small one — the same stance every other judge here takes.
      // Reported as an unbounded cost, which is what an unprovable one
      // is.
      None => return record(u64::MAX),
      // Nothing to buy, so nothing to refuse.
      Some(0) => {}
      // A budget of zero admits nothing, and this is the arm that used
      // to be a skipped guard.
      Some(bytes) if byte_ceiling == 0 => return record(bytes as u64),
      Some(bytes) if bytes as u128 > byte_ceiling => return record(bytes as u64),
      Some(_) => {}
    }
  }

  // SAFETY: delegating to the allocator libavcodec would have used.
  unsafe { ffmpeg_next::ffi::avcodec_default_get_buffer2(ctx, frame, flags) }
}

/// Prices the CPU frame `av_hwframe_transfer_data` would allocate, and
/// refuses it if it is over the ceiling — **before** the transfer runs.
///
/// # Why the hardware road needs its own seat
///
/// [`judge_buffer`] is not a universal choke point, and the census says
/// so on this machine. `ff_get_buffer` calls `hwaccel->alloc_frame`
/// directly and never reaches `get_buffer2` at all: a VideoToolbox
/// h264 decode of a 160x120 clip records **zero** `get_buffer2` calls
/// while producing a hardware frame. And the CPU destination of a
/// download is allocated by `av_hwframe_transfer_data` itself, outside
/// both hooks.
///
/// # What the census settled about the surface itself
///
/// `max_pixels` **does** bite before `alloc_frame`, and this was
/// measured rather than assumed: with `max_pixels = 100`, a 160x120
/// VideoToolbox h264 decode fails at `avcodec_open2` with
/// `Picture size 160x120 exceeds specified max pixel count 100` from
/// `av_image_check_size2`, zero `get_buffer2` calls and no frame. The
/// check lives in `ff_set_dimensions`, which every decoder runs when it
/// learns its dimensions and before any surface pool exists — so the
/// seat `max_pixels` already occupies covers the hardware surface too.
///
/// The residual on that road is the aligned-dimensions gap
/// [`judge_buffer`] closes for software frames, and it applies to
/// **driver-owned GPU memory** rather than to anything this crate
/// carries. What this crate does carry off the hardware road is the CPU
/// frame downloaded here, and that is bounded exactly, by this
/// function.
///
/// # How the price is taken
///
/// The destination format is not chosen by this crate: `dst.format` is
/// `AV_PIX_FMT_NONE` on entry and FFmpeg picks from
/// `av_hwframe_transfer_get_formats`. So the whole candidate list is
/// priced and the **worst** taken — walked as `*const c_int` through
/// the shim, because a driver may offer a format this build's bindings
/// do not name, which is the same discipline the pixel census keeps.
///
/// When the list cannot be obtained the global worst rate stands in;
/// over-refusing is the safe direction for a ceiling.
///
/// # Safety
///
/// `hw_frame` must be a live `*const AVFrame`.
unsafe fn judge_hw_transfer(
  hw_frame: *const ffmpeg_next::ffi::AVFrame,
  limits: crate::FrameLimits,
) -> std::result::Result<(), crate::error::HwTransferTooLarge> {
  // SAFETY: `hw_frame` is live per the contract; the field is a plain
  // pointer.
  let frames_ctx = unsafe { (*hw_frame).hw_frames_ctx };

  // **The allocated extent, not the displayed one.** `AVFrame.width` /
  // `.height` are the *display* dims; what
  // `av_hwframe_transfer_data` allocates is sized from the frames
  // context, and on a cropped stream the two diverge by orders of
  // magnitude — measured on this build, an h264 stream with SPS
  // cropping shows 32x32 display over a 1920x1088 coded surface, a
  // 2040x gap. This crate already had a helper that reads the pool
  // dims, with a doc comment naming this exact trap; the first version
  // of this judge reached past it for `AVFrame.width` anyway.
  //
  // **Fail closed.** No context, no dims, or no priceable candidate
  // means the allocation extent cannot be proved — and an unprovable
  // extent is not a small one. The same stance
  // `estimate_transfer_bytes` takes next door, and for the same reason:
  // falling back to display dims here would restore precisely the hole
  // this judge exists to close.
  if frames_ctx.is_null() {
    // Not a hardware frame at all. `av_hwframe_transfer_data` refuses
    // such a source with `EINVAL` and allocates nothing, so there is no
    // extent to bound here — and answering "too large" would put a
    // ceiling's name on a completely different fault. The existing path
    // reports it accurately.
    return Ok(());
  }
  let Some((width, height)) = (unsafe { hw_frames_ctx_dimensions_raw(hw_frame) }) else {
    // A hardware frame whose pool extent cannot be read. The transfer
    // may well allocate; nothing here can say how much. Charged as
    // unbounded, which is what an unprovable extent is.
    return Err(crate::error::HwTransferTooLarge::new(
      usize::MAX,
      limits.max_frame_bytes(),
    ));
  };

  // **Every candidate folded in, priceable or not.**
  //
  // FFmpeg picks the destination format from this list; this crate does
  // not get to choose. So the bound has to be the maximum over the
  // *whole* list — and the fold used to skip the members libavutil
  // would not size, updating `worst` only on priceable ones and
  // reaching for a fallback only when *nothing* priced. A list holding
  // one cheap priceable format beside one unpriceable format was
  // therefore judged at the cheap price, while FFmpeg remained free to
  // select the one that was ignored.
  //
  // An unpriceable candidate is charged
  // [`crate::footprint::video_frame_bytes_upper_bound`] instead: the
  // same dimension alignment and per-plane overhead at the widest rate,
  // so it dominates whatever that layout would have cost had it been
  // priceable.
  let mut worst: usize = 0;
  let mut judged_any = false;
  if !frames_ctx.is_null() {
    let mut list: *mut libc::c_int = ptr::null_mut();
    // `AV_HWFRAME_TRANSFER_DIRECTION_FROM` is 0 — passed as the integer
    // it is, like every other open C enum on this road.
    // SAFETY: `frames_ctx` is the frame's live `AVHWFramesContext`
    // reference; on success FFmpeg allocates a NONE-terminated list
    // that the caller frees.
    let rc = unsafe { c_shims::av_hwframe_transfer_get_formats(frames_ctx, 0, &mut list, 0) };
    if rc >= 0 && !list.is_null() {
      let none = ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE as libc::c_int;
      let mut p = list;
      loop {
        // SAFETY: FFmpeg guarantees the list is NONE-terminated; reads
        // up to and including the sentinel are in bounds.
        let candidate = unsafe { ptr::read(p) };
        if candidate == none {
          break;
        }
        // **The allocator's arithmetic, not the payload's.** Pricing
        // `av_image_get_buffer_size` at a fixed alignment is what the
        // pixels weigh laid out tightly — for a 16x16 NV12 destination
        // that is 768 bytes against the 1,792 `av_frame_get_buffer`
        // really takes. See [`crate::footprint`].
        let cost = crate::footprint::video_frame_bytes(candidate, width, height)
          .or_else(|| crate::footprint::video_frame_bytes_upper_bound(width, height));
        match cost {
          Some(size) => {
            worst = worst.max(size);
            judged_any = true;
          }
          // Not even the dimension-only bound could be formed, so the
          // extent itself is not a picture. Nothing here will guess.
          None => {
            // SAFETY: `list` is freed exactly once, on every road out.
            unsafe { ffmpeg_next::ffi::av_freep(ptr::addr_of_mut!(list).cast()) };
            return Err(crate::error::HwTransferTooLarge::new(
              usize::MAX,
              limits.max_frame_bytes(),
            ));
          }
        }
        p = unsafe { p.add(1) };
      }
      // SAFETY: `list` was allocated by `av_hwframe_transfer_get_formats`
      // and is freed exactly once here.
      unsafe { ffmpeg_next::ffi::av_freep(ptr::addr_of_mut!(list).cast()) };
    }
  }

  if !judged_any {
    // An empty list, or a query that failed: no candidate was seen at
    // all. Charge the dimension-only bound over the pool extent, which
    // is the most any format this build can emit could cost there.
    let Some(bound) = crate::footprint::video_frame_bytes_upper_bound(width, height) else {
      return Err(crate::error::HwTransferTooLarge::new(
        usize::MAX,
        limits.max_frame_bytes(),
      ));
    };
    worst = bound;
  }

  if worst > limits.max_frame_bytes() {
    return Err(crate::error::HwTransferTooLarge::new(
      worst,
      limits.max_frame_bytes(),
    ));
  }
  Ok(())
}
/// Reads and clears the coded-surface refusal a `get_format` callback
/// left in its state, if it left one.
///
/// Free-standing rather than a method because the reason has to survive
/// on **every** hardware exit, and one of them — the open-time failure
/// path — runs before a decoder exists to ask.
fn ceiling_declination_of(state: *const CallbackState) -> Option<Error> {
  use core::sync::atomic::Ordering;
  if state.is_null() {
    return None;
  }
  // SAFETY: `state` is the live `CallbackState` the caller owns; it is
  // freed only after the codec context it belongs to.
  let (declined, pixels, limit) = unsafe {
    (
      (*state).ceiling_declined.swap(false, Ordering::Acquire),
      (*state).declined_pixels.load(Ordering::Relaxed),
      (*state).declined_limit.load(Ordering::Relaxed),
    )
  };
  declined.then(|| Error::HwSurfaceTooLarge(crate::error::HwSurfaceTooLarge::new(pixels, limit)))
}
/// The software decoders' error funnel.
///
/// Every road that turns a libavcodec decode failure into an `Error`
/// goes through here, so a frame the allocator judge refused comes back
/// named instead of as the `EINVAL` libavcodec also uses for corrupt
/// input. The hardware roads have their own funnel (`hw_exit`); this is
/// its software twin, and the discipline is the same one: **a consumer
/// added helper-by-helper is lost the next time the surrounding code is
/// restructured, so every exit calls one function.**
///
/// # Safety
///
/// `state` must be null or a live `CallbackState` the caller owns.
pub(crate) fn software_exit(state: *const CallbackState, e: ffmpeg_next::Error) -> Error {
  frame_budget_declination_of(state).unwrap_or(Error::Ffmpeg(e))
}

/// **The software road's only way to read an errno — funnel and
/// classify in one call, because the order between them is a law and
/// laws that depend on remembering get broken.**
///
/// Every receive site used to write the two steps out: funnel, then
/// classify. The R1 report called that ordering load-bearing and
/// explained why — a `get_format` declination or an allocator-judge
/// refusal sits in the callback state waiting to be collected, and a
/// classifier that runs first reads the errno libavcodec reported
/// instead of the refusal this crate made, answering `Ended` or
/// `NeedsInput` for a frame that was declined. Then a restructure
/// reordered one road and the law was simply gone, silently, because
/// nothing enforced it.
///
/// So the classifiers are private to this module now and this is the
/// door. A caller cannot classify a raw error because it cannot reach a
/// classifier; the funnel is not something to remember to call first,
/// it is the only thing there is to call.
///
/// # The verdict is minted once and threaded
///
/// **A funnel consumes what it collects.** `take_ceiling_declination`
/// and `take_frame_budget_declination` both *clear* the latch they
/// read, because a refusal reported twice would be a refusal invented
/// once. That makes the verdict a one-shot value, and the rule that
/// follows is the whole of this invariant:
///
/// > The first funnel on a road mints the verdict. Every later step on
/// > that road **threads it**. A site that re-funnels, or that rebuilds
/// > `Error::Ffmpeg(raw)` after a funnel has run, is the bug class —
/// > the second call finds the latch empty and reports the errno the
/// > substrate happened to give over the refusal this crate made.
///
/// A raw errno may still be *read* after minting — `is_hw_decode_failure`
/// does, to decide whether a fallback is required — but reading it to
/// decide a route is not the same as reporting it. What the caller is
/// told is always the verdict.
///
/// # Safety
///
/// `state` must be null or a live [`CallbackState`] the caller owns.
pub(crate) fn software_receive(
  state: *const CallbackState,
  e: ffmpeg_next::Error,
  phase: SessionPhase,
) -> Result<Received> {
  receive_status(software_exit(state, e), phase)
}

/// The send road's half of [`software_receive`]. Same law, same door.
///
/// # Safety
///
/// `state` must be null or a live [`CallbackState`] the caller owns.
pub(crate) fn software_send(
  state: *const CallbackState,
  e: ffmpeg_next::Error,
  phase: SessionPhase,
) -> Result<Sent> {
  send_status(software_exit(state, e), phase)
}

/// Reads and clears a software frame-budget refusal left by
/// [`judge_buffer`], as the named error it deserves.
///
/// The software twin of [`ceiling_declination_of`]: the allocator judge
/// can only answer libavcodec with an errno, so the reason lives in the
/// callback state and every decoder funnel collects it.
pub(crate) fn frame_budget_declination_of(state: *const CallbackState) -> Option<Error> {
  crate::ffi::take_frame_budget_declination(state).map(|(bytes, limit, audio)| {
    Error::FrameBudgetExceeded(crate::error::FrameBudgetExceeded::new(
      bytes,
      limit,
      if audio {
        crate::error::FrameMedium::Audio
      } else {
        crate::error::FrameMedium::Video
      },
    ))
  })
}

/// Proves an opened codec context is a **video** one without going
/// through `Opened::video()`.
///
/// `Opened::video()` calls `Context::medium()`, which reads
/// `AVCodecContext.codec_type` as the bindgen `AVMediaType` enum — a
/// value outside this build's discriminant set is UB the moment it is
/// formed, before any comparison can run. The hardware path has always
/// bypassed that API for this reason; this is that bypass, extracted so
/// the second caller reuses it instead of restating it.
///
/// The caller keeps ownership of `opened` on failure, so its `Drop`
/// still releases the codec context.
pub(crate) fn ensure_video_codec_type(opened: &codec::decoder::Opened) -> Result<()> {
  ensure_codec_type(opened, AVMediaType::AVMEDIA_TYPE_VIDEO)
}

/// The general form: proves an opened context has the medium expected,
/// reading `codec_type` as the integer it is.
///
/// `Opened::{video,audio,subtitle}()` all go through
/// `Context::medium()`, so all three carried the same hazard and all
/// three now come through here.
pub(crate) fn ensure_codec_type(
  opened: &codec::decoder::Opened,
  expected: AVMediaType,
) -> Result<()> {
  // SAFETY: `codec_type` is bound as `AVMediaType` (`#[repr(i32)]`),
  // the same size and alignment as `i32`; reading the bytes as `i32`
  // cannot be UB whatever FFmpeg wrote there.
  let codec_type_int: i32 =
    unsafe { ptr::read(ptr::addr_of!((*opened.as_ptr()).codec_type) as *const i32) };
  if codec_type_int != expected as i32 {
    // The same error `Opened::video()` would have produced, without the
    // enum construction.
    return Err(Error::Ffmpeg(ffmpeg_next::Error::InvalidData));
  }
  Ok(())
}

/// Look up the decoder for `parameters` without going through the bindgen
/// `AVCodecID` Rust enum. Reads the codec_id field as raw `u32` via
/// `addr_of!` + `ptr::read` so a value not in our build's discriminant
/// set never invokes UB.
pub(crate) fn find_decoder(parameters: &codec::Parameters) -> Result<Codec> {
  ensure_parameters_non_null(parameters)?;
  // SAFETY: parameters' inner pointer is non-null (checked above);
  // addr_of! projects to the codec_id field; the *const u32 cast is sound
  // because AVCodecID is `#[repr(u32)]` (same size and alignment as u32).
  // Reading as u32 cannot be UB regardless of the value FFmpeg wrote.
  let raw_id: u32 =
    unsafe { ptr::read(ptr::addr_of!((*parameters.as_ptr()).codec_id) as *const u32) };

  // Call C `avcodec_find_decoder` via our local `c_int`-typed shim — we
  // never construct an `AVCodecID` enum from `raw_id`. The C function
  // returns NULL for unknown ids, which we surface as `Error::NoCodec`.
  // SAFETY: avcodec_find_decoder is a pure FFmpeg lookup; passing any
  // c_int is sound (returns NULL for unknown).
  let codec_ptr = unsafe { c_shims::avcodec_find_decoder(raw_id as libc::c_int) };
  if codec_ptr.is_null() {
    return Err(Error::NoCodec(raw_id));
  }
  // SAFETY: codec_ptr is a non-null *const AVCodec into FFmpeg's static
  // codec table; it lives for the duration of the program.
  Ok(unsafe { Codec::wrap(codec_ptr) })
}

/// Drain output frames from a candidate decoder during probe replay,
/// transferring each one from the candidate's HW context to a fresh CPU
/// frame and queueing it. Returns `Ok(())` once the candidate signals
/// EAGAIN/EOF. The transfer happens while the candidate is still alive
/// (its `AVHWFramesContext` is reachable); the resulting CPU frames remain
/// valid after the candidate is committed because they hold their own
/// buffer references with no dependency on the original device context.
fn drain_into_pending(
  decoder: &mut ffmpeg_next::decoder::Video,
  hw_buf: &mut frame::Video,
  pending: &mut VecDeque<frame::Video>,
  pending_bytes: &mut usize,
  max_bytes: usize,
  frame_limits: crate::FrameLimits,
) -> std::result::Result<(), ffmpeg_next::Error> {
  loop {
    match decoder.receive_frame(hw_buf) {
      Ok(()) => {
        // Pre-transfer cap check: if we are already at or over either cap,
        // the candidate is producing more than we can hold. Treat as an
        // explicit candidate failure so `advance_probe` can try the next
        // backend instead of committing a stream with silently-dropped
        // frames in the middle.
        //
        // TODO: at very large frame sizes (8K HDR P010, > ~96 MiB each)
        // even a single retained frame is significant. Future direction:
        // memmap-backed pending frames (write to a temp file or shared
        // memory segment) so the resident set stays bounded even when the
        // byte cap is raised. Out of scope for now.
        if pending.len() >= MAX_PROBE_PENDING_FRAMES || *pending_bytes >= max_bytes {
          tracing::warn!(
            frames = pending.len(),
            bytes = *pending_bytes,
            max_frames = MAX_PROBE_PENDING_FRAMES,
            max_bytes = max_bytes,
            "hwdecode: probe pending cap reached; failing candidate replay"
          );
          // SAFETY: hw_buf is owned and valid; unref of an empty frame is a no-op.
          unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
          return Err(ffmpeg_next::Error::Other {
            errno: libc::ENOMEM,
          });
        }
        // Pre-transfer size guard: `av_hwframe_transfer_data` will
        // allocate the CPU buffer based on `hw_buf`'s dimensions. If a
        // single frame's worst-case footprint already pushes past the
        // cap, refuse the candidate **before** allocating so RSS does
        // not spike on a frame we'd immediately drop. Uses a width *
        // height * `WORST_CASE_BYTES_PER_PIXEL` upper bound; the
        // post-transfer accounting via `cpu_frame_bytes` below stays in
        // place as a backstop using the actual stride/format.
        let estimated_bytes = match estimate_transfer_bytes(hw_buf) {
          Some(b) => b,
          None => {
            // SAFETY: AVFrame.width/height are c_int reads.
            let (w, h) = unsafe {
              let raw = hw_buf.as_ptr();
              ((*raw).width, (*raw).height)
            };
            tracing::warn!(
              width = w,
              height = h,
              "hwdecode: HW frame dimensions invalid for sizing; failing candidate replay"
            );
            unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
            return Err(ffmpeg_next::Error::Other {
              errno: libc::ENOMEM,
            });
          }
        };
        let estimated_total = pending_bytes.saturating_add(estimated_bytes);
        if estimated_total > max_bytes {
          // SAFETY: AVFrame.width/height are c_int reads.
          let (w, h) = unsafe {
            let raw = hw_buf.as_ptr();
            ((*raw).width, (*raw).height)
          };
          tracing::warn!(
            pending_bytes = *pending_bytes,
            estimated_bytes,
            width = w,
            height = h,
            max_bytes = max_bytes,
            "hwdecode: pre-transfer size estimate exceeds cap; \
             refusing candidate replay before allocating CPU frame"
          );
          unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
          return Err(ffmpeg_next::Error::Other {
            errno: libc::ENOMEM,
          });
        }
        // **The same exact judge, on the replay road.** This site
        // already had a pre-transfer *estimate* (`w * h * 8`) against
        // the probe's own pending budget; that stays, and this adds the
        // frame ceiling itself, priced exactly.
        //
        // The refusal is reported through this function's existing
        // `ffmpeg_next::Error` channel rather than the named arm: every
        // error out of a probe-replay drain is collapsed by the caller
        // into "this candidate failed, try the next backend", so a name
        // has no consumer here. The reason is logged so it is not lost.
        // SAFETY: `hw_buf` holds a live decoded HW frame.
        if let Err(e) = unsafe { judge_hw_transfer(hw_buf.as_ptr(), frame_limits) } {
          tracing::warn!(
            bytes = e.bytes(),
            limit = e.limit(),
            "hwdecode: candidate's hw->cpu transfer would exceed the frame ceiling; \
             refusing the candidate before the download"
          );
          // SAFETY: `hw_buf` is owned and valid.
          unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
          return Err(ffmpeg_next::Error::Other {
            errno: libc::EINVAL,
          });
        }
        let mut cpu = alloc_av_frame()?;
        // SAFETY: hw_buf is a freshly-decoded HW frame;
        // `av_hwframe_transfer_data` allocates pixel buffers on `cpu`.
        // We use `copy_frame_props_minimal` (only `pts`) instead of
        // `av_frame_copy_props` for the same reason as
        // `transfer_hw_frame`: the public `Frame` API does not expose
        // side data / metadata / opaque refs, so deep-copying them per
        // frame is pure cost and an unbounded allocation source on
        // attacker-controlled streams.
        unsafe {
          let r1 = av_hwframe_transfer_data(cpu.as_mut_ptr(), hw_buf.as_ptr(), 0);
          if r1 < 0 {
            return Err(ffmpeg_next::Error::from(r1));
          }
        }
        // Same post-transfer pix_fmt validation as `transfer_hw_frame`.
        // A driver that picks a CPU format outside our supported set
        // would queue an unusable frame here; later, when
        // `try_pop_pending` hands it to the caller, `Frame::row` /
        // `Frame::as_ptr` would return `None`. Refuse the candidate
        // before the queue grows so probing advances to the next
        // backend instead.
        let cpu_raw_fmt: i32 = unsafe { (*cpu.as_ptr()).format };
        let cpu_pix_fmt = crate::boundary::from_av_pixel_format(cpu_raw_fmt);
        if !crate::frame::is_supported_cpu_pix_fmt(&cpu_pix_fmt) {
          tracing::warn!(
            pix_fmt = cpu_raw_fmt,
            "hwdecode: candidate produced unsupported CPU pix_fmt during \
             probe replay; failing candidate"
          );
          return Err(ffmpeg_next::Error::Other {
            errno: libc::EINVAL,
          });
        }
        let pixel_bytes = match cpu_frame_bytes(&cpu) {
          Some(b) => b,
          None => {
            // Unknown pix_fmt or vertically-flipped layout — we cannot
            // bound this frame's contribution against the byte cap, so up
            // to MAX_PROBE_PENDING_FRAMES of them could exhaust memory.
            // Fail the candidate so probing tries the next backend
            // rather than queueing untracked allocations.
            // SAFETY: AVFrame.format is c_int, safe to read.
            let pix_fmt: i32 = unsafe { (*cpu.as_ptr()).format };
            tracing::warn!(
              pix_fmt,
              "hwdecode: cannot size unknown CPU pix_fmt during replay; failing candidate"
            );
            // cpu drops here.
            return Err(ffmpeg_next::Error::Other {
              errno: libc::ENOMEM,
            });
          }
        };
        // Account for side-data bytes that `av_frame_copy_props`
        // will deep-copy from the source HW frame. HDR streams
        // typically carry mastering display + content light level
        // (~50 bytes) and dynamic HDR metadata (~few hundred bytes);
        // pathological side-data could otherwise quietly bypass the
        // pixel-data byte cap.
        // SAFETY: hw_buf is a valid AVFrame; we read scalar fields
        // and pointer arrays without forming a `&AVFrame`.
        let side_data_bytes = unsafe { sum_side_data_bytes(hw_buf.as_ptr()) };
        let new_total = pending_bytes
          .saturating_add(pixel_bytes)
          .saturating_add(side_data_bytes);
        if new_total > max_bytes {
          tracing::warn!(
            pending_bytes = *pending_bytes,
            pixel_bytes,
            side_data_bytes,
            max_bytes,
            "hwdecode: queueing this frame would exceed byte cap; \
             failing candidate replay"
          );
          // cpu drops here without ever paying a metadata deep copy.
          return Err(ffmpeg_next::Error::Other {
            errno: libc::ENOMEM,
          });
        }
        // Cap check passed — copy AVFrame metadata. SAFETY: cpu and
        // hw_buf are both valid AVFrames we own. On failure (OOM
        // during side-data alloc) we propagate so the probe candidate
        // is treated as failed rather than queueing a frame whose
        // metadata silently disappeared.
        unsafe { copy_frame_props_minimal(cpu.as_mut_ptr(), hw_buf.as_ptr()) }?;
        *pending_bytes = new_total;
        pending.push_back(cpu);
      }
      Err(e) if is_transient(&e) => return Ok(()),
      Err(e) => return Err(e),
    }
  }
}

/// Allocated frame dimensions according to `hw_buf.hw_frames_ctx`.
///
/// Per FFmpeg's `libavutil/hwcontext.c::transfer_data_alloc`, the CPU
/// destination of `av_hwframe_transfer_data` is allocated using
/// `AVHWFramesContext.width / .height` (the *allocated* surface size of
/// the HW pool); only afterwards is `dst->width / dst->height` reset to
/// `src->width / src->height` (the *display* size). For cropped or
/// heavily aligned streams the allocated dims can be much larger than
/// the display dims (e.g. coded 8192×8192 surface with a 100×100
/// display crop), so any byte-cap accounting that uses display dims
/// undercounts by `allocated_height / display_height` and lets the
/// real allocation slip past the cap.
///
/// Returns `None` when no `hw_frames_ctx` is attached or the dimensions
/// are non-positive — the caller treats `None` as "cannot prove
/// allocation extent, fail the candidate."
fn hw_frames_ctx_dimensions(frame: &frame::Video) -> Option<(i32, i32)> {
  // SAFETY: `frame` owns a live `AVFrame` for the call.
  unsafe { hw_frames_ctx_dimensions_raw(frame.as_ptr()) }
}

/// Pointer form of [`hw_frames_ctx_dimensions`], for the judges that
/// hold a raw `AVFrame` rather than a wrapper.
///
/// # Safety
///
/// `raw` must be a live `*const AVFrame`.
unsafe fn hw_frames_ctx_dimensions_raw(raw: *const AVFrame) -> Option<(i32, i32)> {
  // SAFETY: AVFrame.hw_frames_ctx is `*mut AVBufferRef`. When non-null,
  // its `data` field points to an `AVHWFramesContext`. We read `.width`
  // and `.height` (both `c_int`) via field projection — neither field is
  // enum-typed, so no bindgen-enum UB hazard.
  unsafe {
    let hw_ctx_ref = (*raw).hw_frames_ctx;
    if hw_ctx_ref.is_null() {
      return None;
    }
    let data = (*hw_ctx_ref).data;
    if data.is_null() {
      return None;
    }
    let frames_ctx = data as *const AVHWFramesContext;
    let w: i32 = ptr::read(ptr::addr_of!((*frames_ctx).width));
    let h: i32 = ptr::read(ptr::addr_of!((*frames_ctx).height));
    if w <= 0 || h <= 0 {
      return None;
    }
    Some((w, h))
  }
}

/// Conservative upper-bound estimate of the bytes
/// `av_hwframe_transfer_data` will allocate when downloading `hw_buf` to
/// a CPU frame. Used by [`drain_into_pending`] as a pre-transfer guard
/// so a candidate replay can refuse a frame whose footprint would
/// exceed the byte budget *without* first paying the allocation.
///
/// Sizes from `hw_buf.hw_frames_ctx` (the allocated dims used by the
/// FFmpeg transfer path) rather than `AVFrame.width / .height` (display
/// dims). On a cropped stream the two can differ by orders of magnitude
/// and using display dims would let the real allocation slip past the
/// cap.
///
/// Returns `None` when `hw_frames_ctx` is missing or its width/height
/// are non-positive — caller treats as candidate failure since we
/// cannot prove the allocation extent. (A SW source frame on the probe
/// replay path is not expected; we don't fall back to display dims
/// because that's the exact attack the cap is meant to prevent.)
fn estimate_transfer_bytes(hw_buf: &frame::Video) -> Option<usize> {
  let (w, h) = hw_frames_ctx_dimensions(hw_buf)?;
  Some(
    (w as usize)
      .saturating_mul(h as usize)
      .saturating_mul(WORST_CASE_BYTES_PER_PIXEL),
  )
}

/// Exact resident size of a CPU frame: sum of `AVFrame.buf[i].size`
/// across every populated buffer.
///
/// `AVBufferRef.size` is documented as "Size of data in bytes" — the
/// real allocated extent FFmpeg used. Reading it directly handles the
/// cropped/aligned case where `AVFrame.height` (display) is smaller
/// than the underlying allocation height (the `AVHWFramesContext`
/// surface size FFmpeg sized the buffer for); a `linesize *
/// plane_height_for(display_height)` formula would undercount in that
/// case.
///
/// Returns `None` only when `linesize[0]` is negative — FFmpeg's
/// vertically-flipped layout. The crate's safe row accessors
/// ([`crate::Frame::row`] / [`crate::Frame::rows`]) already reject
/// negative-stride frames, so queueing one during probe replay would
/// just delay the failure to the consumer; refusing here lets the
/// probe loop advance to the next backend instead.
fn cpu_frame_bytes(frame: &frame::Video) -> Option<usize> {
  // SAFETY: AVFrame.linesize is `[c_int; 8]`; AVFrame.buf is
  // `[*mut AVBufferRef; 8]`; AVBufferRef.size is `usize`. All are
  // primitive reads / pointer dereferences with no enum interpretation.
  unsafe {
    let raw = frame.as_ptr();
    let first_linesize = (*raw).linesize[0];
    // Vertically-flipped (negative linesize) is the only "unsizeable"
    // case we still surface as `None`; everything else can be exactly
    // measured from buf[i].size.
    if first_linesize < 0 {
      return None;
    }
    let mut total: usize = 0;
    for i in 0..(*raw).buf.len() {
      let buf = (*raw).buf[i];
      if buf.is_null() {
        continue;
      }
      total = total.saturating_add((*buf).size);
    }
    Some(total)
  }
}

#[allow(dead_code)]
fn _assert_send() {
  fn check<T: Send>() {}
  check::<VideoDecoder>();
}

#[cfg(test)]
mod tests;