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
// 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 (encoder/stateless/h264/vaapi.rs), itself
// BSD-3-Clause / Copyright The ChromiumOS Authors. See LICENSE.cros-codecs.

//! Thin VA-API H.264 and H.265 encoder built on the vendored libva binding.
//!
//! For H.264 it writes the SPS, PPS, and slice headers with kodecs-h264, and
//! drives libva directly for surface upload +
//! slice submission, rather than vendoring cros-codecs's generic multi-backend
//! encoder framework. The per-frame VA buffer population is ported from
//! cros-codecs's `encoder/stateless/h264/vaapi.rs`. H.265 writes its own
//! parameter sets and slice headers (see `h265.rs`).
//!
//! Low-latency only: IPPP (no B-frames), one reference frame, matching the
//! VideoToolbox / Media Foundation / NVENC backends in moq-video.
//!
//! Three ways in, cheapest first:
//! - [`Encoder::encode_dmabuf`] with an NV12 DMA-BUF at the encoder's size
//!   encodes the producer's memory in place.
//! - [`Encoder::encode_dmabuf`] with any other importable DMA-BUF (packed RGB
//!   from a screen capture, YUYV from a camera, NV12 at another size) converts
//!   and scales it into the encoder's own surface with the video processor, on
//!   the GPU.
//! - [`Encoder::encode_nv12`] uploads CPU pixels.
//!
//! Checked on Intel Meteor Lake and Arrow Lake with the iHD driver, and on an
//! AMD RX 9070 with radeonsi, by decoding with ffmpeg's software decoder: CPU
//! and DMA-BUF input come back above 35 dB luma PSNR, and BGRX converts to
//! BT.601 and BT.709 with every channel within 6 code values of the reference.
//! The low-power entrypoint is untested, since those devices expose the full
//! one.

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

use anyhow::Context as _;

use crate::codec::Codec;
use crate::dmabuf::DmaBuf;
use crate::vpp::Processor;
use crate::{
	BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter,
	EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter,
	EncPackedHeaderType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
	EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264, GenericValue,
	H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture,
	PictureH264, RcFlags, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
	VAEntrypoint, VAImageFormat, VAProfile, VASurfaceAttribType, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE,
	VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX,
	VA_FOURCC_NV12, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
	VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
};
use kodecs_h264::{
	AspectRatio, Colour, Level, NaluHeader, NaluType, PicOrderCnt, Pps, PpsBuilder, Profile, Restriction, SliceHeader,
	SliceHeaderBuilder, SliceType, Sps, SpsBuilder, Timing, VideoSignal, Vui,
};

mod h265;

/// Quantizer bounds for the rate controller.
///
/// The floor is the quality: the rate controller holds the stream to
/// [`Config::bitrate`], and a calm scene the floor already codes cleanly spends
/// less instead of buying a finer quantizer than anyone can see. 24 is the
/// coarsest that kept a 720p30 talking head at VMAF 95, the usual mark for
/// transparent, on both iHD (Arrow Lake: 95.8 at 2.9 Mbit/s under a 4 Mbit/s
/// cap, H.265 95.7 at 1.6 under 2.8) and radeonsi (RX 9070: 95.4 at 1.7, H.265
/// 95.4 at 1.5). It also keeps an IDR on easy content from taking a large share
/// of the rate. The ceiling is the codecs' own: iHD and radeonsi both honor it,
/// so a lower one sets a smallest picture, and a stream asked for less
/// overshoots its rate several times over. A lower ceiling does steady iHD's
/// H.264 IDRs, but under congestion missing the rate costs more than that.
const MIN_QP: u8 = 24;
const MAX_QP: u8 = 51;
/// The HRD buffer, in frames of the bitrate, sent with every picture. The
/// driver's own default is a second of the rate, which let a second of high
/// motion run half again over the bitrate on radeonsi. It is also what a still
/// scene banks: the first busy frames after one spend all of it, so that second
/// runs this many frames over the bitrate.
pub const HRD_FRAMES: u32 = 3;
/// Window over which libva's rate controller targets the configured bitrate.
///
/// This matches cros-codecs. The old `framerate * 1000` value confused frames
/// per second with seconds and gave a 30 fps encoder a 30-second window.
pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
/// `max_frame_num` upper bound for the low-delay GOP; matches cros-codecs.
const LIMIT: u32 = 2048;

/// Encoder configuration. Dimensions must be even (4:2:0 chroma).
#[derive(Clone, Debug)]
pub struct Config {
	/// The format to encode, H.264 unless set. Main profile either way.
	pub codec: Codec,
	pub width: u32,
	pub height: u32,
	pub framerate: u32,
	/// The bitrate in bits per second the stream is held to. A calm scene
	/// spends less; see [`RateControl`].
	pub bitrate: u32,
	/// Keyframe interval in frames.
	pub gop: NonZeroU32,
	/// DRM render node to open (e.g. `/dev/dri/renderD128`).
	///
	/// `None`, the default, opens the first node whose driver can encode
	/// [`codec`](Self::codec) at this frame size, and [`Encoder::config`] then
	/// names the node it picked.
	pub device: Option<PathBuf>,
	/// Color space written into the SPS, and the target of a conversion from RGB.
	///
	/// Defaults to [`Color::infer`] for the height, which is what a decoder
	/// assumes for an unlabelled stream.
	pub color: Color,
}

/// The rate control mode that holds a stream to [`Config::bitrate`], picked at
/// open for the driver.
///
/// Either way the bitrate is the ceiling the driver's rate controller aims to
/// hold the stream under, through the [`HRD_FRAMES`] buffer, and the quantizer
/// floor is its quality, so a calm scene falls below the bitrate. It is a
/// target, not a guarantee: a busy second can still overshoot it by a few
/// percent (iHD's H.264 peaked at 4.36 Mbit/s in one second under 4 Mbit/s). Neither driver's
/// `VA_RC_QVBR` gets there: on iHD it held a high-motion clip to 59% of the
/// bitrate whatever the quality factor, and on radeonsi it scored 93.3 VMAF at
/// the full bitrate where CBR and the floor scored 95.4 at 43% of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RateControl {
	/// `VA_RC_VBR` with the bitrate as both target and peak, for iHD, whose CBR
	/// ignores the floor and spends the bitrate on a still picture.
	Variable,
	/// `VA_RC_CBR` without filler, for every other driver. radeonsi honors the
	/// floor and the HRD here, where its VBR let a high-motion second run half
	/// again over the bitrate.
	Constant,
}

impl RateControl {
	/// The mode for the driver named `vendor` (`vaQueryVendorString`), whose
	/// `VAConfigAttribRateControl` reads `offered`.
	fn pick(vendor: &str, offered: u32) -> Self {
		match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
			true => Self::Variable,
			false => Self::Constant,
		}
	}

	fn va(self) -> u32 {
		match self {
			Self::Variable => VA_RC_VBR,
			Self::Constant => VA_RC_CBR,
		}
	}
}

/// Per-frame reference metadata. (Mirrors cros-codecs `DpbEntryMeta`.)
#[derive(Copy, Clone)]
struct FrameMeta {
	poc: u32,
	frame_num: u32,
}

impl FrameMeta {
	/// Returns the H.264 order count and frame number of the picture `count` pictures after an IDR.
	///
	/// frame_num counts modulo MaxFrameNum, and the slice header carries only
	/// the low bits of the picture order count; the full count goes to the
	/// driver in the picture parameters.
	fn new(count: u32) -> Self {
		Self {
			poc: count.wrapping_mul(2),
			frame_num: count % LIMIT,
		}
	}
}

/// The picture a P picture predicts from: the previous one.
#[derive(Copy, Clone)]
struct Reference {
	/// Its reconstructed surface.
	surface: crate::bindings::VASurfaceID,
	/// How many pictures after the IDR it came.
	count: u32,
}

/// What one picture's parameter buffers are built from.
struct PictureInfo<'a> {
	idr: bool,
	/// How many IDR pictures came before this one.
	idr_id: u32,
	/// How many pictures after the IDR this one comes.
	count: u32,
	/// The surface its reconstruction is written to.
	recon: crate::bindings::VASurfaceID,
	reference: Option<Reference>,
	coded: &'a EncCodedBuffer,
	bitrate: u32,
}

/// The bitstream syntax of the stream being encoded.
enum Syntax {
	H264 {
		sps: Sps,
		pps: Pps,
		/// The packed header kinds the driver takes from us; it writes the rest.
		packed: u32,
	},
	H265 {
		stream: h265::Stream,
		/// The packed header kinds the driver takes from us; it writes the rest.
		packed: u32,
	},
}

