kodecs-vaapi 0.2.1

VA-API H.264 and H.265 hardware encode and decode, forked from discord/cros-libva and discord/cros-codecs, with libva loaded at runtime
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
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Adapted from discord/cros-codecs (`decoder/stateless/h264.rs` and
// `decoder/stateless/h264/vaapi.rs`), itself BSD-3-Clause / Copyright The
// ChromiumOS Authors. See LICENSE.cros-codecs.

//! Thin VA-API H.264 and H.265 decoder built on the vendored libva binding.
//!
//! The mirror of [`crate::encode`]. It parses H.264 parameter sets and slices
//! with kodecs-h264, and reuses the backend-agnostic layers (`codec::h264`,
//! `codec::h265`) from discord/cros-codecs (BSD-3-Clause) for H.265 parsing,
//! reference marking, and DPB bumping, then drives libva directly rather than
//! vendoring cros-codecs's generic multi-backend decoder framework. The
//! per-picture and per-slice VA buffer population is ported from cros-codecs's
//! `decoder/stateless/h264/vaapi.rs` and, in `h265.rs`, from
//! `decoder/stateless/h265.rs` and `decoder/stateless/h265/vaapi.rs`.
//!
//! Feed [`Decoder::decode`] one Annex-B access unit at a time. Its picture is
//! submitted and completed before the call returns, rather than when the next
//! unit's first slice arrives, so the hardware is never left holding a
//! half-submitted picture between calls.
//!
//! Output trails input by the reorder depth the SPS declares. H.264 bumps
//! the DPB when a new picture needs a frame buffer (C.4.5.3), and also lets a
//! picture out as soon as more pictures wait than the SPS's reorder limit
//! allows, so a stream that declares no reordering comes out as it decodes
//! rather than one picture behind. An SPS without `bitstream_restriction`
//! declares nothing, so E.2.1 infers the DPB size and such a stream still
//! trails by it, unless its profile is an intra one, which reorders nothing. H.265 bumps by the SPS's reorder limit (C.5.2) to the same
//! effect. A stream with B-frames still holds pictures back, so [`Frame`]
//! carries the timestamp of the access unit it was coded in, and
//! [`Decoder::flush`] is what releases the tail at the end of a stream.
//!
//! Progressive 8-bit 4:2:0 only: a sequence that is interlaced, deeper than 8
//! bits, or not 4:2:0 is rejected rather than decoded wrongly. That covers every
//! stream this crate's encoder, WebRTC, or a browser's `VideoEncoder` produces.
//! H.265 is the Main profile, with Main 10 and Main Still Picture streams that
//! hold 8-bit samples decoded the same way. Left and top cropping are rejected;
//! right and bottom cropping are supported.

use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use anyhow::{anyhow, bail, Context as _};

use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists};
use crate::codec::h264::picture::{PictureData, Reference};
use crate::codec::Codec;
use crate::pool::{PooledSurface, SurfacePool};
use crate::{
	bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields,
	H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter,
	PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib,
	VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
	VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420,
	VA_SLICE_DATA_FLAG_ALL,
};
use kodecs_h264::{
	Marking, Matrix, Mmco, Modification, Nalu, NaluHeader, NaluType, Parser, PicOrderCnt, Pps, Profile, SliceHeader,
	SliceType, Sps, Unit,
};

mod h265;

/// Decoder configuration.
#[derive(Clone, Debug)]
pub struct Config {
	/// The format to decode, H.264 unless set.
	pub codec: Codec,
	/// DRM render node to open (e.g. `/dev/dri/renderD128`).
	///
	/// `None`, the default, opens the first node whose driver can decode
	/// [`codec`](Self::codec).
	pub device: Option<PathBuf>,
}

impl Config {
	/// Returns an H.264 configuration that opens the first render node whose driver can decode it.
	pub fn new() -> Self {
		Self {
			codec: Codec::H264,
			device: None,
		}
	}
}

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

/// One decoded picture, downloaded to client memory as tightly packed NV12.
#[derive(Clone)]
pub struct Frame {
	/// Timestamp of the access unit this picture was coded in, as handed to
	/// [`Decoder::decode`].
	pub timestamp: u64,
	/// Visible width in pixels, i.e. after the SPS cropping rectangle.
	pub width: u32,
	/// Visible height in pixels.
	pub height: u32,
	/// NV12 planes with no row padding: `width * height` luma bytes followed by
	/// `width * height / 2` interleaved chroma bytes.
	pub data: Vec<u8>,
}

/// One decoded picture, left in the surface the hardware wrote it into.
///
/// The GPU counterpart of [`Frame`]: same picture, same timestamp, but a DRM
/// PRIME descriptor for the surface rather than a copy of its pixels. The
/// descriptor owns the exported file descriptors and the surface travels with
/// it, so both the allocation and libva's handle on it outlive the decoder.
///
/// The export is NV12 in one object holding both planes, which is what the
/// Intel and AMD drivers produce. Read the modifier off the object before
/// assuming anything about the layout: a decode target is tiled, and the plane
/// pitches carry padding the visible size does not imply. That is also why
/// [`ExportedFrame::download`] goes back through the surface instead of reading
/// the file descriptor as rows.
///
/// Dropping the frame hands its surface back to the decoder, which decodes a
/// later picture into it. So keep the frame for as long as anything reads the
/// descriptor or an import of it: a GPU consumer holds it until the work that
/// samples it has finished, not merely until that work is submitted. A frame
/// that outlives its decoder, or the sequence it was decoded in, releases its
/// surface to the driver instead.
///
/// This is [`Send`] and [`Sync`] even though [`Decoder`] is neither: a surface
/// is a display and an id, both of which libva serializes internally, and none
/// of the decoder's `Rc`s come along.
pub struct ExportedFrame {
	/// Timestamp of the access unit this picture was coded in, as handed to
	/// [`Decoder::decode_exported`].
	pub timestamp: u64,
	/// Visible width in pixels, i.e. after the SPS cropping rectangle.
	pub width: u32,
	/// Visible height in pixels.
	pub height: u32,
	/// The surface's export: format, modifier, and the offset and pitch of each
	/// plane.
	pub descriptor: DrmPrimeSurfaceDescriptor,
	/// The surface the picture was decoded into, held here so the decoder does
	/// not decode into it again until this drops, and so
	/// [`ExportedFrame::download`] has something to map.
	surface: Arc<PooledSurface>,
}

impl ExportedFrame {
	/// Exports `surface`, an NV12 picture from somewhere other than the decoder, the way the decoder exports its own.
	///
	/// A picture the video processor produced, such as a scaled copy of a
	/// captured frame, then reaches its consumer with the same descriptor and
	/// the same [`download`](Self::download) fallback as a decoded one, so one
	/// consumer handles both. `timestamp` is carried through untouched.
	///
	/// # Errors
	///
	/// Fails when the surface is not NV12, cannot be synced, or the driver will
	/// not export it.
	pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result<Self> {
		let size = surface.size();
		Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size)
	}

	/// Exports `surface`, whose picture is the top-left `width` by `height` of it, copying nothing.
	///
	/// The frame holds a reference to the surface, so a pool does not hand it
	/// out again while the caller holds the descriptor, and
	/// [`download`](Self::download) can still map it.
	pub(crate) fn export(
		surface: Arc<PooledSurface>,
		timestamp: u64,
		(width, height): (u32, u32),
	) -> anyhow::Result<Self> {
		surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
		let descriptor = surface
			.get()
			.export_prime()
			.map_err(|e| anyhow!("export the surface: {e:?}"))?;
		if descriptor.fourcc != VA_FOURCC_NV12 {
			anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc);
		}
		Ok(Self {
			timestamp,
			width,
			height,
			descriptor,
			surface,
		})
	}

	/// Reads this picture back to client memory as tightly packed NV12.
	///
	/// The way back for a caller that took a descriptor and then found itself
	/// with a consumer that wants bytes. It costs the read [`Decoder::decode`]
	/// would have done up front, so prefer that entry point when nothing on the
	/// path draws on the GPU.
	///
	/// Same layout as [`Frame::data`], with the driver's row padding dropped.
	pub fn download(&self) -> anyhow::Result<Frame> {
		read_back(self.surface.get(), self.timestamp, self.width, self.height)
	}
}

impl std::fmt::Debug for ExportedFrame {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("ExportedFrame")
			.field("timestamp", &self.timestamp)
			.field("width", &self.width)
			.field("height", &self.height)
			.field("fourcc", &self.descriptor.fourcc)
			.finish()
	}
}

impl std::fmt::Debug for Frame {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Frame")
			.field("timestamp", &self.timestamp)
			.field("width", &self.width)
			.field("height", &self.height)
			.field("bytes", &self.data.len())
			.finish()
	}
}

/// A VA-API H.264 or H.265 decoder. Built once, fed Annex-B access units, emits NV12.
///
/// # Examples
///
/// ```no_run
/// use kodecs_vaapi::decode::{Config, Decoder};
///
/// # fn main() -> anyhow::Result<()> {
/// # let access_units: Vec<Vec<u8>> = Vec::new();
/// let mut decoder = Decoder::new(Config::new())?;
/// let mut pictures = Vec::new();
///
/// for (index, access_unit) in access_units.iter().enumerate() {
///     pictures.extend(decoder.decode(access_unit, index as u64)?);
/// }
///
/// // Output trails input, so the tail of the stream only arrives here.
/// pictures.extend(decoder.flush()?);
/// # Ok(())
/// # }
/// ```
pub struct Decoder {
	inner: Inner,
}

/// The decoder for each format. They share the VA plumbing: [`Sequence`],
/// [`Handle`], and the read-back and export of a decoded picture.
enum Inner {
	H264(H264),
	H265(h265::Decoder),
}

/// The H.264 decoder.
struct H264 {
	parser: Parser,
	dpb: Dpb<Handle>,
	/// Cached variables from the previous reference picture.
	prev_ref_pic_info: PrevReferencePicInfo,
	/// Cached variables from the previous picture.
	prev_pic_info: PrevPicInfo,
	/// `MaxLongTermFrameIdx + 1`, zero for "no long-term frame indices".
	max_long_term_frame_idx_plus1: u32,
	/// VA state for the active sequence, rebuilt when the SPS changes something
	/// the config, context, or surface pool depends on.
	sequence: Option<Sequence>,
	/// Pictures bumped out of the DPB, in output order, awaiting download.
	ready: Vec<Handle>,
	/// Drop order: everything above borrows the display.
	display: Arc<Display>,
}

impl Decoder {
	/// Opens [`Config::device`], or the first render node that decodes
	/// [`Config::codec`], and checks that the driver exposes a decode
	/// entrypoint for it.
	///
	/// The VA config, context, and surface pool are built later, from the first
	/// SPS, since their profile and size come from the stream. This still fails
	/// early enough for a caller to fall back to another decoder when libva is
	/// missing, the node cannot be opened, or the driver does not decode the
	/// codec. A named node is never swapped for another.
	pub fn new(config: Config) -> anyhow::Result<Self> {
		let codec = config.codec;
		let (device, display) = match config.device {
			Some(device) => {
				let display =
					Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
				probe(&display, codec)?;
				(device, display)
			}
			None => crate::display::open_first(|display| probe(display, codec))
				.map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
		};

		tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
		let inner = match codec {
			Codec::H264 => Inner::H264(H264::new(display)),
			Codec::H265 => Inner::H265(h265::Decoder::new(display)),
		};
		Ok(Self { inner })
	}

