1use std::num::NonZeroU32;
37use std::ops::RangeInclusive;
38use std::path::PathBuf;
39use std::rc::Rc;
40use std::sync::Arc;
41
42use anyhow::Context as _;
43
44use crate::codec::Codec;
45use crate::dmabuf::DmaBuf;
46use crate::vpp::Processor;
47use crate::{
48 BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter,
49 EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter,
50 EncPackedHeaderType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
51 EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264, GenericValue,
52 H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture,
53 PictureH264, RcFlags, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
54 VAEntrypoint, VAImageFormat, VAProfile, VASurfaceAttribType, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE,
55 VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX,
56 VA_FOURCC_NV12, VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
57 VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
58};
59use kodecs_h264::{
60 AspectRatio, Colour, Level, NaluHeader, NaluType, PicOrderCnt, Pps, PpsBuilder, Profile, Restriction, SliceHeader,
61 SliceHeaderBuilder, SliceType, Sps, SpsBuilder, Timing, VideoSignal, Vui,
62};
63
64mod h265;
65
66pub const DEFAULT_MIN_QP: u8 = 24;
78pub const MAX_QP: u8 = 51;
87pub const HRD_FRAMES: u32 = 3;
93pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
98const LIMIT: u32 = 2048;
100
101#[derive(Clone, Debug)]
105#[non_exhaustive]
106pub struct Config {
107 pub codec: Codec,
109 pub width: u32,
110 pub height: u32,
111 pub framerate: u32,
112 pub bitrate: u32,
116 pub gop: NonZeroU32,
118 pub qp: RangeInclusive<u8>,
125 pub device: Option<PathBuf>,
131 pub color: Color,
136}
137
138impl Config {
139 pub fn new(width: u32, height: u32, framerate: u32, bitrate: u32, gop: NonZeroU32) -> Self {
142 Self {
143 codec: Codec::H264,
144 width,
145 height,
146 framerate,
147 bitrate,
148 gop,
149 qp: DEFAULT_MIN_QP..=MAX_QP,
150 device: None,
151 color: Color::infer(height),
152 }
153 }
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub enum RateControl {
169 Variable,
172 Constant,
176}
177
178impl RateControl {
179 fn pick(vendor: &str, offered: u32) -> Self {
182 match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
183 true => Self::Variable,
184 false => Self::Constant,
185 }
186 }
187
188 fn va(self) -> u32 {
189 match self {
190 Self::Variable => VA_RC_VBR,
191 Self::Constant => VA_RC_CBR,
192 }
193 }
194}
195
196#[derive(Copy, Clone)]
198struct FrameMeta {
199 poc: u32,
200 frame_num: u32,
201}
202
203impl FrameMeta {
204 fn new(count: u32) -> Self {
210 Self {
211 poc: count.wrapping_mul(2),
212 frame_num: count % LIMIT,
213 }
214 }
215}
216
217#[derive(Copy, Clone)]
219struct Reference {
220 surface: crate::bindings::VASurfaceID,
222 count: u32,
224}
225
226struct PictureInfo<'a> {
228 idr: bool,
229 idr_id: u32,
231 count: u32,
233 recon: crate::bindings::VASurfaceID,
235 reference: Option<Reference>,
236 coded: &'a EncCodedBuffer,
237 bitrate: u32,
238}
239
240enum Syntax {
242 H264 {
243 sps: Sps,
244 pps: Pps,
245 packed: u32,
247 },
248 H265 {
249 stream: h265::Stream,
250 packed: u32,
252 },
253}
254
255pub struct Encoder {
257 config: Config,
258 syntax: Syntax,
259
260 input: Option<Surface<()>>,
263 nv12: Option<VAImageFormat>,
265 recon: Vec<Surface<()>>,
266 reference: Option<(usize, u32)>,
268
269 counter: u32,
270 idrs: u32,
272
273 processor: Option<Processor>,
276 reset_rate_control: bool,
279 rate_control: RateControl,
280
281 coded: EncCodedBuffer,
283 context: Rc<Context>,
284 _va_config: VaConfig,
285 display: Arc<Display>,
286}
287
288impl Encoder {
289 pub fn new(mut config: Config) -> anyhow::Result<Self> {
301 let (width, height) = (config.width, config.height);
302 if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
303 anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
304 }
305 if config.qp.is_empty() || !(1..=MAX_QP).contains(config.qp.end()) {
308 anyhow::bail!(
309 "a QP range of {:?}, which needs a floor at or below a ceiling of 1 to {MAX_QP}",
310 config.qp
311 );
312 }
313 let codec = config.codec;
314 let (device, display) = match config.device.take() {
315 Some(device) => {
316 let display = Display::open_drm_display(&device)
317 .map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
318 (device, display)
319 }
320 None => crate::display::open_first(|display| probe(display, codec)?.check(width, height))
321 .map_err(|e| e.context(format!("find a render node that encodes {codec:?} at {width}x{height}")))?,
322 };
323
324 let entrypoint = encode_entrypoint(&display, codec)?;
325 let rate_control = RateControl::pick(
326 &display.query_vendor_string().unwrap_or_default(),
327 config_attribute(
328 &display,
329 codec,
330 entrypoint,
331 VAConfigAttribType::VAConfigAttribRateControl,
332 ),
333 );
334 let mut attrs = vec![
335 VAConfigAttrib {
336 type_: VAConfigAttribType::VAConfigAttribRTFormat,
337 value: VA_RT_FORMAT_YUV420,
338 },
339 VAConfigAttrib {
340 type_: VAConfigAttribType::VAConfigAttribRateControl,
341 value: rate_control.va(),
342 },
343 ];
344 let wanted = match codec {
353 Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
354 Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
355 };
356 let packed = packed_headers(&display, codec, entrypoint) & wanted;
357 if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
360 anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
361 }
362 if packed != 0 {
363 attrs.push(VAConfigAttrib {
364 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
365 value: packed,
366 });
367 } else {
368 tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
369 }
370 let mut va_config = display
371 .create_config(attrs, profile(codec), entrypoint)
372 .map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
373 limits(&display, codec, entrypoint, &mut va_config)?.check(width, height)?;
374
375 let syntax = match codec {
376 Codec::H264 => {
377 let (sps, pps) = build_sps_pps(&config)?;
378 Syntax::H264 { sps, pps, packed }
379 }
380 Codec::H265 => Syntax::H265 {
381 stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
382 packed,
383 },
384 };
385 let size = match &syntax {
389 Syntax::H264 { .. } => (config.width, config.height),
390 Syntax::H265 { stream, .. } => stream.coded(),
391 };
392
393 let context = display
394 .create_context::<()>(&va_config, size.0, size.1, None, true)
395 .map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;
396
397 let coded = context
398 .create_enc_coded(coded_size(size))
399 .map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
400
401 let input = make_surface(&display, (config.width, config.height))?;
402 let nv12 = display
403 .query_image_formats()
404 .map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
405 .into_iter()
406 .find(|format| format.fourcc == VA_FOURCC_NV12);
407 let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];
408
409 tracing::info!(
410 "opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
411 device,
412 config.width,
413 config.height,
414 config.framerate,
415 config.bitrate,
416 rate_control,
417 entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
418 );
419 config.device = Some(device);
420 Ok(Self {
421 config,
422 syntax,
423 input: Some(input),
424 nv12,
425 recon,
426 reference: None,
427 counter: 0,
428 idrs: 0,
429 processor: None,
430 reset_rate_control: false,
431 rate_control,
432 coded,
433 context,
434 _va_config: va_config,
435 display,
436 })
437 }
438
439 pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
451 let format = self
452 .nv12
453 .ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
454 let mut input = self.input.take().expect("input surface present");
455 let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
456 .and_then(|()| self.encode_surface(&input, keyframe));
457 self.input = Some(input);
458 result
459 }
460
461 pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
490 let fourcc = buffer
491 .fourcc()
492 .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
493 let color = self.config.color;
494 let size = (self.config.width, self.config.height);
495 let unpadded = match &self.syntax {
496 Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
497 Syntax::H265 { stream, .. } => stream.coded() == size,
498 };
499 let in_place = fourcc == VA_FOURCC_NV12
500 && (buffer.width, buffer.height) == size
501 && unpadded
502 && buffer.color.is_none_or(|own| own == color);
503 if in_place {
504 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
505 return self.encode_surface(&source, keyframe);
506 }
507
508 let input_color = match is_rgb(fourcc) {
509 true => None,
510 false => Some(buffer.color.unwrap_or(color)),
511 };
512 let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
513 let input = self.input.take().expect("input surface present");
514 let result = self
515 .processor()
516 .and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
517 .and_then(|()| self.encode_surface(&input, keyframe));
518 self.input = Some(input);
519 result
520 }
521
522 pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
536 if bitrate == 0 {
537 anyhow::bail!("a bitrate of zero");
538 }
539 if bitrate != self.config.bitrate {
540 self.reset_rate_control = true;
541 }
542 self.config.bitrate = bitrate;
543 Ok(())
544 }
545
546 pub fn rate_control(&self) -> RateControl {
548 self.rate_control
549 }
550
551 pub fn config(&self) -> &Config {
553 &self.config
554 }
555
556 fn processor(&mut self) -> anyhow::Result<&Processor> {
558 if self.processor.is_none() {
559 self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
560 }
561 Ok(self.processor.as_ref().expect("opened above"))
562 }
563
564 fn encode_surface<D: SurfaceMemoryDescriptor>(
566 &mut self,
567 source: &Surface<D>,
568 keyframe: bool,
569 ) -> anyhow::Result<Vec<u8>> {
570 let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
571 if is_idr {
572 self.counter = 0;
574 self.reference = None;
575 }
576
577 let recon_idx = (self.counter as usize) % self.recon.len();
578 let reference = match (is_idr, self.reference) {
580 (false, Some((index, count))) => Some(Reference {
581 surface: self.recon[index].id(),
582 count,
583 }),
584 _ => None,
585 };
586 let info = PictureInfo {
587 idr: is_idr,
588 idr_id: self.idrs,
589 count: self.counter,
590 recon: self.recon[recon_idx].id(),
591 reference,
592 coded: &self.coded,
593 bitrate: self.config.bitrate,
594 };
595 let buffers = match &self.syntax {
596 Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
597 Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
598 };
599
600 let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);
601
602 for buffer in buffers {
605 picture.add_buffer(self.create(buffer)?);
606 }
607
608 let bits_per_second = self.config.bitrate;
609 let (min_qp, max_qp) = (*self.config.qp.start(), *self.config.qp.end());
612 let rc = EncMiscParameterRateControl::new(
613 bits_per_second,
614 100, RATE_CONTROL_WINDOW_MS, u32::from(min_qp.midpoint(max_qp).max(1)),
618 u32::from(min_qp),
619 0, RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
624 0, u32::from(max_qp),
626 0, 0, );
629 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
630 let hrd = hrd_size(bits_per_second, self.config.framerate);
632 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
633 EncMiscParameterHRD::new(hrd, hrd),
634 )))?);
635
636 let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
637 picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);
638
639 let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
640 let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
641 let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
642 picture
645 .sync()
646 .map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;
647
648 let bitstream = self.read_coded()?;
650
651 self.reference = Some((recon_idx, self.counter));
652 self.counter += 1;
653 self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
654 self.reset_rate_control = false;
655 Ok(bitstream)
656 }
657
658 fn create(&self, buffer: BufferType) -> anyhow::Result<crate::Buffer> {
659 self.context
660 .create_buffer(buffer)
661 .map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}"))
662 }
663
664 fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
665 let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
666 concat_coded(mapped.iter().map(|segment| (segment.status, segment.buf)))
667 }
668}
669
670fn concat_coded<'a>(segments: impl IntoIterator<Item = (u32, &'a [u8])>) -> anyhow::Result<Vec<u8>> {
674 let mut out = Vec::new();
675 for (status, buf) in segments {
676 if status & crate::bindings::VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK != 0 {
677 anyhow::bail!("the coded picture overflowed its buffer");
678 }
679 out.extend_from_slice(buf);
680 }
681 Ok(out)
682}
683
684#[derive(Clone, Copy, Debug, PartialEq, Eq)]
691pub struct Limits {
692 pub min_width: Option<u32>,
693 pub min_height: Option<u32>,
694 pub max_width: Option<u32>,
695 pub max_height: Option<u32>,
696 round: (u32, u32),
698}
699
700impl Limits {
701 pub fn check(&self, width: u32, height: u32) -> anyhow::Result<()> {
707 let round = |size: u32, to: u32| size.checked_next_multiple_of(to).unwrap_or(u32::MAX);
708 let coded = (round(width, self.round.0), round(height, self.round.1));
709 let at = match coded == (width, height) {
710 true => String::new(),
711 false => format!(" (coded {}x{})", coded.0, coded.1),
712 };
713 for (axis, size, min, max) in [
714 ("width", coded.0, self.min_width, self.max_width),
715 ("height", coded.1, self.min_height, self.max_height),
716 ] {
717 if let Some(min) = min.filter(|&min| size < min) {
718 anyhow::bail!("a {width}x{height} frame{at} is under the driver's minimum encode {axis} of {min}");
719 }
720 if let Some(max) = max.filter(|&max| size > max) {
721 anyhow::bail!("a {width}x{height} frame{at} is over the driver's maximum encode {axis} of {max}");
722 }
723 }
724 Ok(())
725 }
726}
727
728pub fn probe(display: &Arc<Display>, codec: Codec) -> anyhow::Result<Limits> {
737 let entrypoint = encode_entrypoint(display, codec)?;
738 let attrs = vec![VAConfigAttrib {
739 type_: VAConfigAttribType::VAConfigAttribRTFormat,
740 value: VA_RT_FORMAT_YUV420,
741 }];
742 let mut va_config = display
743 .create_config(attrs, profile(codec), entrypoint)
744 .map_err(|e| anyhow::anyhow!("create {codec:?} encode config: {e:?}"))?;
745 limits(display, codec, entrypoint, &mut va_config)
746}
747
748fn limits(
750 display: &Display,
751 codec: Codec,
752 entrypoint: VAEntrypoint::Type,
753 va_config: &mut VaConfig,
754) -> anyhow::Result<Limits> {
755 let mut bound = |type_: VASurfaceAttribType::Type| -> anyhow::Result<Option<u32>> {
756 let values = va_config
757 .query_surface_attributes_by_type(type_)
758 .map_err(|e| anyhow::anyhow!("query {codec:?} encode surface attributes: {e:?}"))?;
759 Ok(match values.first() {
760 Some(&GenericValue::Integer(value)) => u32::try_from(value).ok().filter(|&value| value > 0),
761 _ => None,
762 })
763 };
764 let (min_width, min_height, max_width, max_height) = (
765 bound(VASurfaceAttribType::VASurfaceAttribMinWidth)?,
766 bound(VASurfaceAttribType::VASurfaceAttribMinHeight)?,
767 bound(VASurfaceAttribType::VASurfaceAttribMaxWidth)?,
768 bound(VASurfaceAttribType::VASurfaceAttribMaxHeight)?,
769 );
770 let round = match codec {
771 Codec::H264 => (1, 1),
772 Codec::H265 => h265::round(display, entrypoint, va_config)?,
773 };
774 Ok(Limits {
775 min_width,
776 min_height,
777 max_width,
778 max_height,
779 round,
780 })
781}
782
783fn profile(codec: Codec) -> VAProfile::Type {
785 match codec {
786 Codec::H264 => VAProfile::VAProfileH264Main,
787 Codec::H265 => h265::PROFILE,
788 }
789}
790
791fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
795 let entrypoints = display
796 .query_config_entrypoints(profile(codec))
797 .map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
798 pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
799}
800
801fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option<VAEntrypoint::Type> {
803 [VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
804 .into_iter()
805 .find(|entrypoint| offered.contains(entrypoint))
806}
807
808fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 {
812 config_attribute(
813 display,
814 codec,
815 entrypoint,
816 VAConfigAttribType::VAConfigAttribEncPackedHeaders,
817 )
818}
819
820fn config_attribute(
822 display: &Display,
823 codec: Codec,
824 entrypoint: VAEntrypoint::Type,
825 type_: VAConfigAttribType::Type,
826) -> u32 {
827 let mut attrs = [VAConfigAttrib { type_, value: 0 }];
828 if display
829 .get_config_attributes(profile(codec), entrypoint, &mut attrs)
830 .is_err()
831 || attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
832 {
833 return 0;
834 }
835 attrs[0].value
836}
837
838fn level(width: u32, height: u32, framerate: u32) -> Level {
848 const LEVELS: [(Level, u64, u64); 8] = [
850 (Level::L4, 245_760, 8_192),
851 (Level::L4_2, 522_240, 8_704),
852 (Level::L5, 589_824, 22_080),
853 (Level::L5_1, 983_040, 36_864),
854 (Level::L5_2, 2_073_600, 36_864),
855 (Level::L6, 4_177_920, 139_264),
856 (Level::L6_1, 8_355_840, 139_264),
857 (Level::L6_2, 16_711_680, 139_264),
858 ];
859 let (width_mbs, height_mbs) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
860 let frame = width_mbs * height_mbs;
861 let rate = frame * u64::from(framerate.max(1));
862 let side = width_mbs.max(height_mbs);
864 LEVELS
865 .into_iter()
866 .find(|&(_, max_rate, max_frame)| frame <= max_frame && side * side <= 8 * max_frame && rate <= max_rate)
867 .map(|(level, _, _)| level)
868 .unwrap_or(Level::L6_2)
869}
870
871fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
873 (u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
874}
875
876fn coded_size(size: (u32, u32)) -> usize {
884 let (width, height) = (
885 size.0.next_multiple_of(16) as usize,
886 size.1.next_multiple_of(16) as usize,
887 );
888 3 * width * height + (1 << 16)
889}
890
891fn is_rgb(fourcc: u32) -> bool {
893 matches!(
894 fourcc,
895 VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
896 )
897}
898
899fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
901 let mut surfaces = display
902 .create_surfaces::<()>(
903 VA_RT_FORMAT_YUV420,
904 Some(VA_FOURCC_NV12),
905 width,
906 height,
907 Some(UsageHint::USAGE_HINT_ENCODER),
908 vec![()],
909 )
910 .map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
911 surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
912}
913
914fn upload_nv12(
918 format: VAImageFormat,
919 surface: &mut Surface<()>,
920 width: u32,
921 height: u32,
922 data: &[u8],
923) -> anyhow::Result<()> {
924 let (w, h) = (width as usize, height as usize);
925 let luma = w * h;
926 let expected = luma + w * (h / 2);
927 if data.len() < expected {
928 anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
929 }
930
931 let mut image =
932 ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
933 let va_image = *image.image();
934 let dest: &mut [u8] = image.as_mut();
935 let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
936 for (plane, (src, rows)) in planes.into_iter().enumerate() {
937 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
938 fill_plane(dest, offset, pitch, src, w, rows)?;
939 }
940 image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
941}
942
943fn fill_plane(
947 dst: &mut [u8],
948 offset: usize,
949 pitch: usize,
950 src: &[u8],
951 width: usize,
952 rows: usize,
953) -> anyhow::Result<()> {
954 if rows == 0 || width == 0 {
955 return Ok(());
956 }
957 let end = (rows - 1)
959 .checked_mul(pitch)
960 .and_then(|start| start.checked_add(offset)?.checked_add(width));
961 if pitch < width || end.is_none_or(|end| end > dst.len()) {
962 anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
963 }
964 for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
965 let start = offset + row * pitch;
966 dst[start..start + width].copy_from_slice(src);
967 }
968 Ok(())
969}
970
971fn build_sps_pps(config: &Config) -> anyhow::Result<(Sps, Pps)> {
976 let (primaries, transfer, matrix) = config.color.vui();
977 let vui = Vui {
978 aspect_ratio: Some(AspectRatio {
979 idc: 1, sar_width: 0,
981 sar_height: 0,
982 }),
983 overscan_appropriate: None,
984 video_signal: Some(VideoSignal {
985 video_format: 5, full_range: config.color.full_range,
987 colour: Some(Colour {
988 primaries,
989 transfer,
990 matrix,
991 }),
992 }),
993 chroma_loc: None,
994 timing: Some(Timing {
995 num_units_in_tick: 1,
996 time_scale: config.framerate.max(1) * 2,
998 fixed_frame_rate: false,
999 }),
1000 nal_hrd: None,
1001 vcl_hrd: None,
1002 low_delay_hrd: false,
1003 pic_struct_present: false,
1004 restriction: Some(Restriction {
1007 motion_vectors_over_pic_boundaries: true,
1008 max_bytes_per_pic_denom: 2,
1009 max_bits_per_mb_denom: 1,
1010 log2_max_mv_length_horizontal: 16,
1011 log2_max_mv_length_vertical: 16,
1012 max_num_reorder_frames: 0,
1013 max_dec_frame_buffering: 1,
1014 }),
1015 };
1016 let sps = SpsBuilder::new(Profile::Main, level(config.width, config.height, config.framerate))
1017 .log2_max_frame_num(LIMIT.ilog2() as u8)
1018 .pic_order_cnt(PicOrderCnt::Lsb {
1019 log2_max_lsb: (LIMIT * 2).ilog2() as u8,
1020 })
1021 .max_num_ref_frames(1)
1022 .resolution(config.width, config.height)
1023 .vui(vui)
1024 .build()
1025 .context("build the SPS")?;
1026
1027 let pps = PpsBuilder::new(&sps)
1028 .entropy_coding_mode(true)
1029 .deblocking_filter_control_present(true)
1030 .build()
1031 .context("build the PPS")?;
1032
1033 Ok((sps, pps))
1034}
1035
1036fn h264_buffers(sps: &Sps, pps: &Pps, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
1038 let meta = FrameMeta::new(picture.count);
1039 let (slice_type, nal) = match picture.idr {
1041 true => (
1042 SliceType::I,
1043 NaluHeader {
1044 ref_idc: 3,
1045 type_: NaluType::SliceIdr,
1046 },
1047 ),
1048 false => (
1049 SliceType::P,
1050 NaluHeader {
1051 ref_idc: 1,
1052 type_: NaluType::Slice,
1053 },
1054 ),
1055 };
1056 let mut builder = SliceHeaderBuilder::new(sps, pps, slice_type)
1057 .frame_num(meta.frame_num)
1058 .pic_order_cnt_lsb(meta.poc % (LIMIT * 2));
1059 if picture.idr {
1060 builder = builder.idr_pic_id(picture.idr_id % 2);
1062 }
1063 let header = builder.build(nal).context("build the slice header")?;
1064 let macroblocks = sps.width_mbs * sps.height_mbs;
1065 let reference = picture
1066 .reference
1067 .map(|reference| (reference.surface, FrameMeta::new(reference.count)));
1068
1069 let mut buffers = vec![
1070 build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
1071 build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
1072 build_enc_slice_param(pps, &header, reference, macroblocks),
1073 ];
1074 if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
1075 buffers.extend(packed_parameter_sets(sps, pps)?);
1076 }
1077 if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
1078 let mut out = Vec::new();
1079 let trailing = header
1080 .write(nal, sps, pps, &mut out)
1081 .context("write the slice header")?;
1082 let bits = out.len() * 8 - usize::from(trailing);
1084 buffers.extend(packed_header(EncPackedHeaderType::Slice, &out, bits));
1085 }
1086 Ok(buffers)
1087}
1088
1089fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
1091 let mut sps_nal = Vec::new();
1092 sps.write(3, &mut sps_nal).context("write the SPS")?;
1093 let mut pps_nal = Vec::new();
1094 pps.write(3, &mut pps_nal).context("write the PPS")?;
1095
1096 let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
1097 let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
1098 Ok([sps_param, sps_data, pps_param, pps_data])
1099}
1100
1101fn build_invalid_pic() -> PictureH264 {
1102 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1103}
1104
1105fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
1106 PictureH264::new(
1107 surface_id,
1108 meta.frame_num,
1109 VA_PICTURE_H264_SHORT_TERM_REFERENCE,
1110 meta.poc as i32,
1111 meta.poc as i32,
1112 )
1113}
1114
1115fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
1117 let (log2_max_lsb, delta_always_zero, offset_for_non_ref_pic, offset_for_top_to_bottom_field, cycle) =
1118 match &sps.pic_order_cnt {
1119 PicOrderCnt::Lsb { log2_max_lsb } => (*log2_max_lsb, false, 0, 0, &[][..]),
1120 PicOrderCnt::Cycle {
1121 delta_always_zero,
1122 offset_for_non_ref_pic,
1123 offset_for_top_to_bottom_field,
1124 offset_for_ref_frame,
1125 } => (
1126 4,
1127 *delta_always_zero,
1128 *offset_for_non_ref_pic,
1129 *offset_for_top_to_bottom_field,
1130 &offset_for_ref_frame[..],
1131 ),
1132 PicOrderCnt::Decode => (4, false, 0, 0, &[][..]),
1133 };
1134 let seq_fields = H264EncSeqFields::new(
1135 1, 1, 0, sps.scaling.is_some() as u32,
1139 sps.direct_8x8_inference as u32,
1140 u32::from(sps.log2_max_frame_num - 4),
1141 poc_type(&sps.pic_order_cnt),
1142 u32::from(log2_max_lsb - 4),
1143 delta_always_zero as u32,
1144 );
1145
1146 let frame_crop = sps
1148 .crop
1149 .map(|crop| H264EncFrameCropOffsets::new(crop.left / 2, crop.right / 2, crop.top / 2, crop.bottom / 2));
1150
1151 let vui = sps.vui.as_ref();
1152 let aspect_ratio = vui.and_then(|vui| vui.aspect_ratio);
1153 let timing = vui.and_then(|vui| vui.timing);
1154 let restriction = vui.and_then(|vui| vui.restriction);
1155 let vui_fields = vui.map(|vui| {
1156 H264VuiFields::new(
1157 aspect_ratio.is_some() as u32,
1158 timing.is_some() as u32,
1159 restriction.is_some() as u32,
1160 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_horizontal)),
1161 restriction.map_or(0, |r| u32::from(r.log2_max_mv_length_vertical)),
1162 timing.is_some_and(|t| t.fixed_frame_rate) as u32,
1163 vui.low_delay_hrd as u32,
1164 restriction.is_some_and(|r| r.motion_vectors_over_pic_boundaries) as u32,
1165 )
1166 });
1167
1168 let mut offset_for_ref_frame = [0i32; 256];
1169 offset_for_ref_frame[..cycle.len()].copy_from_slice(cycle);
1170
1171 BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
1173 sps.id,
1174 sps.level.value(),
1175 intra_period,
1176 intra_period,
1177 ip_period,
1178 bits_per_second,
1179 u32::from(sps.max_num_ref_frames),
1180 sps.width_mbs as u16,
1181 sps.height_mbs as u16,
1182 &seq_fields,
1183 0, 0, cycle.len() as u8,
1186 offset_for_non_ref_pic,
1187 offset_for_top_to_bottom_field,
1188 offset_for_ref_frame,
1189 frame_crop,
1190 vui_fields,
1191 aspect_ratio.map_or(0, |a| a.idc),
1192 aspect_ratio.map_or(0, |a| u32::from(a.sar_width)),
1193 aspect_ratio.map_or(0, |a| u32::from(a.sar_height)),
1194 timing.map_or(0, |t| t.num_units_in_tick),
1195 timing.map_or(0, |t| t.time_scale),
1196 )))
1197}
1198
1199fn poc_type(poc: &PicOrderCnt) -> u32 {
1201 match poc {
1202 PicOrderCnt::Lsb { .. } => 0,
1203 PicOrderCnt::Cycle { .. } => 1,
1204 PicOrderCnt::Decode => 2,
1205 }
1206}
1207
1208fn build_enc_pic_param(
1210 pps: &Pps,
1211 coded: &EncCodedBuffer,
1212 recon_id: u32,
1213 meta: FrameMeta,
1214 is_idr: bool,
1215 reference: Option<(u32, FrameMeta)>,
1216) -> BufferType {
1217 let pic_fields = H264EncPicFields::new(
1218 is_idr as u32,
1219 1, pps.entropy_coding_mode as u32,
1221 pps.weighted_pred as u32,
1222 u32::from(pps.weighted_bipred_idc),
1223 pps.constrained_intra_pred as u32,
1224 pps.transform_8x8_mode as u32,
1225 pps.deblocking_filter_control_present as u32,
1226 pps.redundant_pic_cnt_present as u32,
1227 0,
1228 pps.scaling.is_some() as u32,
1229 );
1230
1231 let curr_pic = build_h264_pic(recon_id, meta);
1232 let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
1233 if let Some((id, m)) = reference {
1234 reference_frames[0] = build_h264_pic(id, m);
1235 }
1236
1237 BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
1239 curr_pic,
1240 reference_frames,
1241 coded.id(),
1242 pps.id,
1243 pps.sps_id,
1244 0,
1245 meta.frame_num as u16,
1246 pps.pic_init_qp as u8,
1247 pps.num_ref_idx_l0_default_active - 1,
1248 pps.num_ref_idx_l1_default_active - 1,
1249 pps.chroma_qp_index_offset as i8,
1250 pps.second_chroma_qp_index_offset as i8,
1251 &pic_fields,
1252 )))
1253}
1254
1255fn build_enc_slice_param(
1258 pps: &Pps,
1259 header: &SliceHeader,
1260 reference: Option<(u32, FrameMeta)>,
1261 num_macroblocks: u32,
1262) -> BufferType {
1263 let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1264 if let Some((id, m)) = reference {
1265 ref_pic_list_0[0] = build_h264_pic(id, m);
1266 }
1267 let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1268
1269 let override_counts = match header.slice_type {
1272 SliceType::I | SliceType::Si => false,
1273 SliceType::P | SliceType::Sp => header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active,
1274 SliceType::B => {
1275 header.num_ref_idx_l0_active != pps.num_ref_idx_l0_default_active
1276 || header.num_ref_idx_l1_active != pps.num_ref_idx_l1_default_active
1277 }
1278 };
1279 let (l0, l1) = match override_counts {
1280 true => (header.num_ref_idx_l0_active, header.num_ref_idx_l1_active),
1281 false => (pps.num_ref_idx_l0_default_active, pps.num_ref_idx_l1_default_active),
1282 };
1283
1284 BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
1286 header.first_mb_in_slice,
1287 num_macroblocks,
1288 VA_INVALID_ID,
1289 header.slice_type_raw % 5,
1290 pps.id,
1291 header.idr_pic_id.unwrap_or(0) as u16,
1292 header.pic_order_cnt_lsb as u16,
1293 header.delta_pic_order_cnt_bottom,
1294 header.delta_pic_order_cnt,
1295 header.direct_spatial_mv_pred as u8,
1296 override_counts as u8,
1297 l0.saturating_sub(1),
1298 l1.saturating_sub(1),
1299 ref_pic_list_0,
1300 ref_pic_list_1,
1301 0,
1302 0,
1303 0,
1304 [0i16; 32],
1305 [0i16; 32],
1306 0,
1307 [[0i16; 2]; 32],
1308 [[0i16; 2]; 32],
1309 0,
1310 [0i16; 32],
1311 [0i16; 32],
1312 0,
1313 [[0i16; 2]; 32],
1314 [[0i16; 2]; 32],
1315 header.cabac_init_idc,
1316 (header.slice_qp - pps.pic_init_qp) as i8,
1317 header.disable_deblocking_filter_idc,
1318 header.slice_alpha_c0_offset_div2 as i8,
1319 header.slice_beta_offset_div2 as i8,
1320 )))
1321}
1322
1323fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
1325 let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
1326 let payload = BufferType::EncPackedHeaderData(data.to_vec());
1327 [param, payload]
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332 use std::path::PathBuf;
1333 use std::process::Command;
1334 use std::sync::atomic::{AtomicU32, Ordering};
1335
1336 use super::*;
1337 use crate::dmabuf::DmaBuf;
1338 use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};
1339
1340 const WIDTH: u32 = 640;
1342 const HEIGHT: u32 = 480;
1343 const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];
1344
1345 fn config(codec: Codec) -> Config {
1346 Config {
1347 codec,
1348 ..Config::new(WIDTH, HEIGHT, 30, 2_000_000, NonZeroU32::new(30).unwrap())
1349 }
1350 }
1351
1352 fn encoder(config: Config) -> Encoder {
1354 Encoder::new(Config {
1355 device: config.device.clone().or_else(|| Some(crate::testing::device())),
1356 ..config
1357 })
1358 .expect("open the VA-API encoder")
1359 }
1360
1361 fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
1363 match codec {
1364 Codec::H264 => (5, &[7, 8]),
1365 Codec::H265 => (19, &[32, 33, 34]),
1366 }
1367 }
1368
1369 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
1372 let (w, h) = (width as usize, height as usize);
1373 let mut data = vec![128u8; w * h + w * h.div_ceil(2)];
1374 for y in 0..h {
1375 for x in 0..w {
1376 data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
1377 }
1378 }
1379 let x0 = (step as usize * 8) % (w / 2);
1380 for y in h / 4..h / 2 {
1381 for x in x0..x0 + w / 4 {
1382 data[y * w + x] = 220;
1383 }
1384 }
1385 data
1386 }
1387
1388 fn temp_path(codec: Codec, label: &str) -> PathBuf {
1395 static NEXT: AtomicU32 = AtomicU32::new(0);
1396 let index = NEXT.fetch_add(1, Ordering::Relaxed);
1397 let extension = match codec {
1398 Codec::H264 => "264",
1399 Codec::H265 => "265",
1400 };
1401 std::env::temp_dir().join(format!(
1402 "kodecs-vaapi-{label}-{}-{index}.{extension}",
1403 std::process::id()
1404 ))
1405 }
1406
1407 fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> Vec<u8> {
1410 let path = temp_path(codec, name);
1413 std::fs::write(&path, stream).expect("write the elementary stream");
1414 let output = Command::new("ffmpeg")
1415 .args(["-v", "error", "-i"])
1416 .arg(&path)
1417 .args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
1418 .output();
1419 let _ = std::fs::remove_file(&path);
1420 let output = output.expect("run ffmpeg");
1421 assert!(
1422 output.status.success(),
1423 "ffmpeg refused the stream: {}",
1424 String::from_utf8_lossy(&output.stderr)
1425 );
1426 output.stdout
1427 }
1428
1429 fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
1431 let path = temp_path(codec, "probe");
1432 std::fs::write(&path, stream).expect("write the elementary stream");
1433 let output = Command::new("ffprobe")
1434 .args([
1435 "-v",
1436 "error",
1437 "-show_entries",
1438 "stream=color_range,color_space",
1439 "-of",
1440 "csv=p=0",
1441 ])
1442 .arg(&path)
1443 .output()
1444 .ok();
1445 let _ = std::fs::remove_file(&path);
1446 Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
1447 }
1448
1449 fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
1451 let len = (width * height) as usize;
1452 let mse = a[..len]
1453 .iter()
1454 .zip(&b[..len])
1455 .map(|(&x, &y)| (x as f64 - y as f64).powi(2))
1456 .sum::<f64>()
1457 / len as f64;
1458 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
1459 }
1460
1461 fn mean(
1463 plane: &[u8],
1464 stride: usize,
1465 (x0, y0, x1, y1): (usize, usize, usize, usize),
1466 step: usize,
1467 at: usize,
1468 ) -> f64 {
1469 let mut sum = 0.0;
1470 let mut count = 0.0;
1471 for y in y0..y1 {
1472 for x in x0..x1 {
1473 sum += plane[y * stride + x * step + at] as f64;
1474 count += 1.0;
1475 }
1476 }
1477 sum / count
1478 }
1479
1480 fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
1482 let mut types = Vec::new();
1483 let mut i = 0;
1484 while i + 3 < unit.len() {
1485 if unit[i..i + 3] == [0, 0, 1] {
1486 types.push(match codec {
1487 Codec::H264 => unit[i + 3] & 0x1f,
1488 Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
1489 });
1490 i += 3;
1491 }
1492 i += 1;
1493 }
1494 types
1495 }
1496
1497 fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
1499 display
1500 .create_surfaces(
1501 rt_format,
1502 Some(fourcc),
1503 width,
1504 height,
1505 Some(UsageHint::USAGE_HINT_EXPORT),
1506 vec![()],
1507 )
1508 .expect("allocate a surface")
1509 .pop()
1510 .expect("one surface")
1511 }
1512
1513 fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
1515 display
1516 .query_image_formats()
1517 .expect("query image formats")
1518 .into_iter()
1519 .find(|f| f.fourcc == fourcc)
1520 .expect("the driver has an image format for the surface format")
1521 }
1522
1523 fn surface_with(
1525 display: &Arc<Display>,
1526 fourcc: u32,
1527 rt_format: u32,
1528 size: (u32, u32),
1529 fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage),
1530 ) -> Surface<()> {
1531 let mut surface = blank_surface(display, fourcc, rt_format, size);
1532 let mut image =
1533 ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
1534 let va_image = *image.image();
1535 fill(image.as_mut(), &va_image);
1536 image.put().expect("put the image");
1537 surface.sync().expect("sync the filled surface");
1538 surface
1539 }
1540
1541 fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
1543 let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1544 let format = image_format(display, VA_FOURCC_NV12);
1545 upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
1546 DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
1547 }
1548
1549 #[test]
1552 #[ignore = "requires a VA-API render node"]
1553 fn the_render_node_is_found_or_named() {
1554 for codec in CODECS {
1555 let encoder = Encoder::new(config(codec)).expect("open the VA-API encoder");
1556 let device = encoder.config().device.clone().expect("the picked node is recorded");
1557 let display = Display::open_drm_display(&device).expect("reopen the picked node");
1558 probe(&display, codec).expect("the picked node encodes the codec");
1559
1560 let named = Config {
1561 device: Some(PathBuf::from("/dev/null")),
1562 ..config(codec)
1563 };
1564 assert!(
1565 Encoder::new(named).is_err(),
1566 "a named node that is not a render node was swapped for one that is"
1567 );
1568 }
1569 }
1570
1571 #[test]
1574 #[ignore = "requires a VA-API render node and FFmpeg"]
1575 fn nv12_round_trips_through_a_software_decoder() {
1576 for codec in CODECS {
1577 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1578 let mut encoder = encoder(Config {
1579 width,
1580 height,
1581 ..config(codec)
1582 });
1583 let mut stream = Vec::new();
1584 let mut frames = Vec::new();
1585 for step in 0..10 {
1586 let frame = nv12_frame(width, height, step);
1587 stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
1588 frames.push(frame);
1589 }
1590 let decoded = ffmpeg_decode(codec, &stream, "nv12");
1591 let len = frames[0].len();
1592 assert_eq!(
1593 decoded.len(),
1594 len * frames.len(),
1595 "{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
1596 );
1597 for (index, frame) in frames.iter().enumerate() {
1598 let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
1599 assert!(
1600 psnr > 35.0,
1601 "{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
1602 );
1603 }
1604 }
1605 }
1606 }
1607
1608 #[test]
1611 fn a_truncated_picture_is_refused() {
1612 let joined = concat_coded([(0, &[1, 2][..]), (0, &[3][..])]).expect("no overflow");
1613 assert_eq!(joined, [1, 2, 3]);
1614
1615 let overflow = crate::bindings::VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK;
1616 for statuses in [[overflow, 0], [0, overflow | 1]] {
1617 let segments = statuses.into_iter().zip([&[1u8][..], &[2u8][..]]);
1618 concat_coded(segments).expect_err("an overflow is refused");
1619 }
1620 }
1621
1622 #[test]
1625 #[ignore = "requires a VA-API render node and FFmpeg"]
1626 fn a_noise_keyframe_at_a_low_qp_decodes_whole() {
1627 let (width, height) = (1920, 1080);
1628 let mut seed = 0x2545_f491_u32;
1629 let noise: Vec<u8> = (0..width * height * 3 / 2)
1630 .map(|_| {
1631 seed ^= seed << 13;
1632 seed ^= seed >> 17;
1633 seed ^= seed << 5;
1634 seed as u8
1635 })
1636 .collect();
1637 for codec in CODECS {
1638 let mut encoder = encoder(Config {
1639 codec,
1640 qp: 1..=8,
1641 ..Config::new(width, height, 30, 2_000_000, NonZeroU32::new(30).unwrap())
1642 });
1643 let unit = encoder.encode_nv12(&noise, true).expect("encode");
1644 assert!(unit.len() > 2_000_000, "{codec:?}: only {} bytes", unit.len());
1646 let decoded = ffmpeg_decode(codec, &unit, "noise");
1647 assert_eq!(decoded.len(), noise.len(), "{codec:?}: ffmpeg decoded a different size");
1648 let psnr = luma_psnr(&noise, &decoded, width, height);
1649 assert!(psnr > 40.0, "{codec:?}: decoded at {psnr:.1} dB");
1650 }
1651 }
1652
1653 #[test]
1655 #[ignore = "requires a VA-API render node and FFmpeg"]
1656 fn the_stream_is_labelled_with_its_color_space() {
1657 for codec in CODECS {
1658 for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
1659 let mut encoder = encoder(Config { color, ..config(codec) });
1660 let unit = encoder
1661 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1662 .expect("encode");
1663 let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
1664 assert_eq!(found, expected, "{codec:?}");
1665 }
1666 }
1667 }
1668
1669 #[test]
1672 fn a_plane_fills_up_to_its_last_byte_and_no_further() {
1673 let src = [1, 2, 3, 4, 5, 6];
1674 let mut tight = [0; 11];
1677 fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
1678 assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);
1679
1680 assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
1681 assert!(
1682 fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
1683 "a pitch narrower than a row"
1684 );
1685 assert!(
1686 fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
1687 "a pitch that overflows"
1688 );
1689 fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
1690 }
1691
1692 #[test]
1694 fn limits_check_the_coded_size_against_each_bound() {
1695 let limits = Limits {
1696 min_width: Some(384),
1697 min_height: None,
1698 max_width: Some(4096),
1699 max_height: Some(2304),
1700 round: (64, 16),
1701 };
1702 for (width, height) in [(384, 2), (322, 2304), (4096, 128)] {
1703 limits.check(width, height).expect("inside every bound");
1704 }
1705 for (width, height, named) in [
1706 (320, 240, "minimum encode width of 384"),
1707 (4098, 240, "maximum encode width of 4096"),
1708 (640, 2306, "maximum encode height of 2304"),
1709 (u32::MAX - 1, 240, "maximum encode width of 4096"),
1710 ] {
1711 let err = limits.check(width, height).expect_err("outside a bound");
1712 assert!(err.to_string().contains(named), "{width}x{height}: {err:#}");
1713 }
1714
1715 let unknown = Limits {
1716 min_width: None,
1717 min_height: None,
1718 max_width: None,
1719 max_height: None,
1720 round: (1, 1),
1721 };
1722 unknown.check(2, 2).expect("no bound to break");
1723 unknown.check(u32::MAX, u32::MAX).expect("no bound to break");
1724 }
1725
1726 #[test]
1730 #[ignore = "requires a VA-API render node"]
1731 fn a_frame_under_the_minimum_width_is_refused_naming_it() {
1732 let display = crate::testing::display();
1733 let vendor = display.query_vendor_string().unwrap_or_default();
1734 for codec in CODECS {
1735 let limits = probe(&display, codec).unwrap_or_else(|e| panic!("{vendor}: no {codec:?} encoder: {e:#}"));
1736 eprintln!("{vendor} {codec:?}: {limits:?}");
1737 let min = limits.min_width.expect("the driver names a minimum width");
1738 let step = limits.round.0.max(2);
1740 let (under, over) = ((min - 1) / step * step, min.next_multiple_of(step) - step + 2);
1741 let named = |width| Config {
1742 width,
1743 device: Some(crate::testing::device()),
1744 ..config(codec)
1745 };
1746 if under > 0 {
1747 let err = Encoder::new(named(under))
1748 .err()
1749 .expect("a frame under the minimum is refused");
1750 let wanted = format!("minimum encode width of {min}");
1751 assert!(err.to_string().contains(&wanted), "{codec:?} {under} wide: {err:#}");
1752 }
1753 let mut encoder = Encoder::new(named(over)).unwrap_or_else(|e| panic!("{codec:?} {over} wide: {e:#}"));
1754 let frame = encoder.encode_nv12(&nv12_frame(over, HEIGHT, 0), true);
1755 assert!(
1756 !frame.expect("encode").is_empty(),
1757 "{codec:?} {over} wide coded nothing"
1758 );
1759 }
1760 }
1761
1762 #[test]
1764 fn an_odd_or_empty_size_is_refused() {
1765 for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
1766 let err = Encoder::new(Config {
1767 width,
1768 height,
1769 ..config(Codec::H264)
1770 })
1771 .err()
1772 .expect("refused");
1773 assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
1774 }
1775 }
1776
1777 #[test]
1780 fn an_invalid_qp_range_is_refused() {
1781 for qp in [30..=52, RangeInclusive::new(34, 30), 0..=0] {
1782 let err = Encoder::new(Config {
1783 qp: qp.clone(),
1784 ..config(Codec::H264)
1785 })
1786 .err()
1787 .expect("refused");
1788 assert!(err.to_string().contains("QP range"), "{qp:?}: {err:#}");
1789 }
1790 }
1791
1792 fn coded_sizes(config: Config, frames: u32, picture: impl Fn(u32) -> Vec<u8>) -> Vec<usize> {
1794 let mut encoder = encoder(config);
1795 (0..frames)
1796 .map(|step| encoder.encode_nv12(&picture(step), false).expect("encode").len())
1797 .collect()
1798 }
1799
1800 #[test]
1804 #[ignore = "requires a VA-API render node"]
1805 fn a_qp_ceiling_keeps_a_still_keyframe_sharp() {
1806 const SIZE: (u32, u32) = (640, 360);
1807 let (w, h) = (SIZE.0 as usize, SIZE.1 as usize);
1809 let mut text = vec![128u8; w * h + w * h / 2];
1810 for y in 0..h {
1811 for x in 0..w {
1812 let stroke = y % 14 < 10 && x % 8 < 6 && (x / 8 * 31 + y / 14 * 17 + x % 8 * 3 + y % 14 * 5) % 7 < 3;
1813 text[y * w + x] = if stroke { 40 } else { 235 };
1814 }
1815 }
1816 for codec in CODECS {
1817 let second_idr = |qp: RangeInclusive<u8>| {
1820 let config = Config {
1821 codec,
1822 qp,
1823 ..Config::new(SIZE.0, SIZE.1, 30, 1_400_000, NonZeroU32::new(30).unwrap())
1824 };
1825 coded_sizes(config, 31, |_| text.clone())[30]
1826 };
1827 let held = second_idr(DEFAULT_MIN_QP..=MAX_QP);
1828 let sharp = second_idr(DEFAULT_MIN_QP..=34);
1829 eprintln!("{codec:?} second IDR: {held} bytes within QP 24-51, {sharp} within 24-34");
1830 assert!(
1831 sharp > 2 * held,
1832 "{codec:?}: the ceiling did not sharpen the IDR: {held} -> {sharp} bytes"
1833 );
1834 }
1835 }
1836
1837 #[test]
1840 #[ignore = "requires a VA-API render node"]
1841 fn the_qp_floor_holds_under_a_ceiling() {
1842 const SIZE: (u32, u32) = (640, 360);
1843 let calm = |step: u32| {
1845 let (w, h) = (SIZE.0 as usize, SIZE.1 as usize);
1846 let mut frame = vec![128u8; w * h + w * h / 2];
1847 for y in 0..h {
1848 for x in 0..w {
1849 let sx = x + step as usize;
1850 frame[y * w + x] = (((sx * 7) ^ (y * 13)) & 0xff) as u8 / 2 + ((sx / 9 + y / 5) % 2) as u8 * 64;
1851 }
1852 }
1853 frame
1854 };
1855 for codec in CODECS {
1856 let mean = |qp: RangeInclusive<u8>| {
1858 let config = Config {
1859 codec,
1860 qp,
1861 ..Config::new(SIZE.0, SIZE.1, 30, 8_000_000, NonZeroU32::new(300).unwrap())
1862 };
1863 let sizes = coded_sizes(config, 90, calm);
1864 sizes[30..].iter().sum::<usize>() / 60
1865 };
1866 let floored = mean(36..=40);
1867 let unfloored = mean(10..=40);
1868 eprintln!("{codec:?} calm picture: {floored} bytes within QP 36-40, {unfloored} within 10-40");
1869 assert!(
1870 unfloored > floored * 3 / 2,
1871 "{codec:?}: a floor of 36 spent {floored} bytes a picture, a floor of 10 {unfloored}"
1872 );
1873 }
1874 }
1875
1876 #[test]
1879 #[ignore = "requires a VA-API render node"]
1880 fn an_upload_reads_back_as_the_same_pixels() {
1881 let display = crate::testing::display();
1882 for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1883 let frame = nv12_frame(width, height, 3);
1884 let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1885 let format = image_format(&display, VA_FOURCC_NV12);
1886 upload_nv12(format, &mut surface, width, height, &frame).expect("upload");
1887
1888 let image =
1889 crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
1890 let (va_image, data) = (*image.image(), image.as_ref());
1891 let (w, h) = (width as usize, height as usize);
1892 for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
1893 let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
1894 for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
1895 let at = offset + row * pitch;
1896 assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
1897 }
1898 }
1899 }
1900 }
1901
1902 #[test]
1904 #[ignore = "requires a VA-API render node"]
1905 fn keyframes_follow_the_group_length() {
1906 for codec in CODECS {
1907 let mut encoder = encoder(Config {
1908 gop: NonZeroU32::new(10).unwrap(),
1909 ..config(codec)
1910 });
1911 let (idr_type, parameter_sets) = idr_types(codec);
1912 for step in 0..25 {
1913 let unit = encoder
1914 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
1915 .expect("encode");
1916 let types = nal_types(codec, &unit);
1917 let idr = types.contains(&idr_type);
1918 assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
1919 if idr {
1920 assert!(
1921 parameter_sets.iter().all(|kind| types.contains(kind)),
1922 "a {codec:?} IDR carries its parameter sets: {types:?}"
1923 );
1924 }
1925 }
1926 for step in 0..=10 {
1928 let unit = encoder
1929 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
1930 .expect("encode");
1931 assert_eq!(
1932 nal_types(codec, &unit).contains(&idr_type),
1933 step % 10 == 0,
1934 "{codec:?} frame {step} after the forced keyframe"
1935 );
1936 }
1937 }
1938 }
1939
1940 #[test]
1941 fn the_full_entrypoint_wins_and_low_power_is_the_fallback() {
1942 use VAEntrypoint::{
1943 VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode,
1944 };
1945 assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full));
1946 assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower));
1947 assert_eq!(pick_entrypoint(&[Decode]), None);
1948 }
1949
1950 #[test]
1953 #[ignore = "requires a VA-API render node and FFmpeg"]
1954 fn a_refused_import_leaves_the_encoder_usable() {
1955 let mut encoder = encoder(config(Codec::H264));
1956 let display = crate::testing::display();
1957 let unmapped = DmaBuf {
1959 drm_format: u32::from_le_bytes(*b"ZZZZ"),
1960 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1961 };
1962 assert!(encoder.encode_dmabuf(unmapped, true).is_err());
1963 let unknown_modifier = DmaBuf {
1964 modifier: 0x00ff_ffff_ffff_fffe,
1965 ..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1966 };
1967 assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());
1968
1969 let unit = encoder
1970 .encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1971 .expect("the CPU path still encodes");
1972 let decoded = ffmpeg_decode(Codec::H264, &unit, "refused");
1973 let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
1974 assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
1975 }
1976
1977 #[test]
1982 #[ignore = "requires a VA-API render node and FFmpeg"]
1983 fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
1984 for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
1985 let mut encoder = encoder(Config {
1986 width,
1987 height,
1988 bitrate: 4_000_000,
1989 color: Color::infer(height),
1990 ..config(codec)
1991 });
1992 let display = crate::testing::display();
1993 let unit = encoder
1994 .encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
1995 .expect("encode the DMA-BUF");
1996 let decoded = ffmpeg_decode(codec, &unit, "short");
1997 let frame = nv12_frame(width, height, 0);
1998 assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
1999 let psnr = luma_psnr(&frame, &decoded, width, height);
2000 assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
2001 }
2002 }
2003
2004 #[test]
2007 #[ignore = "requires a VA-API render node and FFmpeg"]
2008 fn a_yuv_dmabuf_in_another_space_is_converted() {
2009 for codec in CODECS {
2010 yuv_dmabuf_in_another_space_is_converted(codec);
2011 }
2012 }
2013
2014 fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) {
2015 let mut encoder = encoder(Config {
2016 color: Color::BT601,
2017 ..config(codec)
2018 });
2019 let display = crate::testing::display();
2020 let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
2022 let surface = surface_with(
2023 &display,
2024 VA_FOURCC_NV12,
2025 VA_RT_FORMAT_YUV420,
2026 (WIDTH, HEIGHT),
2027 |data, image| {
2028 for row in 0..HEIGHT as usize {
2029 let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
2030 data[at..at + WIDTH as usize].fill(y);
2031 }
2032 for row in 0..HEIGHT as usize / 2 {
2033 let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
2034 for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
2035 pair.copy_from_slice(&[u, v]);
2036 }
2037 }
2038 },
2039 );
2040 let buffer = DmaBuf {
2041 color: Some(Color::BT709),
2042 ..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
2043 };
2044 let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
2045 let decoded = ffmpeg_decode(codec, &unit, "yuv-color");
2046
2047 let (w, h) = (WIDTH as usize, HEIGHT as usize);
2048 let (luma, chroma) = decoded.split_at(w * h);
2049 let actual = [
2050 mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
2051 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
2052 mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
2053 ];
2054 let expected = limited([255, 0, 0], Color::BT601);
2055 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
2056 assert!(
2057 (a - e).abs() < 6.0,
2058 "{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
2059 );
2060 }
2061 }
2062
2063 #[test]
2065 #[ignore = "requires a VA-API render node and FFmpeg"]
2066 fn an_nv12_dmabuf_encodes_in_place() {
2067 for codec in CODECS {
2068 let mut encoder = encoder(config(codec));
2069 let display = crate::testing::display();
2070 let mut stream = Vec::new();
2071 for step in 0..5 {
2072 let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
2073 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
2074 }
2075 let decoded = ffmpeg_decode(codec, &stream, "dmabuf");
2076 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
2077 assert_eq!(decoded.len(), 5 * len, "{codec:?}");
2078 for step in 0..5 {
2079 let psnr = luma_psnr(
2080 &nv12_frame(WIDTH, HEIGHT, step),
2081 &decoded[step as usize * len..],
2082 WIDTH,
2083 HEIGHT,
2084 );
2085 assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
2086 }
2087 }
2088 }
2089
2090 #[test]
2092 #[ignore = "requires a VA-API render node and FFmpeg"]
2093 fn a_dmabuf_at_another_size_is_scaled() {
2094 for codec in CODECS {
2095 dmabuf_at_another_size_is_scaled(codec);
2096 }
2097 }
2098
2099 fn dmabuf_at_another_size_is_scaled(codec: Codec) {
2100 let mut encoder = encoder(config(codec));
2101 let display = crate::testing::display();
2102 let mut stream = Vec::new();
2103 for step in 0..3 {
2104 let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
2105 stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
2106 }
2107 let decoded = ffmpeg_decode(codec, &stream, "scaled");
2108 let len = nv12_frame(WIDTH, HEIGHT, 0).len();
2109 assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
2110 for step in 0..3u32 {
2114 let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
2115 let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
2116 for y in 0..HEIGHT as usize {
2117 for x in 0..WIDTH as usize {
2118 expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
2119 }
2120 }
2121 let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
2122 assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
2123 }
2124 }
2125
2126 #[test]
2128 #[ignore = "requires a VA-API render node and FFmpeg"]
2129 fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
2130 const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
2132 for (codec, color) in CODECS
2133 .into_iter()
2134 .flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
2135 {
2136 let mut encoder = encoder(Config { color, ..config(codec) });
2137 let display = crate::testing::display();
2138 let surface = surface_with(
2139 &display,
2140 VA_FOURCC_BGRX,
2141 VA_RT_FORMAT_RGB32,
2142 (WIDTH, HEIGHT),
2143 |data, image| {
2144 let pitch = image.pitches[0] as usize;
2145 let offset = image.offsets[0] as usize;
2146 for y in 0..HEIGHT as usize {
2147 for x in 0..WIDTH as usize {
2148 let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
2149 let [r, g, b] = QUADRANTS[quadrant];
2150 let at = offset + y * pitch + x * 4;
2151 data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
2152 }
2153 }
2154 },
2155 );
2156 let exported = surface.export_prime().expect("export");
2157 let buffer = DmaBuf::from_prime(exported).expect("one object");
2158 assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
2159 let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
2160 let decoded = ffmpeg_decode(codec, &unit, "rgb");
2161
2162 let (w, h) = (WIDTH as usize, HEIGHT as usize);
2163 let (luma, chroma) = decoded.split_at(w * h);
2164 for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
2165 let (qx, qy) = (quadrant % 2, quadrant / 2);
2166 let area = |scale: usize| {
2168 let (qw, qh) = (w / 2 / scale, h / 2 / scale);
2169 (
2170 qx * qw + qw / 4,
2171 qy * qh + qh / 4,
2172 qx * qw + qw * 3 / 4,
2173 qy * qh + qh * 3 / 4,
2174 )
2175 };
2176 let actual = [
2177 mean(luma, w, area(1), 1, 0),
2178 mean(chroma, w, area(2), 2, 0),
2179 mean(chroma, w, area(2), 2, 1),
2180 ];
2181 let expected = limited(*rgb, color);
2182 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
2183 assert!(
2184 (a - e).abs() < 6.0,
2185 "{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
2186 );
2187 }
2188 }
2189 }
2190 }
2191
2192 #[test]
2193 fn the_level_covers_the_frame_size_and_rate() {
2194 assert_eq!(level(320, 240, 30), Level::L4);
2195 assert_eq!(level(1920, 1080, 30), Level::L4);
2196 assert_eq!(level(1920, 1080, 60), Level::L4_2);
2197 assert_eq!(level(2560, 1440, 30), Level::L5);
2198 assert_eq!(level(3840, 2160, 30), Level::L5_1);
2199 assert_eq!(level(3840, 2160, 60), Level::L5_2);
2200 assert_eq!(level(4352, 240, 30), Level::L5);
2202 }
2203
2204 #[test]
2205 fn an_unknown_framerate_still_builds_the_parameter_sets() {
2206 build_sps_pps(&Config {
2207 framerate: 0,
2208 ..config(Codec::H264)
2209 })
2210 .expect("build the SPS and PPS for framerate 0");
2211 }
2212
2213 fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
2215 let (kr, kb) = match color.matrix {
2216 crate::Matrix::Bt601 => (0.299, 0.114),
2217 crate::Matrix::Bt709 => (0.2126, 0.0722),
2218 };
2219 let (r, g, b) = (r as f64, g as f64, b as f64);
2220 let y = kr * r + (1.0 - kr - kb) * g + kb * b;
2221 [
2222 16.0 + y * 219.0 / 255.0,
2223 128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
2224 128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
2225 ]
2226 }
2227
2228 #[test]
2231 #[ignore = "requires a VA-API render node"]
2232 fn a_bitrate_change_takes_effect_without_a_keyframe() {
2233 for codec in CODECS {
2234 bitrate_change_takes_effect_without_a_keyframe(codec);
2235 }
2236 }
2237
2238 fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) {
2239 let mut encoder = encoder(Config {
2240 gop: NonZeroU32::new(1_000).unwrap(),
2241 ..config(codec)
2242 });
2243 let (idr_type, _) = idr_types(codec);
2244 let frame = |step: u32| {
2248 let (w, h) = (WIDTH as usize, HEIGHT as usize);
2249 let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
2250 for y in 0..h {
2251 for x in 0..w {
2252 let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
2253 let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
2254 frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
2255 }
2256 }
2257 frame
2258 };
2259 let average = |encoder: &mut Encoder, from: u32| {
2263 let sizes: Vec<usize> = (from..from + 60)
2264 .map(|step| {
2265 let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
2266 if step > 0 {
2267 assert!(
2268 !nal_types(codec, &unit).contains(&idr_type),
2269 "{codec:?} picture {step} is an IDR"
2270 );
2271 }
2272 unit.len()
2273 })
2274 .collect();
2275 sizes[30..].iter().sum::<usize>() / 30
2276 };
2277
2278 let within = |bytes: usize, bitrate: u32| {
2281 let target = bitrate as usize / 8 / 30;
2282 assert!(
2283 bytes * 4 <= target * 5,
2284 "{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
2285 );
2286 };
2287
2288 let high = average(&mut encoder, 0);
2289 within(high, 2_000_000);
2290 encoder.set_bitrate(250_000).expect("set the bitrate");
2291 assert_eq!(encoder.config().bitrate, 250_000);
2292 assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
2293 let low = average(&mut encoder, 60);
2294 eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
2295 within(low, 250_000);
2296 assert!(
2297 low * 3 < high,
2298 "{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
2299 );
2300 }
2301}