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, H264EncFrameCropOffsets,
51 H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture, PictureH264, RcFlags,
52 Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType, VAEntrypoint, VAImageFormat,
53 VAProfile, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE,
54 VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX, VA_FOURCC_NV12, VA_FOURCC_RGBA,
55 VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID, VA_PICTURE_H264_SHORT_TERM_REFERENCE,
56 VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
57};
58use kodecs_h264::{
59 Level, NaluHeader, NaluType, Pps, PpsBuilder, Profile, SliceHeader, SliceHeaderBuilder, SliceType, Sps, SpsBuilder,
60};
61
62mod h265;
63
64const MIN_QP: u8 = 24;
78const MAX_QP: u8 = 51;
79pub const HRD_FRAMES: u32 = 3;
85pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
90const LIMIT: u32 = 2048;
92
93#[derive(Clone, Debug)]
95pub struct Config {
96 pub codec: Codec,
98 pub width: u32,
99 pub height: u32,
100 pub framerate: u32,
101 pub bitrate: u32,
104 pub gop: NonZeroU32,
106 pub device: Option<PathBuf>,
112 pub color: Color,
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum RateControl {
132 Variable,
135 Constant,
139}
140
141impl RateControl {
142 fn pick(vendor: &str, offered: u32) -> Self {
145 match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
146 true => Self::Variable,
147 false => Self::Constant,
148 }
149 }
150
151 fn va(self) -> u32 {
152 match self {
153 Self::Variable => VA_RC_VBR,
154 Self::Constant => VA_RC_CBR,
155 }
156 }
157}
158
159#[derive(Copy, Clone)]
161struct FrameMeta {
162 poc: u32,
163 frame_num: u32,
164}
165
166impl FrameMeta {
167 fn new(count: u32) -> Self {
173 Self {
174 poc: count.wrapping_mul(2),
175 frame_num: count % LIMIT,
176 }
177 }
178}
179
180#[derive(Copy, Clone)]
182struct Reference {
183 surface: crate::bindings::VASurfaceID,
185 count: u32,
187}
188
189struct PictureInfo<'a> {
191 idr: bool,
192 idr_id: u32,
194 count: u32,
196 recon: crate::bindings::VASurfaceID,
198 reference: Option<Reference>,
199 coded: &'a EncCodedBuffer,
200 bitrate: u32,
201}
202
203enum Syntax {
205 H264 {
206 sps: Arc<Sps>,
207 pps: Arc<Pps>,
208 packed: u32,
210 },
211 H265 {
212 stream: h265::Stream,
213 packed: u32,
215 },
216}
217
218pub struct Encoder {
220 config: Config,
221 syntax: Syntax,
222
223 input: Option<Surface<()>>,
226 nv12: Option<VAImageFormat>,
228 recon: Vec<Surface<()>>,
229 reference: Option<(usize, u32)>,
231
232 counter: u32,
233 idrs: u32,
235
236 processor: Option<Processor>,
239 reset_rate_control: bool,
242 rate_control: RateControl,
243
244 coded: EncCodedBuffer,
246 coded_size: usize,
247 context: Rc<Context>,
248 _va_config: VaConfig,
249 display: Arc<Display>,
250}
251
252impl Encoder {
253 pub fn new(mut config: Config) -> anyhow::Result<Self> {
263 let (width, height) = (config.width, config.height);
264 if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
265 anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
266 }
267 let codec = config.codec;
268 let (device, display) = match config.device.take() {
269 Some(device) => {
270 let display = Display::open_drm_display(&device)
271 .map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
272 (device, display)
273 }
274 None => crate::display::open_first(|display| probe(display, codec))
275 .map_err(|e| e.context(format!("find a render node that encodes {codec:?}")))?,
276 };
277
278 let entrypoint = encode_entrypoint(&display, codec)?;
279 let rate_control = RateControl::pick(
280 &display.query_vendor_string().unwrap_or_default(),
281 config_attribute(
282 &display,
283 codec,
284 entrypoint,
285 VAConfigAttribType::VAConfigAttribRateControl,
286 ),
287 );
288 let mut attrs = vec![
289 VAConfigAttrib {
290 type_: VAConfigAttribType::VAConfigAttribRTFormat,
291 value: VA_RT_FORMAT_YUV420,
292 },
293 VAConfigAttrib {
294 type_: VAConfigAttribType::VAConfigAttribRateControl,
295 value: rate_control.va(),
296 },
297 ];
298 let wanted = match codec {
307 Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
308 Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
309 };
310 let packed = packed_headers(&display, codec, entrypoint) & wanted;
311 if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
314 anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
315 }
316 if packed != 0 {
317 attrs.push(VAConfigAttrib {
318 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
319 value: packed,
320 });
321 } else {
322 tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
323 }
324 let mut va_config = display
325 .create_config(attrs, profile(codec), entrypoint)
326 .map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
327
328 let syntax = match codec {
329 Codec::H264 => {
330 let (sps, pps) = build_sps_pps(&config);
331 Syntax::H264 { sps, pps, packed }
332 }
333 Codec::H265 => Syntax::H265 {
334 stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
335 packed,
336 },
337 };
338 let size = match &syntax {
342 Syntax::H264 { .. } => (config.width, config.height),
343 Syntax::H265 { stream, .. } => stream.coded(),
344 };
345
346 let context = display
347 .create_context::<()>(&va_config, size.0, size.1, None, true)
348 .map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;
349
350 let coded_size = coded_size(config.bitrate);
351 let coded = context
352 .create_enc_coded(coded_size)
353 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
354
355 let input = make_surface(&display, (config.width, config.height))?;
356 let nv12 = display
357 .query_image_formats()
358 .map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
359 .into_iter()
360 .find(|format| format.fourcc == VA_FOURCC_NV12);
361 let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];
362
363 tracing::info!(
364 "opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
365 device,
366 config.width,
367 config.height,
368 config.framerate,
369 config.bitrate,
370 rate_control,
371 entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
372 );
373 config.device = Some(device);
374 Ok(Self {
375 config,
376 syntax,
377 input: Some(input),
378 nv12,
379 recon,
380 reference: None,
381 counter: 0,
382 idrs: 0,
383 processor: None,
384 reset_rate_control: false,
385 rate_control,
386 coded,
387 coded_size,
388 context,
389 _va_config: va_config,
390 display,
391 })
392 }
393
394 pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
402 let format = self
403 .nv12
404 .ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
405 let mut input = self.input.take().expect("input surface present");
406 let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
407 .and_then(|()| self.encode_surface(&input, keyframe));
408 self.input = Some(input);
409 result
410 }
411
412 pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
440 let fourcc = buffer
441 .fourcc()
442 .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
443 let color = self.config.color;
444 let size = (self.config.width, self.config.height);
445 let unpadded = match &self.syntax {
446 Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
447 Syntax::H265 { stream, .. } => stream.coded() == size,
448 };
449 let in_place = fourcc == VA_FOURCC_NV12
450 && (buffer.width, buffer.height) == size
451 && unpadded
452 && buffer.color.is_none_or(|own| own == color);
453 if in_place {
454 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
455 return self.encode_surface(&source, keyframe);
456 }
457
458 let input_color = match is_rgb(fourcc) {
459 true => None,
460 false => Some(buffer.color.unwrap_or(color)),
461 };
462 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
463 let input = self.input.take().expect("input surface present");
464 let result = self
465 .processor()
466 .and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
467 .and_then(|()| self.encode_surface(&input, keyframe));
468 self.input = Some(input);
469 result
470 }
471
472 pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
487 if bitrate == 0 {
488 anyhow::bail!("a bitrate of zero");
489 }
490 let size = coded_size(bitrate);
491 if size > self.coded_size {
492 self.coded = self
495 .context
496 .create_enc_coded(size)
497 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
498 self.coded_size = size;
499 }
500 if bitrate != self.config.bitrate {
501 self.reset_rate_control = true;
502 }
503 self.config.bitrate = bitrate;
504 Ok(())
505 }
506
507 pub fn rate_control(&self) -> RateControl {
509 self.rate_control
510 }
511
512 pub fn config(&self) -> &Config {
514 &self.config
515 }
516
517 fn processor(&mut self) -> anyhow::Result<&Processor> {
519 if self.processor.is_none() {
520 self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
521 }
522 Ok(self.processor.as_ref().expect("opened above"))
523 }
524
525 fn encode_surface<D: SurfaceMemoryDescriptor>(
527 &mut self,
528 source: &Surface<D>,
529 keyframe: bool,
530 ) -> anyhow::Result<Vec<u8>> {
531 let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
532 if is_idr {
533 self.counter = 0;
535 self.reference = None;
536 }
537
538 let recon_idx = (self.counter as usize) % self.recon.len();
539 let reference = match (is_idr, self.reference) {
541 (false, Some((index, count))) => Some(Reference {
542 surface: self.recon[index].id(),
543 count,
544 }),
545 _ => None,
546 };
547 let info = PictureInfo {
548 idr: is_idr,
549 idr_id: self.idrs,
550 count: self.counter,
551 recon: self.recon[recon_idx].id(),
552 reference,
553 coded: &self.coded,
554 bitrate: self.config.bitrate,
555 };
556 let buffers = match &self.syntax {
557 Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
558 Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
559 };
560
561 let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);
562
563 for buffer in buffers {
566 picture.add_buffer(self.create(buffer)?);
567 }
568
569 let bits_per_second = self.config.bitrate;
570 let rc = EncMiscParameterRateControl::new(
571 bits_per_second,
572 100, RATE_CONTROL_WINDOW_MS, u32::from((MIN_QP + MAX_QP) / 2),
575 MIN_QP as u32,
576 0, RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
581 0, MAX_QP as u32,
583 0, 0, );
586 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
587 let hrd = hrd_size(bits_per_second, self.config.framerate);
589 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
590 EncMiscParameterHRD::new(hrd, hrd),
591 )))?);
592
593 let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
594 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);
595
596 let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
597 let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
598 let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
599 picture
602 .sync()
603 .map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;
604
605 let bitstream = self.read_coded()?;
607
608 self.reference = Some((recon_idx, self.counter));
609 self.counter += 1;
610 self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
611 self.reset_rate_control = false;
612 Ok(bitstream)
613 }
614
615 fn create(&self, buffer: BufferType) -> anyhow::Result<crate::Buffer> {
616 self.context
617 .create_buffer(buffer)
618 .map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}"))
619 }
620
621 fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
622 let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
623 let mut out = Vec::new();
624 for segment in mapped.iter() {
625 out.extend_from_slice(segment.buf);
626 }
627 Ok(out)
628 }
629}
630
631pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
638 encode_entrypoint(display, codec).map(drop)
639}
640
641fn profile(codec: Codec) -> VAProfile::Type {
643 match codec {
644 Codec::H264 => VAProfile::VAProfileH264Main,
645 Codec::H265 => h265::PROFILE,
646 }
647}
648
649fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
653 let entrypoints = display
654 .query_config_entrypoints(profile(codec))
655 .map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
656 pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
657}
658
659fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option<VAEntrypoint::Type> {
661 [VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
662 .into_iter()
663 .find(|entrypoint| offered.contains(entrypoint))
664}
665
666fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 {
670 config_attribute(
671 display,
672 codec,
673 entrypoint,
674 VAConfigAttribType::VAConfigAttribEncPackedHeaders,
675 )
676}
677
678fn config_attribute(
680 display: &Display,
681 codec: Codec,
682 entrypoint: VAEntrypoint::Type,
683 type_: VAConfigAttribType::Type,
684) -> u32 {
685 let mut attrs = [VAConfigAttrib { type_, value: 0 }];
686 if display
687 .get_config_attributes(profile(codec), entrypoint, &mut attrs)
688 .is_err()
689 || attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
690 {
691 return 0;
692 }
693 attrs[0].value
694}
695
696fn level(width: u32, height: u32, framerate: u32) -> Level {
705 const LEVELS: [(Level, u64, u64); 8] = [
707 (Level::L4, 245_760, 8_192),
708 (Level::L4_2, 522_240, 8_704),
709 (Level::L5, 589_824, 22_080),
710 (Level::L5_1, 983_040, 36_864),
711 (Level::L5_2, 2_073_600, 36_864),
712 (Level::L6, 4_177_920, 139_264),
713 (Level::L6_1, 8_355_840, 139_264),
714 (Level::L6_2, 16_711_680, 139_264),
715 ];
716 let frame = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
717 let rate = frame * u64::from(framerate.max(1));
718 LEVELS
719 .into_iter()
720 .find(|&(_, max_rate, max_frame)| frame <= max_frame && rate <= max_rate)
721 .map(|(level, _, _)| level)
722 .unwrap_or(Level::L6_2)
723}
724
725fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
727 (u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
728}
729
730fn coded_size(bitrate: u32) -> usize {
732 (bitrate as usize / 4).max(1_500_000)
733}
734
735fn is_rgb(fourcc: u32) -> bool {
737 matches!(
738 fourcc,
739 VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
740 )
741}
742
743fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
745 let mut surfaces = display
746 .create_surfaces::<()>(
747 VA_RT_FORMAT_YUV420,
748 Some(VA_FOURCC_NV12),
749 width,
750 height,
751 Some(UsageHint::USAGE_HINT_ENCODER),
752 vec![()],
753 )
754 .map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
755 surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
756}
757
758fn upload_nv12(
762 format: VAImageFormat,
763 surface: &mut Surface<()>,
764 width: u32,
765 height: u32,
766 data: &[u8],
767) -> anyhow::Result<()> {
768 let (w, h) = (width as usize, height as usize);
769 let luma = w * h;
770 let expected = luma + w * (h / 2);
771 if data.len() < expected {
772 anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
773 }
774
775 let mut image =
776 ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
777 let va_image = *image.image();
778 let dest: &mut [u8] = image.as_mut();
779 let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
780 for (plane, (src, rows)) in planes.into_iter().enumerate() {
781 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
782 fill_plane(dest, offset, pitch, src, w, rows)?;
783 }
784 image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
785}
786
787fn fill_plane(
791 dst: &mut [u8],
792 offset: usize,
793 pitch: usize,
794 src: &[u8],
795 width: usize,
796 rows: usize,
797) -> anyhow::Result<()> {
798 if rows == 0 || width == 0 {
799 return Ok(());
800 }
801 let end = (rows - 1)
803 .checked_mul(pitch)
804 .and_then(|start| start.checked_add(offset)?.checked_add(width));
805 if pitch < width || end.is_none_or(|end| end > dst.len()) {
806 anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
807 }
808 for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
809 let start = offset + row * pitch;
810 dst[start..start + width].copy_from_slice(src);
811 }
812 Ok(())
813}
814
815fn build_sps_pps(config: &Config) -> (Arc<Sps>, Arc<Pps>) {
818 let level = level(config.width, config.height, config.framerate);
819 let (primaries, transfer, matrix) = config.color.vui();
820 let sps = SpsBuilder::new()
821 .seq_parameter_set_id(0)
822 .profile_idc(Profile::Main)
823 .chroma_format_idc(1)
824 .level_idc(level)
825 .max_frame_num(LIMIT)
826 .pic_order_cnt_type(0)
827 .max_pic_order_cnt_lsb(LIMIT * 2)
828 .max_num_ref_frames(1)
829 .frame_mbs_only_flag(true)
830 .direct_8x8_inference_flag(level >= Level::L3)
831 .resolution(config.width, config.height)
832 .bit_depth_luma(8)
833 .bit_depth_chroma(8)
834 .aspect_ratio(1, 1)
835 .timing_info(1, config.framerate * 2, false)
836 .video_signal_type(config.color.full_range, primaries, transfer, matrix)
837 .max_num_reorder_frames(0)
838 .max_dec_frame_buffering(1)
839 .build();
840
841 let pps = PpsBuilder::new(Arc::clone(&sps))
842 .pic_parameter_set_id(0)
843 .pic_init_qp(26)
844 .entropy_coding_mode_flag(true)
845 .transform_8x8_mode_flag(false)
846 .deblocking_filter_control_present_flag(true)
847 .num_ref_idx_l0_default_active(1)
848 .num_ref_idx_l1_default_active_minus1(0)
849 .build();
850
851 (sps, pps)
852}
853
854fn h264_buffers(sps: &Sps, pps: &Arc<Pps>, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
856 let meta = FrameMeta::new(picture.count);
857 let slice_type = if picture.idr { SliceType::I } else { SliceType::P };
858 let header = SliceHeaderBuilder::new(pps)
859 .slice_type(slice_type)
860 .first_mb_in_slice(0)
861 .frame_num(meta.frame_num as u16)
862 .pic_order_cnt_lsb((meta.poc % (LIMIT * 2)) as u16)
863 .idr_pic_id((picture.idr_id % 2) as u16)
865 .build();
866 let macroblocks = (sps.pic_width_in_mbs_minus1 as u32 + 1) * (sps.pic_height_in_map_units_minus1 as u32 + 1);
867 let reference = picture
868 .reference
869 .map(|reference| (reference.surface, FrameMeta::new(reference.count)));
870
871 let mut buffers = vec![
872 build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
873 build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
874 build_enc_slice_param(pps, &header, reference, macroblocks),
875 ];
876 if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
877 buffers.extend(packed_parameter_sets(sps, pps)?);
878 }
879 if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
880 let mut nal = Vec::new();
881 let nal_header = match picture.idr {
883 true => NaluHeader {
884 ref_idc: 3,
885 type_: NaluType::SliceIdr,
886 },
887 false => NaluHeader {
888 ref_idc: 1,
889 type_: NaluType::Slice,
890 },
891 };
892 let trailing = header
893 .write(nal_header, pps, &mut nal)
894 .context("write the slice header")?;
895 let bits = nal.len() * 8 - usize::from(trailing);
897 buffers.extend(packed_header(EncPackedHeaderType::Slice, &nal, bits));
898 }
899 Ok(buffers)
900}
901
902fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
904 let mut sps_nal = Vec::new();
905 sps.write(3, &mut sps_nal).context("write the SPS")?;
906 let mut pps_nal = Vec::new();
907 pps.write(3, &mut pps_nal).context("write the PPS")?;
908
909 let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
910 let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
911 Ok([sps_param, sps_data, pps_param, pps_data])
912}
913
914fn build_invalid_pic() -> PictureH264 {
915 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
916}
917
918fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
919 PictureH264::new(
920 surface_id,
921 meta.frame_num,
922 VA_PICTURE_H264_SHORT_TERM_REFERENCE,
923 meta.poc as i32,
924 meta.poc as i32,
925 )
926}
927
928fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
930 let seq_fields = H264EncSeqFields::new(
931 sps.chroma_format_idc as u32,
932 sps.frame_mbs_only_flag as u32,
933 sps.mb_adaptive_frame_field_flag as u32,
934 sps.seq_scaling_matrix_present_flag as u32,
935 sps.direct_8x8_inference_flag as u32,
936 sps.log2_max_frame_num_minus4 as u32,
937 sps.pic_order_cnt_type as u32,
938 sps.log2_max_pic_order_cnt_lsb_minus4 as u32,
939 sps.delta_pic_order_always_zero_flag as u32,
940 );
941
942 let frame_crop = if sps.frame_cropping_flag {
943 Some(H264EncFrameCropOffsets::new(
944 sps.frame_crop_left_offset,
945 sps.frame_crop_right_offset,
946 sps.frame_crop_top_offset,
947 sps.frame_crop_bottom_offset,
948 ))
949 } else {
950 None
951 };
952
953 let vui_fields = if sps.vui_parameters_present_flag {
954 Some(H264VuiFields::new(
955 sps.vui_parameters.aspect_ratio_idc as u32,
956 sps.vui_parameters.timing_info_present_flag as u32,
957 sps.vui_parameters.bitstream_restriction_flag as u32,
958 sps.vui_parameters.log2_max_mv_length_horizontal,
959 sps.vui_parameters.log2_max_mv_length_vertical,
960 sps.vui_parameters.fixed_frame_rate_flag as u32,
961 sps.vui_parameters.low_delay_hrd_flag as u32,
962 sps.vui_parameters.motion_vectors_over_pic_boundaries_flag as u32,
963 ))
964 } else {
965 None
966 };
967
968 let mut offset_for_ref_frame = [0i32; 256];
969 offset_for_ref_frame[..255].copy_from_slice(&sps.offset_for_ref_frame[..]);
970
971 BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
972 sps.seq_parameter_set_id,
973 sps.level_idc as u8,
974 intra_period,
975 intra_period,
976 ip_period,
977 bits_per_second,
978 sps.max_num_ref_frames as u32,
979 sps.pic_width_in_mbs_minus1 + 1,
980 sps.pic_height_in_map_units_minus1 + 1,
981 &seq_fields,
982 sps.bit_depth_luma_minus8,
983 sps.bit_depth_chroma_minus8,
984 sps.num_ref_frames_in_pic_order_cnt_cycle,
985 sps.offset_for_non_ref_pic,
986 sps.offset_for_top_to_bottom_field,
987 offset_for_ref_frame,
988 frame_crop,
989 vui_fields,
990 sps.vui_parameters.aspect_ratio_idc,
991 sps.vui_parameters.sar_width as u32,
992 sps.vui_parameters.sar_height as u32,
993 sps.vui_parameters.num_units_in_tick,
994 sps.vui_parameters.time_scale,
995 )))
996}
997
998fn build_enc_pic_param(
1000 pps: &Pps,
1001 coded: &EncCodedBuffer,
1002 recon_id: u32,
1003 meta: FrameMeta,
1004 is_idr: bool,
1005 reference: Option<(u32, FrameMeta)>,
1006) -> BufferType {
1007 let pic_fields = H264EncPicFields::new(
1008 is_idr as u32,
1009 1, pps.entropy_coding_mode_flag as u32,
1011 pps.weighted_pred_flag as u32,
1012 pps.weighted_bipred_idc as u32,
1013 pps.constrained_intra_pred_flag as u32,
1014 pps.transform_8x8_mode_flag as u32,
1015 pps.deblocking_filter_control_present_flag as u32,
1016 pps.redundant_pic_cnt_present_flag as u32,
1017 0,
1018 pps.pic_scaling_matrix_present_flag as u32,
1019 );
1020
1021 let curr_pic = build_h264_pic(recon_id, meta);
1022 let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
1023 if let Some((id, m)) = reference {
1024 reference_frames[0] = build_h264_pic(id, m);
1025 }
1026
1027 BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
1028 curr_pic,
1029 reference_frames,
1030 coded.id(),
1031 pps.pic_parameter_set_id,
1032 pps.sps.seq_parameter_set_id,
1033 0,
1034 meta.frame_num as u16,
1035 (pps.pic_init_qp_minus26 + 26) as u8,
1036 pps.num_ref_idx_l0_default_active_minus1,
1037 pps.num_ref_idx_l1_default_active_minus1,
1038 pps.chroma_qp_index_offset,
1039 pps.second_chroma_qp_index_offset,
1040 &pic_fields,
1041 )))
1042}
1043
1044fn build_enc_slice_param(
1047 pps: &Pps,
1048 header: &SliceHeader,
1049 reference: Option<(u32, FrameMeta)>,
1050 num_macroblocks: u32,
1051) -> BufferType {
1052 let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1053 if let Some((id, m)) = reference {
1054 ref_pic_list_0[0] = build_h264_pic(id, m);
1055 }
1056 let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1057
1058 let (num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1) = if header.num_ref_idx_active_override_flag {
1059 (header.num_ref_idx_l0_active_minus1, header.num_ref_idx_l1_active_minus1)
1060 } else {
1061 (
1062 pps.num_ref_idx_l0_default_active_minus1,
1063 pps.num_ref_idx_l1_default_active_minus1,
1064 )
1065 };
1066
1067 BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
1068 header.first_mb_in_slice,
1069 num_macroblocks,
1070 VA_INVALID_ID,
1071 header.slice_type as u8,
1072 pps.pic_parameter_set_id,
1073 header.idr_pic_id,
1074 header.pic_order_cnt_lsb,
1075 header.delta_pic_order_cnt_bottom,
1076 header.delta_pic_order_cnt,
1077 header.direct_spatial_mv_pred_flag as u8,
1078 header.num_ref_idx_active_override_flag as u8,
1079 num_ref_idx_l0_active_minus1,
1080 num_ref_idx_l1_active_minus1,
1081 ref_pic_list_0,
1082 ref_pic_list_1,
1083 header.pred_weight_table.luma_log2_weight_denom,
1084 header.pred_weight_table.chroma_log2_weight_denom,
1085 0,
1086 header.pred_weight_table.luma_weight_l0,
1087 [0i16; 32],
1088 0,
1089 header.pred_weight_table.chroma_weight_l0,
1090 [[0i16; 2]; 32],
1091 0,
1092 header.pred_weight_table.luma_weight_l1,
1093 [0i16; 32],
1094 0,
1095 header.pred_weight_table.chroma_weight_l1,
1096 [[0i16; 2]; 32],
1097 header.cabac_init_idc,
1098 header.slice_qp_delta,
1099 header.disable_deblocking_filter_idc,
1100 header.slice_alpha_c0_offset_div2,
1101 header.slice_beta_offset_div2,
1102 )))
1103}
1104
1105fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
1107 let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
1108 let payload = BufferType::EncPackedHeaderData(data.to_vec());
1109 [param, payload]
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114 use std::path::PathBuf;
1115 use std::process::Command;
1116 use std::sync::atomic::{AtomicU32, Ordering};
1117
1118 use super::*;
1119 use crate::dmabuf::DmaBuf;
1120 use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};
1121
1122 const WIDTH: u32 = 640;
1124 const HEIGHT: u32 = 480;
1125 const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];
1126
1127 fn config(codec: Codec) -> Config {
1128 Config {
1129 codec,
1130 width: WIDTH,
1131 height: HEIGHT,
1132 framerate: 30,
1133 bitrate: 2_000_000,
1134 gop: NonZeroU32::new(30).unwrap(),
1135 device: None,
1136 color: Color::infer(HEIGHT),
1137 }
1138 }
1139
1140 fn encoder(config: Config) -> Encoder {
1141 Encoder::new(config).expect("open the VA-API encoder")
1142 }
1143
1144 fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
1146 match codec {
1147 Codec::H264 => (5, &[7, 8]),
1148 Codec::H265 => (19, &[32, 33, 34]),
1149 }
1150 }
1151
1152 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
1155 let (w, h) = (width as usize, height as usize);
1156 let mut data = vec![128u8; w * h + w * h.div_ceil(2)];
1157 for y in 0..h {
1158 for x in 0..w {
1159 data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
1160 }
1161 }
1162 let x0 = (step as usize * 8) % (w / 2);
1163 for y in h / 4..h / 2 {
1164 for x in x0..x0 + w / 4 {
1165 data[y * w + x] = 220;
1166 }
1167 }
1168 data
1169 }
1170
1171 fn temp_path(codec: Codec, label: &str) -> PathBuf {
1178 static NEXT: AtomicU32 = AtomicU32::new(0);
1179 let index = NEXT.fetch_add(1, Ordering::Relaxed);
1180 let extension = match codec {
1181 Codec::H264 => "264",
1182 Codec::H265 => "265",
1183 };
1184 std::env::temp_dir().join(format!(
1185 "kodecs-vaapi-{label}-{}-{index}.{extension}",
1186 std::process::id()
1187 ))
1188 }
1189
1190 fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> Vec<u8> {
1193 let path = temp_path(codec, name);
1196 std::fs::write(&path, stream).expect("write the elementary stream");
1197 let output = Command::new("ffmpeg")
1198 .args(["-v", "error", "-i"])
1199 .arg(&path)
1200 .args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
1201 .output();
1202 let _ = std::fs::remove_file(&path);
1203 let output = output.expect("run ffmpeg");
1204 assert!(
1205 output.status.success(),
1206 "ffmpeg refused the stream: {}",
1207 String::from_utf8_lossy(&output.stderr)
1208 );
1209 output.stdout
1210 }
1211
1212 fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
1214 let path = temp_path(codec, "probe");
1215 std::fs::write(&path, stream).expect("write the elementary stream");
1216 let output = Command::new("ffprobe")
1217 .args([
1218 "-v",
1219 "error",
1220 "-show_entries",
1221 "stream=color_range,color_space",
1222 "-of",
1223 "csv=p=0",
1224 ])
1225 .arg(&path)
1226 .output()
1227 .ok();
1228 let _ = std::fs::remove_file(&path);
1229 Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
1230 }
1231
1232 fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
1234 let len = (width * height) as usize;
1235 let mse = a[..len]
1236 .iter()
1237 .zip(&b[..len])
1238 .map(|(&x, &y)| (x as f64 - y as f64).powi(2))
1239 .sum::<f64>()
1240 / len as f64;
1241 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
1242 }
1243
1244 fn mean(
1246 plane: &[u8],
1247 stride: usize,
1248 (x0, y0, x1, y1): (usize, usize, usize, usize),
1249 step: usize,
1250 at: usize,
1251 ) -> f64 {
1252 let mut sum = 0.0;
1253 let mut count = 0.0;
1254 for y in y0..y1 {
1255 for x in x0..x1 {
1256 sum += plane[y * stride + x * step + at] as f64;
1257 count += 1.0;
1258 }
1259 }
1260 sum / count
1261 }
1262
1263 fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
1265 let mut types = Vec::new();
1266 let mut i = 0;
1267 while i + 3 < unit.len() {
1268 if unit[i..i + 3] == [0, 0, 1] {
1269 types.push(match codec {
1270 Codec::H264 => unit[i + 3] & 0x1f,
1271 Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
1272 });
1273 i += 3;
1274 }
1275 i += 1;
1276 }
1277 types
1278 }
1279
1280 fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
1282 display
1283 .create_surfaces(
1284 rt_format,
1285 Some(fourcc),
1286 width,
1287 height,
1288 Some(UsageHint::USAGE_HINT_EXPORT),
1289 vec![()],
1290 )
1291 .expect("allocate a surface")
1292 .pop()
1293 .expect("one surface")
1294 }
1295
1296 fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
1298 display
1299 .query_image_formats()
1300 .expect("query image formats")
1301 .into_iter()
1302 .find(|f| f.fourcc == fourcc)
1303 .expect("the driver has an image format for the surface format")
1304 }
1305
1306 fn surface_with(
1308 display: &Arc<Display>,
1309 fourcc: u32,
1310 rt_format: u32,
1311 size: (u32, u32),
1312 fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage),
1313 ) -> Surface<()> {
1314 let mut surface = blank_surface(display, fourcc, rt_format, size);
1315 let mut image =
1316 ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
1317 let va_image = *image.image();
1318 fill(image.as_mut(), &va_image);
1319 image.put().expect("put the image");
1320 surface.sync().expect("sync the filled surface");
1321 surface
1322 }
1323
1324 fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
1326 let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1327 let format = image_format(display, VA_FOURCC_NV12);
1328 upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
1329 DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
1330 }
1331
1332 #[test]
1335 #[ignore = "requires a VA-API render node"]
1336 fn the_render_node_is_found_or_named() {
1337 for codec in CODECS {
1338 let encoder = encoder(config(codec));
1339 let device = encoder.config().device.clone().expect("the picked node is recorded");
1340 let display = Display::open_drm_display(&device).expect("reopen the picked node");
1341 probe(&display, codec).expect("the picked node encodes the codec");
1342
1343 let named = Config {
1344 device: Some(PathBuf::from("/dev/null")),
1345 ..config(codec)
1346 };
1347 assert!(
1348 Encoder::new(named).is_err(),
1349 "a named node that is not a render node was swapped for one that is"
1350 );
1351 }
1352 }
1353
1354 #[test]
1357 #[ignore = "requires a VA-API render node and FFmpeg"]
1358 fn nv12_round_trips_through_a_software_decoder() {
1359 for codec in CODECS {
1360 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1361 let mut encoder = encoder(Config {
1362 width,
1363 height,
1364 ..config(codec)
1365 });
1366 let mut stream = Vec::new();
1367 let mut frames = Vec::new();
1368 for step in 0..10 {
1369 let frame = nv12_frame(width, height, step);
1370 stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
1371 frames.push(frame);
1372 }
1373 let decoded = ffmpeg_decode(codec, &stream, "nv12");
1374 let len = frames[0].len();
1375 assert_eq!(
1376 decoded.len(),
1377 len * frames.len(),
1378 "{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
1379 );
1380 for (index, frame) in frames.iter().enumerate() {
1381 let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
1382 assert!(
1383 psnr > 35.0,
1384 "{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
1385 );
1386 }
1387 }
1388 }
1389 }
1390
1391 #[test]
1393 #[ignore = "requires a VA-API render node and FFmpeg"]
1394 fn the_stream_is_labelled_with_its_color_space() {
1395 for codec in CODECS {
1396 for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
1397 let mut encoder = encoder(Config { color, ..config(codec) });
1398 let unit = encoder
1399 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1400 .expect("encode");
1401 let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
1402 assert_eq!(found, expected, "{codec:?}");
1403 }
1404 }
1405 }
1406
1407 #[test]
1410 fn a_plane_fills_up_to_its_last_byte_and_no_further() {
1411 let src = [1, 2, 3, 4, 5, 6];
1412 let mut tight = [0; 11];
1415 fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
1416 assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);
1417
1418 assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
1419 assert!(
1420 fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
1421 "a pitch narrower than a row"
1422 );
1423 assert!(
1424 fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
1425 "a pitch that overflows"
1426 );
1427 fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
1428 }
1429
1430 #[test]
1432 fn an_odd_or_empty_size_is_refused() {
1433 for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
1434 let err = Encoder::new(Config {
1435 width,
1436 height,
1437 ..config(Codec::H264)
1438 })
1439 .err()
1440 .expect("refused");
1441 assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
1442 }
1443 }
1444
1445 #[test]
1448 #[ignore = "requires a VA-API render node"]
1449 fn an_upload_reads_back_as_the_same_pixels() {
1450 let display = Display::open().expect("no VA-API display");
1451 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1452 let frame = nv12_frame(width, height, 3);
1453 let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1454 let format = image_format(&display, VA_FOURCC_NV12);
1455 upload_nv12(format, &mut surface, width, height, &frame).expect("upload");
1456
1457 let image =
1458 crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
1459 let (va_image, data) = (*image.image(), image.as_ref());
1460 let (w, h) = (width as usize, height as usize);
1461 for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
1462 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
1463 for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
1464 let at = offset + row * pitch;
1465 assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
1466 }
1467 }
1468 }
1469 }
1470
1471 #[test]
1473 #[ignore = "requires a VA-API render node"]
1474 fn keyframes_follow_the_group_length() {
1475 for codec in CODECS {
1476 let mut encoder = encoder(Config {
1477 gop: NonZeroU32::new(10).unwrap(),
1478 ..config(codec)
1479 });
1480 let (idr_type, parameter_sets) = idr_types(codec);
1481 for step in 0..25 {
1482 let unit = encoder
1483 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
1484 .expect("encode");
1485 let types = nal_types(codec, &unit);
1486 let idr = types.contains(&idr_type);
1487 assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
1488 if idr {
1489 assert!(
1490 parameter_sets.iter().all(|kind| types.contains(kind)),
1491 "a {codec:?} IDR carries its parameter sets: {types:?}"
1492 );
1493 }
1494 }
1495 for step in 0..=10 {
1497 let unit = encoder
1498 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
1499 .expect("encode");
1500 assert_eq!(
1501 nal_types(codec, &unit).contains(&idr_type),
1502 step % 10 == 0,
1503 "{codec:?} frame {step} after the forced keyframe"
1504 );
1505 }
1506 }
1507 }
1508
1509 #[test]
1510 fn the_full_entrypoint_wins_and_low_power_is_the_fallback() {
1511 use VAEntrypoint::{
1512 VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode,
1513 };
1514 assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full));
1515 assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower));
1516 assert_eq!(pick_entrypoint(&[Decode]), None);
1517 }
1518
1519 #[test]
1522 #[ignore = "requires a VA-API render node and FFmpeg"]
1523 fn a_refused_import_leaves_the_encoder_usable() {
1524 let mut encoder = encoder(config(Codec::H264));
1525 let display = Display::open().expect("no VA-API display");
1526 let unmapped = DmaBuf {
1528 drm_format: u32::from_le_bytes(*b"ZZZZ"),
1529 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1530 };
1531 assert!(encoder.encode_dmabuf(unmapped, true).is_err());
1532 let unknown_modifier = DmaBuf {
1533 modifier: 0x00ff_ffff_ffff_fffe,
1534 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1535 };
1536 assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());
1537
1538 let unit = encoder
1539 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1540 .expect("the CPU path still encodes");
1541 let decoded = ffmpeg_decode(Codec::H264, &unit, "refused");
1542 let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
1543 assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
1544 }
1545
1546 #[test]
1551 #[ignore = "requires a VA-API render node and FFmpeg"]
1552 fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
1553 for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
1554 let mut encoder = encoder(Config {
1555 width,
1556 height,
1557 bitrate: 4_000_000,
1558 color: Color::infer(height),
1559 ..config(codec)
1560 });
1561 let display = Display::open().expect("no VA-API display");
1562 let unit = encoder
1563 .encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
1564 .expect("encode the DMA-BUF");
1565 let decoded = ffmpeg_decode(codec, &unit, "short");
1566 let frame = nv12_frame(width, height, 0);
1567 assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
1568 let psnr = luma_psnr(&frame, &decoded, width, height);
1569 assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
1570 }
1571 }
1572
1573 #[test]
1576 #[ignore = "requires a VA-API render node and FFmpeg"]
1577 fn a_yuv_dmabuf_in_another_space_is_converted() {
1578 for codec in CODECS {
1579 yuv_dmabuf_in_another_space_is_converted(codec);
1580 }
1581 }
1582
1583 fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) {
1584 let mut encoder = encoder(Config {
1585 color: Color::BT601,
1586 ..config(codec)
1587 });
1588 let display = Display::open().expect("no VA-API display");
1589 let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
1591 let surface = surface_with(
1592 &display,
1593 VA_FOURCC_NV12,
1594 VA_RT_FORMAT_YUV420,
1595 (WIDTH, HEIGHT),
1596 |data, image| {
1597 for row in 0..HEIGHT as usize {
1598 let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
1599 data[at..at + WIDTH as usize].fill(y);
1600 }
1601 for row in 0..HEIGHT as usize / 2 {
1602 let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
1603 for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
1604 pair.copy_from_slice(&[u, v]);
1605 }
1606 }
1607 },
1608 );
1609 let buffer = DmaBuf {
1610 color: Some(Color::BT709),
1611 ..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
1612 };
1613 let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
1614 let decoded = ffmpeg_decode(codec, &unit, "yuv-color");
1615
1616 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1617 let (luma, chroma) = decoded.split_at(w * h);
1618 let actual = [
1619 mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
1620 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
1621 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
1622 ];
1623 let expected = limited([255, 0, 0], Color::BT601);
1624 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1625 assert!(
1626 (a - e).abs() < 6.0,
1627 "{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
1628 );
1629 }
1630 }
1631
1632 #[test]
1634 #[ignore = "requires a VA-API render node and FFmpeg"]
1635 fn an_nv12_dmabuf_encodes_in_place() {
1636 for codec in CODECS {
1637 let mut encoder = encoder(config(codec));
1638 let display = Display::open().expect("no VA-API display");
1639 let mut stream = Vec::new();
1640 for step in 0..5 {
1641 let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
1642 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1643 }
1644 let decoded = ffmpeg_decode(codec, &stream, "dmabuf");
1645 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1646 assert_eq!(decoded.len(), 5 * len, "{codec:?}");
1647 for step in 0..5 {
1648 let psnr = luma_psnr(
1649 &nv12_frame(WIDTH, HEIGHT, step),
1650 &decoded[step as usize * len..],
1651 WIDTH,
1652 HEIGHT,
1653 );
1654 assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1655 }
1656 }
1657 }
1658
1659 #[test]
1661 #[ignore = "requires a VA-API render node and FFmpeg"]
1662 fn a_dmabuf_at_another_size_is_scaled() {
1663 for codec in CODECS {
1664 dmabuf_at_another_size_is_scaled(codec);
1665 }
1666 }
1667
1668 fn dmabuf_at_another_size_is_scaled(codec: Codec) {
1669 let mut encoder = encoder(config(codec));
1670 let display = Display::open().expect("no VA-API display");
1671 let mut stream = Vec::new();
1672 for step in 0..3 {
1673 let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
1674 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1675 }
1676 let decoded = ffmpeg_decode(codec, &stream, "scaled");
1677 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1678 assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
1679 for step in 0..3u32 {
1683 let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
1684 let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
1685 for y in 0..HEIGHT as usize {
1686 for x in 0..WIDTH as usize {
1687 expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
1688 }
1689 }
1690 let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
1691 assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1692 }
1693 }
1694
1695 #[test]
1697 #[ignore = "requires a VA-API render node and FFmpeg"]
1698 fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
1699 const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
1701 for (codec, color) in CODECS
1702 .into_iter()
1703 .flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
1704 {
1705 let mut encoder = encoder(Config { color, ..config(codec) });
1706 let display = Display::open().expect("no VA-API display");
1707 let surface = surface_with(
1708 &display,
1709 VA_FOURCC_BGRX,
1710 VA_RT_FORMAT_RGB32,
1711 (WIDTH, HEIGHT),
1712 |data, image| {
1713 let pitch = image.pitches[0] as usize;
1714 let offset = image.offsets[0] as usize;
1715 for y in 0..HEIGHT as usize {
1716 for x in 0..WIDTH as usize {
1717 let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
1718 let [r, g, b] = QUADRANTS[quadrant];
1719 let at = offset + y * pitch + x * 4;
1720 data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
1721 }
1722 }
1723 },
1724 );
1725 let exported = surface.export_prime().expect("export");
1726 let buffer = DmaBuf::from_prime(exported).expect("one object");
1727 assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
1728 let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
1729 let decoded = ffmpeg_decode(codec, &unit, "rgb");
1730
1731 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1732 let (luma, chroma) = decoded.split_at(w * h);
1733 for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
1734 let (qx, qy) = (quadrant % 2, quadrant / 2);
1735 let area = |scale: usize| {
1737 let (qw, qh) = (w / 2 / scale, h / 2 / scale);
1738 (
1739 qx * qw + qw / 4,
1740 qy * qh + qh / 4,
1741 qx * qw + qw * 3 / 4,
1742 qy * qh + qh * 3 / 4,
1743 )
1744 };
1745 let actual = [
1746 mean(luma, w, area(1), 1, 0),
1747 mean(chroma, w, area(2), 2, 0),
1748 mean(chroma, w, area(2), 2, 1),
1749 ];
1750 let expected = limited(*rgb, color);
1751 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1752 assert!(
1753 (a - e).abs() < 6.0,
1754 "{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
1755 );
1756 }
1757 }
1758 }
1759 }
1760
1761 #[test]
1762 fn the_level_covers_the_frame_size_and_rate() {
1763 assert_eq!(level(320, 240, 30), Level::L4);
1764 assert_eq!(level(1920, 1080, 30), Level::L4);
1765 assert_eq!(level(1920, 1080, 60), Level::L4_2);
1766 assert_eq!(level(2560, 1440, 30), Level::L5);
1767 assert_eq!(level(3840, 2160, 30), Level::L5_1);
1768 assert_eq!(level(3840, 2160, 60), Level::L5_2);
1769 }
1770
1771 fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
1773 let (kr, kb) = match color.matrix {
1774 crate::Matrix::Bt601 => (0.299, 0.114),
1775 crate::Matrix::Bt709 => (0.2126, 0.0722),
1776 };
1777 let (r, g, b) = (r as f64, g as f64, b as f64);
1778 let y = kr * r + (1.0 - kr - kb) * g + kb * b;
1779 [
1780 16.0 + y * 219.0 / 255.0,
1781 128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
1782 128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
1783 ]
1784 }
1785
1786 #[test]
1789 #[ignore = "requires a VA-API render node"]
1790 fn a_bitrate_change_takes_effect_without_a_keyframe() {
1791 for codec in CODECS {
1792 bitrate_change_takes_effect_without_a_keyframe(codec);
1793 }
1794 }
1795
1796 fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) {
1797 let mut encoder = encoder(Config {
1798 gop: NonZeroU32::new(1_000).unwrap(),
1799 ..config(codec)
1800 });
1801 let (idr_type, _) = idr_types(codec);
1802 let frame = |step: u32| {
1806 let (w, h) = (WIDTH as usize, HEIGHT as usize);
1807 let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
1808 for y in 0..h {
1809 for x in 0..w {
1810 let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
1811 let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
1812 frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
1813 }
1814 }
1815 frame
1816 };
1817 let average = |encoder: &mut Encoder, from: u32| {
1821 let sizes: Vec<usize> = (from..from + 60)
1822 .map(|step| {
1823 let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
1824 if step > 0 {
1825 assert!(
1826 !nal_types(codec, &unit).contains(&idr_type),
1827 "{codec:?} picture {step} is an IDR"
1828 );
1829 }
1830 unit.len()
1831 })
1832 .collect();
1833 sizes[30..].iter().sum::<usize>() / 30
1834 };
1835
1836 let within = |bytes: usize, bitrate: u32| {
1839 let target = bitrate as usize / 8 / 30;
1840 assert!(
1841 bytes * 4 <= target * 5,
1842 "{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
1843 );
1844 };
1845
1846 let high = average(&mut encoder, 0);
1847 within(high, 2_000_000);
1848 encoder.set_bitrate(250_000).expect("set the bitrate");
1849 assert_eq!(encoder.config().bitrate, 250_000);
1850 assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
1851 let low = average(&mut encoder, 60);
1852 eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
1853 within(low, 250_000);
1854 assert!(
1855 low * 3 < high,
1856 "{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
1857 );
1858 }
1859}