	/// Decodes one Annex-B access unit, returning the pictures that came due, in
	/// output order.
	///
	/// `timestamp` is opaque and travels with the picture coded in this access
	/// unit, so it survives DPB reordering. Parameter sets are read from the
	/// stream, so an access unit carrying only an SPS and a PPS decodes to no
	/// frames.
	pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
		self.submit(access_unit, timestamp)?;
		self.take_frames()
	}

	/// Decodes one Annex-B access unit, leaving the pictures that came due on
	/// the GPU.
	///
	/// The same decode as [`Decoder::decode`], differing only in what the caller
	/// gets back: a DRM PRIME descriptor for each picture's surface instead of a
	/// copy of its pixels. For a consumer that draws on the GPU that is the
	/// whole picture never touching system memory.
	///
	/// An exported surface stays out of the recycling pool until the
	/// [`ExportedFrame`] drops, since the next picture would otherwise be decoded
	/// over pixels the consumer still holds a descriptor for. A consumer that
	/// lets each picture go once it has drawn it therefore costs no allocation
	/// per picture; one that holds on to pictures costs one surface per picture
	/// held.
	///
	/// A consumer that turns out to want bytes after all is not stuck: the
	/// surface travels with the descriptor, and [`ExportedFrame::download`] reads
	/// it back.
	pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
		self.submit(access_unit, timestamp)?;
		self.take_exported()
	}

	/// Decodes one access unit, leaving the pictures that came due in the ready
	/// queue for whichever of [`Decoder::take_frames`] or
	/// [`Decoder::take_exported`] the caller asked for.
	fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
		let nalus = match &mut self.inner {
			Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
			Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
		};

		// Length-prefixed input often holds no start code at all, which a
		// decoder cannot tell from an empty unit, so it would otherwise get
		// silence. Say so once per unit rather than leaving the caller to
		// wonder where their pictures went.
		if nalus == 0 && !access_unit.is_empty() {
			tracing::warn!(
				"access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
				access_unit.len()
			);
		}
		Ok(())
	}

	/// Returns every picture still held in the DPB, in output order.
	///
	/// The DPB lets a picture out only when a later one needs it to (C.4.5.3
	/// for H.264, C.5.2 for H.265), so a stream that simply stops leaves its
	/// tail sitting there. This releases that tail and empties the DPB, so a
	/// second call returns nothing.
	///
	/// The parsed parameter sets survive, and nothing here waits for an IDR: a
	/// stream picked up part way through decodes against an empty DPB, which
	/// gives distorted pictures until its next IDR rather than an error.
	pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
		self.reset();
		self.take_frames()
	}

	/// [`Decoder::flush`] for a caller taking its pictures on the GPU.
	pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
		self.reset();
		self.take_exported()
	}

	/// Moves the DPB to the ready queue and forgets the state the next picture
	/// would otherwise be derived against.
	fn reset(&mut self) {
		match &mut self.inner {
			Inner::H264(decoder) => decoder.reset(),
			Inner::H265(decoder) => decoder.reset(),
		}
	}

	/// The pictures bumped out of the DPB, in output order, awaiting download.
	fn ready(&mut self) -> &mut Vec<Handle> {
		match &mut self.inner {
			Inner::H264(decoder) => &mut decoder.ready,
			Inner::H265(decoder) => &mut decoder.ready,
		}
	}

	/// Downloads every picture waiting in the ready queue.
	fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
		std::mem::take(self.ready()).iter().map(download).collect()
	}

	/// Exports every picture waiting in the ready queue, leaving the pixels
	/// where the hardware wrote them.
	fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
		std::mem::take(self.ready()).iter().map(export).collect()
	}

	/// The VA state of the active sequence, for tests that look at its pool.
	#[cfg(test)]
	fn sequence(&self) -> Option<&Sequence> {
		match &self.inner {
			Inner::H264(decoder) => decoder.sequence.as_ref(),
			Inner::H265(decoder) => decoder.sequence.as_ref(),
		}
	}
}

impl H264 {
	fn new(display: Arc<Display>) -> Self {
		Self {
			// The access unit is already in memory, so the budget only has to
			// bound what a level allows, which the parser caps it to once an SPS
			// arrives.
			parser: Parser::new(usize::MAX),
			dpb: Dpb::default(),
			prev_ref_pic_info: PrevReferencePicInfo::default(),
			prev_pic_info: PrevPicInfo::default(),
			max_long_term_frame_idx_plus1: 0,
			sequence: None,
			ready: Vec::new(),
			display,
		}
	}

	/// Decodes one access unit into the ready queue, returning how many NAL units it held.
	fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
		let mut stream = access_unit;
		let mut current: Option<CurrentPicture> = None;
		let mut nalus = 0usize;

		loop {
			let before = stream;
			let Some(nalu) = next_nalu(&mut stream, self.parser.max_nal_bytes())? else {
				break;
			};
			nalus += 1;
			let nal = nalu.header;
			match nal.type_ {
				// Data partition A fails to parse, since VA-API has no way to decode it.
				NaluType::Sps | NaluType::Pps | NaluType::Slice | NaluType::SliceIdr | NaluType::SliceDpa => {}
				// Data partitions B and C, and the SVC and MVC extensions, carry nothing the base
				// layer decodes.
				other => {
					tracing::trace!("ignoring NAL unit of type {other:?}");
					continue;
				}
			}

			// The parser frames the unit as sent again, charging its whole Annex B length,
			// padding and leading zeros included, against the SPS it refers to. A refused SPS or
			// PPS evicts the stored set of its id, so the slices meant for its replacement fail.
			let mut sent = &before[..before.len() - stream.len()];
			let unit = self
				.parser
				.next(&mut sent)
				.map_err(|e| match e {
					kodecs_h264::Error::Unsupported => anyhow!(
						"{:?} NAL unit: {e}: only progressive 8-bit 4:2:0 up to High profile decodes",
						nal.type_
					),
					e => anyhow!(e).context(format!("parse a {:?} NAL unit", nal.type_)),
				})?
				.expect("the unit framed above");
			let Unit::Slice(header) = unit else {
				continue;
			};
			// The slice data handed to the driver starts at the NAL header and ends before the padding.
			let start = nalu.payload.as_ptr() as usize - before.as_ptr() as usize - 1;
			let data = before[start..start + 1 + nalu.payload.len()].to_vec();
			let slice = Slice { header, nal, data };

			let mut picture = match current.take() {
				// An access unit normally holds one picture, but nothing
				// forces that: `first_mb_in_slice == 0` starts a new one,
				// so the picture in flight is done.
				Some(picture) if slice.header.first_mb_in_slice == 0 => {
					self.finish_picture(picture)?;
					self.begin_picture(&slice, timestamp)?
				}
				Some(picture) => picture,
				None => self.begin_picture(&slice, timestamp)?,
			};

			self.decode_slice(&mut picture, slice)?;
			current = Some(picture);
		}

		// Finishing here rather than on the next unit's first slice keeps the
		// hardware from holding a half-submitted picture between calls.
		if let Some(picture) = current.take() {
			self.finish_picture(picture)?;
		}

