1use std::num::NonZeroU32;
37use std::path::PathBuf;
38use std::rc::Rc;
39use std::sync::Arc;
40
41use anyhow::Context as _;
42
43use crate::codec::Codec;
44use crate::dmabuf::DmaBuf;
45use crate::vpp::Processor;
46use crate::{
47 BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter,
48 EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter,
49 EncPackedHeaderType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
50 EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264, GenericValue,
51 H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture,
52 PictureH264, RcFlags, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
53 VAEntrypoint, VAImageFormat, VAProfile, VASurfaceAttribType, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE,
54 VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX,
55 VA_FOURCC_NV12, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
56 VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
57};
58use kodecs_h264::{
59 AspectRatio, Colour, Level, NaluHeader, NaluType, PicOrderCnt, Pps, PpsBuilder, Profile, Restriction, SliceHeader,
60 SliceHeaderBuilder, SliceType, Sps, SpsBuilder, Timing, VideoSignal, Vui,
61};
62
63mod h265;
64
65const MIN_QP: u8 = 24;
79const MAX_QP: u8 = 51;
80pub const HRD_FRAMES: u32 = 3;
86pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
91const LIMIT: u32 = 2048;
93
94#[derive(Clone, Debug)]
96pub struct Config {
97 pub codec: Codec,
99 pub width: u32,
100 pub height: u32,
101 pub framerate: u32,
102 pub bitrate: u32,
105 pub gop: NonZeroU32,
107 pub device: Option<PathBuf>,
113 pub color: Color,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum RateControl {
133 Variable,
136 Constant,
140}
141
142impl RateControl {
143 fn pick(vendor: &str, offered: u32) -> Self {
146 match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
147 true => Self::Variable,
148 false => Self::Constant,
149 }
150 }
151
152 fn va(self) -> u32 {
153 match self {
154 Self::Variable => VA_RC_VBR,
155 Self::Constant => VA_RC_CBR,
156 }
157 }
158}
159
160#[derive(Copy, Clone)]
162struct FrameMeta {
163 poc: u32,
164 frame_num: u32,
165}
166
167impl FrameMeta {
168 fn new(count: u32) -> Self {
174 Self {
175 poc: count.wrapping_mul(2),
176 frame_num: count % LIMIT,
177 }
178 }
179}
180
181#[derive(Copy, Clone)]
183struct Reference {
184 surface: crate::bindings::VASurfaceID,
186 count: u32,
188}
189
190struct PictureInfo<'a> {
192 idr: bool,
193 idr_id: u32,
195 count: u32,
197 recon: crate::bindings::VASurfaceID,
199 reference: Option<Reference>,
200 coded: &'a EncCodedBuffer,
201 bitrate: u32,
202}
203
204enum Syntax {
206 H264 {
207 sps: Sps,
208 pps: Pps,
209 packed: u32,
211 },
212 H265 {
213 stream: h265::Stream,
214 packed: u32,
216 },
217}
218
219pub struct Encoder {
221 config: Config,
222 syntax: Syntax,
223
224 input: Option<Surface<()>>,
227 nv12: Option<VAImageFormat>,
229 recon: Vec<Surface<()>>,
230 reference: Option<(usize, u32)>,
232
233 counter: u32,
234 idrs: u32,
236
237 processor: Option<Processor>,
240 reset_rate_control: bool,
243 rate_control: RateControl,
244
245 coded: EncCodedBuffer,
247 coded_size: usize,
248 context: Rc<Context>,
249 _va_config: VaConfig,
250 display: Arc<Display>,
251}
252
253impl Encoder {
254 pub fn new(mut config: Config) -> anyhow::Result<Self> {
265 let (width, height) = (config.width, config.height);
266 if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
267 anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
268 }
269 let codec = config.codec;
270 let (device, display) = match config.device.take() {
271 Some(device) => {
272 let display = Display::open_drm_display(&device)
273 .map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
274 (device, display)
275 }
276 None => crate::display::open_first(|display| probe(display, codec)?.check(width, height))
277 .map_err(|e| e.context(format!("find a render node that encodes {codec:?} at {width}x{height}")))?,
278 };
279
280 let entrypoint = encode_entrypoint(&display, codec)?;
281 let rate_control = RateControl::pick(
282 &display.query_vendor_string().unwrap_or_default(),
283 config_attribute(
284 &display,
285 codec,
286 entrypoint,
287 VAConfigAttribType::VAConfigAttribRateControl,
288 ),
289 );
290 let mut attrs = vec![
291 VAConfigAttrib {
292 type_: VAConfigAttribType::VAConfigAttribRTFormat,
293 value: VA_RT_FORMAT_YUV420,
294 },
295 VAConfigAttrib {
296 type_: VAConfigAttribType::VAConfigAttribRateControl,
297 value: rate_control.va(),
298 },
299 ];
300 let wanted = match codec {
309 Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
310 Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
311 };
312 let packed = packed_headers(&display, codec, entrypoint) & wanted;
313 if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
316 anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
317 }
318 if packed != 0 {
319 attrs.push(VAConfigAttrib {
320 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
321 value: packed,
322 });
323 } else {
324 tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
325 }
326 let mut va_config = display
327 .create_config(attrs, profile(codec), entrypoint)
328 .map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
329 limits(&display, codec, entrypoint, &mut va_config)?.check(width, height)?;
330
331 let syntax = match codec {
332 Codec::H264 => {
333 let (sps, pps) = build_sps_pps(&config)?;
334 Syntax::H264 { sps, pps, packed }
335 }
336 Codec::H265 => Syntax::H265 {
337 stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
338 packed,
339 },
340 };
341 let size = match &syntax {
345 Syntax::H264 { .. } => (config.width, config.height),
346 Syntax::H265 { stream, .. } => stream.coded(),
347 };
348
349 let context = display
350 .create_context::<()>(&va_config, size.0, size.1, None, true)
351 .map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;
352
353 let coded_size = coded_size(config.bitrate);
354 let coded = context
355 .create_enc_coded(coded_size)
356 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
357
358 let input = make_surface(&display, (config.width, config.height))?;
359 let nv12 = display
360 .query_image_formats()
361 .map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
362 .into_iter()
363 .find(|format| format.fourcc == VA_FOURCC_NV12);
364 let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];
365
366 tracing::info!(
367 "opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
368 device,
369 config.width,
370 config.height,
371 config.framerate,
372 config.bitrate,
373 rate_control,
374 entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
375 );
376 config.device = Some(device);
377 Ok(Self {
378 config,
379 syntax,
380 input: Some(input),
381 nv12,
382 recon,
383 reference: None,
384 counter: 0,
385 idrs: 0,
386 processor: None,
387 reset_rate_control: false,
388 rate_control,
389 coded,
390 coded_size,
391 context,
392 _va_config: va_config,
393 display,
394 })
395 }
396
397 pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
405 let format = self
406 .nv12
407 .ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
408 let mut input = self.input.take().expect("input surface present");
409 let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
410 .and_then(|()| self.encode_surface(&input, keyframe));
411 self.input = Some(input);
412 result
413 }
414
415 pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
443 let fourcc = buffer
444 .fourcc()
445 .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
446 let color = self.config.color;
447 let size = (self.config.width, self.config.height);
448 let unpadded = match &self.syntax {
449 Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
450 Syntax::H265 { stream, .. } => stream.coded() == size,
451 };
452 let in_place = fourcc == VA_FOURCC_NV12
453 && (buffer.width, buffer.height) == size
454 && unpadded
455 && buffer.color.is_none_or(|own| own == color);
456 if in_place {
457 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
458 return self.encode_surface(&source, keyframe);
459 }
460
461 let input_color = match is_rgb(fourcc) {
462 true => None,
463 false => Some(buffer.color.unwrap_or(color)),
464 };
465 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
466 let input = self.input.take().expect("input surface present");
467 let result = self
468 .processor()
469 .and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
470 .and_then(|()| self.encode_surface(&input, keyframe));
471 self.input = Some(input);
472 result
473 }
474
475 pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
490 if bitrate == 0 {
491 anyhow::bail!("a bitrate of zero");
492 }
493 let size = coded_size(bitrate);
494 if size > self.coded_size {
495 self.coded = self
498 .context
499 .create_enc_coded(size)
500 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
501 self.coded_size = size;
502 }
503 if bitrate != self.config.bitrate {
504 self.reset_rate_control = true;
505 }
506 self.config.bitrate = bitrate;
507 Ok(())
508 }
509
510 pub fn rate_control(&self) -> RateControl {
512 self.rate_control
513 }
514
515 pub fn config(&self) -> &Config {
517 &self.config
518 }
519
520 fn processor(&mut self) -> anyhow::Result<&Processor> {
522 if self.processor.is_none() {
523 self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
524 }
525 Ok(self.processor.as_ref().expect("opened above"))
526 }
527
528 fn encode_surface<D: SurfaceMemoryDescriptor>(
530 &mut self,
531 source: &Surface<D>,
532 keyframe: bool,
533 ) -> anyhow::Result<Vec<u8>> {
534 let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
535 if is_idr {
536 self.counter = 0;
538 self.reference = None;
539 }
540
541 let recon_idx = (self.counter as usize) % self.recon.len();
542 let reference = match (is_idr, self.reference) {
544 (false, Some((index, count))) => Some(Reference {
545 surface: self.recon[index].id(),
546 count,
547 }),
548 _ => None,
549 };
550 let info = PictureInfo {
551 idr: is_idr,
552 idr_id: self.idrs,
553 count: self.counter,
554 recon: self.recon[recon_idx].id(),
555 reference,
556 coded: &self.coded,
557 bitrate: self.config.bitrate,
558 };
559 let buffers = match &self.syntax {
560 Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
561 Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
562 };
563
564 let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);
565
566 for buffer in buffers {
569 picture.add_buffer(self.create(buffer)?);
570 }
571
572 let bits_per_second = self.config.bitrate;
573 let rc = EncMiscParameterRateControl::new(
574 bits_per_second,
575 100, RATE_CONTROL_WINDOW_MS, u32::from((MIN_QP + MAX_QP) / 2),
578 MIN_QP as u32,
579 0, RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
584 0, MAX_QP as u32,
586 0, 0, );
589 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
590 let hrd = hrd_size(bits_per_second, self.config.framerate);
592 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
593 EncMiscParameterHRD::new(hrd, hrd),
594 )))?);
595
596 let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
597 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);
598
599 let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
600 let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
601 let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
602 picture
605 .sync()
606 .map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;
607
608 let bitstream = self.read_coded()?;
610
611 self.reference = Some((recon_idx, self.counter));
612 self.counter += 1;
613 self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
614 self.reset_rate_control = false;
615 Ok(bitstream)
616 }
617
618 fn create(&self, buffer: BufferType) -> anyhow::Result<crate::Buffer> {
619 self.context
620 .create_buffer(buffer)
621 .map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}"))
622 }
623
624 fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
625 let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
626 let mut out = Vec::new();
627 for segment in mapped.iter() {
628 out.extend_from_slice(segment.buf);
629 }
630 Ok(out)
631 }
632}
633
634#[derive(Clone, Copy, Debug, PartialEq, Eq)]
641pub struct Limits {
642 pub min_width: Option<u32>,
643 pub min_height: Option<u32>,
644 pub max_width: Option<u32>,
645 pub max_height: Option<u32>,
646 round: (u32, u32),
648}
649
650impl Limits {
651 pub fn check(&self, width: u32, height: u32) -> anyhow::Result<()> {
657 let round = |size: u32, to: u32| size.checked_next_multiple_of(to).unwrap_or(u32::MAX);
658 let coded = (round(width, self.round.0), round(height, self.round.1));
659 let at = match coded == (width, height) {
660 true => String::new(),
661 false => format!(" (coded {}x{})", coded.0, coded.1),
662 };
663 for (axis, size, min, max) in [
664 ("width", coded.0, self.min_width, self.max_width),
665 ("height", coded.1, self.min_height, self.max_height),
666 ] {
667 if let Some(min) = min.filter(|&min| size < min) {
668 anyhow::bail!("a {width}x{height} frame{at} is under the driver's minimum encode {axis} of {min}");
669 }
670 if let Some(max) = max.filter(|&max| size > max) {
671 anyhow::bail!("a {width}x{height} frame{at} is over the driver's maximum encode {axis} of {max}");
672 }
673 }
674 Ok(())
675 }
676}
677
678pub fn probe(display: &Arc<Display>, codec: Codec) -> anyhow::Result<Limits> {
687 let entrypoint = encode_entrypoint(display, codec)?;
688 let attrs = vec![VAConfigAttrib {
689 type_: VAConfigAttribType::VAConfigAttribRTFormat,
690 value: VA_RT_FORMAT_YUV420,
691 }];
692 let mut va_config = display
693 .create_config(attrs, profile(codec), entrypoint)
694 .map_err(|e| anyhow::anyhow!("create {codec:?} encode config: {e:?}"))?;
695 limits(display, codec, entrypoint, &mut va_config)
696}
697
698fn limits(
700 display: &Display,
701 codec: Codec,
702 entrypoint: VAEntrypoint::Type,
703 va_config: &mut VaConfig,
704) -> anyhow::Result<Limits> {
705 let mut bound = |type_: VASurfaceAttribType::Type| -> anyhow::Result<Option<u32>> {
706 let values = va_config
707 .query_surface_attributes_by_type(type_)
708 .map_err(|e| anyhow::anyhow!("query {codec:?} encode surface attributes: {e:?}"))?;
709 Ok(match values.first() {
710 Some(&GenericValue::Integer(value)) => u32::try_from(value).ok().filter(|&value| value > 0),
711 _ => None,
712 })
713 };
714 let (min_width, min_height, max_width, max_height) = (
715 bound(VASurfaceAttribType::VASurfaceAttribMinWidth)?,
716 bound(VASurfaceAttribType::VASurfaceAttribMinHeight)?,
717 bound(VASurfaceAttribType::VASurfaceAttribMaxWidth)?,
718 bound(VASurfaceAttribType::VASurfaceAttribMaxHeight)?,
719 );
720 let round = match codec {
721 Codec::H264 => (1, 1),
722 Codec::H265 => h265::round(display, entrypoint, va_config)?,
723 };
724 Ok(Limits {
725 min_width,
726 min_height,
727 max_width,
728 max_height,
729 round,
730 })
731}
732
733fn profile(codec: Codec) -> VAProfile::Type {
735 match codec {
736 Codec::H264 => VAProfile::VAProfileH264Main,
737 Codec::H265 => h265::PROFILE,
738 }
739}
740
741fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
745 let entrypoints = display
746 .query_config_entrypoints(profile(codec))
747 .map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
748 pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
749}
750
751fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option<VAEntrypoint::Type> {
753 [VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
754 .into_iter()
755 .find(|entrypoint| offered.contains(entrypoint))
756}
757
758fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 {
762 config_attribute(
763 display,
764 codec,
765 entrypoint,
766 VAConfigAttribType::VAConfigAttribEncPackedHeaders,
767 )
768}
769
770fn config_attribute(
772 display: &Display,
773 codec: Codec,
774 entrypoint: VAEntrypoint::Type,
775 type_: VAConfigAttribType::Type,
776) -> u32 {
777 let mut attrs = [VAConfigAttrib { type_, value: 0 }];
778 if display
779 .get_config_attributes(profile(codec), entrypoint, &mut attrs)
780 .is_err()
781 || attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
782 {
783 return 0;
784 }
785 attrs[0].value
786}
787
788fn level(width: u32, height: u32, framerate: u32) -> Level {
798 const LEVELS: [(Level, u64, u64); 8] = [
800 (Level::L4, 245_760, 8_192),
801 (Level::L4_2, 522_240, 8_704),
802 (Level::L5, 589_824, 22_080),
803 (Level::L5_1, 983_040, 36_864),
804 (Level::L5_2, 2_073_600, 36_864),
805 (Level::L6, 4_177_920, 139_264),
806 (Level::L6_1, 8_355_840, 139_264),
807 (Level::L6_2, 16_711_680, 139_264),
808 ];
809 let (width_mbs, height_mbs) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
810 let frame = width_mbs * height_mbs;
811 let rate = frame * u64::from(framerate.max(1));
812 let side = width_mbs.max(height_mbs);
814 LEVELS
815 .into_iter()
816 .find(|&(_, max_rate, max_frame)| frame <= max_frame && side * side <= 8 * max_frame && rate <= max_rate)
817 .map(|(level, _, _)| level)
818 .unwrap_or(Level::L6_2)
819}
820
821fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
823 (u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
824}
825
826fn coded_size(bitrate: u32) -> usize {
828 (bitrate as usize / 4).max(1_500_000)
829}
830
831fn is_rgb(fourcc: u32) -> bool {
833 matches!(
834 fourcc,
835 VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
836 )
837}
838
839fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
841 let mut surfaces = display
842 .create_surfaces::<()>(
843 VA_RT_FORMAT_YUV420,
844 Some(VA_FOURCC_NV12),
845 width,
846 height,
847 Some(UsageHint::USAGE_HINT_ENCODER),
848 vec![()],
849 )
850 .map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
851 surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
852}
853
854fn upload_nv12(
858 format: VAImageFormat,
859 surface: &mut Surface<()>,
860 width: u32,
861 height: u32,
862 data: &[u8],
863) -> anyhow::Result<()> {
864 let (w, h) = (width as usize, height as usize);
865 let luma = w * h;
866 let expected = luma + w * (h / 2);
867 if data.len() < expected {
868 anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
869 }
870
871 let mut image =
872 ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
873 let va_image = *image.image();
874 let dest: &mut [u8] = image.as_mut();
875 let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
876 for (plane, (src, rows)) in planes.into_iter().enumerate() {
877 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
878 fill_plane(dest, offset, pitch, src, w, rows)?;
879 }
880 image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
881}
882
883fn fill_plane(
887 dst: &mut [u8],
888 offset: usize,
889 pitch: usize,
890 src: &[u8],
891 width: usize,
892 rows: usize,
893) -> anyhow::Result<()> {
894 if rows == 0 || width == 0 {
895 return Ok(());
896 }
897 let end = (rows - 1)
899 .checked_mul(pitch)
900 .and_then(|start| start.checked_add(offset)?.checked_add(width));
901 if pitch < width || end.is_none_or(|end| end > dst.len()) {
902 anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
903 }
904 for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
905 let start = offset + row * pitch;
906 dst[start..start + width].copy_from_slice(src);
907 }
908 Ok(())
909}
910
911fn build_sps_pps(config: &Config) -> anyhow::Result<(Sps, Pps)> {
916 let (primaries, transfer, matrix) = config.color.vui();
917 let vui = Vui {
918 aspect_ratio: Some(AspectRatio {
919 idc: 1, sar_width: 0,
921 sar_height: 0,
922 }),
923 overscan_appropriate: None,
924 video_signal: Some(VideoSignal {
925 video_format: 5, full_range: config.color.full_range,
927 colour: Some(Colour {
928 primaries,
929 transfer,
930 matrix,
931 }),
932 }),
933 chroma_loc: None,
934 timing: Some(Timing {
935 num_units_in_tick: 1,
936 time_scale: config.framerate.max(1) * 2,
938 fixed_frame_rate: false,
939 }),
940 nal_hrd: None,
941 vcl_hrd: None,
942 low_delay_hrd: false,
943 pic_struct_present: false,
944 restriction: Some(Restriction {
947 motion_vectors_over_pic_boundaries: true,
948 max_bytes_per_pic_denom: 2,
949 max_bits_per_mb_denom: 1,
950 log2_max_mv_length_horizontal: 16,
951 log2_max_mv_length_vertical: 16,
952 max_num_reorder_frames: 0,
953 max_dec_frame_buffering: 1,
954 }),
955 };
956 let sps = SpsBuilder::new(Profile::Main, level(config.width, config.height, config.framerate))
957 .log2_max_frame_num(LIMIT.ilog2() as u8)
958 .pic_order_cnt(PicOrderCnt::Lsb {
959 log2_max_lsb: (LIMIT * 2).ilog2() as u8,
960 })
961 .max_num_ref_frames(1)
962 .resolution(config.width, config.height)
963 .vui(vui)
964 .build()
965 .context("build the SPS")?;
966
967 let pps = PpsBuilder::new(&sps)
968 .entropy_coding_mode(true)
969 .deblocking_filter_control_present(true)
970 .build()
971 .context("build the PPS")?;
972
973 Ok((sps, pps))
974}
975
976fn h264_buffers(sps: &Sps, pps: &Pps, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
978 let meta = FrameMeta::new(picture.count);
979 let (slice_type, nal) = match picture.idr {
981 true => (
982 SliceType::I,
983 NaluHeader {
984 ref_idc: 3,
985 type_: NaluType::SliceIdr,
986 },
987 ),
988 false => (
989 SliceType::P,
990 NaluHeader {
991 ref_idc: 1,
992 type_: NaluType::Slice,
993 },
994 ),
995 };
996 let mut builder = SliceHeaderBuilder::new(sps, pps, slice_type)
997 .frame_num(meta.frame_num)
998 .pic_order_cnt_lsb(meta.poc % (LIMIT * 2));
999 if picture.idr {
1000 builder = builder.idr_pic_id(picture.idr_id % 2);
1002 }
1003 let header = builder.build(nal).context("build the slice header")?;
1004 let macroblocks = sps.width_mbs * sps.height_mbs;
1005 let reference = picture
1006 .reference
1007 .map(|reference| (reference.surface, FrameMeta::new(reference.count)));
1008
1009 let mut buffers = vec![
1010 build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
1011 build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
1012 build_enc_slice_param(pps, &header, reference, macroblocks),
1013 ];
1014 if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
1015 buffers.extend(packed_parameter_sets(sps, pps)?);
1016 }
1017 if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
1018 let mut out = Vec::new();
1019 let trailing = header
1020 .write(nal, sps, pps, &mut out)
1021 .context("write the slice header")?;
1022 let bits = out.len() * 8 - usize::from(trailing);
1024 buffers.extend(packed_header(EncPackedHeaderType::Slice, &out, bits));
1025 }
1026 Ok(buffers)
1027}
1028
1029fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
1031 let mut sps_nal = Vec::new();
1032 sps.write(3, &mut sps_nal).context("write the SPS")?;
1033 let mut pps_nal = Vec::new();
1034 pps.write(3, &mut pps_nal).context("write the PPS")?;
1035
1036 let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
1037 let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
1038 Ok([sps_param, sps_data, pps_param, pps_data])
1039}
1040
1041fn build_invalid_pic() -> PictureH264 {
1042 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1043}
1044
1045fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
1046 PictureH264::new(
1047 surface_id,
1048 meta.frame_num,
1049 VA_PICTURE_H264_SHORT_TERM_REFERENCE,
1050 meta.poc as i32,
1051 meta.poc as i32,
1052 )
1053}
1054
1055fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
1057 let (log2_max_lsb, delta_always_zero, offset_for_non_ref_pic, offset_for_top_to_bottom_field, cycle) =
1058 match &sps.pic_order_cnt {
1059 PicOrderCnt::Lsb { log2_max_lsb } => (*log2_max_lsb, false, 0, 0, &[][..]),
1060 PicOrderCnt::Cycle {
1061 delta_always_zero,
1062 offset_for_non_ref_pic,
1063 offset_for_top_to_bottom_field,
1064 offset_for_ref_frame,
1065 } => (
1066 4,
1067 *delta_always_zero,
1068 *offset_for_non_ref_pic,
1069 *offset_for_top_to_bottom_field,
1070 &offset_for_ref_frame[..],
1071 ),
1072 PicOrderCnt::Decode => (4, false, 0, 0, &[][..]),
1073 };
1074 let seq_fields = H264EncSeqFields::new(
1075 1, 1, 0, sps.scaling.is_some() as u32,
1079 sps.direct_8x8_inference as u32,
1080 u32::from(sps.log2_max_frame_num - 4),
1081 poc_type(&sps.pic_order_cnt),
1082 u32::from(log2_max_lsb - 4),
1083 delta_always_zero as u32,
1084 );
1085
1086 let frame_crop = sps
1088 .crop
1089 .map(|crop| H264EncFrameCropOffsets::new(crop.left / 2, crop.right / 2, crop.top / 2, crop.bottom / 2));
1090
1091 let vui = sps.vui.as_ref();
1092 let aspect_ratio = vui.and_then(|vui| vui.aspect_ratio);
1093 let timing = vui.and_then(|vui| vui.timing);
1094 let restriction = vui.and_then(|vui| vui.restriction);
1095 let vui_fields = vui.map(|vui| {
1096 H264VuiFields::new(
1097 aspect_ratio.is_some() as u32,
1098 timing.is_some() as u32,
1099 restriction.is_some() as u32,
1100 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_horizontal)),
1101 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_vertical)),
1102 timing.is_some_and(|t| t.fixed_frame_rate) as u32,
1103 vui.low_delay_hrd as u32,
1104 restriction.is_some_and(|r| r.motion_vectors_over_pic_boundaries) as u32,
1105 )
1106 });
1107
1108 let mut offset_for_ref_frame = [0i32; 256];
1109 offset_for_ref_frame[..cycle.len()].copy_from_slice(cycle);
1110
1111 BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
1113 sps.id,
1114 sps.level.value(),
1115 intra_period,
1116 intra_period,
1117 ip_period,
1118 bits_per_second,
1119 u32::from(sps.max_num_ref_frames),
1120 sps.width_mbs as u16,
1121 sps.height_mbs as u16,
1122 &seq_fields,
1123 0, 0, cycle.len() as u8,
1126 offset_for_non_ref_pic,
1127 offset_for_top_to_bottom_field,
1128 offset_for_ref_frame,
1129 frame_crop,
1130 vui_fields,
1131 aspect_ratio.map_or(0, |a| a.idc),
1132 aspect_ratio.map_or(0, |a| u32::from(a.sar_width)),
1133 aspect_ratio.map_or(0, |a| u32::from(a.sar_height)),
1134 timing.map_or(0, |t| t.num_units_in_tick),
1135 timing.map_or(0, |t| t.time_scale),
1136 )))
1137}
1138
1139fn poc_type(poc: &PicOrderCnt) -> u32 {
1141 match poc {
1142 PicOrderCnt::Lsb { .. } => 0,
1143 PicOrderCnt::Cycle { .. } => 1,
1144 PicOrderCnt::Decode => 2,
1145 }
1146}
1147
1148fn build_enc_pic_param(
1150 pps: &Pps,
1151 coded: &EncCodedBuffer,
1152 recon_id: u32,
1153 meta: FrameMeta,
1154 is_idr: bool,
1155 reference: Option<(u32, FrameMeta)>,
1156) -> BufferType {
1157 let pic_fields = H264EncPicFields::new(
1158 is_idr as u32,
1159 1, pps.entropy_coding_mode as u32,
1161 pps.weighted_pred as u32,
1162 u32::from(pps.weighted_bipred_idc),
1163 pps.constrained_intra_pred as u32,
1164 pps.transform_8x8_mode as u32,
1165 pps.deblocking_filter_control_present as u32,
1166 pps.redundant_pic_cnt_present as u32,
1167 0,
1168 pps.scaling.is_some() as u32,
1169 );
1170
1171 let curr_pic = build_h264_pic(recon_id, meta);
1172 let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
1173 if let Some((id, m)) = reference {
1174 reference_frames[0] = build_h264_pic(id, m);
1175 }
1176
1177 BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
1179 curr_pic,
1180 reference_frames,
1181 coded.id(),
1182 pps.id,
1183 pps.sps_id,
1184 0,
1185 meta.frame_num as u16,
1186 pps.pic_init_qp as u8,
1187 pps.num_ref_idx_l0_default_active - 1,
1188 pps.num_ref_idx_l1_default_active - 1,
1189 pps.chroma_qp_index_offset as i8,
1190 pps.second_chroma_qp_index_offset as i8,
1191 &pic_fields,
1192 )))
1193}
1194
1195fn build_enc_slice_param(
1198 pps: &Pps,
1199 header: &SliceHeader,
1200 reference: Option<(u32, FrameMeta)>,
1201 num_macroblocks: u32,
1202) -> BufferType {
1203 let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1204 if let Some((id, m)) = reference {
1205 ref_pic_list_0[0] = build_h264_pic(id, m);
1206 }
1207 let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1208
1209 let override_counts = match header.slice_type {
1212 SliceType::I => false,
1213 SliceType::P => header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active,
1214 SliceType::B => {
1215 header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active
1216 || header.num_ref_idx_l1_active != pps.num_ref_idx_l1_default_active
1217 }
1218 };
1219 let (l0, l1) = match override_counts {
1220 true => (header.num_ref_idx_l0_active, header.num_ref_idx_l1_active),
1221 false => (pps.num_ref_idx_l0_default_active, pps.num_ref_idx_l1_default_active),
1222 };
1223
1224 BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
1226 header.first_mb_in_slice,
1227 num_macroblocks,
1228 VA_INVALID_ID,
1229 header.slice_type_raw % 5,
1230 pps.id,
1231 header.idr_pic_id.unwrap_or(0) as u16,
1232 header.pic_order_cnt_lsb as u16,
1233 header.delta_pic_order_cnt_bottom,
1234 header.delta_pic_order_cnt,
1235 header.direct_spatial_mv_pred as u8,
1236 override_counts as u8,
1237 l0.saturating_sub(1),
1238 l1.saturating_sub(1),
1239 ref_pic_list_0,
1240 ref_pic_list_1,
1241 0,
1242 0,
1243 0,
1244 [0i16; 32],
1245 [0i16; 32],
1246 0,
1247 [[0i16; 2]; 32],
1248 [[0i16; 2]; 32],
1249 0,
1250 [0i16; 32],
1251 [0i16; 32],
1252 0,
1253 [[0i16; 2]; 32],
1254 [[0i16; 2]; 32],
1255 header.cabac_init_idc,
1256 (header.slice_qp - pps.pic_init_qp) as i8,
1257 header.disable_deblocking_filter_idc,
1258 header.slice_alpha_c0_offset_div2 as i8,
1259 header.slice_beta_offset_div2 as i8,
1260 )))
1261}
1262
1263fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
1265 let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
1266 let payload = BufferType::EncPackedHeaderData(data.to_vec());
1267 [param, payload]
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272 use std::path::PathBuf;
1273 use std::process::Command;
1274 use std::sync::atomic::{AtomicU32, Ordering};
1275
1276 use super::*;
1277 use crate::dmabuf::DmaBuf;
1278 use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};
1279
1280 const WIDTH: u32 = 640;
1282 const HEIGHT: u32 = 480;
1283 const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];
1284
1285 fn config(codec: Codec) -> Config {
1286 Config {
1287 codec,
1288 width: WIDTH,
1289 height: HEIGHT,
1290 framerate: 30,
1291 bitrate: 2_000_000,
1292 gop: NonZeroU32::new(30).unwrap(),
1293 device: None,
1294 color: Color::infer(HEIGHT),
1295 }
1296 }
1297
1298 fn encoder(config: Config) -> Encoder {
1299 Encoder::new(config).expect("open the VA-API encoder")
1300 }
1301
1302 fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
1304 match codec {
1305 Codec::H264 => (5, &[7, 8]),
1306 Codec::H265 => (19, &[32, 33, 34]),
1307 }
1308 }
1309
1310 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
1313 let (w, h) = (width as usize, height as usize);
1314 let mut data = vec![128u8; w * h + w * h.div_ceil(2)];
1315 for y in 0..h {
1316 for x in 0..w {
1317 data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
1318 }
1319 }
1320 let x0 = (step as usize * 8) % (w / 2);
1321 for y in h / 4..h / 2 {
1322 for x in x0..x0 + w / 4 {
1323 data[y * w + x] = 220;
1324 }
1325 }
1326 data
1327 }
1328
1329 fn temp_path(codec: Codec, label: &str) -> PathBuf {
1336 static NEXT: AtomicU32 = AtomicU32::new(0);
1337 let index = NEXT.fetch_add(1, Ordering::Relaxed);
1338 let extension = match codec {
1339 Codec::H264 => "264",
1340 Codec::H265 => "265",
1341 };
1342 std::env::temp_dir().join(format!(
1343 "kodecs-vaapi-{label}-{}-{index}.{extension}",
1344 std::process::id()
1345 ))
1346 }
1347
1348 fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> Vec<u8> {
1351 let path = temp_path(codec, name);
1354 std::fs::write(&path, stream).expect("write the elementary stream");
1355 let output = Command::new("ffmpeg")
1356 .args(["-v", "error", "-i"])
1357 .arg(&path)
1358 .args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
1359 .output();
1360 let _ = std::fs::remove_file(&path);
1361 let output = output.expect("run ffmpeg");
1362 assert!(
1363 output.status.success(),
1364 "ffmpeg refused the stream: {}",
1365 String::from_utf8_lossy(&output.stderr)
1366 );
1367 output.stdout
1368 }
1369
1370 fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
1372 let path = temp_path(codec, "probe");
1373 std::fs::write(&path, stream).expect("write the elementary stream");
1374 let output = Command::new("ffprobe")
1375 .args([
1376 "-v",
1377 "error",
1378 "-show_entries",
1379 "stream=color_range,color_space",
1380 "-of",
1381 "csv=p=0",
1382 ])
1383 .arg(&path)
1384 .output()
1385 .ok();
1386 let _ = std::fs::remove_file(&path);
1387 Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
1388 }
1389
1390 fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
1392 let len = (width * height) as usize;
1393 let mse = a[..len]
1394 .iter()
1395 .zip(&b[..len])
1396 .map(|(&x, &y)| (x as f64 - y as f64).powi(2))
1397 .sum::<f64>()
1398 / len as f64;
1399 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
1400 }
1401
1402 fn mean(
1404 plane: &[u8],
1405 stride: usize,
1406 (x0, y0, x1, y1): (usize, usize, usize, usize),
1407 step: usize,
1408 at: usize,
1409 ) -> f64 {
1410 let mut sum = 0.0;
1411 let mut count = 0.0;
1412 for y in y0..y1 {
1413 for x in x0..x1 {
1414 sum += plane[y * stride + x * step + at] as f64;
1415 count += 1.0;
1416 }
1417 }
1418 sum / count
1419 }
1420
1421 fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
1423 let mut types = Vec::new();
1424 let mut i = 0;
1425 while i + 3 < unit.len() {
1426 if unit[i..i + 3] == [0, 0, 1] {
1427 types.push(match codec {
1428 Codec::H264 => unit[i + 3] & 0x1f,
1429 Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
1430 });
1431 i += 3;
1432 }
1433 i += 1;
1434 }
1435 types
1436 }
1437
1438 fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
1440 display
1441 .create_surfaces(
1442 rt_format,
1443 Some(fourcc),
1444 width,
1445 height,
1446 Some(UsageHint::USAGE_HINT_EXPORT),
1447 vec![()],
1448 )
1449 .expect("allocate a surface")
1450 .pop()
1451 .expect("one surface")
1452 }
1453
1454 fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
1456 display
1457 .query_image_formats()
1458 .expect("query image formats")
1459 .into_iter()
1460 .find(|f| f.fourcc == fourcc)
1461 .expect("the driver has an image format for the surface format")
1462 }
1463
1464 fn surface_with(
1466 display: &Arc<Display>,
1467 fourcc: u32,
1468 rt_format: u32,
1469 size: (u32, u32),
1470 fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage),
1471 ) -> Surface<()> {
1472 let mut surface = blank_surface(display, fourcc, rt_format, size);
1473 let mut image =
1474 ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
1475 let va_image = *image.image();
1476 fill(image.as_mut(), &va_image);
1477 image.put().expect("put the image");
1478 surface.sync().expect("sync the filled surface");
1479 surface
1480 }
1481
1482 fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
1484 let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1485 let format = image_format(display, VA_FOURCC_NV12);
1486 upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
1487 DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
1488 }
1489
1490 #[test]
1493 #[ignore = "requires a VA-API render node"]
1494 fn the_render_node_is_found_or_named() {
1495 for codec in CODECS {
1496 let encoder = encoder(config(codec));
1497 let device = encoder.config().device.clone().expect("the picked node is recorded");
1498 let display = Display::open_drm_display(&device).expect("reopen the picked node");
1499 probe(&display, codec).expect("the picked node encodes the codec");
1500
1501 let named = Config {
1502 device: Some(PathBuf::from("/dev/null")),
1503 ..config(codec)
1504 };
1505 assert!(
1506 Encoder::new(named).is_err(),
1507 "a named node that is not a render node was swapped for one that is"
1508 );
1509 }
1510 }
1511
1512 #[test]
1515 #[ignore = "requires a VA-API render node and FFmpeg"]
1516 fn nv12_round_trips_through_a_software_decoder() {
1517 for codec in CODECS {
1518 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1519 let mut encoder = encoder(Config {
1520 width,
1521 height,
1522 ..config(codec)
1523 });
1524 let mut stream = Vec::new();
1525 let mut frames = Vec::new();
1526 for step in 0..10 {
1527 let frame = nv12_frame(width, height, step);
1528 stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
1529 frames.push(frame);
1530 }
1531 let decoded = ffmpeg_decode(codec, &stream, "nv12");
1532 let len = frames[0].len();
1533 assert_eq!(
1534 decoded.len(),
1535 len * frames.len(),
1536 "{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
1537 );
1538 for (index, frame) in frames.iter().enumerate() {
1539 let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
1540 assert!(
1541 psnr > 35.0,
1542 "{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
1543 );
1544 }
1545 }
1546 }
1547 }
1548
1549 #[test]
1551 #[ignore = "requires a VA-API render node and FFmpeg"]
1552 fn the_stream_is_labelled_with_its_color_space() {
1553 for codec in CODECS {
1554 for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
1555 let mut encoder = encoder(Config { color, ..config(codec) });
1556 let unit = encoder
1557 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1558 .expect("encode");
1559 let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
1560 assert_eq!(found, expected, "{codec:?}");
1561 }
1562 }
1563 }
1564
1565 #[test]
1568 fn a_plane_fills_up_to_its_last_byte_and_no_further() {
1569 let src = [1, 2, 3, 4, 5, 6];
1570 let mut tight = [0; 11];
1573 fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
1574 assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);
1575
1576 assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
1577 assert!(
1578 fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
1579 "a pitch narrower than a row"
1580 );
1581 assert!(
1582 fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
1583 "a pitch that overflows"
1584 );
1585 fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
1586 }
1587
1588 #[test]
1590 fn limits_check_the_coded_size_against_each_bound() {
1591 let limits = Limits {
1592 min_width: Some(384),
1593 min_height: None,
1594 max_width: Some(4096),
1595 max_height: Some(2304),
1596 round: (64, 16),
1597 };
1598 for (width, height) in [(384, 2), (322, 2304), (4096, 128)] {
1599 limits.check(width, height).expect("inside every bound");
1600 }
1601 for (width, height, named) in [
1602 (320, 240, "minimum encode width of 384"),
1603 (4098, 240, "maximum encode width of 4096"),
1604 (640, 2306, "maximum encode height of 2304"),
1605 (u32::MAX - 1, 240, "maximum encode width of 4096"),
1606 ] {
1607 let err = limits.check(width, height).expect_err("outside a bound");
1608 assert!(err.to_string().contains(named), "{width}x{height}: {err:#}");
1609 }
1610
1611 let unknown = Limits {
1612 min_width: None,
1613 min_height: None,
1614 max_width: None,
1615 max_height: None,
1616 round: (1, 1),
1617 };
1618 unknown.check(2, 2).expect("no bound to break");
1619 unknown.check(u32::MAX, u32::MAX).expect("no bound to break");
1620 }
1621
1622 #[test]
1627 #[ignore = "requires a VA-API render node"]
1628 fn a_frame_under_the_minimum_width_is_refused_naming_it() {
1629 let mut probed = 0;
1630 for device in crate::DrmDeviceIterator::default() {
1631 let display = Display::open_drm_display(&device).expect("open a render node");
1632 let vendor = display.query_vendor_string().unwrap_or_default();
1633 for codec in CODECS {
1634 let Ok(limits) = probe(&display, codec) else { continue };
1635 eprintln!("{device:?} ({vendor}) {codec:?}: {limits:?}");
1636 probed += 1;
1637 let min = limits.min_width.expect("the driver names a minimum width");
1638 let step = limits.round.0.max(2);
1640 let (under, over) = ((min - 1) / step * step, min.next_multiple_of(step) - step + 2);
1641 let named = |width| Config {
1642 width,
1643 device: Some(device.clone()),
1644 ..config(codec)
1645 };
1646 if under > 0 {
1647 let err = Encoder::new(named(under))
1648 .err()
1649 .expect("a frame under the minimum is refused");
1650 let wanted = format!("minimum encode width of {min}");
1651 assert!(err.to_string().contains(&wanted), "{codec:?} {under} wide: {err:#}");
1652 }
1653 let mut encoder =
1654 Encoder::new(named(over)).unwrap_or_else(|e| panic!("{device:?} {codec:?} {over} wide: {e:#}"));
1655 let frame = encoder.encode_nv12(&nv12_frame(over, HEIGHT, 0), true);
1656 assert!(
1657 !frame.expect("encode").is_empty(),
1658 "{device:?} {codec:?} {over} wide coded nothing"
1659 );
1660 }
1661 }
1662 assert!(probed > 0, "no render node encodes");
1663 }
1664
1665 #[test]
1667 fn an_odd_or_empty_size_is_refused() {
1668 for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
1669 let err = Encoder::new(Config {
1670 width,
1671 height,
1672 ..config(Codec::H264)
1673 })
1674 .err()
1675 .expect("refused");
1676 assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
1677 }
1678 }
1679
1680 #[test]
1683 #[ignore = "requires a VA-API render node"]
1684 fn an_upload_reads_back_as_the_same_pixels() {
1685 let display = Display::open().expect("no VA-API display");
1686 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1687 let frame = nv12_frame(width, height, 3);
1688 let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1689 let format = image_format(&display, VA_FOURCC_NV12);
1690 upload_nv12(format, &mut surface, width, height, &frame).expect("upload");
1691
1692 let image =
1693 crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
1694 let (va_image, data) = (*image.image(), image.as_ref());
1695 let (w, h) = (width as usize, height as usize);
1696 for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
1697 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
1698 for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
1699 let at = offset + row * pitch;
1700 assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
1701 }
1702 }
1703 }
1704 }
1705
1706 #[test]
1708 #[ignore = "requires a VA-API render node"]
1709 fn keyframes_follow_the_group_length() {
1710 for codec in CODECS {
1711 let mut encoder = encoder(Config {
1712 gop: NonZeroU32::new(10).unwrap(),
1713 ..config(codec)
1714 });
1715 let (idr_type, parameter_sets) = idr_types(codec);
1716 for step in 0..25 {
1717 let unit = encoder
1718 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
1719 .expect("encode");
1720 let types = nal_types(codec, &unit);
1721 let idr = types.contains(&idr_type);
1722 assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
1723 if idr {
1724 assert!(
1725 parameter_sets.iter().all(|kind| types.contains(kind)),
1726 "a {codec:?} IDR carries its parameter sets: {types:?}"
1727 );
1728 }
1729 }
1730 for step in 0..=10 {
1732 let unit = encoder
1733 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
1734 .expect("encode");
1735 assert_eq!(
1736 nal_types(codec, &unit).contains(&idr_type),
1737 step % 10 == 0,
1738 "{codec:?} frame {step} after the forced keyframe"
1739 );
1740 }
1741 }
1742 }
1743
1744 #[test]
1745 fn the_full_entrypoint_wins_and_low_power_is_the_fallback() {
1746 use VAEntrypoint::{
1747 VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode,
1748 };
1749 assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full));
1750 assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower));
1751 assert_eq!(pick_entrypoint(&[Decode]), None);
1752 }
1753
1754 #[test]
1757 #[ignore = "requires a VA-API render node and FFmpeg"]
1758 fn a_refused_import_leaves_the_encoder_usable() {
1759 let mut encoder = encoder(config(Codec::H264));
1760 let display = Display::open().expect("no VA-API display");
1761 let unmapped = DmaBuf {
1763 drm_format: u32::from_le_bytes(*b"ZZZZ"),
1764 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1765 };
1766 assert!(encoder.encode_dmabuf(unmapped, true).is_err());
1767 let unknown_modifier = DmaBuf {
1768 modifier: 0x00ff_ffff_ffff_fffe,
1769 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1770 };
1771 assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());
1772
1773 let unit = encoder
1774 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1775 .expect("the CPU path still encodes");
1776 let decoded = ffmpeg_decode(Codec::H264, &unit, "refused");
1777 let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
1778 assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
1779 }
1780
1781 #[test]
1786 #[ignore = "requires a VA-API render node and FFmpeg"]
1787 fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
1788 for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
1789 let mut encoder = encoder(Config {
1790 width,
1791 height,
1792 bitrate: 4_000_000,
1793 color: Color::infer(height),
1794 ..config(codec)
1795 });
1796 let display = Display::open().expect("no VA-API display");
1797 let unit = encoder
1798 .encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
1799 .expect("encode the DMA-BUF");
1800 let decoded = ffmpeg_decode(codec, &unit, "short");
1801 let frame = nv12_frame(width, height, 0);
1802 assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
1803 let psnr = luma_psnr(&frame, &decoded, width, height);
1804 assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
1805 }
1806 }
1807
1808 #[test]
1811 #[ignore = "requires a VA-API render node and FFmpeg"]
1812 fn a_yuv_dmabuf_in_another_space_is_converted() {
1813 for codec in CODECS {
1814 yuv_dmabuf_in_another_space_is_converted(codec);
1815 }
1816 }
1817
1818 fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) {
1819 let mut encoder = encoder(Config {
1820 color: Color::BT601,
1821 ..config(codec)
1822 });
1823 let display = Display::open().expect("no VA-API display");
1824 let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
1826 let surface = surface_with(
1827 &display,
1828 VA_FOURCC_NV12,
1829 VA_RT_FORMAT_YUV420,
1830 (WIDTH, HEIGHT),
1831 |data, image| {
1832 for row in 0..HEIGHT as usize {
1833 let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
1834 data[at..at + WIDTH as usize].fill(y);
1835 }
1836 for row in 0..HEIGHT as usize / 2 {
1837 let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
1838 for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
1839 pair.copy_from_slice(&[u, v]);
1840 }
1841 }
1842 },
1843 );
1844 let buffer = DmaBuf {
1845 color: Some(Color::BT709),
1846 ..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
1847 };
1848 let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
1849 let decoded = ffmpeg_decode(codec, &unit, "yuv-color");
1850
1851 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1852 let (luma, chroma) = decoded.split_at(w * h);
1853 let actual = [
1854 mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
1855 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
1856 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
1857 ];
1858 let expected = limited([255, 0, 0], Color::BT601);
1859 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1860 assert!(
1861 (a - e).abs() < 6.0,
1862 "{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
1863 );
1864 }
1865 }
1866
1867 #[test]
1869 #[ignore = "requires a VA-API render node and FFmpeg"]
1870 fn an_nv12_dmabuf_encodes_in_place() {
1871 for codec in CODECS {
1872 let mut encoder = encoder(config(codec));
1873 let display = Display::open().expect("no VA-API display");
1874 let mut stream = Vec::new();
1875 for step in 0..5 {
1876 let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
1877 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1878 }
1879 let decoded = ffmpeg_decode(codec, &stream, "dmabuf");
1880 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1881 assert_eq!(decoded.len(), 5 * len, "{codec:?}");
1882 for step in 0..5 {
1883 let psnr = luma_psnr(
1884 &nv12_frame(WIDTH, HEIGHT, step),
1885 &decoded[step as usize * len..],
1886 WIDTH,
1887 HEIGHT,
1888 );
1889 assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1890 }
1891 }
1892 }
1893
1894 #[test]
1896 #[ignore = "requires a VA-API render node and FFmpeg"]
1897 fn a_dmabuf_at_another_size_is_scaled() {
1898 for codec in CODECS {
1899 dmabuf_at_another_size_is_scaled(codec);
1900 }
1901 }
1902
1903 fn dmabuf_at_another_size_is_scaled(codec: Codec) {
1904 let mut encoder = encoder(config(codec));
1905 let display = Display::open().expect("no VA-API display");
1906 let mut stream = Vec::new();
1907 for step in 0..3 {
1908 let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
1909 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1910 }
1911 let decoded = ffmpeg_decode(codec, &stream, "scaled");
1912 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1913 assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
1914 for step in 0..3u32 {
1918 let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
1919 let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
1920 for y in 0..HEIGHT as usize {
1921 for x in 0..WIDTH as usize {
1922 expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
1923 }
1924 }
1925 let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
1926 assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1927 }
1928 }
1929
1930 #[test]
1932 #[ignore = "requires a VA-API render node and FFmpeg"]
1933 fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
1934 const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
1936 for (codec, color) in CODECS
1937 .into_iter()
1938 .flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
1939 {
1940 let mut encoder = encoder(Config { color, ..config(codec) });
1941 let display = Display::open().expect("no VA-API display");
1942 let surface = surface_with(
1943 &display,
1944 VA_FOURCC_BGRX,
1945 VA_RT_FORMAT_RGB32,
1946 (WIDTH, HEIGHT),
1947 |data, image| {
1948 let pitch = image.pitches[0] as usize;
1949 let offset = image.offsets[0] as usize;
1950 for y in 0..HEIGHT as usize {
1951 for x in 0..WIDTH as usize {
1952 let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
1953 let [r, g, b] = QUADRANTS[quadrant];
1954 let at = offset + y * pitch + x * 4;
1955 data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
1956 }
1957 }
1958 },
1959 );
1960 let exported = surface.export_prime().expect("export");
1961 let buffer = DmaBuf::from_prime(exported).expect("one object");
1962 assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
1963 let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
1964 let decoded = ffmpeg_decode(codec, &unit, "rgb");
1965
1966 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1967 let (luma, chroma) = decoded.split_at(w * h);
1968 for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
1969 let (qx, qy) = (quadrant % 2, quadrant / 2);
1970 let area = |scale: usize| {
1972 let (qw, qh) = (w / 2 / scale, h / 2 / scale);
1973 (
1974 qx * qw + qw / 4,
1975 qy * qh + qh / 4,
1976 qx * qw + qw * 3 / 4,
1977 qy * qh + qh * 3 / 4,
1978 )
1979 };
1980 let actual = [
1981 mean(luma, w, area(1), 1, 0),
1982 mean(chroma, w, area(2), 2, 0),
1983 mean(chroma, w, area(2), 2, 1),
1984 ];
1985 let expected = limited(*rgb, color);
1986 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1987 assert!(
1988 (a - e).abs() < 6.0,
1989 "{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
1990 );
1991 }
1992 }
1993 }
1994 }
1995
1996 #[test]
1997 fn the_level_covers_the_frame_size_and_rate() {
1998 assert_eq!(level(320, 240, 30), Level::L4);
1999 assert_eq!(level(1920, 1080, 30), Level::L4);
2000 assert_eq!(level(1920, 1080, 60), Level::L4_2);
2001 assert_eq!(level(2560, 1440, 30), Level::L5);
2002 assert_eq!(level(3840, 2160, 30), Level::L5_1);
2003 assert_eq!(level(3840, 2160, 60), Level::L5_2);
2004 assert_eq!(level(4352, 240, 30), Level::L5);
2006 }
2007
2008 #[test]
2009 fn an_unknown_framerate_still_builds_the_parameter_sets() {
2010 build_sps_pps(&Config {
2011 framerate: 0,
2012 ..config(Codec::H264)
2013 })
2014 .expect("build the SPS and PPS for framerate 0");
2015 }
2016
2017 fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
2019 let (kr, kb) = match color.matrix {
2020 crate::Matrix::Bt601 => (0.299, 0.114),
2021 crate::Matrix::Bt709 => (0.2126, 0.0722),
2022 };
2023 let (r, g, b) = (r as f64, g as f64, b as f64);
2024 let y = kr * r + (1.0 - kr - kb) * g + kb * b;
2025 [
2026 16.0 + y * 219.0 / 255.0,
2027 128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
2028 128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
2029 ]
2030 }
2031
2032 #[test]
2035 #[ignore = "requires a VA-API render node"]
2036 fn a_bitrate_change_takes_effect_without_a_keyframe() {
2037 for codec in CODECS {
2038 bitrate_change_takes_effect_without_a_keyframe(codec);
2039 }
2040 }
2041
2042 fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) {
2043 let mut encoder = encoder(Config {
2044 gop: NonZeroU32::new(1_000).unwrap(),
2045 ..config(codec)
2046 });
2047 let (idr_type, _) = idr_types(codec);
2048 let frame = |step: u32| {
2052 let (w, h) = (WIDTH as usize, HEIGHT as usize);
2053 let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
2054 for y in 0..h {
2055 for x in 0..w {
2056 let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
2057 let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
2058 frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
2059 }
2060 }
2061 frame
2062 };
2063 let average = |encoder: &mut Encoder, from: u32| {
2067 let sizes: Vec<usize> = (from..from + 60)
2068 .map(|step| {
2069 let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
2070 if step > 0 {
2071 assert!(
2072 !nal_types(codec, &unit).contains(&idr_type),
2073 "{codec:?} picture {step} is an IDR"
2074 );
2075 }
2076 unit.len()
2077 })
2078 .collect();
2079 sizes[30..].iter().sum::<usize>() / 30
2080 };
2081
2082 let within = |bytes: usize, bitrate: u32| {
2085 let target = bitrate as usize / 8 / 30;
2086 assert!(
2087 bytes * 4 <= target * 5,
2088 "{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
2089 );
2090 };
2091
2092 let high = average(&mut encoder, 0);
2093 within(high, 2_000_000);
2094 encoder.set_bitrate(250_000).expect("set the bitrate");
2095 assert_eq!(encoder.config().bitrate, 250_000);
2096 assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
2097 let low = average(&mut encoder, 60);
2098 eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
2099 within(low, 250_000);
2100 assert!(
2101 low * 3 < high,
2102 "{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
2103 );
2104 }
2105}