/// A VA-API H.264 or H.265 encoder. Built once, fed NV12 frames, emits an Annex-B stream.
pub struct Encoder {
	config: Config,
	syntax: Syntax,

	// Source surface (reused; NV12 re-uploaded per frame) and a 2-deep
	// reconstructed surface ring (current + previous reference for IPPP).
	input: Option<Surface<()>>,
	/// The driver's NV12 image format, which [`Encoder::encode_nv12`] uploads through; `None` when it has none.
	nv12: Option<VAImageFormat>,
	recon: Vec<Surface<()>>,
	/// Reference from the previous encoded frame: (recon index, pictures after the IDR).
	reference: Option<(usize, u32)>,

	counter: u32,
	/// IDR pictures coded so far, so two in a row carry different H.264 `idr_pic_id`s.
	idrs: u32,

	/// The video processor converting and scaling DMA-BUF input, opened on the
	/// first frame that needs it.
	processor: Option<Processor>,
	/// Set by a bitrate change, and cleared by the next frame, which asks the
	/// driver to restart its rate controller at the new target.
	reset_rate_control: bool,
	rate_control: RateControl,

	// Drop order: encode resources before the display they belong to.
	coded: EncCodedBuffer,
	coded_size: usize,
	context: Rc<Context>,
	_va_config: VaConfig,
	display: Arc<Display>,
}

impl Encoder {
	/// Opens [`Config::device`], or the first render node that encodes [`Config::codec`] at the frame size, and sets up an encode session for `config`.
	///
	/// # Errors
	///
	/// Fails when the frame size is zero or odd or outside the driver's [`Limits`], when libva cannot be loaded, when the named node cannot be opened
	/// or does not encode the codec (a named node is never swapped for
	/// another), when no node encodes it, and when the driver refuses the
	/// session or, for H.265, requires a coding tool this encoder does not write
	/// or takes no packed sequence header. H.264 also fails on a frame larger than
	/// the highest level (6.2) allows.
	pub fn new(mut config: Config) -> anyhow::Result<Self> {
		let (width, height) = (config.width, config.height);
		if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
			anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
		}
		let codec = config.codec;
		let (device, display) = match config.device.take() {
			Some(device) => {
				let display = Display::open_drm_display(&device)
					.map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
				(device, display)
			}
			None => crate::display::open_first(|display| probe(display, codec)?.check(width, height))
				.map_err(|e| e.context(format!("find a render node that encodes {codec:?} at {width}x{height}")))?,
		};

		let entrypoint = encode_entrypoint(&display, codec)?;
		let rate_control = RateControl::pick(
			&display.query_vendor_string().unwrap_or_default(),
			config_attribute(
				&display,
				codec,
				entrypoint,
				VAConfigAttribType::VAConfigAttribRateControl,
			),
		);
		let mut attrs = vec![
			VAConfigAttrib {
				type_: VAConfigAttribType::VAConfigAttribRTFormat,
				value: VA_RT_FORMAT_YUV420,
			},
			VAConfigAttrib {
				type_: VAConfigAttribType::VAConfigAttribRateControl,
				value: rate_control.va(),
			},
		];
		// The parameter sets go out as packed headers, so the VUI (color, frame
		// buffering) and the level are ours. For H.264 that is the SPS and PPS;
		// iHD takes them without being told, and a driver that follows the spec
		// writes its own unless the config asks. For H.265 it is the VPS, SPS and
		// PPS as one sequence header. Each slice header is packed too, as ffmpeg
		// packs them; the driver writes the slice headers if it does not take
		// them. radeonsi needs them for H.264: it takes the slice's NAL header
		// from the packed one, and drops the packed parameter sets without one.
		let wanted = match codec {
			Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
			Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
		};
		let packed = packed_headers(&display, codec, entrypoint) & wanted;
		// VA's H.265 sequence parameters have no conformance window and carry no
		// VUI here, so an SPS the driver writes would lose the crop and the color.
		if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
			anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
		}
		if packed != 0 {
			attrs.push(VAConfigAttrib {
				type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
				value: packed,
			});
		} else {
			tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
		}
		let mut va_config = display
			.create_config(attrs, profile(codec), entrypoint)
			.map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
		limits(&display, codec, entrypoint, &mut va_config)?.check(width, height)?;

		let syntax = match codec {
			Codec::H264 => {
				let (sps, pps) = build_sps_pps(&config)?;
				Syntax::H264 { sps, pps, packed }
			}
			Codec::H265 => Syntax::H265 {
				stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
				packed,
			},
		};
		// H.264 sizes the context and its references to the frame, which has
		// always worked; H.265 to whole minimum coding blocks, as ffmpeg does,
		// and to the driver's surface alignment.
		let size = match &syntax {
			Syntax::H264 { .. } => (config.width, config.height),
			Syntax::H265 { stream, .. } => stream.coded(),
		};

		let context = display
			.create_context::<()>(&va_config, size.0, size.1, None, true)
			.map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;

		let coded_size = coded_size(config.bitrate);
		let coded = context
			.create_enc_coded(coded_size)
			.map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;

		let input = make_surface(&display, (config.width, config.height))?;
		let nv12 = display
			.query_image_formats()
			.map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
			.into_iter()
			.find(|format| format.fourcc == VA_FOURCC_NV12);
		let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];

		tracing::info!(
			"opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
			device,
			config.width,
			config.height,
			config.framerate,
			config.bitrate,
			rate_control,
			entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
		);
		config.device = Some(device);
		Ok(Self {
			config,
			syntax,
			input: Some(input),
			nv12,
			recon,
			reference: None,
			counter: 0,
			idrs: 0,
			processor: None,
			reset_rate_control: false,
			rate_control,
			coded,
			coded_size,
			context,
			_va_config: va_config,
			display,
		})
	}

	/// Encodes one tightly-packed NV12 frame, returning Annex-B (with the
	/// parameter sets inline on each IDR). `keyframe` forces an IDR.
	///
	/// # Errors
	///
	/// Fails when `nv12` is shorter than a frame at the encoder's size, when the
	/// driver has no NV12 image format, and when the upload or the encode fails.
	pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
		let format = self
			.nv12
			.ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
		let mut input = self.input.take().expect("input surface present");
		let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
			.and_then(|()| self.encode_surface(&input, keyframe));
		self.input = Some(input);
		result
	}

	/// Encodes one frame held in a DMA-BUF, returning Annex-B like
	/// [`encode_nv12`](Self::encode_nv12).
	///
	/// An NV12 buffer at the encoder's size, which the encoder reads without
	/// padding (whole macroblocks for H.264; for H.265, whole minimum coding
	/// blocks at the driver's surface alignment), and whose
	/// [`color`](DmaBuf::color) is the stream's or unknown, is imported and
	/// encoded in place. Any other mapped format or size goes through the video processor into the encoder's own surface
	/// first: scaled to the encoder's size and converted to [`Config::color`].
	/// A YUV buffer with no color of its own is taken to be in that space
	/// already. Nothing reaches the CPU on either path.
	///
	/// The macroblock condition is not a formality: the encoder reads whole
	/// macroblocks, so it reads 1088 rows of a 1080-row picture, and a producer
	/// that places the chroma plane right after the last visible luma row
	/// (PipeWire does) has nothing there to read.
	///
	/// The producer must have finished writing the buffer; this does not wait
	/// on its fence.
	///
	/// # Errors
	///
	/// Fails when the driver refuses to import the buffer (an unsupported
	/// modifier or layout), when the device has no video processor and the
	/// buffer needs one, and when the encode itself fails. The encoder stays
	/// usable after a refused import, so a caller can fall back to
	/// [`encode_nv12`](Self::encode_nv12) for the same frame.
	pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
		let fourcc = buffer
			.fourcc()
			.ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
		let color = self.config.color;
		let size = (self.config.width, self.config.height);
		let unpadded = match &self.syntax {
			Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
			Syntax::H265 { stream, .. } => stream.coded() == size,
		};
		let in_place = fourcc == VA_FOURCC_NV12
			&& (buffer.width, buffer.height) == size
			&& unpadded
			&& buffer.color.is_none_or(|own| own == color);
		if in_place {
			let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
			return self.encode_surface(&source, keyframe);
		}

		let input_color = match is_rgb(fourcc) {
			true => None,
			false => Some(buffer.color.unwrap_or(color)),
		};
		let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
		let input = self.input.take().expect("input surface present");
		let result = self
			.processor()
			.and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
			.and_then(|()| self.encode_surface(&input, keyframe));
		self.input = Some(input);
		result
	}

	/// Changes [`Config::bitrate`], in bits per second, from the next frame on.
	///
	/// The rate control parameters go out with every frame, so this neither
	/// forces an IDR nor rebuilds the session; the next frame also asks the
	/// driver to reset its rate controller. It then converges over its window,
	/// [`RATE_CONTROL_WINDOW_MS`].
	///
	/// The level in the SPS is not revisited, so a rate far above the one the
	/// stream opened with can exceed what that level allows.
	///
	/// # Errors
	///
	/// Fails for a bitrate of zero, and when a larger coded buffer for the new
	/// rate cannot be allocated, in which case the old rate stays.
	pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
		if bitrate == 0 {
			anyhow::bail!("a bitrate of zero");
		}
		let size = coded_size(bitrate);
		if size > self.coded_size {
			// A higher rate can produce a picture larger than the buffer sized for
			// the old one, and a truncated picture is corrupt rather than short.
			self.coded = self
				.context
				.create_enc_coded(size)
				.map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
			self.coded_size = size;
		}
		if bitrate != self.config.bitrate {
			self.reset_rate_control = true;
		}
		self.config.bitrate = bitrate;
		Ok(())
	}

	/// Returns how the bitrate is spent, picked at open from what the driver offers.
	pub fn rate_control(&self) -> RateControl {
		self.rate_control
	}

	/// Returns the configuration in effect, including a bitrate changed since opening and the render node picked when none was named.
	pub fn config(&self) -> &Config {
		&self.config
	}

	/// Returns the video processor, opening it on first use.
	fn processor(&mut self) -> anyhow::Result<&Processor> {
		if self.processor.is_none() {
			self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
		}
		Ok(self.processor.as_ref().expect("opened above"))
	}

	/// Encodes the picture in `source`, which must be NV12 at the encoder's size.
	fn encode_surface<D: SurfaceMemoryDescriptor>(
		&mut self,
		source: &Surface<D>,
		keyframe: bool,
	) -> anyhow::Result<Vec<u8>> {
		let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
		if is_idr {
			// An IDR restarts the picture count and drops the reference.
			self.counter = 0;
			self.reference = None;
		}

		let recon_idx = (self.counter as usize) % self.recon.len();
		// The reference is the previous picture's reconstruction, for a P picture.
		let reference = match (is_idr, self.reference) {
			(false, Some((index, count))) => Some(Reference {
				surface: self.recon[index].id(),
				count,
			}),
			_ => None,
		};
		let info = PictureInfo {
			idr: is_idr,
			idr_id: self.idrs,
			count: self.counter,
			recon: self.recon[recon_idx].id(),
			reference,
			coded: &self.coded,
			bitrate: self.config.bitrate,
		};
		let buffers = match &self.syntax {
			Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
			Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
		};

		let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);

		// VA-API spec buffer order: sequence, picture, slice, then packed headers,
		// then rate-control misc params.
		for buffer in buffers {
			picture.add_buffer(self.create(buffer)?);
		}

		let bits_per_second = self.config.bitrate;
		let rc = EncMiscParameterRateControl::new(
			bits_per_second,
			100,                    // target_percentage: VBR's target is its peak
			RATE_CONTROL_WINDOW_MS, // window_size (ms)
			u32::from((MIN_QP + MAX_QP) / 2),
			MIN_QP as u32,
			0, // basic_unit_size
			// Do not let rate control drop a frame to meet the bitrate. A live
			// encoder has already admitted this frame into the media timeline.
			// Nor pad a cheap one up to it: filler bits carry no picture.
			RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
			0, // icq_quality_factor
			MAX_QP as u32,
			0, // quality_factor
			0, // target_frame_size
		);
		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
		// After the rate control parameters, which radeonsi reads as resetting the buffer.
		let hrd = hrd_size(bits_per_second, self.config.framerate);
		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
			EncMiscParameterHRD::new(hrd, hrd),
		)))?);

		let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);

		let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
		let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
		let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
		// Sync (PictureEnd -> PictureSync) so the source is no longer read and
		// the coded buffer is ready.
		picture
			.sync()
			.map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;

		// The reconstructed surface syncs implicitly; read the coded bitstream.
		let bitstream = self.read_coded()?;

		self.reference = Some((recon_idx, self.counter));
		self.counter += 1;
		self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
		self.reset_rate_control = false;
		Ok(bitstream)
	}

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

	fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
		let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
		let mut out = Vec::new();
		for segment in mapped.iter() {
			out.extend_from_slice(segment.buf);
		}
		Ok(out)
	}
}