		Ok(nalus)
	}

	/// Moves the DPB to the ready queue and forgets the order count state the
	/// next picture would otherwise be derived against.
	fn reset(&mut self) {
		self.drain();
		self.prev_ref_pic_info = PrevReferencePicInfo::default();
		self.prev_pic_info = PrevPicInfo::default();
		self.max_long_term_frame_idx_plus1 = 0;
	}

	/// Moves everything left in the DPB to the ready queue.
	fn drain(&mut self) {
		self.ready.extend(self.dpb.drain().into_iter().flatten());
	}

	/// Applies `sps` to the DPB limits, rebuilding the VA config, context, and
	/// surface pool if it changes anything they depend on.
	fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
		let info = SequenceInfo::new(sps)?;
		// C.4.5.3: the DPB limits follow the active SPS whether or not the VA
		// state has to be rebuilt.
		self.dpb
			.set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));

		let format = Format {
			codec: Codec::H264,
			profile: va_profile(info.profile)?,
			coded: info.coded,
			visible: info.visible,
			max_dpb_frames: info.max_dpb_frames,
		};
		if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
			return Ok(());
		}

		// Surfaces are about to change shape, so let everything decoded against
		// the old sequence out first. Those handles keep their own surfaces (and
		// through them the old pool) alive until they are downloaded.
		self.drain();

		self.sequence = Some(Sequence::new(&self.display, format)?);
		Ok(())
	}

	/// Starts a picture: computes its order count, updates the DPB's picture
	/// numbers, and hands the driver the picture parameters.
	fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
		let (sps, pps) = self.parameter_sets(&slice.header)?;
		self.apply_sps(&sps)?;

		if slice.nal.type_ == NaluType::SliceIdr {
			self.prev_ref_pic_info.frame_num = 0;
		}

		let frame_num = slice.header.frame_num;
		if frame_num != self.prev_ref_pic_info.frame_num
			&& frame_num != (self.prev_ref_pic_info.frame_num + 1) % max_frame_num(&sps)
		{
			self.handle_frame_num_gap(&sps, frame_num)?;
		}

		let pic = self.init_current_pic(slice, &sps)?;
		let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic, &sps);

		// `apply_sps` above either kept the sequence or built a new one.
		let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
		let context = Rc::clone(&sequence.context);
		let handle = sequence.handle(timestamp)?;

		let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
		let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
		picture.add_buffer(create_buffer(&context, pic_param)?);
		picture.add_buffer(create_buffer(&context, build_iq_matrix(&sps, &pps))?);

		tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
		Ok(CurrentPicture {
			pic,
			sps,
			pps,
			handle,
			picture,
			ref_pic_lists,
		})
	}

	/// Returns the SPS and PPS the slice with `header` parsed against.
	fn parameter_sets(&self, header: &SliceHeader) -> anyhow::Result<(Sps, Pps)> {
		let pps = self
			.parser
			.pps(header.pps_id)
			.context("slice refers to an unknown PPS")?;
		let sps = self.parser.sps(pps.sps_id).context("PPS refers to an unknown SPS")?;
		Ok((sps.clone(), pps.clone()))
	}

	/// Hands the driver one slice: its parameters, its reference lists, and the
	/// slice NAL itself.
	fn decode_slice(&mut self, current: &mut CurrentPicture, slice: Slice) -> anyhow::Result<()> {
		// A VA slice parameter carries both of these in 16 bits, so refuse what
		// would otherwise be truncated into a plausible wrong offset. Only a
		// picture past 65536 macroblocks, which is beyond 8K, gets close.
		if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
			bail!(
				"slice starts at macroblock {}, past what a VA slice parameter addresses",
				slice.header.first_mb_in_slice
			);
		}
		if slice.header.header_bit_size > usize::from(u16::MAX) {
			bail!(
				"slice header is {} bits long, past what a VA slice parameter addresses",
				slice.header.header_bit_size
			);
		}

		// A slice may refer to a different PPS than the one that started the
		// picture, as long as it names the same sequence.
		let (sps, pps) = self.parameter_sets(&slice.header)?;
		if SequenceInfo::new(&sps)? != SequenceInfo::new(&current.sps)? {
			bail!("invalid stream: the sequence changed between slices of one picture");
		}
		current.sps = sps;
		current.pps = pps;

		let (list0, list1) =
			self.create_ref_pic_lists(&current.pic, &slice.header, &current.sps, &current.ref_pic_lists)?;
		let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;

		let slice_param = build_slice_param(&slice.header, slice.data.len(), &list0, &list1, &current.pps);
		current.picture.add_buffer(create_buffer(context, slice_param)?);
		current
			.picture
			.add_buffer(create_buffer(context, BufferType::SliceData(slice.data))?);

		Ok(())
	}

	/// Submits the picture to the hardware, then runs the reference marking and
	/// bumping the specification calls for once a picture is decoded.
	fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
		let CurrentPicture {
			mut pic,
			sps,
			handle,
			picture,
			..
		} = current;

		run(picture)?;
		tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);

		if pic.is_ref() {
			self.reference_pic_marking(&mut pic, &sps)?;
			self.prev_ref_pic_info.fill(&pic);
		}
		self.prev_pic_info.fill(&pic);

		// C.4.5.3 clause 3: a picture with memory_management_control_operation
		// equal to 5 empties the DPB.
		if pic.has_mmco_5 {
			self.drain();
		}

		// C.4.4 and C.4.5: free what the marking released, then store or output.
		self.dpb
			.finish_picture(pic, handle, &mut self.ready)
			.map_err(|e| anyhow!("store picture in DPB: {e}"))?;

		Ok(())
	}

	/// Builds the picture for `slice` and makes room for it in the DPB.
	fn init_current_pic(&mut self, slice: &Slice, sps: &Sps) -> anyhow::Result<PictureData> {
		let mut pic = PictureData::new_from_slice(&slice.header, slice.nal, &sps.pic_order_cnt);
		self.compute_pic_order_count(&mut pic, sps)?;

		if pic.idr {
			// C.4.5.3 clause 2: an IDR bumps the whole DPB, unless
			// no_output_of_prior_pics_flag says to discard it instead (C.4.4).
			if matches!(pic.marking, Some(Marking::Idr(true, _))) {
				self.dpb.clear();
			} else {
				self.drain();
			}
		}

		self.dpb.update_pic_nums(slice.header.frame_num, max_frame_num(sps));

		Ok(pic)
	}

	/// 8.2.5.2: invents the pictures for the frame numbers a lossy stream skipped,
	/// so reference marking keeps working.
	fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> anyhow::Result<()> {
		if self.dpb.is_empty() {
			return Ok(());
		}

		if !sps.gaps_in_frame_num_allowed {
			bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
		}
		tracing::debug!("frame_num gap up to {frame_num}");

		let max_frame_num = max_frame_num(sps);
		let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
		while unused != frame_num {
			let mut pic = PictureData::new_non_existing(unused);
			self.compute_pic_order_count(&mut pic, sps)?;

			self.dpb.update_pic_nums(unused, max_frame_num);
			self.dpb.sliding_window_marking(sps);
			self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
			self.dpb
				.store_picture(pic, None)
				.map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;

			unused = (unused + 1) % max_frame_num;
		}

		Ok(())
	}

	/// 8.2.1: derives the picture order count, which drives output ordering.
	fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
		pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
	}

	/// 8.2.5.1: marks the decoded picture as used or unused for reference.
	fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
		if pic.idr {
			self.dpb.mark_all_as_unused_for_ref();

			if matches!(pic.marking, Some(Marking::Idr(_, true))) {
				pic.set_reference(Reference::LongTerm);
				pic.long_term_frame_idx = 0;
				self.max_long_term_frame_idx_plus1 = 1;
			} else {
				pic.set_reference(Reference::ShortTerm);
				self.max_long_term_frame_idx_plus1 = 0;
			}

			return Ok(());
		}

		match pic.marking.take() {
			Some(Marking::Adaptive(mmcos)) => self.handle_memory_management_ops(pic, &mmcos)?,
			_ => self.dpb.sliding_window_marking(sps),
		}

		Ok(())
	}

	/// 8.2.5.4: runs the picture's adaptive memory management control operations.
	fn handle_memory_management_ops(&mut self, pic: &mut PictureData, mmcos: &[Mmco]) -> Result<(), MmcoError> {
		for &mmco in mmcos {
			match mmco {
				Mmco::ForgetShort(difference) => self.dpb.mmco_op_1(pic, difference)?,
				Mmco::ForgetLong(long_term_pic_num) => self.dpb.mmco_op_2(long_term_pic_num)?,
				Mmco::ShortToLong(difference, idx) => self.dpb.mmco_op_3(pic, difference, idx)?,
				Mmco::MaxLong(plus1) => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_4(plus1),
				Mmco::ForgetAll => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_5(pic),
				Mmco::CurrentToLong(idx) => self.dpb.mmco_op_6(pic, idx),
			}
		}

		Ok(())
	}

	/// 8.2.4: derives RefPicList0 and RefPicList1 for one slice, from the
	/// per-picture lists the DPB built.
	fn create_ref_pic_lists<'a>(
		&'a self,
		pic: &PictureData,
		hdr: &SliceHeader,
		sps: &Sps,
		lists: &ReferencePicLists,
	) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
		// MaxPicNum, which for a frame is MaxFrameNum.
		let max_pic_num = max_frame_num(sps) as i32;
		let list0 = match hdr.slice_type {
			SliceType::P => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0, max_pic_num)?,
			SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0, max_pic_num)?,
			SliceType::I => Vec::new(),
		};

		let list1 = match hdr.slice_type {
			SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1, max_pic_num)?,
			SliceType::P | SliceType::I => Vec::new(),
		};

		Ok((list0, list1))
	}

	/// 8.2.4.3: applies the slice header's reference picture list modifications.
	fn modify_ref_pic_list<'a>(
		&'a self,
		pic: &PictureData,
		hdr: &SliceHeader,
		list1: bool,
		indices: &[usize],
		max_pic_num: i32,
	) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
		let (active, modifications) = match list1 {
			true => (hdr.num_ref_idx_l1_active, &hdr.modification_l1),
			false => (hdr.num_ref_idx_l0_active, &hdr.modification_l0),
		};
		let active = usize::from(active);

		let mut list: DpbPicRefList<'a, Handle> =
			indices.iter().map(|&i| &self.dpb.entries()[i]).take(active).collect();

		let Some(modifications) = modifications else {
			return Ok(list);
		};

		let mut pic_num_pred = pic.pic_num;
		let mut ref_idx = 0;

		for modification in modifications {
			match modification.idc {
				idc @ (0 | 1) => self.short_term_modification(
					pic,
					&mut list,
					active,
					max_pic_num,
					idc,
					modification,
					&mut pic_num_pred,
					&mut ref_idx,
				)?,
				2 => self.long_term_modification(&mut list, active, modification, &mut ref_idx)?,
				other => bail!("unexpected modification_of_pic_nums_idc {other}"),
			}
		}

		Ok(list)
	}

	/// 8.2.4.3.1: modification for short-term reference pictures.
	fn short_term_modification<'a>(
		&'a self,
		pic: &PictureData,
		list: &mut DpbPicRefList<'a, Handle>,
		active: usize,
		max_pic_num: i32,
		idc: u8,
		modification: &Modification,
		pic_num_pred: &mut i32,
		ref_idx: &mut usize,
	) -> anyhow::Result<()> {
		// The parser bounds abs_diff_pic_num_minus1 below MaxPicNum.
		let abs_diff_pic_num = modification.value as i32 + 1;

		let pic_num_no_wrap = if idc == 0 {
			if *pic_num_pred - abs_diff_pic_num < 0 {
				*pic_num_pred - abs_diff_pic_num + max_pic_num
			} else {
				*pic_num_pred - abs_diff_pic_num
			}
		} else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
			*pic_num_pred + abs_diff_pic_num - max_pic_num
		} else {
			*pic_num_pred + abs_diff_pic_num
		};

		*pic_num_pred = pic_num_no_wrap;

		let pic_num = if pic_num_no_wrap > pic.pic_num {
			pic_num_no_wrap - max_pic_num
		} else {
			pic_num_no_wrap
		};

		let entry = self
			.dpb
			.find_short_term_with_pic_num(pic_num)
			.with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;

		Self::insert_modification(list, entry, active, ref_idx, |target| {
			target.pic_num_f(max_pic_num) != pic_num
		});

		Ok(())
	}

	/// 8.2.4.3.2: modification for long-term reference pictures.
	fn long_term_modification<'a>(
		&'a self,
		list: &mut DpbPicRefList<'a, Handle>,
		active: usize,
		modification: &Modification,
		ref_idx: &mut usize,
	) -> anyhow::Result<()> {
		let long_term_pic_num = modification.value;
		let max_long_term_frame_idx_plus1 = self.max_long_term_frame_idx_plus1;

		let entry = self
			.dpb
			.find_long_term_with_long_term_pic_num(long_term_pic_num)
			.with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;

		Self::insert_modification(list, entry, active, ref_idx, |target| {
			target.long_term_pic_num_f(max_long_term_frame_idx_plus1) != u64::from(long_term_pic_num)
		});

		Ok(())
	}

	/// The shared tail of 8.2.4.3.1 and 8.2.4.3.2: insert `entry` at `ref_idx`,
	/// then shuffle out the duplicate `keep` identifies and re-truncate the list
	/// to its `active` entries.
	fn insert_modification<'a>(
		list: &mut DpbPicRefList<'a, Handle>,
		entry: &'a DpbEntry<Handle>,
		active: usize,
		ref_idx: &mut usize,
		keep: impl Fn(&PictureData) -> bool,
	) {
		// A modification past the end of the list is a stream error; the spec
		// only defines indices within num_ref_idx_lX_active_minus1 + 1.
		let at = (*ref_idx).min(list.len());
		list.insert(at, entry);
		*ref_idx = at + 1;

		let mut next = *ref_idx;
		for current in *ref_idx..=active {
			if current >= list.len() {
				break;
			}

			if keep(&list[current].pic) {
				list[next] = list[current];
				next += 1;
			}
		}

		list.truncate(active);
	}
}

/// A slice the parser read, with the NAL unit that holds it.
struct Slice {
	header: SliceHeader,
	nal: NaluHeader,
	/// The NAL unit from its header on, emulation prevention included.
	data: Vec<u8>,
}

/// The picture currently being assembled, held across the slices that make it up.
struct CurrentPicture {
	pic: PictureData,
	/// SPS and PPS active for the last slice seen.
	sps: Sps,
	pps: Pps,
	/// Handle to the surface the driver renders into.
	handle: Handle,
	picture: Picture<crate::PictureNew, Handle>,
	/// Per-picture reference lists, modified per slice.
	ref_pic_lists: ReferencePicLists,
}

/// A decoded picture: the surface holding it plus what the caller needs to read
/// it back. Cloned into the DPB, so the surface is not recycled while it is still
/// a reference or still waiting to be output.
#[derive(Clone)]
struct Handle {
	surface: Arc<PooledSurface>,
	timestamp: u64,
	width: u32,
	height: u32,
}

impl std::borrow::Borrow<Surface<()>> for Handle {
	fn borrow(&self) -> &Surface<()> {
		self.surface.get()
	}
}

/// The properties of an SPS that the VA config, context, and surface pool are
/// built from. A change in any of them forces them to be rebuilt.
#[derive(Clone, Debug, PartialEq, Eq)]
struct SequenceInfo {
	visible: (u32, u32),
	coded: (u32, u32),
	profile: Profile,
	max_dpb_frames: usize,
}

impl SequenceInfo {
	/// The parser already refused what is not progressive 8-bit 4:2:0, and a
	/// crop that leaves nothing visible.
	fn new(sps: &Sps) -> anyhow::Result<Self> {
		let (right, bottom) = match sps.crop {
			Some(crop) if crop.left != 0 || crop.top != 0 => bail!("left and top H.264 cropping is not supported"),
			Some(crop) => (crop.right, crop.bottom),
			None => (0, 0),
		};
		let coded = (16 * sps.width_mbs, 16 * sps.height_mbs);

		Ok(Self {
			visible: (coded.0 - right, coded.1 - bottom),
			coded,
			profile: sps.profile,
			max_dpb_frames: max_dpb_frames(sps),
		})
	}
}

/// What the VA config, context, and surface pool of a sequence are built for.
/// A change in any of it rebuilds them.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Format {
	codec: Codec,
	profile: VAProfile::Type,
	coded: (u32, u32),
	/// The size after cropping, which is what a [`Frame`] reports.
	visible: (u32, u32),
	/// The most pictures the DPB holds, which bounds what the pool keeps free.
	max_dpb_frames: usize,
}

