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