/// The frame sizes a driver encodes a codec at, as [`probe`] reports them.
///
/// Each bound is `None` where the driver names none, which leaves it unknown
/// rather than zero. The driver holds the size the frame is coded at to them,
/// which for H.265 is the frame rounded up to whole minimum coding blocks and
/// to the surface alignment, so compare a frame with [`Limits::check`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
	pub min_width: Option<u32>,
	pub min_height: Option<u32>,
	pub max_width: Option<u32>,
	pub max_height: Option<u32>,
	/// The multiple, across and down, a frame is rounded up to when it is coded.
	round: (u32, u32),
}

impl Limits {
	/// Checks that the driver encodes a `width` by `height` frame.
	///
	/// # Errors
	///
	/// Fails naming the bound that the frame, at the size it is coded at, breaks.
	pub fn check(&self, width: u32, height: u32) -> anyhow::Result<()> {
		let round = |size: u32, to: u32| size.checked_next_multiple_of(to).unwrap_or(u32::MAX);
		let coded = (round(width, self.round.0), round(height, self.round.1));
		let at = match coded == (width, height) {
			true => String::new(),
			false => format!(" (coded {}x{})", coded.0, coded.1),
		};
		for (axis, size, min, max) in [
			("width", coded.0, self.min_width, self.max_width),
			("height", coded.1, self.min_height, self.max_height),
		] {
			if let Some(min) = min.filter(|&min| size < min) {
				anyhow::bail!("a {width}x{height} frame{at} is under the driver's minimum encode {axis} of {min}");
			}
			if let Some(max) = max.filter(|&max| size > max) {
				anyhow::bail!("a {width}x{height} frame{at} is over the driver's maximum encode {axis} of {max}");
			}
		}
		Ok(())
	}
}

/// Returns the frame sizes `display`'s driver encodes `codec` at, which is what [`Encoder::new`] checks of a render node.
///
/// # Errors
///
/// Fails when the driver offers neither the full nor the low-power Main
/// profile encode entrypoint for `codec`, refuses an encode config for it, or
/// cannot be asked, and for H.265 when it requires a coding tool this encoder
/// does not write.
pub fn probe(display: &Arc<Display>, codec: Codec) -> anyhow::Result<Limits> {
	let entrypoint = encode_entrypoint(display, codec)?;
	let attrs = vec![VAConfigAttrib {
		type_: VAConfigAttribType::VAConfigAttribRTFormat,
		value: VA_RT_FORMAT_YUV420,
	}];
	let mut va_config = display
		.create_config(attrs, profile(codec), entrypoint)
		.map_err(|e| anyhow::anyhow!("create {codec:?} encode config: {e:?}"))?;
	limits(display, codec, entrypoint, &mut va_config)
}

/// Returns the [`Limits`] of `va_config`, an encode config for `codec` at `entrypoint`.
fn limits(
	display: &Display,
	codec: Codec,
	entrypoint: VAEntrypoint::Type,
	va_config: &mut VaConfig,
) -> anyhow::Result<Limits> {
	let mut bound = |type_: VASurfaceAttribType::Type| -> anyhow::Result<Option<u32>> {
		let values = va_config
			.query_surface_attributes_by_type(type_)
			.map_err(|e| anyhow::anyhow!("query {codec:?} encode surface attributes: {e:?}"))?;
		Ok(match values.first() {
			Some(&GenericValue::Integer(value)) => u32::try_from(value).ok().filter(|&value| value > 0),
			_ => None,
		})
	};
	let (min_width, min_height, max_width, max_height) = (
		bound(VASurfaceAttribType::VASurfaceAttribMinWidth)?,
		bound(VASurfaceAttribType::VASurfaceAttribMinHeight)?,
		bound(VASurfaceAttribType::VASurfaceAttribMaxWidth)?,
		bound(VASurfaceAttribType::VASurfaceAttribMaxHeight)?,
	);
	let round = match codec {
		Codec::H264 => (1, 1),
		Codec::H265 => h265::round(display, entrypoint, va_config)?,
	};
	Ok(Limits {
		min_width,
		min_height,
		max_width,
		max_height,
		round,
	})
}