/// The VA state for one coded video sequence.
struct Sequence {
	format: Format,
	pool: SurfacePool,
	// Drop order: the context must go before the config it was created from.
	context: Rc<Context>,
	_config: VaConfig,
}

impl Sequence {
	fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
		let attrs = vec![VAConfigAttrib {
			type_: VAConfigAttribType::VAConfigAttribRTFormat,
			value: VA_RT_FORMAT_YUV420,
		}];
		let config = display
			.create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
			.map_err(|e| anyhow!("create VA config: {e:?}"))?;

		let (coded_width, coded_height) = format.coded;
		let context = display
			.create_context::<()>(&config, coded_width, coded_height, None, true)
			.map_err(|e| anyhow!("create VA context: {e:?}"))?;

		let (width, height) = format.visible;
		tracing::info!(
			"VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
			 VA profile {}, DPB {} frames",
			format.codec,
			format.profile,
			format.max_dpb_frames
		);

		// What the decoder itself can need at once: a full DPB plus the picture
		// being decoded. Anything free beyond that was let go by a consumer that
		// had been holding pictures, and is memory the stream will not ask for
		// again.
		let capacity = format.max_dpb_frames + 1;
		Ok(Self {
			pool: SurfacePool::new(
				display,
				(coded_width, coded_height),
				UsageHint::USAGE_HINT_DECODER,
				capacity,
			),
			format,
			context,
			_config: config,
		})
	}

	/// Returns a surface to decode a picture coded at `timestamp` into.
	fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
		let (width, height) = self.format.visible;
		Ok(Handle {
			surface: Arc::new(self.pool.alloc()?),
			timestamp,
			width,
			height,
		})
	}
}

/// Submits a picture with all its buffers added, and waits for it to decode.
///
/// The wait comes before the surface enters the DPB: it is about to be read as
/// a reference by later pictures, and the caller may never ask for its pixels.
/// Dropping the synced picture frees the VA buffers with it.
fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
	let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
	let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
	let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
	drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
	Ok(())
}

/// Returns how many frames the DPB holds: the VUI's `max_dec_frame_buffering`
/// when the SPS carries it, else the level's `MaxDpbFrames`.
fn max_dpb_frames(sps: &Sps) -> usize {
	match sps.vui.as_ref().and_then(|vui| vui.restriction) {
		Some(restriction) => usize::from(restriction.max_dec_frame_buffering.max(1)),
		None => usize::from(sps.max_dpb_frames),
	}
}

/// Returns how many H.264 frames may wait for output before the one with the
/// lowest order count is due.
///
/// The VUI's `max_num_reorder_frames` when the SPS carries it, else the
/// inference E.2.1 makes from the profile, which is the DPB size for most
/// streams. An order count derived from `frame_num` (8.2.1.3) makes output
/// order decoding order, so such a stream reorders nothing whatever its VUI
/// says. A limit past the DPB size is out of range, and the DPB size bounds it.
fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
	if matches!(sps.pic_order_cnt, PicOrderCnt::Decode) {
		return 0;
	}
	let declared = match sps.vui.as_ref().and_then(|vui| vui.restriction) {
		Some(restriction) => usize::from(restriction.max_num_reorder_frames),
		// E.2.1: the intra profiles with constraint_set3_flag reorder nothing.
		None if matches!(sps.profile.value(), 44 | 86 | 100 | 110 | 122 | 244) && sps.constraint_flags & 0x10 != 0 => 0,
		None => max_dpb_frames,
	};
	declared.min(max_dpb_frames)
}

/// Returns `MaxFrameNum`.
fn max_frame_num(sps: &Sps) -> u32 {
	1 << sps.log2_max_frame_num
}

/// Exports a decoded surface as a DRM PRIME descriptor, copying nothing.
fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
	ExportedFrame::export(
		Arc::clone(&handle.surface),
		handle.timestamp,
		(handle.width, handle.height),
	)
}

/// Reads a decoded surface back to client memory as tightly packed NV12.
fn download(handle: &Handle) -> anyhow::Result<Frame> {
	read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
}

/// Reads `surface` back to client memory as tightly packed NV12, cropped to
/// `width` by `height`.
///
/// The one read-back path, shared by the picture a decoder downloads itself and
/// the one a caller took as a descriptor and later wants on the CPU after all.
fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
	surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;

	let visible = (width, height);

	// vaDeriveImage exposes the surface's own buffer, so the copy below is the
	// only one. Not every driver can derive every surface; fall back to
	// vaCreateImage + vaGetImage, which always works but copies inside the driver
	// first.
	// Safe since a decoded surface is written again only once the pool hands it
	// out, after every handle and export of it has dropped, and the caller holds one.
	match unsafe { Image::derive_shared(surface, visible) } {
		Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
			return pack_nv12(&image, timestamp, width, height);
		}
		Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
		Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
	}

	let format = surface
		.display()
		.query_image_formats()
		.map_err(|e| anyhow!("query image formats: {e:?}"))?
		.into_iter()
		.find(|format| format.fourcc == VA_FOURCC_NV12)
		.context("driver has no NV12 image format")?;
	let image = Image::create_from(surface, format, surface.size(), visible)
		.map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;

	pack_nv12(&image, timestamp, width, height)
}

/// Copies a mapped NV12 image into a tightly packed buffer, dropping the row
/// padding the driver's pitch may carry.
fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
	let va_image = image.image();
	let src: &[u8] = image.as_ref();
	let (width, height) = (frame_width as usize, frame_height as usize);
	let chroma_rows = height / 2;

	let mut data = vec![0u8; width * (height + chroma_rows)];
	let (luma, chroma) = data.split_at_mut(width * height);
	copy_plane(
		luma,
		src,
		va_image.offsets[0] as usize,
		va_image.pitches[0] as usize,
		width,
		height,
	)?;
	copy_plane(
		chroma,
		src,
		va_image.offsets[1] as usize,
		va_image.pitches[1] as usize,
		width,
		chroma_rows,
	)?;

	Ok(Frame {
		timestamp,
		width: frame_width,
		height: frame_height,
		data,
	})
}

/// Copies `rows` rows of `width` bytes out of a strided plane.
fn copy_plane(
	dst: &mut [u8],
	src: &[u8],
	offset: usize,
	pitch: usize,
	width: usize,
	rows: usize,
) -> anyhow::Result<()> {
	if rows == 0 {
		return Ok(());
	}
	let end = offset + pitch * (rows - 1) + width;
	if pitch < width || src.len() < end {
		bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
	}

	for row in 0..rows {
		let from = offset + row * pitch;
		dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
	}

	Ok(())
}

/// Checks that `display`'s driver can decode `codec`, which is what [`Decoder::new`] needs of a render node.
///
/// # Errors
///
/// Fails unless the driver offers `VAEntrypointVLD` for a Constrained
/// Baseline, Main, or High profile (H.264) or for the Main profile (H.265),
/// or when it cannot be asked.
pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
	let profiles = display
		.query_config_profiles()
		.map_err(|e| anyhow!("query VA profiles: {e:?}"))?;

	let supported = profiles
		.into_iter()
		.filter(|profile| match codec {
			Codec::H264 => matches!(
				*profile,
				VAProfile::VAProfileH264ConstrainedBaseline
					| VAProfile::VAProfileH264Main
					| VAProfile::VAProfileH264High
			),
			Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
		})
		.any(|profile| {
			display
				.query_config_entrypoints(profile)
				.is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
		});

	if !supported {
		bail!("driver exposes no {codec:?} decode entrypoint");
	}

	Ok(())
}

/// Maps the SPS profile onto the VA profile to open the config with.
fn va_profile(profile: Profile) -> anyhow::Result<VAProfile::Type> {
	Ok(match profile {
		// VA-API has no plain Baseline profile, and the picture parameter buffer
		// has no way to describe the FMO and ASO tools that are all that separate
		// it from Constrained Baseline (num_slice_groups_minus1 is pinned to 0
		// below), so both map here. A stream that really uses them decodes wrong
		// rather than not at all, which no encoder in this decade emits.
		Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
		Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
		// The parser refuses other bit depths and chroma formats, so a High10 or
		// High422 SPS only reaches here when its samples are 8-bit 4:2:0.
		Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
		other => bail!("unsupported H.264 profile {other:?}"),
	})
}

fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
	context
		.create_buffer(buffer)
		.map_err(|e| anyhow!("create VA buffer: {e:?}"))
}

/// The first frame_num 8.2.5.2 invents a picture for, before `frame_num`.
///
/// Sliding-window marking keeps only the last `max_num_ref_frames` of the
/// invented pictures, so inventing the earlier ones would change nothing but the
/// work a lossy or hostile stream costs: up to MaxFrameNum pictures per slice.
fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
	let max_frame_num = max_frame_num(sps);
	let first = (prev_frame_num + 1) % max_frame_num;
	let missing = (frame_num + max_frame_num - first) % max_frame_num;
	// Marking keeps one reference even when the SPS declares none.
	let window = u32::from(sps.max_num_ref_frames).max(1);
	let skipped = missing.saturating_sub(window);
	(first + skipped) % max_frame_num
}

/// 8.2.1: derives `pic`'s picture order count, which drives output ordering.
///
/// Fails a picture whose order count leaves the `i32` range the
/// specification bounds it to, as a hostile stream's can. The specification
/// bounds only the final counts, so the sums on the way are taken wider.
fn pic_order_count(
	prev_ref: &PrevReferencePicInfo,
	prev: &mut PrevPicInfo,
	pic: &mut PictureData,
	sps: &Sps,
) -> anyhow::Result<()> {
	let overflow = || anyhow!("picture order count overflows");
	match &sps.pic_order_cnt {
		// 8.2.1.1
		PicOrderCnt::Lsb { log2_max_lsb } => {
			let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if pic.idr {
				(0, 0)
			} else if prev_ref.has_mmco_5 {
				(0, prev_ref.top_field_order_cnt)
			} else {
				(prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
			};

			let max_pic_order_cnt_lsb: i32 = 1 << log2_max_lsb;
			// Both are below 2^16, except a previous top field order count
			// after a memory_management_control_operation 5, which is any `i32`.
			let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
			let half = i64::from(max_pic_order_cnt_lsb / 2);

			pic.pic_order_cnt_msb = if lsb_delta >= half {
				prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
			} else if -lsb_delta > half {
				prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
			} else {
				Some(prev_pic_order_cnt_msb)
			}
			.ok_or_else(overflow)?;

			pic.top_field_order_cnt = pic
				.pic_order_cnt_msb
				.checked_add(pic.pic_order_cnt_lsb)
				.ok_or_else(overflow)?;
			pic.bottom_field_order_cnt = pic
				.top_field_order_cnt
				.checked_add(pic.delta_pic_order_cnt_bottom)
				.ok_or_else(overflow)?;
		}

		// 8.2.1.2
		PicOrderCnt::Cycle {
			offset_for_non_ref_pic,
			offset_for_top_to_bottom_field,
			offset_for_ref_frame,
			..
		} => {
			if prev.has_mmco_5 {
				prev.frame_num_offset = 0;
			}

			pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;

			let mut abs_frame_num = if !offset_for_ref_frame.is_empty() {
				pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
			} else {
				0
			};

			if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
				abs_frame_num -= 1;
			}

			// Never overflows: under 2^32 cycles of a cycle sum under 2^39,
			// plus a few hundred `i32` terms, stays far inside `i128`.
			let mut expected_pic_order_cnt: i128 = 0;

			if abs_frame_num > 0 {
				// The parser bounds the cycle to 255 frames.
				let cycle_len = offset_for_ref_frame.len() as u32;
				let cycles = (abs_frame_num - 1) / cycle_len;
				// The cycle is only summed up to the position this frame sits
				// at within it, not all the way round.
				let position_in_cycle = (abs_frame_num - 1) % cycle_len;
				let expected_delta_per_cycle: i128 =
					offset_for_ref_frame.iter().map(|&offset| i128::from(offset)).sum();
				expected_pic_order_cnt = i128::from(cycles) * expected_delta_per_cycle;

				for &offset in &offset_for_ref_frame[..=position_in_cycle as usize] {
					expected_pic_order_cnt += i128::from(offset);
				}
			}

			if pic.nal_ref_idc == 0 {
				expected_pic_order_cnt += i128::from(*offset_for_non_ref_pic);
			}

			let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
			let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
			let to_bottom = i128::from(*offset_for_top_to_bottom_field);
			pic.top_field_order_cnt = count(top)?;
			pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
		}

		// 8.2.1.3
		PicOrderCnt::Decode => {
			if prev.has_mmco_5 {
				prev.frame_num_offset = 0;
			}

			pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;

			let pic_order_cnt = if pic.idr {
				0
			} else {
				let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
				i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
			};

			pic.top_field_order_cnt = pic_order_cnt;
			pic.bottom_field_order_cnt = pic_order_cnt;
		}
	}

	pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);

	Ok(())
}

