1use std::num::NonZeroU32;
37use std::ops::RangeInclusive;
38use std::path::PathBuf;
39use std::rc::Rc;
40use std::sync::Arc;
41
42use anyhow::Context as _;
43
44use crate::codec::Codec;
45use crate::dmabuf::DmaBuf;
46use crate::vpp::Processor;
47use crate::{
48 BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter,
49 EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter,
50 EncPackedHeaderType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
51 EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264, GenericValue,
52 H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture,
53 PictureH264, RcFlags, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
54 VAEntrypoint, VAImageFormat, VAProfile, VASurfaceAttribType, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE,
55 VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX,
56 VA_FOURCC_NV12, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
57 VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
58};
59use kodecs_h264::{
60 AspectRatio, Colour, Level, NaluHeader, NaluType, PicOrderCnt, Pps, PpsBuilder, Profile, Restriction, SliceHeader,
61 SliceHeaderBuilder, SliceType, Sps, SpsBuilder, Timing, VideoSignal, Vui,
62};
63
64mod h265;
65
66pub const DEFAULT_MIN_QP: u8 = 24;
78pub const MAX_QP: u8 = 51;
87pub const HRD_FRAMES: u32 = 3;
93pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
95const LIMIT: u32 = 2048;
97
98#[derive(Clone, Debug)]
102#[non_exhaustive]
103pub struct Config {
104 pub codec: Codec,
106 pub width: u32,
107 pub height: u32,
108 pub framerate: u32,
109 pub bitrate: u32,
113 pub gop: NonZeroU32,
115 pub qp: RangeInclusive<u8>,
122 pub device: Option<PathBuf>,
128 pub color: Color,
133}
134
135impl Config {
136 pub fn new(width: u32, height: u32, framerate: u32, bitrate: u32, gop: NonZeroU32) -> Self {
139 Self {
140 codec: Codec::H264,
141 width,
142 height,
143 framerate,
144 bitrate,
145 gop,
146 qp: DEFAULT_MIN_QP..=MAX_QP,
147 device: None,
148 color: Color::infer(height),
149 }
150 }
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum RateControl {
166 Variable,
169 Constant,
173}
174
175impl RateControl {
176 fn pick(vendor: &str, offered: u32) -> Self {
179 match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
180 true => Self::Variable,
181 false => Self::Constant,
182 }
183 }
184
185 fn va(self) -> u32 {
186 match self {
187 Self::Variable => VA_RC_VBR,
188 Self::Constant => VA_RC_CBR,
189 }
190 }
191}
192
193#[derive(Copy, Clone)]
195struct FrameMeta {
196 poc: u32,
197 frame_num: u32,
198}
199
200impl FrameMeta {
201 fn new(count: u32) -> Self {
207 Self {
208 poc: count.wrapping_mul(2),
209 frame_num: count % LIMIT,
210 }
211 }
212}
213
214#[derive(Copy, Clone)]
216struct Reference {
217 surface: crate::bindings::VASurfaceID,
219 count: u32,
221}
222
223struct PictureInfo<'a> {
225 idr: bool,
226 idr_id: u32,
228 count: u32,
230 recon: crate::bindings::VASurfaceID,
232 reference: Option<Reference>,
233 coded: &'a EncCodedBuffer,
234 bitrate: u32,
235}
236
237enum Syntax {
239 H264 {
240 sps: Sps,
241 pps: Pps,
242 packed: u32,
244 },
245 H265 {
246 stream: h265::Stream,
247 packed: u32,
249 },
250}
251
252pub struct Encoder {
254 config: Config,
255 syntax: Syntax,
256
257 input: Option<Surface<()>>,
260 nv12: Option<VAImageFormat>,
262 recon: Vec<Surface<()>>,
263 reference: Option<(usize, u32)>,
265
266 counter: u32,
267 idrs: u32,
269
270 processor: Option<Processor>,
273 reset_rate_control: bool,
276 rate_control: RateControl,
277
278 coded: EncCodedBuffer,
280 context: Rc<Context>,
281 _va_config: VaConfig,
282 display: Arc<Display>,
283}
284
285impl Encoder {
286 pub fn new(mut config: Config) -> anyhow::Result<Self> {
298 let (width, height) = (config.width, config.height);
299 if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
300 anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
301 }
302 if config.qp.is_empty() || !(1..=MAX_QP).contains(config.qp.end()) {
305 anyhow::bail!(
306 "a QP range of {:?}, which needs a floor at or below a ceiling of 1 to {MAX_QP}",
307 config.qp
308 );
309 }
310 let codec = config.codec;
311 let (device, display) = match config.device.take() {
312 Some(device) => {
313 let display = Display::open_drm_display(&device)
314 .map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
315 (device, display)
316 }
317 None => crate::display::open_first(|display| probe(display, codec)?.check(width, height))
318 .map_err(|e| e.context(format!("find a render node that encodes {codec:?} at {width}x{height}")))?,
319 };
320
321 let entrypoint = encode_entrypoint(&display, codec)?;
322 let rate_control = RateControl::pick(
323 &display.query_vendor_string().unwrap_or_default(),
324 config_attribute(
325 &display,
326 codec,
327 entrypoint,
328 VAConfigAttribType::VAConfigAttribRateControl,
329 ),
330 );
331 let mut attrs = vec![
332 VAConfigAttrib {
333 type_: VAConfigAttribType::VAConfigAttribRTFormat,
334 value: VA_RT_FORMAT_YUV420,
335 },
336 VAConfigAttrib {
337 type_: VAConfigAttribType::VAConfigAttribRateControl,
338 value: rate_control.va(),
339 },
340 ];
341 let wanted = match codec {
350 Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
351 Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
352 };
353 let packed = config_attribute(
354 &display,
355 codec,
356 entrypoint,
357 VAConfigAttribType::VAConfigAttribEncPackedHeaders,
358 ) & wanted;
359 if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
362 anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
363 }
364 if packed != 0 {
365 attrs.push(VAConfigAttrib {
366 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
367 value: packed,
368 });
369 } else {
370 tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
371 }
372 let mut va_config = display
373 .create_config(attrs, profile(codec), entrypoint)
374 .map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
375 limits(&display, codec, entrypoint, &mut va_config)?.check(width, height)?;
376
377 let syntax = match codec {
378 Codec::H264 => {
379 let (sps, pps) = build_sps_pps(&config)?;
380 Syntax::H264 { sps, pps, packed }
381 }
382 Codec::H265 => Syntax::H265 {
383 stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
384 packed,
385 },
386 };
387 let size = match &syntax {
391 Syntax::H264 { .. } => (config.width, config.height),
392 Syntax::H265 { stream, .. } => stream.coded(),
393 };
394
395 let context = display
396 .create_context::<()>(&va_config, size.0, size.1, None, true)
397 .map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;
398
399 let coded = context
400 .create_enc_coded(coded_size(size))
401 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
402
403 let input = make_surface(&display, (config.width, config.height))?;
404 let nv12 = display
405 .query_image_formats()
406 .map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
407 .into_iter()
408 .find(|format| format.fourcc == VA_FOURCC_NV12);
409 let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];
410
411 tracing::info!(
412 "opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
413 device,
414 config.width,
415 config.height,
416 config.framerate,
417 config.bitrate,
418 rate_control,
419 entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
420 );
421 config.device = Some(device);
422 Ok(Self {
423 config,
424 syntax,
425 input: Some(input),
426 nv12,
427 recon,
428 reference: None,
429 counter: 0,
430 idrs: 0,
431 processor: None,
432 reset_rate_control: false,
433 rate_control,
434 coded,
435 context,
436 _va_config: va_config,
437 display,
438 })
439 }
440
441 pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
453 let format = self
454 .nv12
455 .ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
456 let mut input = self.input.take().expect("input surface present");
457 let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
458 .and_then(|()| self.encode_surface(&input, keyframe));
459 self.input = Some(input);
460 result
461 }
462
463 pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
492 let fourcc = buffer
493 .fourcc()
494 .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
495 let color = self.config.color;
496 let size = (self.config.width, self.config.height);
497 let unpadded = match &self.syntax {
498 Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
499 Syntax::H265 { stream, .. } => stream.coded() == size,
500 };
501 let in_place = fourcc == VA_FOURCC_NV12
502 && (buffer.width, buffer.height) == size
503 && unpadded
504 && buffer.color.is_none_or(|own| own == color);
505 if in_place {
506 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
507 return self.encode_surface(&source, keyframe);
508 }
509
510 let input_color = match is_rgb(fourcc) {
511 true => None,
512 false => Some(buffer.color.unwrap_or(color)),
513 };
514 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
515 let input = self.input.take().expect("input surface present");
516 let result = self
517 .processor()
518 .and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
519 .and_then(|()| self.encode_surface(&input, keyframe));
520 self.input = Some(input);
521 result
522 }
523
524 pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
538 if bitrate == 0 {
539 anyhow::bail!("a bitrate of zero");
540 }
541 if bitrate != self.config.bitrate {
542 self.reset_rate_control = true;
543 }
544 self.config.bitrate = bitrate;
545 Ok(())
546 }
547
548 pub fn rate_control(&self) -> RateControl {
550 self.rate_control
551 }
552
553 pub fn config(&self) -> &Config {
555 &self.config
556 }
557
558 fn processor(&mut self) -> anyhow::Result<&Processor> {
560 if self.processor.is_none() {
561 self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
562 }
563 Ok(self.processor.as_ref().expect("opened above"))
564 }
565
566 fn encode_surface<D: SurfaceMemoryDescriptor>(
568 &mut self,
569 source: &Surface<D>,
570 keyframe: bool,
571 ) -> anyhow::Result<Vec<u8>> {
572 let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
573 if is_idr {
574 self.counter = 0;
576 self.reference = None;
577 }
578
579 let recon_idx = (self.counter as usize) % self.recon.len();
580 let reference = match (is_idr, self.reference) {
582 (false, Some((index, count))) => Some(Reference {
583 surface: self.recon[index].id(),
584 count,
585 }),
586 _ => None,
587 };
588 let info = PictureInfo {
589 idr: is_idr,
590 idr_id: self.idrs,
591 count: self.counter,
592 recon: self.recon[recon_idx].id(),
593 reference,
594 coded: &self.coded,
595 bitrate: self.config.bitrate,
596 };
597 let buffers = match &self.syntax {
598 Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
599 Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
600 };
601
602 let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);
603
604 for buffer in buffers {
607 picture.add_buffer(self.create(buffer)?);
608 }
609
610 let bits_per_second = self.config.bitrate;
611 let (min_qp, max_qp) = (*self.config.qp.start(), *self.config.qp.end());
614 let rc = EncMiscParameterRateControl::new(
615 bits_per_second,
616 100, RATE_CONTROL_WINDOW_MS, u32::from(min_qp.midpoint(max_qp).max(1)),
620 u32::from(min_qp),
621 0, RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
626 0, u32::from(max_qp),
628 0, 0, );
631 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
632 let hrd = hrd_size(bits_per_second, self.config.framerate);
634 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
635 EncMiscParameterHRD::new(hrd, hrd),
636 )))?);
637
638 let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
639 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);
640
641 let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
642 let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
643 let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
644 picture
647 .sync()
648 .map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;
649
650 let bitstream = self.read_coded()?;
652
653 self.reference = Some((recon_idx, self.counter));
654 self.counter += 1;
655 self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
656 self.reset_rate_control = false;
657 Ok(bitstream)
658 }
659
660 fn create(&self, buffer: BufferType) -> anyhow::Result<crate::Buffer> {
661 self.context
662 .create_buffer(buffer)
663 .map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}"))
664 }
665
666 fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
667 let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
668 concat_coded(mapped.iter().map(|segment| (segment.status, segment.buf)))
669 }
670}
671
672fn concat_coded<'a>(segments: impl IntoIterator<Item = (u32, &'a [u8])>) -> anyhow::Result<Vec<u8>> {
676 let mut out = Vec::new();
677 for (status, buf) in segments {
678 if status & crate::bindings::VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK != 0 {
679 anyhow::bail!("the coded picture overflowed its buffer");
680 }
681 out.extend_from_slice(buf);
682 }
683 Ok(out)
684}
685
686#[derive(Clone, Copy, Debug, PartialEq, Eq)]
693pub struct Limits {
694 pub min_width: Option<u32>,
695 pub min_height: Option<u32>,
696 pub max_width: Option<u32>,
697 pub max_height: Option<u32>,
698 round: (u32, u32),
700}
701
702impl Limits {
703 pub fn check(&self, width: u32, height: u32) -> anyhow::Result<()> {
709 let round = |size: u32, to: u32| size.checked_next_multiple_of(to).unwrap_or(u32::MAX);
710 let coded = (round(width, self.round.0), round(height, self.round.1));
711 let at = match coded == (width, height) {
712 true => String::new(),
713 false => format!(" (coded {}x{})", coded.0, coded.1),
714 };
715 for (axis, size, min, max) in [
716 ("width", coded.0, self.min_width, self.max_width),
717 ("height", coded.1, self.min_height, self.max_height),
718 ] {
719 if let Some(min) = min.filter(|&min| size < min) {
720 anyhow::bail!("a {width}x{height} frame{at} is under the driver's minimum encode {axis} of {min}");
721 }
722 if let Some(max) = max.filter(|&max| size > max) {
723 anyhow::bail!("a {width}x{height} frame{at} is over the driver's maximum encode {axis} of {max}");
724 }
725 }
726 Ok(())
727 }
728}
729
730pub fn probe(display: &Arc<Display>, codec: Codec) -> anyhow::Result<Limits> {
739 let entrypoint = encode_entrypoint(display, codec)?;
740 let attrs = vec![VAConfigAttrib {
741 type_: VAConfigAttribType::VAConfigAttribRTFormat,
742 value: VA_RT_FORMAT_YUV420,
743 }];
744 let mut va_config = display
745 .create_config(attrs, profile(codec), entrypoint)
746 .map_err(|e| anyhow::anyhow!("create {codec:?} encode config: {e:?}"))?;
747 limits(display, codec, entrypoint, &mut va_config)
748}
749
750fn limits(
752 display: &Display,
753 codec: Codec,
754 entrypoint: VAEntrypoint::Type,
755 va_config: &mut VaConfig,
756) -> anyhow::Result<Limits> {
757 let mut bound = |type_: VASurfaceAttribType::Type| -> anyhow::Result<Option<u32>> {
758 let values = va_config
759 .query_surface_attributes_by_type(type_)
760 .map_err(|e| anyhow::anyhow!("query {codec:?} encode surface attributes: {e:?}"))?;
761 Ok(match values.first() {
762 Some(&GenericValue::Integer(value)) => u32::try_from(value).ok().filter(|&value| value > 0),
763 _ => None,
764 })
765 };
766 let (min_width, min_height, max_width, max_height) = (
767 bound(VASurfaceAttribType::VASurfaceAttribMinWidth)?,
768 bound(VASurfaceAttribType::VASurfaceAttribMinHeight)?,
769 bound(VASurfaceAttribType::VASurfaceAttribMaxWidth)?,
770 bound(VASurfaceAttribType::VASurfaceAttribMaxHeight)?,
771 );
772 let round = match codec {
773 Codec::H264 => (1, 1),
774 Codec::H265 => h265::round(display, entrypoint, va_config)?,
775 };
776 Ok(Limits {
777 min_width,
778 min_height,
779 max_width,
780 max_height,
781 round,
782 })
783}
784
785fn profile(codec: Codec) -> VAProfile::Type {
787 match codec {
788 Codec::H264 => VAProfile::VAProfileH264Main,
789 Codec::H265 => h265::PROFILE,
790 }
791}
792
793fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
797 let entrypoints = display
798 .query_config_entrypoints(profile(codec))
799 .map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
800 [VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
801 .into_iter()
802 .find(|entrypoint| entrypoints.contains(entrypoint))
803 .ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
804}
805
806fn config_attribute(
808 display: &Display,
809 codec: Codec,
810 entrypoint: VAEntrypoint::Type,
811 type_: VAConfigAttribType::Type,
812) -> u32 {
813 let mut attrs = [VAConfigAttrib { type_, value: 0 }];
814 if display
815 .get_config_attributes(profile(codec), entrypoint, &mut attrs)
816 .is_err()
817 || attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
818 {
819 return 0;
820 }
821 attrs[0].value
822}
823
824fn level(width: u32, height: u32, framerate: u32) -> Level {
834 const LEVELS: [(Level, u64, u64); 8] = [
836 (Level::L4, 245_760, 8_192),
837 (Level::L4_2, 522_240, 8_704),
838 (Level::L5, 589_824, 22_080),
839 (Level::L5_1, 983_040, 36_864),
840 (Level::L5_2, 2_073_600, 36_864),
841 (Level::L6, 4_177_920, 139_264),
842 (Level::L6_1, 8_355_840, 139_264),
843 (Level::L6_2, 16_711_680, 139_264),
844 ];
845 let (width_mbs, height_mbs) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
846 let frame = width_mbs * height_mbs;
847 let rate = frame * u64::from(framerate.max(1));
848 let side = width_mbs.max(height_mbs);
850 LEVELS
851 .into_iter()
852 .find(|&(_, max_rate, max_frame)| frame <= max_frame && side * side <= 8 * max_frame && rate <= max_rate)
853 .map(|(level, _, _)| level)
854 .unwrap_or(Level::L6_2)
855}
856
857fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
859 (u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
860}
861
862fn coded_size(size: (u32, u32)) -> usize {
870 let (width, height) = (
871 size.0.next_multiple_of(16) as usize,
872 size.1.next_multiple_of(16) as usize,
873 );
874 3 * width * height + (1 << 16)
875}
876
877fn is_rgb(fourcc: u32) -> bool {
879 matches!(
880 fourcc,
881 VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
882 )
883}
884
885fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
887 let mut surfaces = display
888 .create_surfaces::<()>(
889 VA_RT_FORMAT_YUV420,
890 Some(VA_FOURCC_NV12),
891 width,
892 height,
893 Some(UsageHint::USAGE_HINT_ENCODER),
894 vec![()],
895 )
896 .map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
897 surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
898}
899
900fn upload_nv12(
904 format: VAImageFormat,
905 surface: &mut Surface<()>,
906 width: u32,
907 height: u32,
908 data: &[u8],
909) -> anyhow::Result<()> {
910 let (w, h) = (width as usize, height as usize);
911 let luma = w * h;
912 let expected = luma + w * (h / 2);
913 if data.len() < expected {
914 anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
915 }
916
917 let mut image =
918 ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
919 let va_image = *image.image();
920 let dest: &mut [u8] = image.as_mut();
921 let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
922 for (plane, (src, rows)) in planes.into_iter().enumerate() {
923 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
924 fill_plane(dest, offset, pitch, src, w, rows)?;
925 }
926 image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
927}
928
929fn fill_plane(
933 dst: &mut [u8],
934 offset: usize,
935 pitch: usize,
936 src: &[u8],
937 width: usize,
938 rows: usize,
939) -> anyhow::Result<()> {
940 if rows == 0 || width == 0 {
941 return Ok(());
942 }
943 let end = (rows - 1)
945 .checked_mul(pitch)
946 .and_then(|start| start.checked_add(offset)?.checked_add(width));
947 if pitch < width || end.is_none_or(|end| end > dst.len()) {
948 anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
949 }
950 for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
951 let start = offset + row * pitch;
952 dst[start..start + width].copy_from_slice(src);
953 }
954 Ok(())
955}
956
957fn build_sps_pps(config: &Config) -> anyhow::Result<(Sps, Pps)> {
962 let (primaries, transfer, matrix) = config.color.vui();
963 let vui = Vui {
964 aspect_ratio: Some(AspectRatio {
965 idc: 1, sar_width: 0,
967 sar_height: 0,
968 }),
969 overscan_appropriate: None,
970 video_signal: Some(VideoSignal {
971 video_format: 5, full_range: config.color.full_range,
973 colour: Some(Colour {
974 primaries,
975 transfer,
976 matrix,
977 }),
978 }),
979 chroma_loc: None,
980 timing: Some(Timing {
981 num_units_in_tick: 1,
982 time_scale: config.framerate.max(1) * 2,
984 fixed_frame_rate: false,
985 }),
986 nal_hrd: None,
987 vcl_hrd: None,
988 low_delay_hrd: false,
989 pic_struct_present: false,
990 restriction: Some(Restriction {
993 motion_vectors_over_pic_boundaries: true,
994 max_bytes_per_pic_denom: 2,
995 max_bits_per_mb_denom: 1,
996 log2_max_mv_length_horizontal: 16,
997 log2_max_mv_length_vertical: 16,
998 max_num_reorder_frames: 0,
999 max_dec_frame_buffering: 1,
1000 }),
1001 };
1002 let sps = SpsBuilder::new(Profile::Main, level(config.width, config.height, config.framerate))
1003 .log2_max_frame_num(LIMIT.ilog2() as u8)
1004 .pic_order_cnt(PicOrderCnt::Lsb {
1005 log2_max_lsb: (LIMIT * 2).ilog2() as u8,
1006 })
1007 .max_num_ref_frames(1)
1008 .resolution(config.width, config.height)
1009 .vui(vui)
1010 .build()
1011 .context("build the SPS")?;
1012
1013 let pps = PpsBuilder::new(&sps)
1014 .entropy_coding_mode(true)
1015 .deblocking_filter_control_present(true)
1016 .build()
1017 .context("build the PPS")?;
1018
1019 Ok((sps, pps))
1020}
1021
1022fn h264_buffers(sps: &Sps, pps: &Pps, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
1024 let meta = FrameMeta::new(picture.count);
1025 let (slice_type, nal) = match picture.idr {
1027 true => (
1028 SliceType::I,
1029 NaluHeader {
1030 ref_idc: 3,
1031 type_: NaluType::SliceIdr,
1032 },
1033 ),
1034 false => (
1035 SliceType::P,
1036 NaluHeader {
1037 ref_idc: 1,
1038 type_: NaluType::Slice,
1039 },
1040 ),
1041 };
1042 let mut builder = SliceHeaderBuilder::new(sps, pps, slice_type)
1043 .frame_num(meta.frame_num)
1044 .pic_order_cnt_lsb(meta.poc % (LIMIT * 2));
1045 if picture.idr {
1046 builder = builder.idr_pic_id(picture.idr_id % 2);
1048 }
1049 let header = builder.build(nal).context("build the slice header")?;
1050 let macroblocks = sps.width_mbs * sps.height_mbs;
1051 let reference = picture
1052 .reference
1053 .map(|reference| (reference.surface, FrameMeta::new(reference.count)));
1054
1055 let mut buffers = vec![
1056 build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
1057 build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
1058 build_enc_slice_param(pps, &header, reference, macroblocks),
1059 ];
1060 if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
1061 buffers.extend(packed_parameter_sets(sps, pps)?);
1062 }
1063 if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
1064 let mut out = Vec::new();
1065 let trailing = header
1066 .write(nal, sps, pps, &mut out)
1067 .context("write the slice header")?;
1068 let bits = out.len() * 8 - usize::from(trailing);
1070 buffers.extend(packed_header(EncPackedHeaderType::Slice, &out, bits));
1071 }
1072 Ok(buffers)
1073}
1074
1075fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
1077 let mut sps_nal = Vec::new();
1078 sps.write(3, &mut sps_nal).context("write the SPS")?;
1079 let mut pps_nal = Vec::new();
1080 pps.write(3, &mut pps_nal).context("write the PPS")?;
1081
1082 let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
1083 let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
1084 Ok([sps_param, sps_data, pps_param, pps_data])
1085}
1086
1087fn build_invalid_pic() -> PictureH264 {
1088 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1089}
1090
1091fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
1092 PictureH264::new(
1093 surface_id,
1094 meta.frame_num,
1095 VA_PICTURE_H264_SHORT_TERM_REFERENCE,
1096 meta.poc as i32,
1097 meta.poc as i32,
1098 )
1099}
1100
1101fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
1103 let PicOrderCnt::Lsb { log2_max_lsb } = sps.pic_order_cnt else {
1104 unreachable!("build_sps_pps writes picture order count type 0")
1105 };
1106 let seq_fields = H264EncSeqFields::new(
1107 1, 1, 0, sps.scaling.is_some() as u32,
1111 sps.direct_8x8_inference as u32,
1112 u32::from(sps.log2_max_frame_num - 4),
1113 0, u32::from(log2_max_lsb - 4),
1115 0, );
1117
1118 let frame_crop = sps
1120 .crop
1121 .map(|crop| H264EncFrameCropOffsets::new(crop.left / 2, crop.right / 2, crop.top / 2, crop.bottom / 2));
1122
1123 let vui = sps.vui.as_ref();
1124 let aspect_ratio = vui.and_then(|vui| vui.aspect_ratio);
1125 let timing = vui.and_then(|vui| vui.timing);
1126 let restriction = vui.and_then(|vui| vui.restriction);
1127 let vui_fields = vui.map(|vui| {
1128 H264VuiFields::new(
1129 aspect_ratio.is_some() as u32,
1130 timing.is_some() as u32,
1131 restriction.is_some() as u32,
1132 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_horizontal)),
1133 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_vertical)),
1134 timing.is_some_and(|t| t.fixed_frame_rate) as u32,
1135 vui.low_delay_hrd as u32,
1136 restriction.is_some_and(|r| r.motion_vectors_over_pic_boundaries) as u32,
1137 )
1138 });
1139
1140 BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
1142 sps.id,
1143 sps.level.value(),
1144 intra_period,
1145 intra_period,
1146 ip_period,
1147 bits_per_second,
1148 u32::from(sps.max_num_ref_frames),
1149 sps.width_mbs as u16,
1150 sps.height_mbs as u16,
1151 &seq_fields,
1152 0, 0, 0,
1155 0,
1156 0,
1157 [0; 256],
1158 frame_crop,
1159 vui_fields,
1160 aspect_ratio.map_or(0, |a| a.idc),
1161 aspect_ratio.map_or(0, |a| u32::from(a.sar_width)),
1162 aspect_ratio.map_or(0, |a| u32::from(a.sar_height)),
1163 timing.map_or(0, |t| t.num_units_in_tick),
1164 timing.map_or(0, |t| t.time_scale),
1165 )))
1166}
1167
1168fn build_enc_pic_param(
1170 pps: &Pps,
1171 coded: &EncCodedBuffer,
1172 recon_id: u32,
1173 meta: FrameMeta,
1174 is_idr: bool,
1175 reference: Option<(u32, FrameMeta)>,
1176) -> BufferType {
1177 let pic_fields = H264EncPicFields::new(
1178 is_idr as u32,
1179 1, pps.entropy_coding_mode as u32,
1181 pps.weighted_pred as u32,
1182 u32::from(pps.weighted_bipred_idc),
1183 pps.constrained_intra_pred as u32,
1184 pps.transform_8x8_mode as u32,
1185 pps.deblocking_filter_control_present as u32,
1186 pps.redundant_pic_cnt_present as u32,
1187 0,
1188 pps.scaling.is_some() as u32,
1189 );
1190
1191 let curr_pic = build_h264_pic(recon_id, meta);
1192 let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
1193 if let Some((id, m)) = reference {
1194 reference_frames[0] = build_h264_pic(id, m);
1195 }
1196
1197 BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
1199 curr_pic,
1200 reference_frames,
1201 coded.id(),
1202 pps.id,
1203 pps.sps_id,
1204 0,
1205 meta.frame_num as u16,
1206 pps.pic_init_qp as u8,
1207 pps.num_ref_idx_l0_default_active - 1,
1208 pps.num_ref_idx_l1_default_active - 1,
1209 pps.chroma_qp_index_offset as i8,
1210 pps.second_chroma_qp_index_offset as i8,
1211 &pic_fields,
1212 )))
1213}
1214
1215fn build_enc_slice_param(
1218 pps: &Pps,
1219 header: &SliceHeader,
1220 reference: Option<(u32, FrameMeta)>,
1221 num_macroblocks: u32,
1222) -> BufferType {
1223 let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1224 if let Some((id, m)) = reference {
1225 ref_pic_list_0[0] = build_h264_pic(id, m);
1226 }
1227 let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1228
1229 let override_counts =
1232 header.slice_type == SliceType::P && header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active;
1233 let (l0, l1) = match override_counts {
1234 true => (header.num_ref_idx_l0_active, header.num_ref_idx_l1_active),
1235 false => (pps.num_ref_idx_l0_default_active, pps.num_ref_idx_l1_default_active),
1236 };
1237
1238 BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
1240 header.first_mb_in_slice,
1241 num_macroblocks,
1242 VA_INVALID_ID,
1243 header.slice_type_raw % 5,
1244 pps.id,
1245 header.idr_pic_id.unwrap_or(0) as u16,
1246 header.pic_order_cnt_lsb as u16,
1247 header.delta_pic_order_cnt_bottom,
1248 header.delta_pic_order_cnt,
1249 header.direct_spatial_mv_pred as u8,
1250 override_counts as u8,
1251 l0.saturating_sub(1),
1252 l1.saturating_sub(1),
1253 ref_pic_list_0,
1254 ref_pic_list_1,
1255 0,
1256 0,
1257 0,
1258 [0i16; 32],
1259 [0i16; 32],
1260 0,
1261 [[0i16; 2]; 32],
1262 [[0i16; 2]; 32],
1263 0,
1264 [0i16; 32],
1265 [0i16; 32],
1266 0,
1267 [[0i16; 2]; 32],
1268 [[0i16; 2]; 32],
1269 header.cabac_init_idc,
1270 (header.slice_qp - pps.pic_init_qp) as i8,
1271 header.disable_deblocking_filter_idc,
1272 header.slice_alpha_c0_offset_div2 as i8,
1273 header.slice_beta_offset_div2 as i8,
1274 )))
1275}
1276
1277fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
1279 let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
1280 let payload = BufferType::EncPackedHeaderData(data.to_vec());
1281 [param, payload]
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286 use std::path::PathBuf;
1287 use std::process::Command;
1288
1289 use super::*;
1290 use crate::dmabuf::DmaBuf;
1291 use crate::testing::{blank_surface, ffmpeg_decode, image_format, nv12_frame, surface_with, temp_path};
1292 use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};
1293
1294 const WIDTH: u32 = 640;
1296 const HEIGHT: u32 = 480;
1297 const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];
1298
1299 fn config(codec: Codec) -> Config {
1300 Config {
1301 codec,
1302 ..Config::new(WIDTH, HEIGHT, 30, 2_000_000, NonZeroU32::new(30).unwrap())
1303 }
1304 }
1305
1306 fn encoder(config: Config) -> Encoder {
1308 Encoder::new(Config {
1309 device: config.device.clone().or_else(|| Some(crate::testing::device())),
1310 ..config
1311 })
1312 .expect("open the VA-API encoder")
1313 }
1314
1315 fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
1317 match codec {
1318 Codec::H264 => (5, &[7, 8]),
1319 Codec::H265 => (19, &[32, 33, 34]),
1320 }
1321 }
1322
1323 fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
1325 let path = temp_path(codec);
1326 std::fs::write(&path, stream).expect("write the elementary stream");
1327 let output = Command::new("ffprobe")
1328 .args([
1329 "-v",
1330 "error",
1331 "-show_entries",
1332 "stream=color_range,color_space",
1333 "-of",
1334 "csv=p=0",
1335 ])
1336 .arg(&path)
1337 .output()
1338 .ok();
1339 let _ = std::fs::remove_file(&path);
1340 Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
1341 }
1342
1343 fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
1345 let len = (width * height) as usize;
1346 let mse = a[..len]
1347 .iter()
1348 .zip(&b[..len])
1349 .map(|(&x, &y)| (x as f64 - y as f64).powi(2))
1350 .sum::<f64>()
1351 / len as f64;
1352 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
1353 }
1354
1355 fn mean(
1357 plane: &[u8],
1358 stride: usize,
1359 (x0, y0, x1, y1): (usize, usize, usize, usize),
1360 step: usize,
1361 at: usize,
1362 ) -> f64 {
1363 let mut sum = 0.0;
1364 let mut count = 0.0;
1365 for y in y0..y1 {
1366 for x in x0..x1 {
1367 sum += plane[y * stride + x * step + at] as f64;
1368 count += 1.0;
1369 }
1370 }
1371 sum / count
1372 }
1373
1374 fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
1376 let mut types = Vec::new();
1377 let mut i = 0;
1378 while i + 3 < unit.len() {
1379 if unit[i..i + 3] == [0, 0, 1] {
1380 types.push(match codec {
1381 Codec::H264 => unit[i + 3] & 0x1f,
1382 Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
1383 });
1384 i += 3;
1385 }
1386 i += 1;
1387 }
1388 types
1389 }
1390
1391 fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
1393 let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1394 let format = image_format(display, VA_FOURCC_NV12);
1395 upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
1396 DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
1397 }
1398
1399 #[test]
1402 #[ignore = "requires a VA-API render node"]
1403 fn the_render_node_is_found_or_named() {
1404 for codec in CODECS {
1405 let encoder = Encoder::new(config(codec)).expect("open the VA-API encoder");
1406 let device = encoder.config().device.clone().expect("the picked node is recorded");
1407 let display = Display::open_drm_display(&device).expect("reopen the picked node");
1408 probe(&display, codec).expect("the picked node encodes the codec");
1409
1410 let named = Config {
1411 device: Some(PathBuf::from("/dev/null")),
1412 ..config(codec)
1413 };
1414 assert!(
1415 Encoder::new(named).is_err(),
1416 "a named node that is not a render node was swapped for one that is"
1417 );
1418 }
1419 }
1420
1421 #[test]
1424 #[ignore = "requires a VA-API render node and FFmpeg"]
1425 fn nv12_round_trips_through_a_software_decoder() {
1426 for codec in CODECS {
1427 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1428 let mut encoder = encoder(Config {
1429 width,
1430 height,
1431 ..config(codec)
1432 });
1433 let mut stream = Vec::new();
1434 let mut frames = Vec::new();
1435 for step in 0..10 {
1436 let frame = nv12_frame(width, height, step);
1437 stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
1438 frames.push(frame);
1439 }
1440 let decoded = ffmpeg_decode(codec, &stream);
1441 let len = frames[0].len();
1442 assert_eq!(
1443 decoded.len(),
1444 len * frames.len(),
1445 "{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
1446 );
1447 for (index, frame) in frames.iter().enumerate() {
1448 let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
1449 assert!(
1450 psnr > 35.0,
1451 "{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
1452 );
1453 }
1454 }
1455 }
1456 }
1457
1458 #[test]
1461 fn a_truncated_picture_is_refused() {
1462 let joined = concat_coded([(0, &[1, 2][..]), (0, &[3][..])]).expect("no overflow");
1463 assert_eq!(joined, [1, 2, 3]);
1464
1465 let overflow = crate::bindings::VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK;
1466 for statuses in [[overflow, 0], [0, overflow | 1]] {
1467 let segments = statuses.into_iter().zip([&[1u8][..], &[2u8][..]]);
1468 concat_coded(segments).expect_err("an overflow is refused");
1469 }
1470 }
1471
1472 #[test]
1475 #[ignore = "requires a VA-API render node and FFmpeg"]
1476 fn a_noise_keyframe_at_a_low_qp_decodes_whole() {
1477 let (width, height) = (1920, 1080);
1478 let mut seed = 0x2545_f491_u32;
1479 let noise: Vec<u8> = (0..width * height * 3 / 2)
1480 .map(|_| {
1481 seed ^= seed << 13;
1482 seed ^= seed >> 17;
1483 seed ^= seed << 5;
1484 seed as u8
1485 })
1486 .collect();
1487 for codec in CODECS {
1488 let mut encoder = encoder(Config {
1489 codec,
1490 qp: 1..=8,
1491 ..Config::new(width, height, 30, 2_000_000, NonZeroU32::new(30).unwrap())
1492 });
1493 let unit = encoder.encode_nv12(&noise, true).expect("encode");
1494 assert!(unit.len() > 2_000_000, "{codec:?}: only {} bytes", unit.len());
1496 let decoded = ffmpeg_decode(codec, &unit);
1497 assert_eq!(decoded.len(), noise.len(), "{codec:?}: ffmpeg decoded a different size");
1498 let psnr = luma_psnr(&noise, &decoded, width, height);
1499 assert!(psnr > 40.0, "{codec:?}: decoded at {psnr:.1} dB");
1500 }
1501 }
1502
1503 #[test]
1505 #[ignore = "requires a VA-API render node and FFmpeg"]
1506 fn the_stream_is_labelled_with_its_color_space() {
1507 for codec in CODECS {
1508 for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
1509 let mut encoder = encoder(Config { color, ..config(codec) });
1510 let unit = encoder
1511 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1512 .expect("encode");
1513 let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
1514 assert_eq!(found, expected, "{codec:?}");
1515 }
1516 }
1517 }
1518
1519 #[test]
1522 fn a_plane_fills_up_to_its_last_byte_and_no_further() {
1523 let src = [1, 2, 3, 4, 5, 6];
1524 let mut tight = [0; 11];
1527 fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
1528 assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);
1529
1530 assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
1531 assert!(
1532 fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
1533 "a pitch narrower than a row"
1534 );
1535 assert!(
1536 fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
1537 "a pitch that overflows"
1538 );
1539 fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
1540 }
1541
1542 #[test]
1544 fn limits_check_the_coded_size_against_each_bound() {
1545 let limits = Limits {
1546 min_width: Some(384),
1547 min_height: None,
1548 max_width: Some(4096),
1549 max_height: Some(2304),
1550 round: (64, 16),
1551 };
1552 for (width, height) in [(384, 2), (322, 2304), (4096, 128)] {
1553 limits.check(width, height).expect("inside every bound");
1554 }
1555 for (width, height, named) in [
1556 (320, 240, "minimum encode width of 384"),
1557 (4098, 240, "maximum encode width of 4096"),
1558 (640, 2306, "maximum encode height of 2304"),
1559 (u32::MAX - 1, 240, "maximum encode width of 4096"),
1560 ] {
1561 let err = limits.check(width, height).expect_err("outside a bound");
1562 assert!(err.to_string().contains(named), "{width}x{height}: {err:#}");
1563 }
1564
1565 let unknown = Limits {
1566 min_width: None,
1567 min_height: None,
1568 max_width: None,
1569 max_height: None,
1570 round: (1, 1),
1571 };
1572 unknown.check(2, 2).expect("no bound to break");
1573 unknown.check(u32::MAX, u32::MAX).expect("no bound to break");
1574 }
1575
1576 #[test]
1580 #[ignore = "requires a VA-API render node"]
1581 fn a_frame_under_the_minimum_width_is_refused_naming_it() {
1582 let display = crate::testing::display();
1583 let vendor = display.query_vendor_string().unwrap_or_default();
1584 for codec in CODECS {
1585 let limits = probe(&display, codec).unwrap_or_else(|e| panic!("{vendor}: no {codec:?} encoder: {e:#}"));
1586 eprintln!("{vendor} {codec:?}: {limits:?}");
1587 let min = limits.min_width.expect("the driver names a minimum width");
1588 let step = limits.round.0.max(2);
1590 let (under, over) = ((min - 1) / step * step, min.next_multiple_of(step) - step + 2);
1591 let named = |width| Config {
1592 width,
1593 device: Some(crate::testing::device()),
1594 ..config(codec)
1595 };
1596 if under > 0 {
1597 let err = Encoder::new(named(under))
1598 .err()
1599 .expect("a frame under the minimum is refused");
1600 let wanted = format!("minimum encode width of {min}");
1601 assert!(err.to_string().contains(&wanted), "{codec:?} {under} wide: {err:#}");
1602 }
1603 let mut encoder = Encoder::new(named(over)).unwrap_or_else(|e| panic!("{codec:?} {over} wide: {e:#}"));
1604 let frame = encoder.encode_nv12(&nv12_frame(over, HEIGHT, 0), true);
1605 assert!(
1606 !frame.expect("encode").is_empty(),
1607 "{codec:?} {over} wide coded nothing"
1608 );
1609 }
1610 }
1611
1612 #[test]
1614 fn an_odd_or_empty_size_is_refused() {
1615 for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
1616 let err = Encoder::new(Config {
1617 width,
1618 height,
1619 ..config(Codec::H264)
1620 })
1621 .err()
1622 .expect("refused");
1623 assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
1624 }
1625 }
1626
1627 #[test]
1630 fn an_invalid_qp_range_is_refused() {
1631 for qp in [30..=52, RangeInclusive::new(34, 30), 0..=0] {
1632 let err = Encoder::new(Config {
1633 qp: qp.clone(),
1634 ..config(Codec::H264)
1635 })
1636 .err()
1637 .expect("refused");
1638 assert!(err.to_string().contains("QP range"), "{qp:?}: {err:#}");
1639 }
1640 }
1641
1642 fn coded_sizes(config: Config, frames: u32, picture: impl Fn(u32) -> Vec<u8>) -> Vec<usize> {
1644 let mut encoder = encoder(config);
1645 (0..frames)
1646 .map(|step| encoder.encode_nv12(&picture(step), false).expect("encode").len())
1647 .collect()
1648 }
1649
1650 #[test]
1654 #[ignore = "requires a VA-API render node"]
1655 fn a_qp_ceiling_keeps_a_still_keyframe_sharp() {
1656 const SIZE: (u32, u32) = (640, 360);
1657 let (w, h) = (SIZE.0 as usize, SIZE.1 as usize);
1659 let mut text = vec![128u8; w * h + w * h / 2];
1660 for y in 0..h {
1661 for x in 0..w {
1662 let stroke = y % 14 < 10 && x % 8 < 6 && (x / 8 * 31 + y / 14 * 17 + x % 8 * 3 + y % 14 * 5) % 7 < 3;
1663 text[y * w + x] = if stroke { 40 } else { 235 };
1664 }
1665 }
1666 for codec in CODECS {
1667 let second_idr = |qp: RangeInclusive<u8>| {
1670 let config = Config {
1671 codec,
1672 qp,
1673 ..Config::new(SIZE.0, SIZE.1, 30, 1_400_000, NonZeroU32::new(30).unwrap())
1674 };
1675 coded_sizes(config, 31, |_| text.clone())[30]
1676 };
1677 let held = second_idr(DEFAULT_MIN_QP..=MAX_QP);
1678 let sharp = second_idr(DEFAULT_MIN_QP..=34);
1679 eprintln!("{codec:?} second IDR: {held} bytes within QP 24-51, {sharp} within 24-34");
1680 assert!(
1681 sharp > 2 * held,
1682 "{codec:?}: the ceiling did not sharpen the IDR: {held} -> {sharp} bytes"
1683 );
1684 }
1685 }
1686
1687 #[test]
1690 #[ignore = "requires a VA-API render node"]
1691 fn the_qp_floor_holds_under_a_ceiling() {
1692 const SIZE: (u32, u32) = (640, 360);
1693 let calm = |step: u32| {
1695 let (w, h) = (SIZE.0 as usize, SIZE.1 as usize);
1696 let mut frame = vec![128u8; w * h + w * h / 2];
1697 for y in 0..h {
1698 for x in 0..w {
1699 let sx = x + step as usize;
1700 frame[y * w + x] = (((sx * 7) ^ (y * 13)) & 0xff) as u8 / 2 + ((sx / 9 + y / 5) % 2) as u8 * 64;
1701 }
1702 }
1703 frame
1704 };
1705 for codec in CODECS {
1706 let mean = |qp: RangeInclusive<u8>| {
1708 let config = Config {
1709 codec,
1710 qp,
1711 ..Config::new(SIZE.0, SIZE.1, 30, 8_000_000, NonZeroU32::new(300).unwrap())
1712 };
1713 let sizes = coded_sizes(config, 90, calm);
1714 sizes[30..].iter().sum::<usize>() / 60
1715 };
1716 let floored = mean(36..=40);
1717 let unfloored = mean(10..=40);
1718 eprintln!("{codec:?} calm picture: {floored} bytes within QP 36-40, {unfloored} within 10-40");
1719 assert!(
1720 unfloored > floored * 3 / 2,
1721 "{codec:?}: a floor of 36 spent {floored} bytes a picture, a floor of 10 {unfloored}"
1722 );
1723 }
1724 }
1725
1726 #[test]
1729 #[ignore = "requires a VA-API render node"]
1730 fn an_upload_reads_back_as_the_same_pixels() {
1731 let display = crate::testing::display();
1732 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1733 let frame = nv12_frame(width, height, 3);
1734 let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1735 let format = image_format(&display, VA_FOURCC_NV12);
1736 upload_nv12(format, &mut surface, width, height, &frame).expect("upload");
1737
1738 let image =
1739 crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
1740 let (va_image, data) = (*image.image(), image.as_ref());
1741 let (w, h) = (width as usize, height as usize);
1742 for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
1743 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
1744 for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
1745 let at = offset + row * pitch;
1746 assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
1747 }
1748 }
1749 }
1750 }
1751
1752 #[test]
1754 #[ignore = "requires a VA-API render node"]
1755 fn keyframes_follow_the_group_length() {
1756 for codec in CODECS {
1757 let mut encoder = encoder(Config {
1758 gop: NonZeroU32::new(10).unwrap(),
1759 ..config(codec)
1760 });
1761 let (idr_type, parameter_sets) = idr_types(codec);
1762 for step in 0..25 {
1763 let unit = encoder
1764 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
1765 .expect("encode");
1766 let types = nal_types(codec, &unit);
1767 let idr = types.contains(&idr_type);
1768 assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
1769 if idr {
1770 assert!(
1771 parameter_sets.iter().all(|kind| types.contains(kind)),
1772 "a {codec:?} IDR carries its parameter sets: {types:?}"
1773 );
1774 }
1775 }
1776 for step in 0..=10 {
1778 let unit = encoder
1779 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
1780 .expect("encode");
1781 assert_eq!(
1782 nal_types(codec, &unit).contains(&idr_type),
1783 step % 10 == 0,
1784 "{codec:?} frame {step} after the forced keyframe"
1785 );
1786 }
1787 }
1788 }
1789
1790 #[test]
1793 #[ignore = "requires a VA-API render node and FFmpeg"]
1794 fn a_refused_import_leaves_the_encoder_usable() {
1795 let mut encoder = encoder(config(Codec::H264));
1796 let display = crate::testing::display();
1797 let unmapped = DmaBuf {
1799 drm_format: u32::from_le_bytes(*b"ZZZZ"),
1800 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1801 };
1802 assert!(encoder.encode_dmabuf(unmapped, true).is_err());
1803 let unknown_modifier = DmaBuf {
1804 modifier: 0x00ff_ffff_ffff_fffe,
1805 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1806 };
1807 assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());
1808
1809 let unit = encoder
1810 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1811 .expect("the CPU path still encodes");
1812 let decoded = ffmpeg_decode(Codec::H264, &unit);
1813 let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
1814 assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
1815 }
1816
1817 #[test]
1822 #[ignore = "requires a VA-API render node and FFmpeg"]
1823 fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
1824 for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
1825 let mut encoder = encoder(Config {
1826 width,
1827 height,
1828 bitrate: 4_000_000,
1829 color: Color::infer(height),
1830 ..config(codec)
1831 });
1832 let display = crate::testing::display();
1833 let unit = encoder
1834 .encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
1835 .expect("encode the DMA-BUF");
1836 let decoded = ffmpeg_decode(codec, &unit);
1837 let frame = nv12_frame(width, height, 0);
1838 assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
1839 let psnr = luma_psnr(&frame, &decoded, width, height);
1840 assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
1841 }
1842 }
1843
1844 #[test]
1847 #[ignore = "requires a VA-API render node and FFmpeg"]
1848 fn a_yuv_dmabuf_in_another_space_is_converted() {
1849 for codec in CODECS {
1850 let mut encoder = encoder(Config {
1851 color: Color::BT601,
1852 ..config(codec)
1853 });
1854 let display = crate::testing::display();
1855 let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
1857 let surface = surface_with(
1858 &display,
1859 VA_FOURCC_NV12,
1860 VA_RT_FORMAT_YUV420,
1861 (WIDTH, HEIGHT),
1862 |data, image| {
1863 for row in 0..HEIGHT as usize {
1864 let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
1865 data[at..at + WIDTH as usize].fill(y);
1866 }
1867 for row in 0..HEIGHT as usize / 2 {
1868 let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
1869 for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
1870 pair.copy_from_slice(&[u, v]);
1871 }
1872 }
1873 },
1874 );
1875 let buffer = DmaBuf {
1876 color: Some(Color::BT709),
1877 ..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
1878 };
1879 let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
1880 let decoded = ffmpeg_decode(codec, &unit);
1881
1882 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1883 let (luma, chroma) = decoded.split_at(w * h);
1884 let actual = [
1885 mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
1886 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
1887 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
1888 ];
1889 let expected = limited([255, 0, 0], Color::BT601);
1890 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1891 assert!(
1892 (a - e).abs() < 6.0,
1893 "{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
1894 );
1895 }
1896 }
1897 }
1898
1899 #[test]
1901 #[ignore = "requires a VA-API render node and FFmpeg"]
1902 fn an_nv12_dmabuf_encodes_in_place() {
1903 for codec in CODECS {
1904 let mut encoder = encoder(config(codec));
1905 let display = crate::testing::display();
1906 let mut stream = Vec::new();
1907 for step in 0..5 {
1908 let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
1909 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1910 }
1911 let decoded = ffmpeg_decode(codec, &stream);
1912 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1913 assert_eq!(decoded.len(), 5 * len, "{codec:?}");
1914 for step in 0..5 {
1915 let psnr = luma_psnr(
1916 &nv12_frame(WIDTH, HEIGHT, step),
1917 &decoded[step as usize * len..],
1918 WIDTH,
1919 HEIGHT,
1920 );
1921 assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1922 }
1923 }
1924 }
1925
1926 #[test]
1928 #[ignore = "requires a VA-API render node and FFmpeg"]
1929 fn a_dmabuf_at_another_size_is_scaled() {
1930 for codec in CODECS {
1931 let mut encoder = encoder(config(codec));
1932 let display = crate::testing::display();
1933 let mut stream = Vec::new();
1934 for step in 0..3 {
1935 let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
1936 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1937 }
1938 let decoded = ffmpeg_decode(codec, &stream);
1939 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1940 assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
1941 for step in 0..3u32 {
1945 let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
1946 let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
1947 for y in 0..HEIGHT as usize {
1948 for x in 0..WIDTH as usize {
1949 expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
1950 }
1951 }
1952 let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
1953 assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1954 }
1955 }
1956 }
1957
1958 #[test]
1960 #[ignore = "requires a VA-API render node and FFmpeg"]
1961 fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
1962 const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
1964 for (codec, color) in CODECS
1965 .into_iter()
1966 .flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
1967 {
1968 let mut encoder = encoder(Config { color, ..config(codec) });
1969 let display = crate::testing::display();
1970 let surface = surface_with(
1971 &display,
1972 VA_FOURCC_BGRX,
1973 VA_RT_FORMAT_RGB32,
1974 (WIDTH, HEIGHT),
1975 |data, image| {
1976 let pitch = image.pitches[0] as usize;
1977 let offset = image.offsets[0] as usize;
1978 for y in 0..HEIGHT as usize {
1979 for x in 0..WIDTH as usize {
1980 let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
1981 let [r, g, b] = QUADRANTS[quadrant];
1982 let at = offset + y * pitch + x * 4;
1983 data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
1984 }
1985 }
1986 },
1987 );
1988 let exported = surface.export_prime().expect("export");
1989 let buffer = DmaBuf::from_prime(exported).expect("one object");
1990 assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
1991 let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
1992 let decoded = ffmpeg_decode(codec, &unit);
1993
1994 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1995 let (luma, chroma) = decoded.split_at(w * h);
1996 for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
1997 let (qx, qy) = (quadrant % 2, quadrant / 2);
1998 let area = |scale: usize| {
2000 let (qw, qh) = (w / 2 / scale, h / 2 / scale);
2001 (
2002 qx * qw + qw / 4,
2003 qy * qh + qh / 4,
2004 qx * qw + qw * 3 / 4,
2005 qy * qh + qh * 3 / 4,
2006 )
2007 };
2008 let actual = [
2009 mean(luma, w, area(1), 1, 0),
2010 mean(chroma, w, area(2), 2, 0),
2011 mean(chroma, w, area(2), 2, 1),
2012 ];
2013 let expected = limited(*rgb, color);
2014 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
2015 assert!(
2016 (a - e).abs() < 6.0,
2017 "{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
2018 );
2019 }
2020 }
2021 }
2022 }
2023
2024 #[test]
2025 fn the_level_covers_the_frame_size_and_rate() {
2026 assert_eq!(level(320, 240, 30), Level::L4);
2027 assert_eq!(level(1920, 1080, 30), Level::L4);
2028 assert_eq!(level(1920, 1080, 60), Level::L4_2);
2029 assert_eq!(level(2560, 1440, 30), Level::L5);
2030 assert_eq!(level(3840, 2160, 30), Level::L5_1);
2031 assert_eq!(level(3840, 2160, 60), Level::L5_2);
2032 assert_eq!(level(4352, 240, 30), Level::L5);
2034 }
2035
2036 #[test]
2037 fn an_unknown_framerate_still_builds_the_parameter_sets() {
2038 build_sps_pps(&Config {
2039 framerate: 0,
2040 ..config(Codec::H264)
2041 })
2042 .expect("build the SPS and PPS for framerate 0");
2043 }
2044
2045 fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
2047 let (kr, kb) = match color.matrix {
2048 crate::Matrix::Bt601 => (0.299, 0.114),
2049 crate::Matrix::Bt709 => (0.2126, 0.0722),
2050 };
2051 let (r, g, b) = (r as f64, g as f64, b as f64);
2052 let y = kr * r + (1.0 - kr - kb) * g + kb * b;
2053 [
2054 16.0 + y * 219.0 / 255.0,
2055 128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
2056 128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
2057 ]
2058 }
2059
2060 #[test]
2063 #[ignore = "requires a VA-API render node"]
2064 fn a_bitrate_change_takes_effect_without_a_keyframe() {
2065 for codec in CODECS {
2066 let mut encoder = encoder(Config {
2067 gop: NonZeroU32::new(1_000).unwrap(),
2068 ..config(codec)
2069 });
2070 let (idr_type, _) = idr_types(codec);
2071 let frame = |step: u32| {
2075 let (w, h) = (WIDTH as usize, HEIGHT as usize);
2076 let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
2077 for y in 0..h {
2078 for x in 0..w {
2079 let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
2080 let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
2081 frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
2082 }
2083 }
2084 frame
2085 };
2086 let average = |encoder: &mut Encoder, from: u32| {
2090 let sizes: Vec<usize> = (from..from + 60)
2091 .map(|step| {
2092 let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
2093 if step > 0 {
2094 assert!(
2095 !nal_types(codec, &unit).contains(&idr_type),
2096 "{codec:?} picture {step} is an IDR"
2097 );
2098 }
2099 unit.len()
2100 })
2101 .collect();
2102 sizes[30..].iter().sum::<usize>() / 30
2103 };
2104
2105 let within = |bytes: usize, bitrate: u32| {
2108 let target = bitrate as usize / 8 / 30;
2109 assert!(
2110 bytes * 4 <= target * 5,
2111 "{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
2112 );
2113 };
2114
2115 let high = average(&mut encoder, 0);
2116 within(high, 2_000_000);
2117 encoder.set_bitrate(250_000).expect("set the bitrate");
2118 assert_eq!(encoder.config().bitrate, 250_000);
2119 assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
2120 let low = average(&mut encoder, 60);
2121 eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
2122 within(low, 250_000);
2123 assert!(
2124 low * 3 < high,
2125 "{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
2126 );
2127 }
2128 }
2129}