/// Returns the VA profile `codec` is encoded in.
fn profile(codec: Codec) -> VAProfile::Type {
	match codec {
		Codec::H264 => VAProfile::VAProfileH264Main,
		Codec::H265 => h265::PROFILE,
	}
}

/// Returns the entrypoint to encode `codec` with: the full one, or the low-power one where it is all there is.
///
/// Some Intel parts expose encode only through `VAEntrypointEncSliceLP`.
fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
	let entrypoints = display
		.query_config_entrypoints(profile(codec))
		.map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
	pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
}

/// Returns the encode entrypoint to use out of those a device offers: the full one when present.
fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option<VAEntrypoint::Type> {
	[VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
		.into_iter()
		.find(|entrypoint| offered.contains(entrypoint))
}

/// Returns the packed header kinds the driver takes for `codec` at `entrypoint`.
///
/// Zero when it takes none, or when asking fails.
fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 {
	config_attribute(
		display,
		codec,
		entrypoint,
		VAConfigAttribType::VAConfigAttribEncPackedHeaders,
	)
}

/// Returns the bits of attribute `type_` the driver offers for encoding `codec`, or none when it does not say.
fn config_attribute(
	display: &Display,
	codec: Codec,
	entrypoint: VAEntrypoint::Type,
	type_: VAConfigAttribType::Type,
) -> u32 {
	let mut attrs = [VAConfigAttrib { type_, value: 0 }];
	if display
		.get_config_attributes(profile(codec), entrypoint, &mut attrs)
		.is_err()
		|| attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
	{
		return 0;
	}
	attrs[0].value
}

/// Returns the lowest H.264 level, from 4 up, whose frame size, frame shape, and macroblock rate
/// cover the stream.
///
/// Only those limits: the level's maximum bitrate is not checked.
///
/// Level 4 is the floor because it was the fixed level before, and decoders
/// take the DPB size from `max_dec_frame_buffering` rather than from the level,
/// so a lower one would buy nothing. Above 1080p (a 1440p or 4K screen share) a
/// fixed level 4 would declare a stream its decoder may refuse.
fn level(width: u32, height: u32, framerate: u32) -> Level {
	// H.264 Table A-1: (level, MaxMBPS, MaxFS).
	const LEVELS: [(Level, u64, u64); 8] = [
		(Level::L4, 245_760, 8_192),
		(Level::L4_2, 522_240, 8_704),
		(Level::L5, 589_824, 22_080),
		(Level::L5_1, 983_040, 36_864),
		(Level::L5_2, 2_073_600, 36_864),
		(Level::L6, 4_177_920, 139_264),
		(Level::L6_1, 8_355_840, 139_264),
		(Level::L6_2, 16_711_680, 139_264),
	];
	let (width_mbs, height_mbs) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
	let frame = width_mbs * height_mbs;
	let rate = frame * u64::from(framerate.max(1));
	// A.3.1 also bounds each side: PicWidthInMbs² and FrameHeightInMbs² <= 8 * MaxFS.
	let side = width_mbs.max(height_mbs);
	LEVELS
		.into_iter()
		.find(|&(_, max_rate, max_frame)| frame <= max_frame && side * side <= 8 * max_frame && rate <= max_rate)
		.map(|(level, _, _)| level)
		.unwrap_or(Level::L6_2)
}

/// Returns the HRD buffer in bits for `bitrate`: [`HRD_FRAMES`] frames of it.
fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
	(u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
}

/// Returns the coded buffer size in bytes for `bitrate`: two seconds of it, and at least 1.5 MB.
fn coded_size(bitrate: u32) -> usize {
	(bitrate as usize / 4).max(1_500_000)
}

/// Returns whether the VA fourcc `fourcc` is packed RGB, which has no YUV matrix of its own.
fn is_rgb(fourcc: u32) -> bool {
	matches!(
		fourcc,
		VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
	)
}

/// Allocate one NV12 encode surface.
fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
	let mut surfaces = display
		.create_surfaces::<()>(
			VA_RT_FORMAT_YUV420,
			Some(VA_FOURCC_NV12),
			width,
			height,
			Some(UsageHint::USAGE_HINT_ENCODER),
			vec![()],
		)
		.map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
	surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
}

/// Uploads tightly-packed NV12 into `surface` through an image in `format`,
/// honoring the image's per-plane offsets and pitches, without reading the
/// surface back first.
fn upload_nv12(
	format: VAImageFormat,
	surface: &mut Surface<()>,
	width: u32,
	height: u32,
	data: &[u8],
) -> anyhow::Result<()> {
	let (w, h) = (width as usize, height as usize);
	let luma = w * h;
	let expected = luma + w * (h / 2);
	if data.len() < expected {
		anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
	}

	let mut image =
		ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
	let va_image = *image.image();
	let dest: &mut [u8] = image.as_mut();
	let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
	for (plane, (src, rows)) in planes.into_iter().enumerate() {
		let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
		fill_plane(dest, offset, pitch, src, w, rows)?;
	}
	image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
}

/// Copies `rows` rows of `width` bytes from tightly packed `src` into the image
/// plane at `offset` with `pitch` bytes per row, failing when the plane does
/// not hold them.
fn fill_plane(
	dst: &mut [u8],
	offset: usize,
	pitch: usize,
	src: &[u8],
	width: usize,
	rows: usize,
) -> anyhow::Result<()> {
	if rows == 0 || width == 0 {
		return Ok(());
	}
	// The last row needs only `width` bytes, not a whole pitch.
	let end = (rows - 1)
		.checked_mul(pitch)
		.and_then(|start| start.checked_add(offset)?.checked_add(width));
	if pitch < width || end.is_none_or(|end| end > dst.len()) {
		anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
	}
	for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
		let start = offset + row * pitch;
		dst[start..start + width].copy_from_slice(src);
	}
	Ok(())
}

/// Build the SPS/PPS for a low-latency IPPP stream. Ported from
/// discord/cros-codecs `LowDelayH264Delegate::new_sequence` (BSD-3-Clause).
///
/// Fails when the frame is larger than the highest level allows.
fn build_sps_pps(config: &Config) -> anyhow::Result<(Sps, Pps)> {
	let (primaries, transfer, matrix) = config.color.vui();
	let vui = Vui {
		aspect_ratio: Some(AspectRatio {
			idc: 1, // 1:1, square samples (Table E-1)
			sar_width: 0,
			sar_height: 0,
		}),
		overscan_appropriate: None,
		video_signal: Some(VideoSignal {
			video_format: 5, // unspecified, what a decoder infers when it is absent
			full_range: config.color.full_range,
			colour: Some(Colour {
				primaries,
				transfer,
				matrix,
			}),
		}),
		chroma_loc: None,
		timing: Some(Timing {
			num_units_in_tick: 1,
			// A frame rate of 0 (unknown) writes 1, as the H.265 VUI does, since a zero time_scale is invalid.
			time_scale: config.framerate.max(1) * 2,
			fixed_frame_rate: false,
		}),
		nal_hrd: None,
		vcl_hrd: None,
		low_delay_hrd: false,
		pic_struct_present: false,
		// E.2.1's inferred values, but for the reordering and buffering an IPPP
		// stream needs.
		restriction: Some(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: 0,
			max_dec_frame_buffering: 1,
		}),
	};
	let sps = SpsBuilder::new(Profile::Main, level(config.width, config.height, config.framerate))
		.log2_max_frame_num(LIMIT.ilog2() as u8)
		.pic_order_cnt(PicOrderCnt::Lsb {
			log2_max_lsb: (LIMIT * 2).ilog2() as u8,
		})
		.max_num_ref_frames(1)
		.resolution(config.width, config.height)
		.vui(vui)
		.build()
		.context("build the SPS")?;

	let pps = PpsBuilder::new(&sps)
		.entropy_coding_mode(true)
		.deblocking_filter_control_present(true)
		.build()
		.context("build the PPS")?;

	Ok((sps, pps))
}