/// 8-6 and 8-11: the FrameNumOffset of `pic`, which grows by MaxFrameNum each
/// time frame_num wraps without an IDR.
fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
	Ok(if pic.idr {
		0
	} else if prev.frame_num > pic.frame_num {
		prev.frame_num_offset
			.checked_add(max_frame_num(sps))
			.context("FrameNumOffset overflows")?
	} else {
		prev.frame_num_offset
	})
}

/// Cached variables from the previous reference picture, needed by 8.2.1.
#[derive(Debug, Default)]
struct PrevReferencePicInfo {
	frame_num: u32,
	has_mmco_5: bool,
	top_field_order_cnt: i32,
	pic_order_cnt_msb: i32,
	pic_order_cnt_lsb: i32,
}

impl PrevReferencePicInfo {
	fn fill(&mut self, pic: &PictureData) {
		self.has_mmco_5 = pic.has_mmco_5;
		self.top_field_order_cnt = pic.top_field_order_cnt;
		self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
		self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
		self.frame_num = pic.frame_num;
	}
}

/// Cached variables from the previous picture, needed by 8.2.1.
#[derive(Debug, Default)]
struct PrevPicInfo {
	frame_num: u32,
	frame_num_offset: u32,
	has_mmco_5: bool,
}

impl PrevPicInfo {
	fn fill(&mut self, pic: &PictureData) {
		self.frame_num = pic.frame_num;
		self.has_mmco_5 = pic.has_mmco_5;
		self.frame_num_offset = pic.frame_num_offset;
	}
}

/// The surface a DPB entry decoded into, or `VA_INVALID_ID` for the non-existing
/// pictures invented for a frame_num gap.
fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
	match handle {
		Some(handle) => handle.surface.id(),
		None => VA_INVALID_ID,
	}
}

/// Ported from cros-codecs `fill_va_h264_pic` (BSD-3-Clause), for frames.
fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
	let mut flags = 0;
	let frame_idx = match pic.reference() {
		Reference::LongTerm => {
			flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
			pic.long_term_frame_idx
		}
		Reference::ShortTerm => {
			flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
			pic.frame_num
		}
		Reference::None => pic.frame_num,
	};

	PictureH264::new(
		surface_id,
		frame_idx,
		flags,
		pic.top_field_order_cnt,
		pic.bottom_field_order_cnt,
	)
}

/// Builds the picture used to fill the array slots there is no reference for.
fn build_invalid_va_h264_pic() -> PictureH264 {
	PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
}

/// Ported from cros-codecs `build_iq_matrix` (BSD-3-Clause). VA-API wants the
/// scaling lists in raster order, the parameter sets carry them zig-zag.
fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType {
	const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
	#[rustfmt::skip]
	const ZIGZAG_8X8: [usize; 64] = [
		0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
		20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
		58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
	];

	// A PPS without lists uses its SPS's, and an SPS without lists is flat (7.4.2.1.1).
	let flat = Matrix {
		lists_4x4: vec![16; 6 * 16],
		lists_8x8: vec![16; 2 * 64],
	};
	let matrix = pps.scaling.as_ref().or(sps.scaling.as_ref()).unwrap_or(&flat);

	let mut scaling_list4x4 = [[0u8; 16]; 6];
	for (list, src) in scaling_list4x4.iter_mut().zip(matrix.lists_4x4.chunks_exact(16)) {
		for (i, &value) in src.iter().enumerate() {
			list[ZIGZAG_4X4[i]] = value;
		}
	}

	let mut scaling_list8x8 = [[0u8; 64]; 2];
	for (list, src) in scaling_list8x8.iter_mut().zip(matrix.lists_8x8.chunks_exact(64)) {
		for (i, &value) in src.iter().enumerate() {
			list[ZIGZAG_8X8[i]] = value;
		}
	}

	BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
		scaling_list4x4,
		scaling_list8x8,
	)))
}

/// Ported from cros-codecs `build_pic_param` (BSD-3-Clause).
fn build_pic_param(
	hdr: &SliceHeader,
	pic: &PictureData,
	surface_id: bindings::VASurfaceID,
	dpb: &Dpb<Handle>,
	sps: &Sps,
	pps: &Pps,
) -> BufferType {
	let curr_pic = fill_va_h264_pic(pic, surface_id);

	let short_term = dpb.short_term_refs_iter().filter(|entry| !entry.pic.nonexisting);
	let mut refs: Vec<PictureH264> = short_term
		.chain(dpb.long_term_refs_iter())
		.take(16)
		.map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
		.collect();
	refs.resize_with(16, build_invalid_va_h264_pic);
	let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));

	let (pic_order_cnt_type, log2_max_lsb, delta_always_zero) = match sps.pic_order_cnt {
		PicOrderCnt::Lsb { log2_max_lsb } => (0, log2_max_lsb, false),
		PicOrderCnt::Cycle { delta_always_zero, .. } => (1, 4, delta_always_zero),
		PicOrderCnt::Decode => (2, 4, false),
	};
	let seq_fields = H264SeqFields::new(
		1, // chroma_format_idc: 4:2:0
		0, // separate_colour_plane_flag
		sps.gaps_in_frame_num_allowed as u32,
		1, // frame_mbs_only_flag
		0, // mb_adaptive_frame_field_flag
		sps.direct_8x8_inference as u32,
		// See A.3.3.2.
		(sps.level.value() >= 31) as u32,
		u32::from(sps.log2_max_frame_num - 4),
		pic_order_cnt_type,
		u32::from(log2_max_lsb - 4),
		delta_always_zero as u32,
	);

	let pic_fields = H264PicFields::new(
		pps.entropy_coding_mode as u32,
		pps.weighted_pred as u32,
		u32::from(pps.weighted_bipred_idc),
		pps.transform_8x8_mode as u32,
		0, // field_pic_flag
		pps.constrained_intra_pred as u32,
		pps.bottom_field_pic_order_in_frame_present as u32,
		pps.deblocking_filter_control_present as u32,
		pps.redundant_pic_cnt_present as u32,
		(pic.nal_ref_idc != 0) as u32,
	);

	// The parser bounds the frame to 1055 macroblocks a side, the quantizer
	// parameters to -26..=25 from 26, and frame_num below 2^16.
	BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
		curr_pic,
		refs,
		(sps.width_mbs - 1) as u16,
		(sps.height_mbs - 1) as u16,
		0, // bit_depth_luma_minus8
		0, // bit_depth_chroma_minus8
		sps.max_num_ref_frames,
		&seq_fields,
		// FMO is not expressible in VA-API.
		0,
		0,
		0,
		(pps.pic_init_qp - 26) as i8,
		(pps.pic_init_qs - 26) as i8,
		pps.chroma_qp_index_offset as i8,
		pps.second_chroma_qp_index_offset as i8,
		&pic_fields,
		hdr.frame_num as u16,
	)))
}

/// Ported from cros-codecs `fill_ref_pic_list` (BSD-3-Clause).
fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
	let mut pics: Vec<PictureH264> = list
		.iter()
		.take(32)
		.map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
		.collect();
	pics.resize_with(32, build_invalid_va_h264_pic);

	pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
}

/// Ported from cros-codecs `build_slice_param` (BSD-3-Clause).
fn build_slice_param(
	hdr: &SliceHeader,
	slice_size: usize,
	list0: &[&DpbEntry<Handle>],
	list1: &[&DpbEntry<Handle>],
	pps: &Pps,
) -> BufferType {
	let mut luma_weight_l0 = [0i16; 32];
	let mut luma_offset_l0 = [0i16; 32];
	let mut chroma_weight_l0 = [[0i16; 2]; 32];
	let mut chroma_offset_l0 = [[0i16; 2]; 32];

	let mut luma_weight_l1 = [0i16; 32];
	let mut luma_offset_l1 = [0i16; 32];
	let mut chroma_weight_l1 = [[0i16; 2]; 32];
	let mut chroma_offset_l1 = [[0i16; 2]; 32];

	// Explicit weighted prediction: the slice header carries weights for list 0
	// of P slices and both lists of B slices when the PPS asks for them.
	// Implicit (weighted_bipred_idc 2) is derived by the hardware. The parser
	// bounds each weight and offset to -128..=127.
	let weights = hdr.weights.as_ref();
	let fill = |weights: &[kodecs_h264::Weight],
	            luma_weight: &mut [i16; 32],
	            luma_offset: &mut [i16; 32],
	            chroma_weight: &mut [[i16; 2]; 32],
	            chroma_offset: &mut [[i16; 2]; 32]| {
		for (i, weight) in weights.iter().take(32).enumerate() {
			luma_weight[i] = weight.luma_weight as i16;
			luma_offset[i] = weight.luma_offset as i16;
			chroma_weight[i] = weight.chroma_weight.map(|w| w as i16);
			chroma_offset[i] = weight.chroma_offset.map(|o| o as i16);
		}
	};
	if let Some(weights) = weights {
		fill(
			&weights.l0,
			&mut luma_weight_l0,
			&mut luma_offset_l0,
			&mut chroma_weight_l0,
			&mut chroma_offset_l0,
		);
		fill(
			&weights.l1,
			&mut luma_weight_l1,
			&mut luma_offset_l1,
			&mut chroma_weight_l1,
			&mut chroma_offset_l1,
		);
	}
	let fill_l0 = weights.is_some();
	let fill_l1 = weights.is_some() && hdr.slice_type == SliceType::B;

	// The parser bounds the quantizer and the deblocking offsets to their VA
	// fields; the caller checked the macroblock and bit offsets.
	BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
		slice_size as u32,
		0,
		VA_SLICE_DATA_FLAG_ALL,
		hdr.header_bit_size as u16,
		hdr.first_mb_in_slice as u16,
		hdr.slice_type_raw % 5,
		hdr.direct_spatial_mv_pred as u8,
		hdr.num_ref_idx_l0_active.saturating_sub(1),
		hdr.num_ref_idx_l1_active.saturating_sub(1),
		hdr.cabac_init_idc,
		(hdr.slice_qp - pps.pic_init_qp) as i8,
		hdr.disable_deblocking_filter_idc,
		hdr.slice_alpha_c0_offset_div2 as i8,
		hdr.slice_beta_offset_div2 as i8,
		fill_ref_pic_list(list0),
		fill_ref_pic_list(list1),
		weights.map_or(0, |w| w.luma_log2_denom),
		weights.map_or(0, |w| w.chroma_log2_denom),
		fill_l0 as u8,
		luma_weight_l0,
		luma_offset_l0,
		fill_l0 as u8,
		chroma_weight_l0,
		chroma_offset_l0,
		fill_l1 as u8,
		luma_weight_l1,
		luma_offset_l1,
		fill_l1 as u8,
		chroma_weight_l1,
		chroma_offset_l1,
	)))
}

/// Takes the next non-empty Annex B unit. Unlike `Nalu::next`, a header that breaks the spec is
/// an error rather than skipped, since it may have been a replacement parameter set.
fn next_nalu<'a>(stream: &mut &'a [u8], max_bytes: usize) -> anyhow::Result<Option<Nalu<'a>>> {
	loop {
		let Some(raw) = kodecs_h264::split_annex_b(stream, max_bytes).context("frame a NAL unit")? else {
			return Ok(None);
		};
		if !raw.is_empty() {
			return Ok(Some(Nalu::new(raw, max_bytes).context("parse a NAL unit header")?));
		}
	}
}

#[cfg(test)]
mod tests {
	use std::os::fd::OwnedFd;
	use std::process::Command;

	use super::*;

	/// Empty units are skipped, but a header that breaks the spec fails even as
	/// the last unit, where no later unit would trip the parser.
	#[test]
	fn a_malformed_header_is_an_error() {
		// An empty unit, an access unit delimiter, then an SPS with nal_ref_idc 0 (7.4.1).
		let bytes = [0, 0, 1, 0, 0, 0, 1, 0x09, 0x10, 0, 0, 0, 1, 0x07, 0x42, 0x00, 0x1e];
		let mut stream = &bytes[..];
		let nalu = next_nalu(&mut stream, usize::MAX).unwrap().expect("a unit");
		assert_eq!(nalu.header.type_, NaluType::AuDelimiter);
		assert!(next_nalu(&mut stream, usize::MAX).is_err());
		assert!(next_nalu(&mut stream, usize::MAX).unwrap().is_none());
	}

	/// A 320x240 Main profile SPS at level 3, with MaxFrameNum 16.
	fn progressive_sps() -> Sps {
		kodecs_h264::SpsBuilder::new(Profile::Main, kodecs_h264::Level::L3)
			.resolution(320, 240)
			.build()
			.unwrap()
	}

	/// A frame_num gap invents pictures only for the last max_num_ref_frames of
	/// the missing frame numbers, however many a stream skips, wrap included.
	#[test]
	fn a_frame_num_gap_invents_only_the_reference_window() {
		// MaxFrameNum 16, two reference frames.
		let mut sps = progressive_sps();
		sps.max_num_ref_frames = 2;
		// No gap: nothing to invent.
		assert_eq!(first_invented(3, 4, &sps), 4);
		// One missing frame number, within the window.
		assert_eq!(first_invented(3, 5, &sps), 4);
		// Six missing, 4..=9: only 8 and 9 are invented.
		assert_eq!(first_invented(3, 10, &sps), 8);
		// Four missing across the wrap, 15, 0, 1, 2: only 1 and 2.
		assert_eq!(first_invented(14, 3, &sps), 1);
		// The largest gap MaxFrameNum allows costs no more than the window.
		assert_eq!(first_invented(4, 3, &sps), 1);

		// Marking keeps one reference even when the SPS declares none, so the
		// gap still invents the picture that replaces it.
		sps.max_num_ref_frames = 0;
		assert_eq!(first_invented(0, 3, &sps), 2);
	}