/// Returns the parameter buffers of one H.264 picture, then the packed headers the driver takes: the SPS and PPS on an IDR, and the slice header.
fn h264_buffers(sps: &Sps, pps: &Pps, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
	let meta = FrameMeta::new(picture.count);
	// Every picture is a short-term reference, an IDR the strongest.
	let (slice_type, nal) = match picture.idr {
		true => (
			SliceType::I,
			NaluHeader {
				ref_idc: 3,
				type_: NaluType::SliceIdr,
			},
		),
		false => (
			SliceType::P,
			NaluHeader {
				ref_idc: 1,
				type_: NaluType::Slice,
			},
		),
	};
	let mut builder = SliceHeaderBuilder::new(sps, pps, slice_type)
		.frame_num(meta.frame_num)
		.pic_order_cnt_lsb(meta.poc % (LIMIT * 2));
	if picture.idr {
		// Only consecutive IDRs must differ.
		builder = builder.idr_pic_id(picture.idr_id % 2);
	}
	let header = builder.build(nal).context("build the slice header")?;
	let macroblocks = sps.width_mbs * sps.height_mbs;
	let reference = picture
		.reference
		.map(|reference| (reference.surface, FrameMeta::new(reference.count)));

	let mut buffers = vec![
		build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
		build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
		build_enc_slice_param(pps, &header, reference, macroblocks),
	];
	if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
		buffers.extend(packed_parameter_sets(sps, pps)?);
	}
	if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
		let mut out = Vec::new();
		let trailing = header
			.write(nal, sps, pps, &mut out)
			.context("write the slice header")?;
		// The slice data follows the header's last bit, not its padded last byte.
		let bits = out.len() * 8 - usize::from(trailing);
		buffers.extend(packed_header(EncPackedHeaderType::Slice, &out, bits));
	}
	Ok(buffers)
}

/// Returns the SPS and PPS as packed headers, which go out with every IDR.
fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
	let mut sps_nal = Vec::new();
	sps.write(3, &mut sps_nal).context("write the SPS")?;
	let mut pps_nal = Vec::new();
	pps.write(3, &mut pps_nal).context("write the PPS")?;

	let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
	let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
	Ok([sps_param, sps_data, pps_param, pps_data])
}

fn build_invalid_pic() -> PictureH264 {
	PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
}

fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
	PictureH264::new(
		surface_id,
		meta.frame_num,
		VA_PICTURE_H264_SHORT_TERM_REFERENCE,
		meta.poc as i32,
		meta.poc as i32,
	)
}

/// Ported from cros-codecs `build_enc_seq_param` (BSD-3-Clause).
fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
	let (log2_max_lsb, delta_always_zero, offset_for_non_ref_pic, offset_for_top_to_bottom_field, cycle) =
		match &sps.pic_order_cnt {
			PicOrderCnt::Lsb { log2_max_lsb } => (*log2_max_lsb, false, 0, 0, &[][..]),
			PicOrderCnt::Cycle {
				delta_always_zero,
				offset_for_non_ref_pic,
				offset_for_top_to_bottom_field,
				offset_for_ref_frame,
			} => (
				4,
				*delta_always_zero,
				*offset_for_non_ref_pic,
				*offset_for_top_to_bottom_field,
				&offset_for_ref_frame[..],
			),
			PicOrderCnt::Decode => (4, false, 0, 0, &[][..]),
		};
	let seq_fields = H264EncSeqFields::new(
		1, // chroma_format_idc: 4:2:0
		1, // frame_mbs_only_flag
		0, // mb_adaptive_frame_field_flag
		sps.scaling.is_some() as u32,
		sps.direct_8x8_inference as u32,
		u32::from(sps.log2_max_frame_num - 4),
		poc_type(&sps.pic_order_cnt),
		u32::from(log2_max_lsb - 4),
		delta_always_zero as u32,
	);

	// VA takes the offsets in 4:2:0 crop units, two luma samples each.
	let frame_crop = sps
		.crop
		.map(|crop| H264EncFrameCropOffsets::new(crop.left / 2, crop.right / 2, crop.top / 2, crop.bottom / 2));

	let vui = sps.vui.as_ref();
	let aspect_ratio = vui.and_then(|vui| vui.aspect_ratio);
	let timing = vui.and_then(|vui| vui.timing);
	let restriction = vui.and_then(|vui| vui.restriction);
	let vui_fields = vui.map(|vui| {
		H264VuiFields::new(
			aspect_ratio.is_some() as u32,
			timing.is_some() as u32,
			restriction.is_some() as u32,
			restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_horizontal)),
			restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_vertical)),
			timing.is_some_and(|t| t.fixed_frame_rate) as u32,
			vui.low_delay_hrd as u32,
			restriction.is_some_and(|r| r.motion_vectors_over_pic_boundaries) as u32,
		)
	});

	let mut offset_for_ref_frame = [0i32; 256];
	offset_for_ref_frame[..cycle.len()].copy_from_slice(cycle);

	// The parser bounds the frame to 1055 macroblocks a side.
	BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
		sps.id,
		sps.level.value(),
		intra_period,
		intra_period,
		ip_period,
		bits_per_second,
		u32::from(sps.max_num_ref_frames),
		sps.width_mbs as u16,
		sps.height_mbs as u16,
		&seq_fields,
		0, // bit_depth_luma_minus8
		0, // bit_depth_chroma_minus8
		cycle.len() as u8,
		offset_for_non_ref_pic,
		offset_for_top_to_bottom_field,
		offset_for_ref_frame,
		frame_crop,
		vui_fields,
		aspect_ratio.map_or(0, |a| a.idc),
		aspect_ratio.map_or(0, |a| u32::from(a.sar_width)),
		aspect_ratio.map_or(0, |a| u32::from(a.sar_height)),
		timing.map_or(0, |t| t.num_units_in_tick),
		timing.map_or(0, |t| t.time_scale),
	)))
}

/// Returns `pic_order_cnt_type`.
fn poc_type(poc: &PicOrderCnt) -> u32 {
	match poc {
		PicOrderCnt::Lsb { .. } => 0,
		PicOrderCnt::Cycle { .. } => 1,
		PicOrderCnt::Decode => 2,
	}
}

/// Ported from cros-codecs `build_enc_pic_param` (BSD-3-Clause).
fn build_enc_pic_param(
	pps: &Pps,
	coded: &EncCodedBuffer,
	recon_id: u32,
	meta: FrameMeta,
	is_idr: bool,
	reference: Option<(u32, FrameMeta)>,
) -> BufferType {
	let pic_fields = H264EncPicFields::new(
		is_idr as u32,
		1, // reference_pic_flag: this frame is a short-term reference
		pps.entropy_coding_mode as u32,
		pps.weighted_pred as u32,
		u32::from(pps.weighted_bipred_idc),
		pps.constrained_intra_pred as u32,
		pps.transform_8x8_mode as u32,
		pps.deblocking_filter_control_present as u32,
		pps.redundant_pic_cnt_present as u32,
		0,
		pps.scaling.is_some() as u32,
	);

	let curr_pic = build_h264_pic(recon_id, meta);
	let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
	if let Some((id, m)) = reference {
		reference_frames[0] = build_h264_pic(id, m);
	}

	// The parser bounds each value to the VA field's range.
	BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
		curr_pic,
		reference_frames,
		coded.id(),
		pps.id,
		pps.sps_id,
		0,
		meta.frame_num as u16,
		pps.pic_init_qp as u8,
		pps.num_ref_idx_l0_default_active - 1,
		pps.num_ref_idx_l1_default_active - 1,
		pps.chroma_qp_index_offset as i8,
		pps.second_chroma_qp_index_offset as i8,
		&pic_fields,
	)))
}

/// Ported from cros-codecs `build_enc_slice_param` (BSD-3-Clause), simplified for
/// IPPP (no weighted prediction, single reference in list 0).
fn build_enc_slice_param(
	pps: &Pps,
	header: &SliceHeader,
	reference: Option<(u32, FrameMeta)>,
	num_macroblocks: u32,
) -> BufferType {
	let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
	if let Some((id, m)) = reference {
		ref_pic_list_0[0] = build_h264_pic(id, m);
	}
	let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());

	// The header holds the counts in effect, the PPS's defaults unless it
	// overrides them; an I slice uses neither.
	let override_counts = match header.slice_type {
		SliceType::I => false,
		SliceType::P => header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active,
		SliceType::B => {
			header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active
				|| header.num_ref_idx_l1_active != pps.num_ref_idx_l1_default_active
		}
	};
	let (l0, l1) = match override_counts {
		true => (header.num_ref_idx_l0_active, header.num_ref_idx_l1_active),
		false => (pps.num_ref_idx_l0_default_active, pps.num_ref_idx_l1_default_active),
	};

	// The parser bounds each value to the VA field's range.
	BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
		header.first_mb_in_slice,
		num_macroblocks,
		VA_INVALID_ID,
		header.slice_type_raw % 5,
		pps.id,
		header.idr_pic_id.unwrap_or(0) as u16,
		header.pic_order_cnt_lsb as u16,
		header.delta_pic_order_cnt_bottom,
		header.delta_pic_order_cnt,
		header.direct_spatial_mv_pred as u8,
		override_counts as u8,
		l0.saturating_sub(1),
		l1.saturating_sub(1),
		ref_pic_list_0,
		ref_pic_list_1,
		0,
		0,
		0,
		[0i16; 32],
		[0i16; 32],
		0,
		[[0i16; 2]; 32],
		[[0i16; 2]; 32],
		0,
		[0i16; 32],
		[0i16; 32],
		0,
		[[0i16; 2]; 32],
		[[0i16; 2]; 32],
		header.cabac_init_idc,
		(header.slice_qp - pps.pic_init_qp) as i8,
		header.disable_deblocking_filter_idc,
		header.slice_alpha_c0_offset_div2 as i8,
		header.slice_beta_offset_div2 as i8,
	)))
}