	/// A non-IDR frame of `pic_order_cnt_type` 0 with `lsb`, after a reference
	/// picture at `prev_msb` and `prev_lsb`, with MaxPicOrderCntLsb 256.
	fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
		let mut sps = progressive_sps();
		sps.pic_order_cnt = PicOrderCnt::Lsb { log2_max_lsb: 8 };
		let mut pic = PictureData::default();
		pic.pic_order_cnt_lsb = lsb;
		pic.nal_ref_idc = 1;
		pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
		Ok(pic.pic_order_cnt)
	}

	fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
		PrevReferencePicInfo {
			pic_order_cnt_msb: msb,
			pic_order_cnt_lsb: lsb,
			..Default::default()
		}
	}

	/// 8.2.1.1: the lsb wrapping either way moves the msb a whole cycle, and an
	/// order count pushed past the `i32` range fails the picture instead of
	/// overflowing.
	#[test]
	fn the_picture_order_count_wraps_and_never_overflows() {
		assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
		assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
		assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
		assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
		assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());

		// After a memory_management_control_operation 5 the previous lsb is a
		// top field order count, any `i32`, which the lsb comparison takes too.
		let after_mmco5 = PrevReferencePicInfo {
			has_mmco_5: true,
			top_field_order_cnt: i32::MIN,
			..Default::default()
		};
		assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
	}

	/// 8.2.1.3: FrameNumOffset grows by MaxFrameNum each time frame_num wraps,
	/// and fails the picture instead of overflowing.
	#[test]
	fn the_frame_num_offset_never_overflows() {
		let mut sps = progressive_sps();
		sps.pic_order_cnt = PicOrderCnt::Decode;
		let order_count = |frame_num_offset| {
			let mut prev = PrevPicInfo {
				frame_num: 5,
				frame_num_offset,
				has_mmco_5: false,
			};
			let mut pic = PictureData::default();
			pic.frame_num = 1;
			pic.nal_ref_idc = 1;
			pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
		};
		// MaxFrameNum is 16, so the wrap adds 16 to the offset.
		assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
		assert!(order_count(u32::MAX - 3).is_err());
		// The offset fits but twice the absolute frame number does not.
		assert!(order_count(i32::MAX as u32 / 2).is_err());
	}

	/// 8.2.1.3: only the final order count must fit, so a non-reference picture
	/// one past where a reference picture overflows still decodes.
	#[test]
	fn the_type2_order_count_is_checked_whole() {
		let mut sps = progressive_sps();
		sps.pic_order_cnt = PicOrderCnt::Decode;
		let order_count = |nal_ref_idc| {
			// The wrap from frame_num 5 to 1 makes the absolute frame number 2^30.
			let mut prev = PrevPicInfo {
				frame_num: 5,
				frame_num_offset: (1 << 30) - 17,
				has_mmco_5: false,
			};
			let mut pic = PictureData::default();
			pic.frame_num = 1;
			pic.nal_ref_idc = nal_ref_idc;
			pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
		};
		assert_eq!(order_count(0).unwrap(), i32::MAX);
		assert!(order_count(1).is_err());
	}

	/// 8.2.1.2: only the final bottom field order count must fit, not the sum
	/// on the way to it.
	#[test]
	fn the_type1_bottom_field_is_checked_whole() {
		let mut sps = progressive_sps();
		sps.pic_order_cnt = PicOrderCnt::Cycle {
			delta_always_zero: false,
			offset_for_non_ref_pic: 0,
			offset_for_top_to_bottom_field: i32::MAX,
			offset_for_ref_frame: Vec::new(),
		};
		let bottom = |delta0, delta1| {
			let mut pic = PictureData::default();
			pic.nal_ref_idc = 1;
			pic.delta_pic_order_cnt0 = delta0;
			pic.delta_pic_order_cnt1 = delta1;
			pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
				.map(|()| pic.bottom_field_order_cnt)
		};
		assert_eq!(bottom(2, -i32::MAX).unwrap(), 2);
		assert!(bottom(2, 0).is_err());
	}

	#[test]
	fn rejects_nonzero_crop_origins() {
		for (left, top) in [(2, 0), (0, 2)] {
			let mut sps = progressive_sps();
			sps.crop = Some(kodecs_h264::Crop {
				left,
				right: 0,
				top,
				bottom: 0,
			});
			assert!(SequenceInfo::new(&sps)
				.unwrap_err()
				.to_string()
				.contains("left and top"));
		}
	}

	#[test]
	fn crop_only_updates_change_sequence_identity() {
		let original = SequenceInfo::new(&progressive_sps()).unwrap();
		for (right, bottom, expected) in [(2, 0, (318, 240)), (0, 2, (320, 238))] {
			let mut sps = progressive_sps();
			sps.crop = Some(kodecs_h264::Crop {
				left: 0,
				right,
				top: 0,
				bottom,
			});
			let cropped = SequenceInfo::new(&sps).unwrap();
			assert_eq!(original.coded, cropped.coded);
			assert_eq!(cropped.visible, expected);
			assert_ne!(original, cropped);
		}
	}

	/// Encoder settings shared by the tests that need a stream rather than a
	/// particular picture.
	fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
		crate::encode::Config {
			codec: crate::Codec::H264,
			width,
			height,
			framerate: 30,
			bitrate: 2_000_000,
			gop: std::num::NonZeroU32::new(30).unwrap(),
			color: crate::Color::infer(height),
			device: None,
		}
	}

	/// A gray field with a moving block, so a picture that decoded into the
	/// wrong surface is visible as the block being in the wrong place.
	fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
		let (w, h) = (width as usize, height as usize);
		let mut data = vec![128u8; w * h * 3 / 2];
		let x0 = (step * 16) as usize % (w / 2);
		for y in h / 4..h / 2 {
			for x in x0..x0 + w / 4 {
				data[y * w + x] = 235;
			}
		}
		data
	}

	/// Exported pictures the caller still holds never share a surface.
	///
	/// The invariant `export` exists to keep: a held surface stays out of the
	/// pool, because recycling it would have a later picture decoded over pixels
	/// the caller still holds a descriptor for. Two pictures coming
	/// back with the same modifier and layout is expected; two coming back on
	/// the same allocation is the bug. The modifier itself is hardware policy,
	/// so it is printed rather than asserted.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn exported_pictures_do_not_share_a_surface() {
		let (width, height) = (320u32, 240u32);
		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");

		let mut exported = Vec::new();
		for step in 0..8 {
			let unit = encoder
				.encode_nv12(&nv12_frame(width, height, step), step == 0)
				.expect("encode a picture");
			exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
		}
		exported.extend(decoder.flush_exported().expect("flush the decoder"));
		assert!(!exported.is_empty(), "the decoder produced no pictures");

		let first = &exported[0];
		eprintln!(
			"exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
			exported.len(),
			first.width,
			first.height,
			first.descriptor.fourcc,
			first.descriptor.objects[0].drm_format_modifier
		);

		let mut seen = Vec::new();
		for (index, frame) in exported.iter().enumerate() {
			assert_eq!((frame.width, frame.height), (width, height));
			assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
			assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
			assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");

			// Two live descriptors for one allocation would mean the pool handed
			// a held surface back out. The inode behind a DMA-BUF names the
			// buffer, and is what identifies one allocation from another.
			let inode = inode(&frame.descriptor.objects[0].fd);
			assert!(
				!seen.contains(&inode),
				"picture {index} was decoded into an allocation an earlier one still holds"
			);
			seen.push(inode);
		}
	}

	/// With no node named, the decoder opens one that decodes H.264. A named
	/// node is used or refused, never swapped for another.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn the_render_node_is_found_or_named() {
		if let Err(err) = Decoder::new(Config::new()) {
			panic!("no VA-API H.264 decoder: {err:#}");
		}
		let named = Config {
			device: Some(PathBuf::from("/dev/null")),
			..Config::new()
		};
		assert!(
			Decoder::new(named).is_err(),
			"a named node that is not a render node was swapped for one that is"
		);
	}

	/// Every picture fed in comes back out, the tail only on flush.
	///
	/// A stream with B-frames holds pictures in the DPB until later ones come
	/// out ahead of them, so a stream that simply stops leaves its tail there.
	/// The first assertion keeps the test honest, since a decoder that held
	/// nothing back would satisfy the rest without a flush ever running.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn flush_returns_the_pictures_the_dpb_still_holds() {
		const PICTURES: usize = 10;

		let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");

		let mut streamed = Vec::new();
		for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
			streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
		}
		assert!(
			streamed.len() < PICTURES,
			"the DPB held nothing back, so this test proves nothing"
		);

		let flushed = decoder.flush().expect("flush the decoder");
		let mut timestamps: Vec<u64> = streamed
			.iter()
			.chain(&flushed)
			.map(|picture| picture.timestamp)
			.collect();
		timestamps.sort_unstable();
		assert_eq!(
			timestamps,
			(0..PICTURES as u64).collect::<Vec<_>>(),
			"the stream lost pictures at its end"
		);

		// The bumping process marks what it hands out, so a second flush finds
		// nothing and a caller that flushes twice never sees a picture twice.
		assert!(decoder.flush().expect("flush an empty decoder").is_empty());
	}

	/// An H.264 stream coded without reordering comes out as it decodes, from
	/// this crate's encoder and from libx264.
	///
	/// Both declare one frame buffer, which C.4.5.3 would empty only when the
	/// next picture needs it, so each picture used to come out one access unit
	/// late. The two cover both ways a stream rules reordering out: this
	/// crate's encoder writes `max_num_reorder_frames` 0 in its VUI, and libx264
	/// without B-frames derives the order count from `frame_num` (type 2).
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn h264_without_reordering_comes_out_as_it_decodes() {
		const PICTURES: usize = 10;
		let (width, height) = (320u32, 240u32);

		let mut streams = Vec::new();
		match crate::encode::Encoder::new(encoder_config(width, height)) {
			Ok(mut encoder) => {
				let units = (0..PICTURES)
					.map(|step| {
						encoder
							.encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
							.expect("encode a picture")
					})
					.collect::<Vec<_>>();
				streams.push(("VA-API", units));
			}
			Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
		}
		match software_encode(Codec::H264, (width, height), PICTURES, false) {
			Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
			None => panic!("FFmpeg with libx264 is required"),
		}

		for (encoder, units) in streams {
			let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
			for (index, unit) in units.iter().enumerate() {
				let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
				let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
				assert_eq!(
					timestamps,
					[index as u64],
					"{encoder}: access unit {index} was held back"
				);
			}
			assert!(decoder.flush().expect("flush the decoder").is_empty());
		}
	}

	/// The reorder limit comes from the VUI, is bounded by the DPB size, and is
	/// zero whenever the order count follows `frame_num`.
	#[test]
	fn the_reorder_limit_follows_the_sps() {
		// 8100 macroblocks over 300 per picture, capped at 16.
		let sps = progressive_sps();
		assert_eq!(sps.max_dpb_frames, 16);
		assert_eq!(max_dpb_frames(&sps), 16);
		assert_eq!(
			reorder_limit(&sps, 16),
			16,
			"without a VUI, the inference is the DPB size"
		);

		let mut intra = progressive_sps();
		intra.profile = Profile::High;
		intra.constraint_flags = 0x10;
		assert_eq!(
			reorder_limit(&intra, 16),
			0,
			"without a VUI, a High intra profile reorders nothing"
		);

		let restriction = |max_num_reorder_frames, max_dec_frame_buffering| kodecs_h264::Restriction {
			motion_vectors_over_pic_boundaries: true,
			max_bytes_per_pic_denom: 2,
			max_bits_per_mb_denom: 1,
			log2_max_mv_length_horizontal: 16,
			log2_max_mv_length_vertical: 16,
			max_num_reorder_frames,
			max_dec_frame_buffering,
		};
		let mut declared = progressive_sps();
		declared.vui = Some(kodecs_h264::Vui {
			aspect_ratio: None,
			overscan_appropriate: None,
			video_signal: None,
			chroma_loc: None,
			timing: None,
			nal_hrd: None,
			vcl_hrd: None,
			low_delay_hrd: false,
			pic_struct_present: false,
			restriction: Some(restriction(0, 1)),
		});
		assert_eq!(max_dpb_frames(&declared), 1, "the VUI's buffering is the DPB size");
		assert_eq!(
			reorder_limit(&declared, max_dpb_frames(&declared)),
			0,
			"the VUI's limit applies"
		);

		if let Some(vui) = declared.vui.as_mut() {
			vui.restriction = Some(restriction(5, 2));
		}
		assert_eq!(
			reorder_limit(&declared, max_dpb_frames(&declared)),
			2,
			"the DPB size bounds the VUI's limit"
		);

		let mut derived = progressive_sps();
		derived.pic_order_cnt = PicOrderCnt::Decode;
		assert_eq!(
			reorder_limit(&derived, 16),
			0,
			"an order count from frame_num reorders nothing"
		);
	}

	/// A picture the consumer has let go of is decoded into again rather than
	/// replaced by a new allocation, and the recycled surfaces still carry the
	/// right pictures.
	///
	/// Each picture is read back and dropped before the next access unit goes
	/// in, the way a renderer that draws a picture and moves on behaves. Without
	/// recycling this allocated one surface per picture.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn a_dropped_export_is_decoded_into_again() {
		const PICTURES: u32 = 60;
		let (width, height) = (320u32, 240u32);
		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
		let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
		let mut downloading = Decoder::new(Config::new()).expect("a second decoder");

		let mut compared = 0;
		for step in 0..PICTURES {
			let unit = encoder
				.encode_nv12(&nv12_frame(width, height, step), step == 0)
				.expect("encode a picture");
			let exported = exporting
				.decode_exported(&unit, step as u64)
				.expect("decode to a descriptor");
			let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
			assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
			for (gpu, cpu) in exported.iter().zip(&downloaded) {
				let read_back = gpu.download().expect("read the exported surface back");
				assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
				compared += 1;
			}
		}
		assert!(compared > 0, "the decoder produced no pictures");

		let pool = &exporting.sequence().expect("a sequence").pool;
		let allocated = pool.allocated.get();
		eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
		assert!(
			allocated <= pool.free.capacity,
			"{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
			pool.free.capacity
		);
	}

	/// A consumer that holds many pictures and then lets them all go leaves at
	/// most the pool's capacity behind, and the next pictures reuse those.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
		const HELD: u32 = 40;
		let (width, height) = (320u32, 240u32);
		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");

		let mut step = 0;
		let mut decode = |decoder: &mut Decoder| {
			let unit = encoder
				.encode_nv12(&nv12_frame(width, height, step), step == 0)
				.expect("encode a picture");
			step += 1;
			decoder.decode_exported(&unit, step as u64).expect("decode a picture")
		};

		let mut held = Vec::new();
		for _ in 0..HELD {
			held.extend(decode(&mut decoder));
		}
		let pool = &decoder.sequence().expect("a sequence").pool;
		let allocated = pool.allocated.get();
		assert!(
			allocated >= held.len(),
			"{} pictures held on {allocated} surfaces",
			held.len()
		);

		drop(held);
		let free = pool.free.surfaces.lock().unwrap().len();
		assert!(
			free <= pool.free.capacity,
			"{free} surfaces left free, more than the capacity of {}",
			pool.free.capacity
		);

		for _ in 0..10 {
			drop(decode(&mut decoder));
		}
		let pool = &decoder.sequence().expect("a sequence").pool;
		assert_eq!(
			pool.allocated.get(),
			allocated,
			"pictures after the release did not reuse the free surfaces"
		);
	}

	/// An exported picture crosses threads, which is the point of handing one to
	/// a renderer: the decoder runs on its own thread and the frame outlives it.
	/// [`Decoder`] is neither [`Send`] nor [`Sync`], so this pins that the export
	/// does not inherit that.
	#[test]
	fn an_exported_frame_is_send_and_sync() {
		const fn assert_send_sync<T: Send + Sync>() {}
		assert_send_sync::<ExportedFrame>();
	}

	/// An exported picture reads back to the same pixels the ordinary path
	/// downloads.
	///
	/// The invariant that lets a GPU-resident frame keep a CPU fallback: the
	/// surface travels with the descriptor, so `vaDeriveImage` still
	/// reaches the picture the descriptor points at. One stream through two
	/// decoders, so both sides see the same pictures in the same order and the
	/// comparison is exact rather than approximate.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn an_exported_picture_downloads_to_the_same_pixels() {
		let (width, height) = (320u32, 240u32);
		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
		let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
		let mut downloading = Decoder::new(Config::new()).expect("a second decoder");

		let mut exported = Vec::new();
		let mut downloaded = Vec::new();
		for step in 0..8 {
			let unit = encoder
				.encode_nv12(&nv12_frame(width, height, step), step == 0)
				.expect("encode a picture");
			exported.extend(
				exporting
					.decode_exported(&unit, step as u64)
					.expect("decode to a descriptor"),
			);
			downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
		}
		exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
		downloaded.extend(downloading.flush().expect("flush the downloading decoder"));

		assert!(!exported.is_empty(), "the decoder produced no pictures");
		assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");

		for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
			let read_back = gpu.download().expect("read the exported surface back");
			assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
			assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
			assert!(
				read_back.data == cpu.data,
				"picture {index} read back differently than it downloaded"
			);
		}
	}

	/// Every picture matches what ffmpeg's software decoder makes of the same
	/// stream, bit for bit, in either codec.
	///
	/// The test that says this is a decoder rather than plumbing. The streams
	/// are coded with B-frames and three reference frames, so matching the
	/// reference means the reference lists, the picture order counts, and the
	/// DPB bumping are all right, not just the surfaces. The second size crops
	/// on the right and bottom. Half the pictures are taken as descriptors and
	/// downloaded after, so both ways out are checked.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn decoded_pictures_match_a_software_decoder() {
		const PICTURES: usize = 30;

		for codec in [Codec::H264, Codec::H265] {
			for (width, height) in [(320u32, 240u32), (852, 478)] {
				let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
					panic!("no ffmpeg that encodes {codec:?}");
				};
				let reference = software_decode(codec, &stream);

				let picture_len = (width * height * 3 / 2) as usize;
				assert_eq!(
					reference.len(),
					PICTURES * picture_len,
					"ffmpeg decoded a different count"
				);

				let Ok(mut decoder) = Decoder::new(Config { codec, ..Config::new() }) else {
					panic!("no VA-API {codec:?} decoder");
				};

				let units = split_access_units(codec, &stream);
				let mut decoded = Vec::new();
				for (index, unit) in units.iter().enumerate() {
					if index % 2 == 0 {
						decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
					} else {
						for exported in decoder
							.decode_exported(unit, index as u64)
							.expect("decode an access unit")
						{
							decoded.push(exported.download().expect("download an exported picture"));
						}
					}
				}
				decoded.extend(decoder.flush().expect("flush the decoder"));
				assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");

				let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
				assert!(
					timestamps.windows(2).any(|pair| pair[0] > pair[1]),
					"the {codec:?} stream came out in decode order, so nothing here tests reordering"
				);
				timestamps.sort_unstable();
				assert_eq!(
					timestamps,
					(0..PICTURES as u64).collect::<Vec<_>>(),
					"a {codec:?} picture's timestamp did not survive reordering"
				);

				for (index, picture) in decoded.iter().enumerate() {
					assert_eq!((picture.width, picture.height), (width, height));
					assert!(
						picture.data == reference[index * picture_len..][..picture_len],
						"{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
					);
				}
			}
		}
	}

	/// The H.264 coding tools a software encoder reaches for beyond the Main
	/// profile defaults decode exactly as a software decoder does them: scaling
	/// matrices, several slices a picture, explicit weighted prediction in P and
	/// B slices over a fade, and a strict B-pyramid's reordered references.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn h264_coding_tools_match_a_software_decoder() {
		const PICTURES: usize = 40;
		let (width, height) = (852u32, 478u32);
		let source = format!("testsrc2=size={width}x{height}:rate=30,fade=in:0:20,fade=out:25:15");
		let pictures = PICTURES.to_string();
		#[rustfmt::skip]
		let stream = ffmpeg(&[
			"-f", "lavfi", "-i", &source, "-frames:v", &pictures, "-pix_fmt", "yuv420p",
			"-c:v", "libx264", "-profile:v", "high", "-bf", "3", "-refs", "4", "-g", "20",
			"-x264-params", "slices=3:weightp=2:weightb=1:cqm=jvt:b-pyramid=strict:log-level=error",
			"-f", "h264", "-",
		])
		.expect("no ffmpeg that encodes H.264");
		let reference = software_decode(Codec::H264, &stream);
		let picture_len = (width * height * 3 / 2) as usize;
		assert_eq!(
			reference.len(),
			PICTURES * picture_len,
			"ffmpeg decoded a different count"
		);

		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
		let mut decoded = Vec::new();
		for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
			decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
		}
		decoded.extend(decoder.flush().expect("flush the decoder"));
		assert_eq!(decoded.len(), PICTURES, "lost or invented pictures");
		for (index, picture) in decoded.iter().enumerate() {
			assert!(
				picture.data == reference[index * picture_len..][..picture_len],
				"picture {index} differs from the software decoder"
			);
		}
	}

	/// An H.265 stream coded without reordering comes out as it decodes: C.5.2
	/// bumps by the SPS's reorder limit, which is zero, rather than holding
	/// pictures until the DPB fills the way H.264's C.4.5.3 does.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn h265_without_reordering_comes_out_as_it_decodes() {
		const PICTURES: usize = 10;

		let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
		let mut decoder = Decoder::new(Config {
			codec: Codec::H265,
			..Config::new()
		})
		.expect("no VA-API H.265 decoder");

		for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
			let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
			let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
			assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
		}
		assert!(decoder.flush().expect("flush the decoder").is_empty());
	}

	/// A 4K H.265 stream coded with wavefronts, as x265 codes by default, signals
	/// an entry point per CTB row: 33 at 64-pixel CTBs, past what a fixed array
	/// of 32 held.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_4k_h265_wavefront_stream_decodes() {
		const PICTURES: usize = 2;
		let size = (3840, 2160);

		let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
		let mut decoder = Decoder::new(Config {
			codec: Codec::H265,
			..Config::new()
		})
		.expect("no VA-API H.265 decoder");

		let mut decoded = Vec::new();
		for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
			decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
		}
		decoded.extend(decoder.flush().expect("flush the decoder"));
		assert_eq!(decoded.len(), PICTURES);
		assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
	}

	/// A second H.265 sequence at another size decodes at that size, and the
	/// first sequence's tail comes out ahead of it.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_new_h265_sequence_decodes_at_its_own_size() {
		const PER_SEQUENCE: usize = 6;
		let sizes = [(320u32, 240u32), (192u32, 144u32)];

		let mut stream = Vec::new();
		for &size in &sizes {
			let sequence =
				software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
			stream.extend(sequence);
		}
		let mut decoder = Decoder::new(Config {
			codec: Codec::H265,
			..Config::new()
		})
		.expect("no VA-API H.265 decoder");

		let mut decoded = Vec::new();
		let units = split_access_units(Codec::H265, &stream);
		for (index, unit) in units.iter().enumerate() {
			decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
		}
		decoded.extend(decoder.flush().expect("flush the decoder"));

		let expected: Vec<(u32, u32)> = sizes
			.iter()
			.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
			.collect();
		let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
		assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");

		for picture in &decoded {
			let expected_len = (picture.width * picture.height * 3 / 2) as usize;
			assert_eq!(
				picture.data.len(),
				expected_len,
				"a picture was read back at the wrong size"
			);
		}
	}

	/// A second sequence at another size decodes at that size, and the first
	/// sequence's tail comes out ahead of it.
	///
	/// What `apply_sps` promises: an SPS that changes the coded size rebuilds the
	/// VA context and the surface pool, and everything decoded against the old
	/// one is let out first so no picture is read back at the wrong size.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn a_new_sequence_decodes_at_its_own_size() {
		const PER_SEQUENCE: u32 = 6;
		let sizes = [(320u32, 240u32), (192u32, 144u32)];

		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");

		let mut decoded = Vec::new();
		let mut timestamp = 0u64;
		for &(width, height) in &sizes {
			let mut encoder =
				crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
			for step in 0..PER_SEQUENCE {
				let unit = encoder
					.encode_nv12(&nv12_frame(width, height, step), step == 0)
					.expect("encode a picture");
				decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
				timestamp += 1;
			}
		}
		decoded.extend(decoder.flush().expect("flush the decoder"));

		let expected: Vec<(u32, u32)> = sizes
			.iter()
			.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
			.collect();
		let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
		assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");

		let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
		assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());

		for picture in &decoded {
			let expected_len = (picture.width * picture.height * 3 / 2) as usize;
			assert_eq!(
				picture.data.len(),
				expected_len,
				"a picture was read back at the wrong size"
			);
		}
	}

	#[test]
	#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
	fn a_refused_sps_leaves_no_stale_set_behind() {
		let (width, height) = (320u32, 240u32);
		let stream = software_encode(Codec::H264, (width, height), 4, false).expect("no ffmpeg that encodes H.264");
		let units = split_access_units(Codec::H264, &stream);
		let source = format!("testsrc2=size={width}x{height}:rate=30");
		#[rustfmt::skip]
		let high422 = ffmpeg(&[
			"-f", "lavfi", "-i", &source, "-frames:v", "1", "-pix_fmt", "yuv422p",
			"-c:v", "libx264", "-profile:v", "high422", "-f", "h264", "-",
		])
		.expect("no ffmpeg that encodes H.264 4:2:2");

		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
		decoder.decode(&units[0], 0).expect("decode the IDR");
		let refused = decoder.decode(&high422, 1).expect_err("a 4:2:2 SPS decodes");
		assert!(format!("{refused:#}").contains("unsupported"), "{refused:#}");

		// The 4:2:0 SPS that shared the refused one's id is gone with it, so its slices fail.
		let stale = decoder
			.decode(&units[1], 2)
			.expect_err("a slice decoded against a replaced SPS");
		assert!(format!("{stale:#}").contains("Slice"), "{stale:#}");

		// Sending them again recovers.
		decoder.decode(&units[0], 3).expect("decode the resent IDR");
	}

	#[test]
	#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
	fn a_refused_pps_leaves_the_other_sets_usable() {
		let stream = software_encode(Codec::H264, (320, 240), 4, false).expect("no ffmpeg that encodes H.264");
		let units = split_access_units(Codec::H264, &stream);

		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
		let mut decoded = decoder.decode(&units[0], 0).expect("decode the IDR");
		// PPS 1 naming SPS 1, which the stream never sent: pic_parameter_set_id and
		// seq_parameter_set_id are both ue(v) 1 (`010`), then the stop bit.
		let refused = decoder
			.decode(&[0, 0, 0, 1, 0x68, 0b0100_1010], 1)
			.expect_err("a PPS naming a missing SPS decodes");
		assert!(format!("{refused:#}").contains("Pps"), "{refused:#}");

		// SPS 0 and PPS 0, sent only with the IDR, still decode the rest.
		for (timestamp, unit) in (2..).zip(&units[1..]) {
			decoded.extend(
				decoder
					.decode(unit, timestamp)
					.expect("decode a picture after the refused PPS"),
			);
		}
		decoded.extend(decoder.flush().expect("flush the decoder"));
		assert_eq!(decoded.len(), units.len());
	}

	/// Runs ffmpeg with `args`, returning its standard output, or `None` when
	/// ffmpeg is missing or refused the arguments.
	fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
		let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
		if !output.status.success() {
			eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
			return None;
		}
		Some(output.stdout)
	}

	/// Encodes `pictures` of ffmpeg's test pattern at `size`, with two B-frames
	/// and three reference frames when `reorder` is set and neither otherwise,
	/// returning the Annex-B stream. `None` without ffmpeg or its encoder.
	fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
		let source = format!("testsrc2=size={width}x{height}:rate=30");
		let pictures = pictures.to_string();
		let mut args = vec![
			"-f",
			"lavfi",
			"-i",
			&source,
			"-frames:v",
			&pictures,
			"-pix_fmt",
			"yuv420p",
		];

		let x265;
		match codec {
			Codec::H264 => args.extend([
				"-c:v",
				"libx264",
				"-profile:v",
				"main",
				"-bf",
				if reorder { "2" } else { "0" },
				"-refs",
				if reorder { "3" } else { "1" },
				"-g",
				"15",
				"-f",
				"h264",
			]),
			Codec::H265 => {
				// x265's defaults are open GOPs, so the second keyframe is a CRA
				// picture with leading pictures that refer across it.
				x265 = if reorder {
					"bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
				} else {
					"bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
				};
				args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
			}
		}
		args.push("-");
		ffmpeg(&args)
	}

	/// Decodes `stream` with ffmpeg into packed NV12, one picture after another.
	fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
		// ffmpeg reads the elementary stream from a file rather than a pipe, so
		// the test never has to drain its output while still writing its input.
		static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
		let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
		let extension = match codec {
			Codec::H264 => "264",
			Codec::H265 => "265",
		};
		let path = std::env::temp_dir().join(format!(
			"kodecs-vaapi-decode-{}-{count}.{extension}",
			std::process::id()
		));
		std::fs::write(&path, stream).expect("write the elementary stream");
		let decoded = ffmpeg(&[
			"-i",
			path.to_str().expect("a UTF-8 temporary path"),
			"-pix_fmt",
			"nv12",
			"-f",
			"rawvideo",
			"-",
		]);
		let _ = std::fs::remove_file(&path);
		decoded.expect("ffmpeg decodes what it just encoded")
	}

	/// Splits an Annex-B elementary stream into access units.
	///
	/// A unit ends at the first slice of the next picture, or at a parameter
	/// set, SEI, or delimiter that comes before one.
	fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
		let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
			.filter(|&i| stream[i..i + 3] == [0, 0, 1])
			.collect();

		let mut units = Vec::new();
		let mut current: Vec<u8> = Vec::new();
		let mut current_has_picture = false;

		for (index, &start) in starts.iter().enumerate() {
			let end = starts.get(index + 1).copied().unwrap_or(stream.len());
			let nal = &stream[start + 3..end];
			// The first bit after the NAL header is first_mb_in_slice == 0 for
			// H.264 and first_slice_segment_in_pic_flag for H.265: either way, set
			// on the first slice of a picture.
			let (is_slice, starts_picture, starts_unit) = match codec {
				Codec::H264 => {
					let nal_type = nal[0] & 0x1f;
					let is_slice = (1..=5).contains(&nal_type);
					(is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
				}
				Codec::H265 => {
					let nal_type = (nal[0] >> 1) & 0x3f;
					let is_slice = nal_type <= 31;
					(
						is_slice,
						is_slice && nal[2] & 0x80 != 0,
						matches!(nal_type, 32..=35 | 39),
					)
				}
			};

			if current_has_picture && (starts_picture || starts_unit) {
				units.push(std::mem::take(&mut current));
				current_has_picture = false;
			}

			current.extend_from_slice(&stream[start..end]);
			current_has_picture |= is_slice;
		}

		if !current.is_empty() {
			units.push(current);
		}
		units
	}

	/// The inode of a descriptor, which for a DMA-BUF names the allocation
	/// behind it: every buffer gets its own on the anonymous dma-buf filesystem.
	fn inode(fd: &OwnedFd) -> u64 {
		use std::os::unix::fs::MetadataExt as _;

		// Stat a duplicate, so the descriptor the caller holds is untouched and
		// the `File` wrapper closes only its own copy.
		let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
		file.metadata().expect("stat the descriptor").ino()
	}
}