/// Returns the packed-header parameter and data buffers for the first `bits` of `data`, a NAL unit that carries its own emulation prevention.
fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
	let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
	let payload = BufferType::EncPackedHeaderData(data.to_vec());
	[param, payload]
}

#[cfg(test)]
mod tests {
	use std::path::PathBuf;
	use std::process::Command;
	use std::sync::atomic::{AtomicU32, Ordering};

	use super::*;
	use crate::dmabuf::DmaBuf;
	use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};

	// A size every driver encodes: radeonsi's H.265 minimum on VCN 5 is 384 wide.
	const WIDTH: u32 = 640;
	const HEIGHT: u32 = 480;
	const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];

	fn config(codec: Codec) -> Config {
		Config {
			codec,
			width: WIDTH,
			height: HEIGHT,
			framerate: 30,
			bitrate: 2_000_000,
			gop: NonZeroU32::new(30).unwrap(),
			device: None,
			color: Color::infer(HEIGHT),
		}
	}

	fn encoder(config: Config) -> Encoder {
		Encoder::new(config).expect("open the VA-API encoder")
	}

	/// The NAL unit types that open an IDR access unit: the IDR slice, then the parameter sets it carries.
	fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
		match codec {
			Codec::H264 => (5, &[7, 8]),
			Codec::H265 => (19, &[32, 33, 34]),
		}
	}

	/// A diagonal gradient with a block moving across it, so a stale or
	/// misplaced reference shows up as the block 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 + w * h.div_ceil(2)];
		for y in 0..h {
			for x in 0..w {
				data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
			}
		}
		let x0 = (step as usize * 8) % (w / 2);
		for y in h / 4..h / 2 {
			for x in x0..x0 + w / 4 {
				data[y * w + x] = 220;
			}
		}
		data
	}

	/// Returns a temporary file path unique to this call.
	///
	/// The tests run as threads of one process, so the process id alone would
	/// let two of them share a file.
	///
	/// Its extension names `codec`, for ffmpeg to pick the demuxer by.
	fn temp_path(codec: Codec, label: &str) -> PathBuf {
		static NEXT: AtomicU32 = AtomicU32::new(0);
		let index = NEXT.fetch_add(1, Ordering::Relaxed);
		let extension = match codec {
			Codec::H264 => "264",
			Codec::H265 => "265",
		};
		std::env::temp_dir().join(format!(
			"kodecs-vaapi-{label}-{}-{index}.{extension}",
			std::process::id()
		))
	}

	/// Decodes an Annex-B stream with ffmpeg's software decoder into NV12
	/// pictures.
	fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> 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.
		let path = temp_path(codec, name);
		std::fs::write(&path, stream).expect("write the elementary stream");
		let output = Command::new("ffmpeg")
			.args(["-v", "error", "-i"])
			.arg(&path)
			.args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
			.output();
		let _ = std::fs::remove_file(&path);
		let output = output.expect("run ffmpeg");
		assert!(
			output.status.success(),
			"ffmpeg refused the stream: {}",
			String::from_utf8_lossy(&output.stderr)
		);
		output.stdout
	}

	/// Asks ffprobe for the stream's `color_range,color_space`.
	fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
		let path = temp_path(codec, "probe");
		std::fs::write(&path, stream).expect("write the elementary stream");
		let output = Command::new("ffprobe")
			.args([
				"-v",
				"error",
				"-show_entries",
				"stream=color_range,color_space",
				"-of",
				"csv=p=0",
			])
			.arg(&path)
			.output()
			.ok();
		let _ = std::fs::remove_file(&path);
		Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
	}

	/// Returns the peak signal-to-noise ratio of the luma planes, in dB.
	fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
		let len = (width * height) as usize;
		let mse = a[..len]
			.iter()
			.zip(&b[..len])
			.map(|(&x, &y)| (x as f64 - y as f64).powi(2))
			.sum::<f64>()
			/ len as f64;
		10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
	}

	/// Returns the mean of the samples in a rectangle of one plane.
	fn mean(
		plane: &[u8],
		stride: usize,
		(x0, y0, x1, y1): (usize, usize, usize, usize),
		step: usize,
		at: usize,
	) -> f64 {
		let mut sum = 0.0;
		let mut count = 0.0;
		for y in y0..y1 {
			for x in x0..x1 {
				sum += plane[y * stride + x * step + at] as f64;
				count += 1.0;
			}
		}
		sum / count
	}

	/// Returns the NAL unit types in an Annex-B access unit.
	fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
		let mut types = Vec::new();
		let mut i = 0;
		while i + 3 < unit.len() {
			if unit[i..i + 3] == [0, 0, 1] {
				types.push(match codec {
					Codec::H264 => unit[i + 3] & 0x1f,
					Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
				});
				i += 3;
			}
			i += 1;
		}
		types
	}

	/// Returns a driver surface of `fourcc` on `display` whose pixels are unspecified.
	fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
		display
			.create_surfaces(
				rt_format,
				Some(fourcc),
				width,
				height,
				Some(UsageHint::USAGE_HINT_EXPORT),
				vec![()],
			)
			.expect("allocate a surface")
			.pop()
			.expect("one surface")
	}

	/// Returns the driver's image format for `fourcc`.
	fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
		display
			.query_image_formats()
			.expect("query image formats")
			.into_iter()
			.find(|f| f.fourcc == fourcc)
			.expect("the driver has an image format for the surface format")
	}

	/// Returns a driver surface of `fourcc` on `display`, every pixel written by `fill` through an image.
	fn surface_with(
		display: &Arc<Display>,
		fourcc: u32,
		rt_format: u32,
		size: (u32, u32),
		fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage),
	) -> Surface<()> {
		let mut surface = blank_surface(display, fourcc, rt_format, size);
		let mut image =
			ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
		let va_image = *image.image();
		fill(image.as_mut(), &va_image);
		image.put().expect("put the image");
		surface.sync().expect("sync the filled surface");
		surface
	}

	/// Returns an NV12 surface holding `nv12_frame`, exported as a DMA-BUF.
	fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
		let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
		let format = image_format(display, VA_FOURCC_NV12);
		upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
		DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
	}

	/// With no node named, the encoder opens one that encodes its codec and
	/// records which. 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() {
		for codec in CODECS {
			let encoder = encoder(config(codec));
			let device = encoder.config().device.clone().expect("the picked node is recorded");
			let display = Display::open_drm_display(&device).expect("reopen the picked node");
			probe(&display, codec).expect("the picked node encodes the codec");

			let named = Config {
				device: Some(PathBuf::from("/dev/null")),
				..config(codec)
			};
			assert!(
				Encoder::new(named).is_err(),
				"a named node that is not a render node was swapped for one that is"
			);
		}
	}

	/// CPU NV12 in, a stream out that an independent decoder reads back as the
	/// same pictures, at a size that is whole coding blocks and at one that is not.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn nv12_round_trips_through_a_software_decoder() {
		for codec in CODECS {
			for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
				let mut encoder = encoder(Config {
					width,
					height,
					..config(codec)
				});
				let mut stream = Vec::new();
				let mut frames = Vec::new();
				for step in 0..10 {
					let frame = nv12_frame(width, height, step);
					stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
					frames.push(frame);
				}
				let decoded = ffmpeg_decode(codec, &stream, "nv12");
				let len = frames[0].len();
				assert_eq!(
					decoded.len(),
					len * frames.len(),
					"{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
				);
				for (index, frame) in frames.iter().enumerate() {
					let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
					assert!(
						psnr > 35.0,
						"{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
					);
				}
			}
		}
	}

	/// The SPS names the color space the encoder was configured with.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn the_stream_is_labelled_with_its_color_space() {
		for codec in CODECS {
			for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
				let mut encoder = encoder(Config { color, ..config(codec) });
				let unit = encoder
					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
					.expect("encode");
				let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
				assert_eq!(found, expected, "{codec:?}");
			}
		}
	}

	/// A plane fills when its last row holds just the frame's width, not a
	/// whole pitch, and fails rather than panics when it holds less.
	#[test]
	fn a_plane_fills_up_to_its_last_byte_and_no_further() {
		let src = [1, 2, 3, 4, 5, 6];
		// Three rows of two bytes at a pitch of four, starting at offset one:
		// the last row ends at byte 1 + 2 * 4 + 2 = 11.
		let mut tight = [0; 11];
		fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
		assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);

		assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
		assert!(
			fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
			"a pitch narrower than a row"
		);
		assert!(
			fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
			"a pitch that overflows"
		);
		fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
	}

	/// A bound holds on the coded size, and an absent bound holds nothing back.
	#[test]
	fn limits_check_the_coded_size_against_each_bound() {
		let limits = Limits {
			min_width: Some(384),
			min_height: None,
			max_width: Some(4096),
			max_height: Some(2304),
			round: (64, 16),
		};
		for (width, height) in [(384, 2), (322, 2304), (4096, 128)] {
			limits.check(width, height).expect("inside every bound");
		}
		for (width, height, named) in [
			(320, 240, "minimum encode width of 384"),
			(4098, 240, "maximum encode width of 4096"),
			(640, 2306, "maximum encode height of 2304"),
			(u32::MAX - 1, 240, "maximum encode width of 4096"),
		] {
			let err = limits.check(width, height).expect_err("outside a bound");
			assert!(err.to_string().contains(named), "{width}x{height}: {err:#}");
		}

		let unknown = Limits {
			min_width: None,
			min_height: None,
			max_width: None,
			max_height: None,
			round: (1, 1),
		};
		unknown.check(2, 2).expect("no bound to break");
		unknown.check(u32::MAX, u32::MAX).expect("no bound to break");
	}

	/// On every node that encodes, a frame whose coded width falls under the
	/// driver's minimum is refused naming it, and the narrowest frame coded at
	/// the minimum encodes, so the driver bounds the coded size rather than the
	/// frame's own.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn a_frame_under_the_minimum_width_is_refused_naming_it() {
		let mut probed = 0;
		for device in crate::DrmDeviceIterator::default() {
			let display = Display::open_drm_display(&device).expect("open a render node");
			let vendor = display.query_vendor_string().unwrap_or_default();
			for codec in CODECS {
				let Ok(limits) = probe(&display, codec) else { continue };
				eprintln!("{device:?} ({vendor}) {codec:?}: {limits:?}");
				probed += 1;
				let min = limits.min_width.expect("the driver names a minimum width");
				// The widest frame coded under the minimum, and the narrowest coded at or above it.
				let step = limits.round.0.max(2);
				let (under, over) = ((min - 1) / step * step, min.next_multiple_of(step) - step + 2);
				let named = |width| Config {
					width,
					device: Some(device.clone()),
					..config(codec)
				};
				if under > 0 {
					let err = Encoder::new(named(under))
						.err()
						.expect("a frame under the minimum is refused");
					let wanted = format!("minimum encode width of {min}");
					assert!(err.to_string().contains(&wanted), "{codec:?} {under} wide: {err:#}");
				}
				let mut encoder =
					Encoder::new(named(over)).unwrap_or_else(|e| panic!("{device:?} {codec:?} {over} wide: {e:#}"));
				let frame = encoder.encode_nv12(&nv12_frame(over, HEIGHT, 0), true);
				assert!(
					!frame.expect("encode").is_empty(),
					"{device:?} {codec:?} {over} wide coded nothing"
				);
			}
		}
		assert!(probed > 0, "no render node encodes");
	}

	/// A size 4:2:0 chroma cannot halve is refused before any device opens.
	#[test]
	fn an_odd_or_empty_size_is_refused() {
		for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
			let err = Encoder::new(Config {
				width,
				height,
				..config(Codec::H264)
			})
			.err()
			.expect("refused");
			assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
		}
	}

	/// The write-only upload puts exactly the frame's pixels into the surface,
	/// as a `vaGetImage` read-back of it sees them.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn an_upload_reads_back_as_the_same_pixels() {
		let display = Display::open().expect("no VA-API display");
		for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
			let frame = nv12_frame(width, height, 3);
			let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
			let format = image_format(&display, VA_FOURCC_NV12);
			upload_nv12(format, &mut surface, width, height, &frame).expect("upload");

			let image =
				crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
			let (va_image, data) = (*image.image(), image.as_ref());
			let (w, h) = (width as usize, height as usize);
			for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
				let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
				for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
					let at = offset + row * pitch;
					assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
				}
			}
		}
	}

	/// An IDR opens every group, and only there, carrying the parameter sets.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn keyframes_follow_the_group_length() {
		for codec in CODECS {
			let mut encoder = encoder(Config {
				gop: NonZeroU32::new(10).unwrap(),
				..config(codec)
			});
			let (idr_type, parameter_sets) = idr_types(codec);
			for step in 0..25 {
				let unit = encoder
					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
					.expect("encode");
				let types = nal_types(codec, &unit);
				let idr = types.contains(&idr_type);
				assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
				if idr {
					assert!(
						parameter_sets.iter().all(|kind| types.contains(kind)),
						"a {codec:?} IDR carries its parameter sets: {types:?}"
					);
				}
			}
			// A forced keyframe restarts the count: the next IDR is a group later.
			for step in 0..=10 {
				let unit = encoder
					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
					.expect("encode");
				assert_eq!(
					nal_types(codec, &unit).contains(&idr_type),
					step % 10 == 0,
					"{codec:?} frame {step} after the forced keyframe"
				);
			}
		}
	}

	#[test]
	fn the_full_entrypoint_wins_and_low_power_is_the_fallback() {
		use VAEntrypoint::{
			VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode,
		};
		assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full));
		assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower));
		assert_eq!(pick_entrypoint(&[Decode]), None);
	}

	/// A buffer the driver refuses leaves the encoder usable, so the caller's
	/// CPU fallback can encode the same frame.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_refused_import_leaves_the_encoder_usable() {
		let mut encoder = encoder(config(Codec::H264));
		let display = Display::open().expect("no VA-API display");
		// A format with no mapping, and a real buffer under a modifier no driver has.
		let unmapped = DmaBuf {
			drm_format: u32::from_le_bytes(*b"ZZZZ"),
			..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
		};
		assert!(encoder.encode_dmabuf(unmapped, true).is_err());
		let unknown_modifier = DmaBuf {
			modifier: 0x00ff_ffff_ffff_fffe,
			..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
		};
		assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());

		let unit = encoder
			.encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
			.expect("the CPU path still encodes");
		let decoded = ffmpeg_decode(Codec::H264, &unit, "refused");
		let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
		assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
	}

	/// A buffer short of whole coding blocks is not encoded in place: the
	/// encoder reads whole blocks, so it goes through the video processor into
	/// the padded input surface. That is 1080 rows for H.264, which reads 1088,
	/// and 1076 for H.265, whose minimum coding blocks are 8 or 16 rows.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
		for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
			let mut encoder = encoder(Config {
				width,
				height,
				bitrate: 4_000_000,
				color: Color::infer(height),
				..config(codec)
			});
			let display = Display::open().expect("no VA-API display");
			let unit = encoder
				.encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
				.expect("encode the DMA-BUF");
			let decoded = ffmpeg_decode(codec, &unit, "short");
			let frame = nv12_frame(width, height, 0);
			assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
			let psnr = luma_psnr(&frame, &decoded, width, height);
			assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
		}
	}

	/// A YUV buffer labelled with another color space is converted into the
	/// stream's, not relabelled.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_yuv_dmabuf_in_another_space_is_converted() {
		for codec in CODECS {
			yuv_dmabuf_in_another_space_is_converted(codec);
		}
	}

	fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) {
		let mut encoder = encoder(Config {
			color: Color::BT601,
			..config(codec)
		});
		let display = Display::open().expect("no VA-API display");
		// Flat red, written in BT.709.
		let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
		let surface = surface_with(
			&display,
			VA_FOURCC_NV12,
			VA_RT_FORMAT_YUV420,
			(WIDTH, HEIGHT),
			|data, image| {
				for row in 0..HEIGHT as usize {
					let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
					data[at..at + WIDTH as usize].fill(y);
				}
				for row in 0..HEIGHT as usize / 2 {
					let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
					for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
						pair.copy_from_slice(&[u, v]);
					}
				}
			},
		);
		let buffer = DmaBuf {
			color: Some(Color::BT709),
			..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
		};
		let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
		let decoded = ffmpeg_decode(codec, &unit, "yuv-color");

		let (w, h) = (WIDTH as usize, HEIGHT as usize);
		let (luma, chroma) = decoded.split_at(w * h);
		let actual = [
			mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
			mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
			mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
		];
		let expected = limited([255, 0, 0], Color::BT601);
		for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
			assert!(
				(a - e).abs() < 6.0,
				"{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
			);
		}
	}

	/// An NV12 DMA-BUF at the encoder's size is encoded from the producer's memory.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn an_nv12_dmabuf_encodes_in_place() {
		for codec in CODECS {
			let mut encoder = encoder(config(codec));
			let display = Display::open().expect("no VA-API display");
			let mut stream = Vec::new();
			for step in 0..5 {
				let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
				stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
			}
			let decoded = ffmpeg_decode(codec, &stream, "dmabuf");
			let len = nv12_frame(WIDTH, HEIGHT, 0).len();
			assert_eq!(decoded.len(), 5 * len, "{codec:?}");
			for step in 0..5 {
				let psnr = luma_psnr(
					&nv12_frame(WIDTH, HEIGHT, step),
					&decoded[step as usize * len..],
					WIDTH,
					HEIGHT,
				);
				assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
			}
		}
	}

	/// An NV12 DMA-BUF at another size is scaled to the encoder's on the GPU.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn a_dmabuf_at_another_size_is_scaled() {
		for codec in CODECS {
			dmabuf_at_another_size_is_scaled(codec);
		}
	}

	fn dmabuf_at_another_size_is_scaled(codec: Codec) {
		let mut encoder = encoder(config(codec));
		let display = Display::open().expect("no VA-API display");
		let mut stream = Vec::new();
		for step in 0..3 {
			let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
			stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
		}
		let decoded = ffmpeg_decode(codec, &stream, "scaled");
		let len = nv12_frame(WIDTH, HEIGHT, 0).len();
		assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
		// Compare against the source scaled on the CPU by point sampling, which
		// differs from the GPU filter only at edges. 25 dB separates a scale
		// from a crop, which scores about 16 dB on this gradient.
		for step in 0..3u32 {
			let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
			let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
			for y in 0..HEIGHT as usize {
				for x in 0..WIDTH as usize {
					expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
				}
			}
			let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
			assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
		}
	}

	/// A packed RGB DMA-BUF is converted on the GPU into the configured color space.
	#[test]
	#[ignore = "requires a VA-API render node and FFmpeg"]
	fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
		// Four flat quadrants, so the check reads colors rather than edges.
		const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
		for (codec, color) in CODECS
			.into_iter()
			.flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
		{
			let mut encoder = encoder(Config { color, ..config(codec) });
			let display = Display::open().expect("no VA-API display");
			let surface = surface_with(
				&display,
				VA_FOURCC_BGRX,
				VA_RT_FORMAT_RGB32,
				(WIDTH, HEIGHT),
				|data, image| {
					let pitch = image.pitches[0] as usize;
					let offset = image.offsets[0] as usize;
					for y in 0..HEIGHT as usize {
						for x in 0..WIDTH as usize {
							let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
							let [r, g, b] = QUADRANTS[quadrant];
							let at = offset + y * pitch + x * 4;
							data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
						}
					}
				},
			);
			let exported = surface.export_prime().expect("export");
			let buffer = DmaBuf::from_prime(exported).expect("one object");
			assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
			let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
			let decoded = ffmpeg_decode(codec, &unit, "rgb");

			let (w, h) = (WIDTH as usize, HEIGHT as usize);
			let (luma, chroma) = decoded.split_at(w * h);
			for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
				let (qx, qy) = (quadrant % 2, quadrant / 2);
				// The middle half of each quadrant, clear of the chroma bleed at its edges.
				let area = |scale: usize| {
					let (qw, qh) = (w / 2 / scale, h / 2 / scale);
					(
						qx * qw + qw / 4,
						qy * qh + qh / 4,
						qx * qw + qw * 3 / 4,
						qy * qh + qh * 3 / 4,
					)
				};
				let actual = [
					mean(luma, w, area(1), 1, 0),
					mean(chroma, w, area(2), 2, 0),
					mean(chroma, w, area(2), 2, 1),
				];
				let expected = limited(*rgb, color);
				for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
					assert!(
						(a - e).abs() < 6.0,
						"{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
					);
				}
			}
		}
	}

	#[test]
	fn the_level_covers_the_frame_size_and_rate() {
		assert_eq!(level(320, 240, 30), Level::L4);
		assert_eq!(level(1920, 1080, 30), Level::L4);
		assert_eq!(level(1920, 1080, 60), Level::L4_2);
		assert_eq!(level(2560, 1440, 30), Level::L5);
		assert_eq!(level(3840, 2160, 30), Level::L5_1);
		assert_eq!(level(3840, 2160, 60), Level::L5_2);
		// 4080 macroblocks fit level 4's MaxFS, but 272 macroblocks across do not.
		assert_eq!(level(4352, 240, 30), Level::L5);
	}

	#[test]
	fn an_unknown_framerate_still_builds_the_parameter_sets() {
		build_sps_pps(&Config {
			framerate: 0,
			..config(Codec::H264)
		})
		.expect("build the SPS and PPS for framerate 0");
	}

	/// Returns the limited-range Y'CbCr of an RGB color, per BT.601 or BT.709.
	fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
		let (kr, kb) = match color.matrix {
			crate::Matrix::Bt601 => (0.299, 0.114),
			crate::Matrix::Bt709 => (0.2126, 0.0722),
		};
		let (r, g, b) = (r as f64, g as f64, b as f64);
		let y = kr * r + (1.0 - kr - kb) * g + kb * b;
		[
			16.0 + y * 219.0 / 255.0,
			128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
			128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
		]
	}

	/// Lowering the bitrate mid-stream shrinks the pictures without an IDR, and
	/// the rate controller holds the stream near each target.
	#[test]
	#[ignore = "requires a VA-API render node"]
	fn a_bitrate_change_takes_effect_without_a_keyframe() {
		for codec in CODECS {
			bitrate_change_takes_effect_without_a_keyframe(codec);
		}
	}

	fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) {
		let mut encoder = encoder(Config {
			gop: NonZeroU32::new(1_000).unwrap(),
			..config(codec)
		});
		let (idr_type, _) = idr_types(codec);
		// A zone plate whose phase moves every picture: detail motion
		// compensation cannot predict, so 2 Mbps is spent, yet the drivers
		// can code it at 250 kbps when the quantizer may go high enough.
		let frame = |step: u32| {
			let (w, h) = (WIDTH as usize, HEIGHT as usize);
			let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
			for y in 0..h {
				for x in 0..w {
					let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
					let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
					frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
				}
			}
			frame
		};
		// The mean picture size over the second half of 60 frames, once the
		// rate controller has settled.
		// Also asserts that no picture after the first is an IDR.
		let average = |encoder: &mut Encoder, from: u32| {
			let sizes: Vec<usize> = (from..from + 60)
				.map(|step| {
					let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
					if step > 0 {
						assert!(
							!nal_types(codec, &unit).contains(&idr_type),
							"{codec:?} picture {step} is an IDR"
						);
					}
					unit.len()
				})
				.collect();
			sizes[30..].iter().sum::<usize>() / 30
		};

		// A settled stream within a quarter above its target; a quantizer
		// ceiling the rate controller cannot get past misses by double or more.
		let within = |bytes: usize, bitrate: u32| {
			let target = bitrate as usize / 8 / 30;
			assert!(
				bytes * 4 <= target * 5,
				"{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
			);
		};

		let high = average(&mut encoder, 0);
		within(high, 2_000_000);
		encoder.set_bitrate(250_000).expect("set the bitrate");
		assert_eq!(encoder.config().bitrate, 250_000);
		assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
		let low = average(&mut encoder, 60);
		eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
		within(low, 250_000);
		assert!(
			low * 3 < high,
			"{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
		);
	}
}