1use std::io::Cursor;
44use std::path::PathBuf;
45use std::rc::Rc;
46use std::sync::Arc;
47
48use anyhow::{anyhow, bail, Context as _};
49
50use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists};
51use crate::codec::h264::picture::{Field, IsIdr, PictureData, Reference};
52use crate::codec::Codec;
53use crate::pool::{PooledSurface, SurfacePool};
54use crate::{
55 bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields,
56 H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter,
57 PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib,
58 VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
59 VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420,
60 VA_SLICE_DATA_FLAG_ALL,
61};
62use kodecs_h264::{
63 Level, MaxLongTermFrameIdx, Nalu, NaluType, Parser, Pps, Profile, RefPicListModification, Slice, SliceHeader,
64 SliceType, Sps,
65};
66
67mod h265;
68
69#[derive(Clone, Debug)]
71pub struct Config {
72 pub codec: Codec,
74 pub device: Option<PathBuf>,
79}
80
81impl Config {
82 pub fn new() -> Self {
84 Self {
85 codec: Codec::H264,
86 device: None,
87 }
88 }
89}
90
91impl Default for Config {
92 fn default() -> Self {
93 Self::new()
94 }
95}
96
97#[derive(Clone)]
99pub struct Frame {
100 pub timestamp: u64,
103 pub width: u32,
105 pub height: u32,
107 pub data: Vec<u8>,
110}
111
112pub struct ExportedFrame {
137 pub timestamp: u64,
140 pub width: u32,
142 pub height: u32,
144 pub descriptor: DrmPrimeSurfaceDescriptor,
147 surface: Arc<PooledSurface>,
151}
152
153impl ExportedFrame {
154 pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result<Self> {
166 let size = surface.size();
167 Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size)
168 }
169
170 pub(crate) fn export(
176 surface: Arc<PooledSurface>,
177 timestamp: u64,
178 (width, height): (u32, u32),
179 ) -> anyhow::Result<Self> {
180 surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
181 let descriptor = surface
182 .get()
183 .export_prime()
184 .map_err(|e| anyhow!("export the surface: {e:?}"))?;
185 if descriptor.fourcc != VA_FOURCC_NV12 {
186 anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc);
187 }
188 Ok(Self {
189 timestamp,
190 width,
191 height,
192 descriptor,
193 surface,
194 })
195 }
196
197 pub fn download(&self) -> anyhow::Result<Frame> {
206 read_back(self.surface.get(), self.timestamp, self.width, self.height)
207 }
208}
209
210impl std::fmt::Debug for ExportedFrame {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 f.debug_struct("ExportedFrame")
213 .field("timestamp", &self.timestamp)
214 .field("width", &self.width)
215 .field("height", &self.height)
216 .field("fourcc", &self.descriptor.fourcc)
217 .finish()
218 }
219}
220
221impl std::fmt::Debug for Frame {
222 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 f.debug_struct("Frame")
224 .field("timestamp", &self.timestamp)
225 .field("width", &self.width)
226 .field("height", &self.height)
227 .field("bytes", &self.data.len())
228 .finish()
229 }
230}
231
232pub struct Decoder {
254 inner: Inner,
255}
256
257enum Inner {
260 H264(H264),
261 H265(h265::Decoder),
262}
263
264struct H264 {
266 parser: Parser,
267 dpb: Dpb<Handle>,
268 prev_ref_pic_info: PrevReferencePicInfo,
270 prev_pic_info: PrevPicInfo,
272 max_long_term_frame_idx: MaxLongTermFrameIdx,
273 sequence: Option<Sequence>,
276 ready: Vec<Handle>,
278 display: Arc<Display>,
280}
281
282impl Decoder {
283 pub fn new(config: Config) -> anyhow::Result<Self> {
293 let codec = config.codec;
294 let (device, display) = match config.device {
295 Some(device) => {
296 let display =
297 Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
298 probe(&display, codec)?;
299 (device, display)
300 }
301 None => crate::display::open_first(|display| probe(display, codec))
302 .map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
303 };
304
305 tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
306 let inner = match codec {
307 Codec::H264 => Inner::H264(H264::new(display)),
308 Codec::H265 => Inner::H265(h265::Decoder::new(display)),
309 };
310 Ok(Self { inner })
311 }
312
313 pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
321 self.submit(access_unit, timestamp)?;
322 self.take_frames()
323 }
324
325 pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
344 self.submit(access_unit, timestamp)?;
345 self.take_exported()
346 }
347
348 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
352 let nalus = match &mut self.inner {
353 Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
354 Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
355 };
356
357 if nalus == 0 && !access_unit.is_empty() {
361 tracing::warn!(
362 "access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
363 access_unit.len()
364 );
365 }
366 Ok(())
367 }
368
369 pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
380 self.reset();
381 self.take_frames()
382 }
383
384 pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
386 self.reset();
387 self.take_exported()
388 }
389
390 fn reset(&mut self) {
393 match &mut self.inner {
394 Inner::H264(decoder) => decoder.reset(),
395 Inner::H265(decoder) => decoder.reset(),
396 }
397 }
398
399 fn ready(&mut self) -> &mut Vec<Handle> {
401 match &mut self.inner {
402 Inner::H264(decoder) => &mut decoder.ready,
403 Inner::H265(decoder) => &mut decoder.ready,
404 }
405 }
406
407 fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
409 std::mem::take(self.ready()).iter().map(download).collect()
410 }
411
412 fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
415 std::mem::take(self.ready()).iter().map(export).collect()
416 }
417
418 #[cfg(test)]
420 fn sequence(&self) -> Option<&Sequence> {
421 match &self.inner {
422 Inner::H264(decoder) => decoder.sequence.as_ref(),
423 Inner::H265(decoder) => decoder.sequence.as_ref(),
424 }
425 }
426}
427
428impl H264 {
429 fn new(display: Arc<Display>) -> Self {
430 Self {
431 parser: Parser::default(),
432 dpb: Dpb::default(),
433 prev_ref_pic_info: PrevReferencePicInfo::default(),
434 prev_pic_info: PrevPicInfo::default(),
435 max_long_term_frame_idx: MaxLongTermFrameIdx::default(),
436 sequence: None,
437 ready: Vec::new(),
438 display,
439 }
440 }
441
442 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
444 let mut cursor = Cursor::new(access_unit);
445 let mut current: Option<CurrentPicture> = None;
446 let mut nalus = 0usize;
447
448 while let Ok(nalu) = Nalu::next(&mut cursor) {
451 nalus += 1;
452 match nalu.header.type_ {
453 NaluType::Sps => {
454 self.parser.parse_sps(&nalu).map_err(|e| anyhow!("parse SPS: {e}"))?;
455 }
456 NaluType::Pps => {
457 self.parser.parse_pps(&nalu).map_err(|e| anyhow!("parse PPS: {e}"))?;
458 }
459 kind if kind.is_slice() => {
462 let slice = self
463 .parser
464 .parse_slice_header(nalu)
465 .map_err(|e| anyhow!("parse slice header: {e}"))?;
466
467 let mut picture = match current.take() {
468 Some(picture) if slice.header.first_mb_in_slice == 0 => {
472 self.finish_picture(picture)?;
473 self.begin_picture(&slice, timestamp)?
474 }
475 Some(picture) => picture,
476 None => self.begin_picture(&slice, timestamp)?,
477 };
478
479 self.decode_slice(&mut picture, &slice)?;
480 current = Some(picture);
481 }
482 other => tracing::trace!("ignoring NAL unit of type {other:?}"),
483 }
484 }
485
486 if let Some(picture) = current.take() {
489 self.finish_picture(picture)?;
490 }
491
492 Ok(nalus)
493 }
494
495 fn reset(&mut self) {
498 self.drain();
499 self.prev_ref_pic_info = PrevReferencePicInfo::default();
500 self.prev_pic_info = PrevPicInfo::default();
501 self.max_long_term_frame_idx = MaxLongTermFrameIdx::default();
502 }
503
504 fn drain(&mut self) {
506 self.ready.extend(self.dpb.drain().into_iter().flatten());
507 }
508
509 fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
512 let info = SequenceInfo::new(sps)?;
513 self.dpb
516 .set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));
517
518 let format = Format {
519 codec: Codec::H264,
520 profile: va_profile(sps)?,
521 coded: info.coded,
522 visible: info.visible,
523 max_dpb_frames: info.max_dpb_frames,
524 };
525 if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
526 return Ok(());
527 }
528
529 self.drain();
533
534 self.sequence = Some(Sequence::new(&self.display, format)?);
535 Ok(())
536 }
537
538 fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
541 let pps = Arc::clone(
542 self.parser
543 .get_pps(slice.header.pic_parameter_set_id)
544 .context("slice refers to an unknown PPS")?,
545 );
546 let sps = Arc::clone(&pps.sps);
547 self.apply_sps(&sps)?;
548
549 if slice.nalu.header.idr_pic_flag() {
550 self.prev_ref_pic_info.frame_num = 0;
551 }
552
553 let frame_num = u32::from(slice.header.frame_num);
554 if frame_num != self.prev_ref_pic_info.frame_num
555 && frame_num != (self.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num()
556 {
557 self.handle_frame_num_gap(&sps, frame_num, timestamp)?;
558 }
559
560 let pic = self.init_current_pic(slice, &sps, timestamp)?;
561 let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic);
562
563 let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
565 let context = Rc::clone(&sequence.context);
566 let handle = sequence.handle(timestamp)?;
567
568 let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
569 let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
570 picture.add_buffer(create_buffer(&context, pic_param)?);
571 picture.add_buffer(create_buffer(&context, build_iq_matrix(&pps))?);
572
573 tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
574 Ok(CurrentPicture {
575 pic,
576 pps,
577 handle,
578 picture,
579 ref_pic_lists,
580 })
581 }
582
583 fn decode_slice(&mut self, current: &mut CurrentPicture, slice: &Slice) -> anyhow::Result<()> {
586 if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
590 bail!(
591 "slice starts at macroblock {}, past what a VA slice parameter addresses",
592 slice.header.first_mb_in_slice
593 );
594 }
595 if slice.header.header_bit_size > usize::from(u16::MAX) {
596 bail!(
597 "slice header is {} bits long, past what a VA slice parameter addresses",
598 slice.header.header_bit_size
599 );
600 }
601
602 let pps = Arc::clone(
605 self.parser
606 .get_pps(slice.header.pic_parameter_set_id)
607 .context("slice refers to an unknown PPS")?,
608 );
609 if SequenceInfo::new(&pps.sps)? != SequenceInfo::new(¤t.pps.sps)? {
610 bail!("invalid stream: the sequence changed between slices of one picture");
611 }
612 current.pps = Arc::clone(&pps);
613
614 let (list0, list1) = self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.ref_pic_lists)?;
615 let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
616
617 let slice_param = build_slice_param(&slice.header, slice.nalu.as_ref().len(), &list0, &list1, &pps.sps, &pps);
618 current.picture.add_buffer(create_buffer(context, slice_param)?);
619 current.picture.add_buffer(create_buffer(
620 context,
621 BufferType::SliceData(slice.nalu.as_ref().to_vec()),
622 )?);
623
624 Ok(())
625 }
626
627 fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
630 let CurrentPicture {
631 mut pic,
632 pps,
633 handle,
634 picture,
635 ..
636 } = current;
637
638 run(picture)?;
639 tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
640
641 if pic.is_ref() {
642 self.reference_pic_marking(&mut pic, &pps.sps)?;
643 self.prev_ref_pic_info.fill(&pic);
644 }
645 self.prev_pic_info.fill(&pic);
646
647 if pic.has_mmco_5 {
650 self.drain();
651 }
652
653 self.dpb
655 .finish_picture(pic, handle, &mut self.ready)
656 .map_err(|e| anyhow!("store picture in DPB: {e}"))?;
657
658 Ok(())
659 }
660
661 fn init_current_pic(&mut self, slice: &Slice, sps: &Sps, timestamp: u64) -> anyhow::Result<PictureData> {
663 let mut pic = PictureData::new_from_slice(slice, sps, timestamp, None);
665 self.compute_pic_order_count(&mut pic, sps)?;
666
667 if matches!(pic.is_idr, IsIdr::Yes { .. }) {
668 if pic.ref_pic_marking.no_output_of_prior_pics_flag {
671 self.dpb.clear();
672 } else {
673 self.drain();
674 }
675 }
676
677 self.dpb
678 .update_pic_nums(u32::from(slice.header.frame_num), sps.max_frame_num(), &pic);
679
680 Ok(pic)
681 }
682
683 fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32, timestamp: u64) -> anyhow::Result<()> {
686 if self.dpb.is_empty() {
687 return Ok(());
688 }
689
690 if !sps.gaps_in_frame_num_value_allowed_flag {
691 bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
692 }
693 tracing::debug!("frame_num gap up to {frame_num}");
694
695 let max_frame_num = sps.max_frame_num();
696 let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
697 while unused != frame_num {
698 let mut pic = PictureData::new_non_existing(unused, timestamp);
699 self.compute_pic_order_count(&mut pic, sps)?;
700
701 self.dpb.update_pic_nums(unused, max_frame_num, &pic);
702 self.dpb.sliding_window_marking(&mut pic, sps);
703 self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
704 self.dpb
705 .store_picture(pic.into_rc(), None)
706 .map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
707
708 unused = (unused + 1) % max_frame_num;
709 }
710
711 Ok(())
712 }
713
714 fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
716 pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
717 }
718
719 fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
721 if matches!(pic.is_idr, IsIdr::Yes { .. }) {
722 self.dpb.mark_all_as_unused_for_ref();
723
724 if pic.ref_pic_marking.long_term_reference_flag {
725 pic.set_reference(Reference::LongTerm, false);
726 pic.long_term_frame_idx = 0;
727 self.max_long_term_frame_idx = MaxLongTermFrameIdx::Idx(0);
728 } else {
729 pic.set_reference(Reference::ShortTerm, false);
730 self.max_long_term_frame_idx = MaxLongTermFrameIdx::NoLongTermFrameIndices;
731 }
732
733 return Ok(());
734 }
735
736 if pic.ref_pic_marking.adaptive_ref_pic_marking_mode_flag {
737 self.handle_memory_management_ops(pic)?;
738 } else {
739 self.dpb.sliding_window_marking(pic, sps);
740 }
741
742 Ok(())
743 }
744
745 fn handle_memory_management_ops(&mut self, pic: &mut PictureData) -> Result<(), MmcoError> {
747 let markings = pic.ref_pic_marking.clone();
748
749 for marking in &markings.inner {
750 match marking.memory_management_control_operation {
751 0 => break,
752 1 => self.dpb.mmco_op_1(pic, marking)?,
753 2 => self.dpb.mmco_op_2(pic, marking)?,
754 3 => self.dpb.mmco_op_3(pic, marking)?,
755 4 => self.max_long_term_frame_idx = self.dpb.mmco_op_4(marking),
756 5 => self.max_long_term_frame_idx = self.dpb.mmco_op_5(pic),
757 6 => self.dpb.mmco_op_6(pic, marking),
758 other => return Err(MmcoError::UnknownMmco(other)),
759 }
760 }
761
762 Ok(())
763 }
764
765 fn create_ref_pic_lists<'a>(
768 &'a self,
769 pic: &PictureData,
770 hdr: &SliceHeader,
771 lists: &ReferencePicLists,
772 ) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
773 let list0 = match hdr.slice_type {
774 SliceType::P | SliceType::Sp => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0)?,
775 SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0)?,
776 _ => Vec::new(),
777 };
778
779 let list1 = match hdr.slice_type {
780 SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1)?,
781 _ => Vec::new(),
782 };
783
784 Ok((list0, list1))
785 }
786
787 fn modify_ref_pic_list<'a>(
789 &'a self,
790 pic: &PictureData,
791 hdr: &SliceHeader,
792 list1: bool,
793 indices: &[usize],
794 ) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
795 let (modify, num_ref_idx_active_minus1, modifications) = if list1 {
796 (
797 hdr.ref_pic_list_modification_flag_l1,
798 hdr.num_ref_idx_l1_active_minus1,
799 &hdr.ref_pic_list_modification_l1,
800 )
801 } else {
802 (
803 hdr.ref_pic_list_modification_flag_l0,
804 hdr.num_ref_idx_l0_active_minus1,
805 &hdr.ref_pic_list_modification_l0,
806 )
807 };
808
809 let mut list: DpbPicRefList<'a, Handle> = indices
810 .iter()
811 .map(|&i| &self.dpb.entries()[i])
812 .take(usize::from(num_ref_idx_active_minus1) + 1)
813 .collect();
814
815 if !modify {
816 return Ok(list);
817 }
818
819 let mut pic_num_pred = pic.pic_num;
820 let mut ref_idx = 0;
821
822 for modification in modifications {
823 match modification.modification_of_pic_nums_idc {
824 idc @ (0 | 1) => self.short_term_modification(
825 pic,
826 &mut list,
827 num_ref_idx_active_minus1,
828 hdr.max_pic_num as i32,
829 idc,
830 modification,
831 &mut pic_num_pred,
832 &mut ref_idx,
833 )?,
834 2 => self.long_term_modification(&mut list, num_ref_idx_active_minus1, modification, &mut ref_idx)?,
835 3 => break,
836 other => bail!("unexpected modification_of_pic_nums_idc {other}"),
837 }
838 }
839
840 Ok(list)
841 }
842
843 fn short_term_modification<'a>(
845 &'a self,
846 pic: &PictureData,
847 list: &mut DpbPicRefList<'a, Handle>,
848 num_ref_idx_active_minus1: u8,
849 max_pic_num: i32,
850 idc: u8,
851 modification: &RefPicListModification,
852 pic_num_pred: &mut i32,
853 ref_idx: &mut usize,
854 ) -> anyhow::Result<()> {
855 if modification.abs_diff_pic_num_minus1 >= max_pic_num as u32 {
856 bail!("short-term picture number difference exceeds MaxPicNum");
857 }
858 let abs_diff_pic_num = modification.abs_diff_pic_num_minus1 as i32 + 1;
859
860 let pic_num_no_wrap = if idc == 0 {
861 if *pic_num_pred - abs_diff_pic_num < 0 {
862 *pic_num_pred - abs_diff_pic_num + max_pic_num
863 } else {
864 *pic_num_pred - abs_diff_pic_num
865 }
866 } else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
867 *pic_num_pred + abs_diff_pic_num - max_pic_num
868 } else {
869 *pic_num_pred + abs_diff_pic_num
870 };
871
872 *pic_num_pred = pic_num_no_wrap;
873
874 let pic_num = if pic_num_no_wrap > pic.pic_num {
875 pic_num_no_wrap - max_pic_num
876 } else {
877 pic_num_no_wrap
878 };
879
880 let entry = self
881 .dpb
882 .find_short_term_with_pic_num(pic_num)
883 .with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
884
885 Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| {
886 target.pic_num_f(max_pic_num) != pic_num
887 });
888
889 Ok(())
890 }
891
892 fn long_term_modification<'a>(
894 &'a self,
895 list: &mut DpbPicRefList<'a, Handle>,
896 num_ref_idx_active_minus1: u8,
897 modification: &RefPicListModification,
898 ref_idx: &mut usize,
899 ) -> anyhow::Result<()> {
900 let long_term_pic_num = modification.long_term_pic_num;
901 let max_long_term_frame_idx = self.max_long_term_frame_idx;
902
903 let entry = self
904 .dpb
905 .find_long_term_with_long_term_pic_num(long_term_pic_num)
906 .with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
907
908 Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| {
909 target.long_term_pic_num_f(max_long_term_frame_idx) != u64::from(long_term_pic_num)
910 });
911
912 Ok(())
913 }
914
915 fn insert_modification<'a>(
918 list: &mut DpbPicRefList<'a, Handle>,
919 entry: &'a DpbEntry<Handle>,
920 num_ref_idx_active_minus1: u8,
921 ref_idx: &mut usize,
922 keep: impl Fn(&PictureData) -> bool,
923 ) {
924 let at = (*ref_idx).min(list.len());
927 list.insert(at, entry);
928 *ref_idx = at + 1;
929
930 let mut next = *ref_idx;
931 for current in *ref_idx..=usize::from(num_ref_idx_active_minus1) + 1 {
932 if current >= list.len() {
933 break;
934 }
935
936 if keep(&list[current].pic.borrow()) {
937 list[next] = list[current];
938 next += 1;
939 }
940 }
941
942 list.truncate(usize::from(num_ref_idx_active_minus1) + 1);
943 }
944}
945
946struct CurrentPicture {
948 pic: PictureData,
949 pps: Arc<Pps>,
951 handle: Handle,
953 picture: Picture<crate::PictureNew, Handle>,
954 ref_pic_lists: ReferencePicLists,
956}
957
958#[derive(Clone)]
962struct Handle {
963 surface: Arc<PooledSurface>,
964 timestamp: u64,
965 width: u32,
966 height: u32,
967}
968
969impl std::borrow::Borrow<Surface<()>> for Handle {
970 fn borrow(&self) -> &Surface<()> {
971 self.surface.get()
972 }
973}
974
975#[derive(Clone, Debug, PartialEq, Eq)]
978struct SequenceInfo {
979 visible: (u32, u32),
980 coded: (u32, u32),
981 profile_idc: u8,
982 bit_depth_luma_minus8: u8,
983 bit_depth_chroma_minus8: u8,
984 chroma_format_idc: u8,
985 frame_mbs_only_flag: bool,
986 max_dpb_frames: usize,
987}
988
989impl SequenceInfo {
990 fn new(sps: &Sps) -> anyhow::Result<Self> {
991 if !sps.frame_mbs_only_flag {
992 bail!("interlaced H.264 is not supported");
993 }
994 if sps.chroma_format_idc != 1 {
995 bail!(
996 "only 4:2:0 chroma is supported, got chroma_format_idc {}",
997 sps.chroma_format_idc
998 );
999 }
1000 if sps.bit_depth_luma_minus8 != 0 || sps.bit_depth_chroma_minus8 != 0 {
1001 bail!(
1002 "only 8-bit samples are supported, got {}-bit luma and {}-bit chroma",
1003 sps.bit_depth_luma_minus8 + 8,
1004 sps.bit_depth_chroma_minus8 + 8
1005 );
1006 }
1007
1008 if sps.frame_cropping_flag && (sps.frame_crop_left_offset != 0 || sps.frame_crop_top_offset != 0) {
1009 bail!("left and top H.264 cropping is not supported");
1010 }
1011 let (crop_right, crop_bottom) = if sps.frame_cropping_flag {
1012 (sps.frame_crop_right_offset, sps.frame_crop_bottom_offset)
1013 } else {
1014 (0, 0)
1015 };
1016 let width = crop_right
1017 .checked_mul(2)
1018 .and_then(|crop| sps.width().checked_sub(crop))
1019 .context("invalid horizontal H.264 crop")?;
1020 let height = crop_bottom
1021 .checked_mul(2)
1022 .and_then(|crop| sps.height().checked_sub(crop))
1023 .context("invalid vertical H.264 crop")?;
1024 if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 {
1025 bail!("visible size {width}x{height} is not a non-zero even 4:2:0 size");
1026 }
1027
1028 Ok(Self {
1029 visible: (width, height),
1030 coded: (sps.width(), sps.height()),
1031 profile_idc: sps.profile_idc,
1032 bit_depth_luma_minus8: sps.bit_depth_luma_minus8,
1033 bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8,
1034 chroma_format_idc: sps.chroma_format_idc,
1035 frame_mbs_only_flag: sps.frame_mbs_only_flag,
1036 max_dpb_frames: sps.max_dpb_frames().context("unknown H.264 level_idc")?,
1037 })
1038 }
1039}
1040
1041#[derive(Clone, Debug, PartialEq, Eq)]
1044struct Format {
1045 codec: Codec,
1046 profile: VAProfile::Type,
1047 coded: (u32, u32),
1048 visible: (u32, u32),
1050 max_dpb_frames: usize,
1052}
1053
1054struct Sequence {
1056 format: Format,
1057 pool: SurfacePool,
1058 context: Rc<Context>,
1060 _config: VaConfig,
1061}
1062
1063impl Sequence {
1064 fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
1065 let attrs = vec![VAConfigAttrib {
1066 type_: VAConfigAttribType::VAConfigAttribRTFormat,
1067 value: VA_RT_FORMAT_YUV420,
1068 }];
1069 let config = display
1070 .create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
1071 .map_err(|e| anyhow!("create VA config: {e:?}"))?;
1072
1073 let (coded_width, coded_height) = format.coded;
1074 let context = display
1075 .create_context::<()>(&config, coded_width, coded_height, None, true)
1076 .map_err(|e| anyhow!("create VA context: {e:?}"))?;
1077
1078 let (width, height) = format.visible;
1079 tracing::info!(
1080 "VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
1081 VA profile {}, DPB {} frames",
1082 format.codec,
1083 format.profile,
1084 format.max_dpb_frames
1085 );
1086
1087 let capacity = format.max_dpb_frames + 1;
1092 Ok(Self {
1093 pool: SurfacePool::new(
1094 display,
1095 (coded_width, coded_height),
1096 UsageHint::USAGE_HINT_DECODER,
1097 capacity,
1098 ),
1099 format,
1100 context,
1101 _config: config,
1102 })
1103 }
1104
1105 fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
1107 let (width, height) = self.format.visible;
1108 Ok(Handle {
1109 surface: Arc::new(self.pool.alloc()?),
1110 timestamp,
1111 width,
1112 height,
1113 })
1114 }
1115}
1116
1117fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
1123 let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
1124 let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
1125 let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
1126 drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
1127 Ok(())
1128}
1129
1130fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
1139 if sps.pic_order_cnt_type == 2 {
1140 return 0;
1141 }
1142 sps.max_num_reorder_frames()
1144 .map_or(max_dpb_frames, |frames| frames as usize)
1145 .min(max_dpb_frames)
1146}
1147
1148fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
1150 ExportedFrame::export(
1151 Arc::clone(&handle.surface),
1152 handle.timestamp,
1153 (handle.width, handle.height),
1154 )
1155}
1156
1157fn download(handle: &Handle) -> anyhow::Result<Frame> {
1159 read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
1160}
1161
1162fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
1168 surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
1169
1170 let visible = (width, height);
1171
1172 match unsafe { Image::derive_shared(surface, visible) } {
1179 Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
1180 return pack_nv12(&image, timestamp, width, height);
1181 }
1182 Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
1183 Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
1184 }
1185
1186 let format = surface
1187 .display()
1188 .query_image_formats()
1189 .map_err(|e| anyhow!("query image formats: {e:?}"))?
1190 .into_iter()
1191 .find(|format| format.fourcc == VA_FOURCC_NV12)
1192 .context("driver has no NV12 image format")?;
1193 let image = Image::create_from(surface, format, surface.size(), visible)
1194 .map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
1195
1196 pack_nv12(&image, timestamp, width, height)
1197}
1198
1199fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
1202 let va_image = image.image();
1203 let src: &[u8] = image.as_ref();
1204 let (width, height) = (frame_width as usize, frame_height as usize);
1205 let chroma_rows = height / 2;
1206
1207 let mut data = vec![0u8; width * (height + chroma_rows)];
1208 let (luma, chroma) = data.split_at_mut(width * height);
1209 copy_plane(
1210 luma,
1211 src,
1212 va_image.offsets[0] as usize,
1213 va_image.pitches[0] as usize,
1214 width,
1215 height,
1216 )?;
1217 copy_plane(
1218 chroma,
1219 src,
1220 va_image.offsets[1] as usize,
1221 va_image.pitches[1] as usize,
1222 width,
1223 chroma_rows,
1224 )?;
1225
1226 Ok(Frame {
1227 timestamp,
1228 width: frame_width,
1229 height: frame_height,
1230 data,
1231 })
1232}
1233
1234fn copy_plane(
1236 dst: &mut [u8],
1237 src: &[u8],
1238 offset: usize,
1239 pitch: usize,
1240 width: usize,
1241 rows: usize,
1242) -> anyhow::Result<()> {
1243 if rows == 0 {
1244 return Ok(());
1245 }
1246 let end = offset + pitch * (rows - 1) + width;
1247 if pitch < width || src.len() < end {
1248 bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
1249 }
1250
1251 for row in 0..rows {
1252 let from = offset + row * pitch;
1253 dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
1254 }
1255
1256 Ok(())
1257}
1258
1259pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
1267 let profiles = display
1268 .query_config_profiles()
1269 .map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
1270
1271 let supported = profiles
1272 .into_iter()
1273 .filter(|profile| match codec {
1274 Codec::H264 => matches!(
1275 *profile,
1276 VAProfile::VAProfileH264ConstrainedBaseline
1277 | VAProfile::VAProfileH264Main
1278 | VAProfile::VAProfileH264High
1279 ),
1280 Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
1281 })
1282 .any(|profile| {
1283 display
1284 .query_config_entrypoints(profile)
1285 .is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
1286 });
1287
1288 if !supported {
1289 bail!("driver exposes no {codec:?} decode entrypoint");
1290 }
1291
1292 Ok(())
1293}
1294
1295fn va_profile(sps: &Sps) -> anyhow::Result<VAProfile::Type> {
1297 let profile = Profile::try_from(sps.profile_idc).map_err(|e| anyhow!("{e}"))?;
1298
1299 Ok(match profile {
1300 Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
1306 Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
1307 Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
1310 other => bail!("unsupported H.264 profile {other:?}"),
1311 })
1312}
1313
1314fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
1315 context
1316 .create_buffer(buffer)
1317 .map_err(|e| anyhow!("create VA buffer: {e:?}"))
1318}
1319
1320fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
1326 let max_frame_num = sps.max_frame_num();
1327 let first = (prev_frame_num + 1) % max_frame_num;
1328 let missing = (frame_num + max_frame_num - first) % max_frame_num;
1329 let window = u32::from(sps.max_num_ref_frames).max(1);
1331 let skipped = missing.saturating_sub(window);
1332 (first + skipped) % max_frame_num
1333}
1334
1335fn pic_order_count(
1341 prev_ref: &PrevReferencePicInfo,
1342 prev: &mut PrevPicInfo,
1343 pic: &mut PictureData,
1344 sps: &Sps,
1345) -> anyhow::Result<()> {
1346 let overflow = || anyhow!("picture order count overflows");
1347 match pic.pic_order_cnt_type {
1348 0 => {
1350 let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1351 (0, 0)
1352 } else if prev_ref.has_mmco_5 {
1353 if matches!(prev_ref.field, Field::Bottom) {
1354 (0, 0)
1355 } else {
1356 (0, prev_ref.top_field_order_cnt)
1357 }
1358 } else {
1359 (prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
1360 };
1361
1362 let max_pic_order_cnt_lsb: i32 = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
1363 let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
1366 let half = i64::from(max_pic_order_cnt_lsb / 2);
1367
1368 pic.pic_order_cnt_msb = if lsb_delta >= half {
1369 prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
1370 } else if -lsb_delta > half {
1371 prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
1372 } else {
1373 Some(prev_pic_order_cnt_msb)
1374 }
1375 .ok_or_else(overflow)?;
1376
1377 if !matches!(pic.field, Field::Bottom) {
1378 pic.top_field_order_cnt = pic
1379 .pic_order_cnt_msb
1380 .checked_add(pic.pic_order_cnt_lsb)
1381 .ok_or_else(overflow)?;
1382 }
1383
1384 if !matches!(pic.field, Field::Top) {
1385 pic.bottom_field_order_cnt = if matches!(pic.field, Field::Frame) {
1386 pic.top_field_order_cnt.checked_add(pic.delta_pic_order_cnt_bottom)
1387 } else {
1388 pic.pic_order_cnt_msb.checked_add(pic.pic_order_cnt_lsb)
1389 }
1390 .ok_or_else(overflow)?;
1391 }
1392 }
1393
1394 1 => {
1396 if prev.has_mmco_5 {
1397 prev.frame_num_offset = 0;
1398 }
1399
1400 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1401
1402 let mut abs_frame_num = if sps.num_ref_frames_in_pic_order_cnt_cycle != 0 {
1403 pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
1404 } else {
1405 0
1406 };
1407
1408 if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
1409 abs_frame_num -= 1;
1410 }
1411
1412 let mut expected_pic_order_cnt: i128 = 0;
1415
1416 if abs_frame_num > 0 {
1417 if sps.num_ref_frames_in_pic_order_cnt_cycle == 0 {
1418 bail!("invalid num_ref_frames_in_pic_order_cnt_cycle");
1419 }
1420
1421 let cycle_len = u32::from(sps.num_ref_frames_in_pic_order_cnt_cycle);
1422 let cycles = (abs_frame_num - 1) / cycle_len;
1423 let position_in_cycle = (abs_frame_num - 1) % cycle_len;
1426 expected_pic_order_cnt = i128::from(cycles) * i128::from(sps.expected_delta_per_pic_order_cnt_cycle);
1427
1428 for i in 0..=position_in_cycle {
1429 expected_pic_order_cnt += i128::from(sps.offset_for_ref_frame[i as usize]);
1430 }
1431 }
1432
1433 if pic.nal_ref_idc == 0 {
1434 expected_pic_order_cnt += i128::from(sps.offset_for_non_ref_pic);
1435 }
1436
1437 let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
1438 let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
1439 let to_bottom = i128::from(sps.offset_for_top_to_bottom_field);
1440 match pic.field {
1441 Field::Frame => {
1442 pic.top_field_order_cnt = count(top)?;
1443 pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
1444 }
1445 Field::Top => {
1446 pic.top_field_order_cnt = count(top)?;
1447 }
1448 Field::Bottom => {
1449 pic.bottom_field_order_cnt = count(top + to_bottom)?;
1450 }
1451 }
1452 }
1453
1454 2 => {
1456 if prev.has_mmco_5 {
1457 prev.frame_num_offset = 0;
1458 }
1459
1460 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1461
1462 let pic_order_cnt = if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1463 0
1464 } else {
1465 let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
1466 i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
1467 };
1468
1469 if matches!(pic.field, Field::Frame | Field::Top) {
1470 pic.top_field_order_cnt = pic_order_cnt;
1471 }
1472 if matches!(pic.field, Field::Frame | Field::Bottom) {
1473 pic.bottom_field_order_cnt = pic_order_cnt;
1474 }
1475 }
1476
1477 other => bail!("invalid pic_order_cnt_type {other}"),
1478 }
1479
1480 pic.pic_order_cnt = match pic.field {
1481 Field::Frame => std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt),
1482 Field::Top => pic.top_field_order_cnt,
1483 Field::Bottom => pic.bottom_field_order_cnt,
1484 };
1485
1486 Ok(())
1487}
1488
1489fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
1492 Ok(if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1493 0
1494 } else if prev.frame_num > pic.frame_num {
1495 prev.frame_num_offset
1496 .checked_add(sps.max_frame_num())
1497 .context("FrameNumOffset overflows")?
1498 } else {
1499 prev.frame_num_offset
1500 })
1501}
1502
1503#[derive(Debug)]
1505struct PrevReferencePicInfo {
1506 frame_num: u32,
1507 has_mmco_5: bool,
1508 top_field_order_cnt: i32,
1509 pic_order_cnt_msb: i32,
1510 pic_order_cnt_lsb: i32,
1511 field: Field,
1512}
1513
1514impl Default for PrevReferencePicInfo {
1515 fn default() -> Self {
1516 Self {
1517 frame_num: 0,
1518 has_mmco_5: false,
1519 top_field_order_cnt: 0,
1520 pic_order_cnt_msb: 0,
1521 pic_order_cnt_lsb: 0,
1522 field: Field::Frame,
1523 }
1524 }
1525}
1526
1527impl PrevReferencePicInfo {
1528 fn fill(&mut self, pic: &PictureData) {
1529 self.has_mmco_5 = pic.has_mmco_5;
1530 self.top_field_order_cnt = pic.top_field_order_cnt;
1531 self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
1532 self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
1533 self.field = pic.field;
1534 self.frame_num = pic.frame_num;
1535 }
1536}
1537
1538#[derive(Debug, Default)]
1540struct PrevPicInfo {
1541 frame_num: u32,
1542 frame_num_offset: u32,
1543 has_mmco_5: bool,
1544}
1545
1546impl PrevPicInfo {
1547 fn fill(&mut self, pic: &PictureData) {
1548 self.frame_num = pic.frame_num;
1549 self.has_mmco_5 = pic.has_mmco_5;
1550 self.frame_num_offset = pic.frame_num_offset;
1551 }
1552}
1553
1554fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
1557 match handle {
1558 Some(handle) => handle.surface.id(),
1559 None => VA_INVALID_ID,
1560 }
1561}
1562
1563fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
1566 let mut flags = 0;
1567 let frame_idx = match pic.reference() {
1568 Reference::LongTerm => {
1569 flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
1570 pic.long_term_frame_idx
1571 }
1572 Reference::ShortTerm => {
1573 flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1574 pic.frame_num
1575 }
1576 Reference::None => pic.frame_num,
1577 };
1578
1579 PictureH264::new(
1580 surface_id,
1581 frame_idx,
1582 flags,
1583 pic.top_field_order_cnt,
1584 pic.bottom_field_order_cnt,
1585 )
1586}
1587
1588fn build_invalid_va_h264_pic() -> PictureH264 {
1590 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1591}
1592
1593fn build_iq_matrix(pps: &Pps) -> BufferType {
1596 const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
1597 #[rustfmt::skip]
1598 const ZIGZAG_8X8: [usize; 64] = [
1599 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
1600 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
1601 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
1602 ];
1603
1604 let mut scaling_list4x4 = [[0u8; 16]; 6];
1605 for (list, src) in scaling_list4x4.iter_mut().zip(pps.scaling_lists_4x4.iter()) {
1606 for (i, &value) in src.iter().enumerate() {
1607 list[ZIGZAG_4X4[i]] = value;
1608 }
1609 }
1610
1611 let mut scaling_list8x8 = [[0u8; 64]; 2];
1612 for (list, src) in scaling_list8x8.iter_mut().zip(pps.scaling_lists_8x8.iter()) {
1613 for (i, &value) in src.iter().enumerate() {
1614 list[ZIGZAG_8X8[i]] = value;
1615 }
1616 }
1617
1618 BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
1619 scaling_list4x4,
1620 scaling_list8x8,
1621 )))
1622}
1623
1624fn build_pic_param(
1626 hdr: &SliceHeader,
1627 pic: &PictureData,
1628 surface_id: bindings::VASurfaceID,
1629 dpb: &Dpb<Handle>,
1630 sps: &Sps,
1631 pps: &Pps,
1632) -> BufferType {
1633 let curr_pic = fill_va_h264_pic(pic, surface_id);
1634
1635 let short_term = dpb
1636 .short_term_refs_iter()
1637 .filter(|entry| !entry.pic.borrow().nonexisting);
1638 let mut refs: Vec<PictureH264> = short_term
1639 .chain(dpb.long_term_refs_iter())
1640 .take(16)
1641 .map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference)))
1642 .collect();
1643 refs.resize_with(16, build_invalid_va_h264_pic);
1644 let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
1645
1646 let seq_fields = H264SeqFields::new(
1647 sps.chroma_format_idc as u32,
1648 sps.separate_colour_plane_flag as u32,
1649 sps.gaps_in_frame_num_value_allowed_flag as u32,
1650 sps.frame_mbs_only_flag as u32,
1651 sps.mb_adaptive_frame_field_flag as u32,
1652 sps.direct_8x8_inference_flag as u32,
1653 (sps.level_idc >= Level::L3_1 as u8) as u32,
1655 sps.log2_max_frame_num_minus4 as u32,
1656 sps.pic_order_cnt_type as u32,
1657 sps.log2_max_pic_order_cnt_lsb_minus4 as u32,
1658 sps.delta_pic_order_always_zero_flag as u32,
1659 );
1660
1661 let pic_fields = H264PicFields::new(
1662 pps.entropy_coding_mode_flag as u32,
1663 pps.weighted_pred_flag as u32,
1664 pps.weighted_bipred_idc as u32,
1665 pps.transform_8x8_mode_flag as u32,
1666 hdr.field_pic_flag as u32,
1667 pps.constrained_intra_pred_flag as u32,
1668 pps.bottom_field_pic_order_in_frame_present_flag as u32,
1669 pps.deblocking_filter_control_present_flag as u32,
1670 pps.redundant_pic_cnt_present_flag as u32,
1671 (pic.nal_ref_idc != 0) as u32,
1672 );
1673
1674 let picture_height_in_mbs_minus1 = sps.pic_height_in_map_units_minus1;
1676
1677 BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
1678 curr_pic,
1679 refs,
1680 sps.pic_width_in_mbs_minus1,
1681 picture_height_in_mbs_minus1,
1682 sps.bit_depth_luma_minus8,
1683 sps.bit_depth_chroma_minus8,
1684 sps.max_num_ref_frames,
1685 &seq_fields,
1686 0,
1688 0,
1689 0,
1690 pps.pic_init_qp_minus26,
1691 pps.pic_init_qs_minus26,
1692 pps.chroma_qp_index_offset,
1693 pps.second_chroma_qp_index_offset,
1694 &pic_fields,
1695 hdr.frame_num,
1696 )))
1697}
1698
1699fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
1701 let mut pics: Vec<PictureH264> = list
1702 .iter()
1703 .take(32)
1704 .map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference)))
1705 .collect();
1706 pics.resize_with(32, build_invalid_va_h264_pic);
1707
1708 pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
1709}
1710
1711fn build_slice_param(
1713 hdr: &SliceHeader,
1714 slice_size: usize,
1715 list0: &[&DpbEntry<Handle>],
1716 list1: &[&DpbEntry<Handle>],
1717 sps: &Sps,
1718 pps: &Pps,
1719) -> BufferType {
1720 let pwt = &hdr.pred_weight_table;
1721
1722 let mut luma_weight_l0 = [0i16; 32];
1723 let mut luma_offset_l0 = [0i16; 32];
1724 let mut chroma_weight_l0 = [[0i16; 2]; 32];
1725 let mut chroma_offset_l0 = [[0i16; 2]; 32];
1726
1727 let mut luma_weight_l1 = [0i16; 32];
1728 let mut luma_offset_l1 = [0i16; 32];
1729 let mut chroma_weight_l1 = [[0i16; 2]; 32];
1730 let mut chroma_offset_l1 = [[0i16; 2]; 32];
1731
1732 let fill_l0 = (pps.weighted_pred_flag && (hdr.slice_type.is_p() || hdr.slice_type.is_sp()))
1735 || (pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b());
1736 let fill_l1 = pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b();
1737 let chroma = sps.chroma_array_type() != 0;
1738
1739 if fill_l0 {
1740 for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) {
1741 luma_weight_l0[i] = pwt.luma_weight_l0[i];
1742 luma_offset_l0[i] = i16::from(pwt.luma_offset_l0[i]);
1743 if chroma {
1744 for j in 0..2 {
1745 chroma_weight_l0[i][j] = pwt.chroma_weight_l0[i][j];
1746 chroma_offset_l0[i][j] = i16::from(pwt.chroma_offset_l0[i][j]);
1747 }
1748 }
1749 }
1750 }
1751
1752 if fill_l1 {
1753 for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) {
1754 luma_weight_l1[i] = pwt.luma_weight_l1[i];
1755 luma_offset_l1[i] = i16::from(pwt.luma_offset_l1[i]);
1756 if chroma {
1757 for j in 0..2 {
1758 chroma_weight_l1[i][j] = pwt.chroma_weight_l1[i][j];
1759 chroma_offset_l1[i][j] = i16::from(pwt.chroma_offset_l1[i][j]);
1760 }
1761 }
1762 }
1763 }
1764
1765 BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
1766 slice_size as u32,
1767 0,
1768 VA_SLICE_DATA_FLAG_ALL,
1769 hdr.header_bit_size as u16,
1770 hdr.first_mb_in_slice as u16,
1771 hdr.slice_type as u8,
1772 hdr.direct_spatial_mv_pred_flag as u8,
1773 hdr.num_ref_idx_l0_active_minus1,
1774 hdr.num_ref_idx_l1_active_minus1,
1775 hdr.cabac_init_idc,
1776 hdr.slice_qp_delta,
1777 hdr.disable_deblocking_filter_idc,
1778 hdr.slice_alpha_c0_offset_div2,
1779 hdr.slice_beta_offset_div2,
1780 fill_ref_pic_list(list0),
1781 fill_ref_pic_list(list1),
1782 pwt.luma_log2_weight_denom,
1783 pwt.chroma_log2_weight_denom,
1784 fill_l0 as u8,
1785 luma_weight_l0,
1786 luma_offset_l0,
1787 (fill_l0 && chroma) as u8,
1788 chroma_weight_l0,
1789 chroma_offset_l0,
1790 fill_l1 as u8,
1791 luma_weight_l1,
1792 luma_offset_l1,
1793 (fill_l1 && chroma) as u8,
1794 chroma_weight_l1,
1795 chroma_offset_l1,
1796 )))
1797}
1798
1799#[cfg(test)]
1800mod tests {
1801 use std::os::fd::OwnedFd;
1802 use std::process::Command;
1803
1804 use super::*;
1805
1806 fn progressive_sps() -> Sps {
1807 Sps {
1808 frame_mbs_only_flag: true,
1809 chroma_format_idc: 1,
1810 pic_width_in_mbs_minus1: 19,
1811 pic_height_in_map_units_minus1: 14,
1812 level_idc: Level::L3 as u8,
1814 ..Default::default()
1815 }
1816 }
1817
1818 #[test]
1821 fn a_frame_num_gap_invents_only_the_reference_window() {
1822 let sps = Sps {
1824 max_num_ref_frames: 2,
1825 ..progressive_sps()
1826 };
1827 assert_eq!(first_invented(3, 4, &sps), 4);
1829 assert_eq!(first_invented(3, 5, &sps), 4);
1831 assert_eq!(first_invented(3, 10, &sps), 8);
1833 assert_eq!(first_invented(14, 3, &sps), 1);
1835 assert_eq!(first_invented(4, 3, &sps), 1);
1837
1838 let none = Sps {
1841 max_num_ref_frames: 0,
1842 ..progressive_sps()
1843 };
1844 assert_eq!(first_invented(0, 3, &none), 2);
1845 }
1846
1847 fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
1850 let sps = Sps {
1851 log2_max_pic_order_cnt_lsb_minus4: 4,
1852 ..progressive_sps()
1853 };
1854 let mut pic = PictureData::default();
1855 pic.pic_order_cnt_lsb = lsb;
1856 pic.nal_ref_idc = 1;
1857 pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
1858 Ok(pic.pic_order_cnt)
1859 }
1860
1861 fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
1862 PrevReferencePicInfo {
1863 pic_order_cnt_msb: msb,
1864 pic_order_cnt_lsb: lsb,
1865 ..Default::default()
1866 }
1867 }
1868
1869 #[test]
1873 fn the_picture_order_count_wraps_and_never_overflows() {
1874 assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
1875 assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
1876 assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
1877 assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
1878 assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
1879
1880 let after_mmco5 = PrevReferencePicInfo {
1883 has_mmco_5: true,
1884 top_field_order_cnt: i32::MIN,
1885 ..Default::default()
1886 };
1887 assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
1888 }
1889
1890 #[test]
1893 fn the_frame_num_offset_never_overflows() {
1894 let sps = Sps {
1895 pic_order_cnt_type: 2,
1896 ..progressive_sps()
1897 };
1898 let order_count = |frame_num_offset| {
1899 let mut prev = PrevPicInfo {
1900 frame_num: 5,
1901 frame_num_offset,
1902 has_mmco_5: false,
1903 };
1904 let mut pic = PictureData::default();
1905 pic.pic_order_cnt_type = 2;
1906 pic.frame_num = 1;
1907 pic.nal_ref_idc = 1;
1908 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1909 };
1910 assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
1912 assert!(order_count(u32::MAX - 3).is_err());
1913 assert!(order_count(i32::MAX as u32 / 2).is_err());
1915 }
1916
1917 #[test]
1920 fn the_type2_order_count_is_checked_whole() {
1921 let sps = Sps {
1922 pic_order_cnt_type: 2,
1923 ..progressive_sps()
1924 };
1925 let order_count = |nal_ref_idc| {
1926 let mut prev = PrevPicInfo {
1928 frame_num: 5,
1929 frame_num_offset: (1 << 30) - 17,
1930 has_mmco_5: false,
1931 };
1932 let mut pic = PictureData::default();
1933 pic.pic_order_cnt_type = 2;
1934 pic.frame_num = 1;
1935 pic.nal_ref_idc = nal_ref_idc;
1936 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1937 };
1938 assert_eq!(order_count(0).unwrap(), i32::MAX);
1939 assert!(order_count(1).is_err());
1940 }
1941
1942 #[test]
1945 fn the_type1_bottom_field_is_checked_whole() {
1946 let sps = Sps {
1947 pic_order_cnt_type: 1,
1948 offset_for_top_to_bottom_field: i32::MAX,
1949 ..progressive_sps()
1950 };
1951 let bottom = |field, delta0, delta1| {
1952 let mut pic = PictureData::default();
1953 pic.pic_order_cnt_type = 1;
1954 pic.nal_ref_idc = 1;
1955 pic.field = field;
1956 pic.delta_pic_order_cnt0 = delta0;
1957 pic.delta_pic_order_cnt1 = delta1;
1958 pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
1959 .map(|()| pic.bottom_field_order_cnt)
1960 };
1961 assert_eq!(bottom(Field::Frame, 2, -i32::MAX).unwrap(), 2);
1962 assert_eq!(bottom(Field::Bottom, 2 - i32::MAX, 0).unwrap(), 2);
1963 assert!(bottom(Field::Frame, 2, 0).is_err());
1964 assert!(bottom(Field::Bottom, 2, 0).is_err());
1965 }
1966
1967 #[test]
1968 fn rejects_nonzero_crop_origins() {
1969 for (left, top) in [(1, 0), (0, 1)] {
1970 let sps = Sps {
1971 frame_cropping_flag: true,
1972 frame_crop_left_offset: left,
1973 frame_crop_top_offset: top,
1974 ..progressive_sps()
1975 };
1976 assert!(SequenceInfo::new(&sps)
1977 .unwrap_err()
1978 .to_string()
1979 .contains("left and top"));
1980 }
1981 }
1982
1983 #[test]
1984 fn crop_only_updates_change_sequence_identity() {
1985 let original = SequenceInfo::new(&progressive_sps()).unwrap();
1986 for (right, bottom, expected) in [(1, 0, (318, 240)), (0, 1, (320, 238))] {
1987 let cropped = SequenceInfo::new(&Sps {
1988 frame_cropping_flag: true,
1989 frame_crop_right_offset: right,
1990 frame_crop_bottom_offset: bottom,
1991 ..progressive_sps()
1992 })
1993 .unwrap();
1994 assert_eq!(original.coded, cropped.coded);
1995 assert_eq!(cropped.visible, expected);
1996 assert_ne!(original, cropped);
1997 }
1998 }
1999
2000 #[test]
2001 fn rejects_invalid_crop_dimensions() {
2002 for crop in [160, 161, u32::MAX] {
2003 assert!(SequenceInfo::new(&Sps {
2004 frame_cropping_flag: true,
2005 frame_crop_right_offset: crop,
2006 ..progressive_sps()
2007 })
2008 .is_err());
2009 }
2010 }
2011
2012 #[test]
2013 fn maximum_progressive_height_does_not_overflow_va_parameters() {
2014 let sps = Arc::new(Sps {
2015 pic_height_in_map_units_minus1: u16::MAX,
2016 ..progressive_sps()
2017 });
2018 let params = build_pic_param(
2019 &SliceHeader::default(),
2020 &PictureData::new_non_existing(0, 0),
2021 VA_INVALID_ID,
2022 &Dpb::default(),
2023 &sps,
2024 &kodecs_h264::PpsBuilder::new(Arc::clone(&sps)).build(),
2025 );
2026 let BufferType::PictureParameter(PictureParameter::H264(params)) = params else {
2027 panic!("expected H.264 picture parameters");
2028 };
2029 assert_eq!(params.inner().picture_height_in_mbs_minus1, u16::MAX);
2030 assert!(SequenceInfo::new(&Sps {
2031 frame_mbs_only_flag: false,
2032 ..progressive_sps()
2033 })
2034 .is_err());
2035 }
2036
2037 fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
2040 crate::encode::Config {
2041 codec: crate::Codec::H264,
2042 width,
2043 height,
2044 framerate: 30,
2045 bitrate: 2_000_000,
2046 gop: std::num::NonZeroU32::new(30).unwrap(),
2047 color: crate::Color::infer(height),
2048 device: None,
2049 }
2050 }
2051
2052 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
2055 let (w, h) = (width as usize, height as usize);
2056 let mut data = vec![128u8; w * h * 3 / 2];
2057 let x0 = (step * 16) as usize % (w / 2);
2058 for y in h / 4..h / 2 {
2059 for x in x0..x0 + w / 4 {
2060 data[y * w + x] = 235;
2061 }
2062 }
2063 data
2064 }
2065
2066 #[test]
2075 #[ignore = "requires a VA-API render node"]
2076 fn exported_pictures_do_not_share_a_surface() {
2077 let (width, height) = (320u32, 240u32);
2078 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2079 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2080
2081 let mut exported = Vec::new();
2082 for step in 0..8 {
2083 let unit = encoder
2084 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2085 .expect("encode a picture");
2086 exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
2087 }
2088 exported.extend(decoder.flush_exported().expect("flush the decoder"));
2089 assert!(!exported.is_empty(), "the decoder produced no pictures");
2090
2091 let first = &exported[0];
2092 eprintln!(
2093 "exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
2094 exported.len(),
2095 first.width,
2096 first.height,
2097 first.descriptor.fourcc,
2098 first.descriptor.objects[0].drm_format_modifier
2099 );
2100
2101 let mut seen = Vec::new();
2102 for (index, frame) in exported.iter().enumerate() {
2103 assert_eq!((frame.width, frame.height), (width, height));
2104 assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
2105 assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
2106 assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
2107
2108 let inode = inode(&frame.descriptor.objects[0].fd);
2112 assert!(
2113 !seen.contains(&inode),
2114 "picture {index} was decoded into an allocation an earlier one still holds"
2115 );
2116 seen.push(inode);
2117 }
2118 }
2119
2120 #[test]
2123 #[ignore = "requires a VA-API render node"]
2124 fn the_render_node_is_found_or_named() {
2125 if let Err(err) = Decoder::new(Config::new()) {
2126 panic!("no VA-API H.264 decoder: {err:#}");
2127 }
2128 let named = Config {
2129 device: Some(PathBuf::from("/dev/null")),
2130 ..Config::new()
2131 };
2132 assert!(
2133 Decoder::new(named).is_err(),
2134 "a named node that is not a render node was swapped for one that is"
2135 );
2136 }
2137
2138 #[test]
2145 #[ignore = "requires a VA-API render node and FFmpeg"]
2146 fn flush_returns_the_pictures_the_dpb_still_holds() {
2147 const PICTURES: usize = 10;
2148
2149 let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
2150 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2151
2152 let mut streamed = Vec::new();
2153 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2154 streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
2155 }
2156 assert!(
2157 streamed.len() < PICTURES,
2158 "the DPB held nothing back, so this test proves nothing"
2159 );
2160
2161 let flushed = decoder.flush().expect("flush the decoder");
2162 let mut timestamps: Vec<u64> = streamed
2163 .iter()
2164 .chain(&flushed)
2165 .map(|picture| picture.timestamp)
2166 .collect();
2167 timestamps.sort_unstable();
2168 assert_eq!(
2169 timestamps,
2170 (0..PICTURES as u64).collect::<Vec<_>>(),
2171 "the stream lost pictures at its end"
2172 );
2173
2174 assert!(decoder.flush().expect("flush an empty decoder").is_empty());
2177 }
2178
2179 #[test]
2188 #[ignore = "requires a VA-API render node and FFmpeg"]
2189 fn h264_without_reordering_comes_out_as_it_decodes() {
2190 const PICTURES: usize = 10;
2191 let (width, height) = (320u32, 240u32);
2192
2193 let mut streams = Vec::new();
2194 match crate::encode::Encoder::new(encoder_config(width, height)) {
2195 Ok(mut encoder) => {
2196 let units = (0..PICTURES)
2197 .map(|step| {
2198 encoder
2199 .encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
2200 .expect("encode a picture")
2201 })
2202 .collect::<Vec<_>>();
2203 streams.push(("VA-API", units));
2204 }
2205 Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
2206 }
2207 match software_encode(Codec::H264, (width, height), PICTURES, false) {
2208 Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
2209 None => panic!("FFmpeg with libx264 is required"),
2210 }
2211
2212 for (encoder, units) in streams {
2213 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2214 for (index, unit) in units.iter().enumerate() {
2215 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2216 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2217 assert_eq!(
2218 timestamps,
2219 [index as u64],
2220 "{encoder}: access unit {index} was held back"
2221 );
2222 }
2223 assert!(decoder.flush().expect("flush the decoder").is_empty());
2224 }
2225 }
2226
2227 #[test]
2230 fn the_reorder_limit_follows_the_sps() {
2231 let sps = || Sps {
2232 level_idc: Level::L3 as u8,
2233 max_num_ref_frames: 1,
2234 ..progressive_sps()
2235 };
2236 assert_eq!(sps().max_dpb_frames(), Some(16));
2238 assert_eq!(
2239 reorder_limit(&sps(), 16),
2240 16,
2241 "without a VUI, the inference is the DPB size"
2242 );
2243
2244 let mut declared = Sps {
2245 vui_parameters_present_flag: true,
2246 ..sps()
2247 };
2248 declared.vui_parameters.bitstream_restriction_flag = true;
2249 declared.vui_parameters.max_num_reorder_frames = 0;
2250 declared.vui_parameters.max_dec_frame_buffering = 1;
2251 assert_eq!(
2252 reorder_limit(&declared, declared.max_dpb_frames().unwrap()),
2253 0,
2254 "the VUI's limit applies"
2255 );
2256
2257 declared.vui_parameters.max_num_reorder_frames = 5;
2258 declared.vui_parameters.max_dec_frame_buffering = 2;
2259 assert_eq!(
2260 reorder_limit(&declared, declared.max_dpb_frames().unwrap()),
2261 2,
2262 "the DPB size bounds the VUI's limit"
2263 );
2264
2265 let derived = Sps {
2266 pic_order_cnt_type: 2,
2267 ..sps()
2268 };
2269 assert_eq!(
2270 reorder_limit(&derived, 16),
2271 0,
2272 "an order count from frame_num reorders nothing"
2273 );
2274 }
2275
2276 #[test]
2284 #[ignore = "requires a VA-API render node"]
2285 fn a_dropped_export_is_decoded_into_again() {
2286 const PICTURES: u32 = 60;
2287 let (width, height) = (320u32, 240u32);
2288 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2289 let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2290 let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2291
2292 let mut compared = 0;
2293 for step in 0..PICTURES {
2294 let unit = encoder
2295 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2296 .expect("encode a picture");
2297 let exported = exporting
2298 .decode_exported(&unit, step as u64)
2299 .expect("decode to a descriptor");
2300 let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
2301 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2302 for (gpu, cpu) in exported.iter().zip(&downloaded) {
2303 let read_back = gpu.download().expect("read the exported surface back");
2304 assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
2305 compared += 1;
2306 }
2307 }
2308 assert!(compared > 0, "the decoder produced no pictures");
2309
2310 let pool = &exporting.sequence().expect("a sequence").pool;
2311 let allocated = pool.allocated.get();
2312 eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
2313 assert!(
2314 allocated <= pool.free.capacity,
2315 "{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
2316 pool.free.capacity
2317 );
2318 }
2319
2320 #[test]
2323 #[ignore = "requires a VA-API render node"]
2324 fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
2325 const HELD: u32 = 40;
2326 let (width, height) = (320u32, 240u32);
2327 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2328 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2329
2330 let mut step = 0;
2331 let mut decode = |decoder: &mut Decoder| {
2332 let unit = encoder
2333 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2334 .expect("encode a picture");
2335 step += 1;
2336 decoder.decode_exported(&unit, step as u64).expect("decode a picture")
2337 };
2338
2339 let mut held = Vec::new();
2340 for _ in 0..HELD {
2341 held.extend(decode(&mut decoder));
2342 }
2343 let pool = &decoder.sequence().expect("a sequence").pool;
2344 let allocated = pool.allocated.get();
2345 assert!(
2346 allocated >= held.len(),
2347 "{} pictures held on {allocated} surfaces",
2348 held.len()
2349 );
2350
2351 drop(held);
2352 let free = pool.free.surfaces.lock().unwrap().len();
2353 assert!(
2354 free <= pool.free.capacity,
2355 "{free} surfaces left free, more than the capacity of {}",
2356 pool.free.capacity
2357 );
2358
2359 for _ in 0..10 {
2360 drop(decode(&mut decoder));
2361 }
2362 let pool = &decoder.sequence().expect("a sequence").pool;
2363 assert_eq!(
2364 pool.allocated.get(),
2365 allocated,
2366 "pictures after the release did not reuse the free surfaces"
2367 );
2368 }
2369
2370 #[test]
2375 fn an_exported_frame_is_send_and_sync() {
2376 const fn assert_send_sync<T: Send + Sync>() {}
2377 assert_send_sync::<ExportedFrame>();
2378 }
2379
2380 #[test]
2389 #[ignore = "requires a VA-API render node"]
2390 fn an_exported_picture_downloads_to_the_same_pixels() {
2391 let (width, height) = (320u32, 240u32);
2392 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2393 let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2394 let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2395
2396 let mut exported = Vec::new();
2397 let mut downloaded = Vec::new();
2398 for step in 0..8 {
2399 let unit = encoder
2400 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2401 .expect("encode a picture");
2402 exported.extend(
2403 exporting
2404 .decode_exported(&unit, step as u64)
2405 .expect("decode to a descriptor"),
2406 );
2407 downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
2408 }
2409 exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
2410 downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
2411
2412 assert!(!exported.is_empty(), "the decoder produced no pictures");
2413 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2414
2415 for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
2416 let read_back = gpu.download().expect("read the exported surface back");
2417 assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
2418 assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
2419 assert!(
2420 read_back.data == cpu.data,
2421 "picture {index} read back differently than it downloaded"
2422 );
2423 }
2424 }
2425
2426 #[test]
2436 #[ignore = "requires a VA-API render node and FFmpeg"]
2437 fn decoded_pictures_match_a_software_decoder() {
2438 const PICTURES: usize = 30;
2439
2440 for codec in [Codec::H264, Codec::H265] {
2441 for (width, height) in [(320u32, 240u32), (852, 478)] {
2442 let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
2443 panic!("no ffmpeg that encodes {codec:?}");
2444 };
2445 let reference = software_decode(codec, &stream);
2446
2447 let picture_len = (width * height * 3 / 2) as usize;
2448 assert_eq!(
2449 reference.len(),
2450 PICTURES * picture_len,
2451 "ffmpeg decoded a different count"
2452 );
2453
2454 let Ok(mut decoder) = Decoder::new(Config { codec, ..Config::new() }) else {
2455 panic!("no VA-API {codec:?} decoder");
2456 };
2457
2458 let units = split_access_units(codec, &stream);
2459 let mut decoded = Vec::new();
2460 for (index, unit) in units.iter().enumerate() {
2461 if index % 2 == 0 {
2462 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2463 } else {
2464 for exported in decoder
2465 .decode_exported(unit, index as u64)
2466 .expect("decode an access unit")
2467 {
2468 decoded.push(exported.download().expect("download an exported picture"));
2469 }
2470 }
2471 }
2472 decoded.extend(decoder.flush().expect("flush the decoder"));
2473 assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
2474
2475 let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2476 assert!(
2477 timestamps.windows(2).any(|pair| pair[0] > pair[1]),
2478 "the {codec:?} stream came out in decode order, so nothing here tests reordering"
2479 );
2480 timestamps.sort_unstable();
2481 assert_eq!(
2482 timestamps,
2483 (0..PICTURES as u64).collect::<Vec<_>>(),
2484 "a {codec:?} picture's timestamp did not survive reordering"
2485 );
2486
2487 for (index, picture) in decoded.iter().enumerate() {
2488 assert_eq!((picture.width, picture.height), (width, height));
2489 assert!(
2490 picture.data == reference[index * picture_len..][..picture_len],
2491 "{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
2492 );
2493 }
2494 }
2495 }
2496 }
2497
2498 #[test]
2502 #[ignore = "requires a VA-API render node and FFmpeg"]
2503 fn h265_without_reordering_comes_out_as_it_decodes() {
2504 const PICTURES: usize = 10;
2505
2506 let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
2507 let mut decoder = Decoder::new(Config {
2508 codec: Codec::H265,
2509 ..Config::new()
2510 })
2511 .expect("no VA-API H.265 decoder");
2512
2513 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2514 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2515 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2516 assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
2517 }
2518 assert!(decoder.flush().expect("flush the decoder").is_empty());
2519 }
2520
2521 #[test]
2525 #[ignore = "requires a VA-API render node and FFmpeg"]
2526 fn a_4k_h265_wavefront_stream_decodes() {
2527 const PICTURES: usize = 2;
2528 let size = (3840, 2160);
2529
2530 let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
2531 let mut decoder = Decoder::new(Config {
2532 codec: Codec::H265,
2533 ..Config::new()
2534 })
2535 .expect("no VA-API H.265 decoder");
2536
2537 let mut decoded = Vec::new();
2538 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2539 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2540 }
2541 decoded.extend(decoder.flush().expect("flush the decoder"));
2542 assert_eq!(decoded.len(), PICTURES);
2543 assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
2544 }
2545
2546 #[test]
2549 #[ignore = "requires a VA-API render node and FFmpeg"]
2550 fn a_new_h265_sequence_decodes_at_its_own_size() {
2551 const PER_SEQUENCE: usize = 6;
2552 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2553
2554 let mut stream = Vec::new();
2555 for &size in &sizes {
2556 let sequence =
2557 software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
2558 stream.extend(sequence);
2559 }
2560 let mut decoder = Decoder::new(Config {
2561 codec: Codec::H265,
2562 ..Config::new()
2563 })
2564 .expect("no VA-API H.265 decoder");
2565
2566 let mut decoded = Vec::new();
2567 let units = split_access_units(Codec::H265, &stream);
2568 for (index, unit) in units.iter().enumerate() {
2569 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2570 }
2571 decoded.extend(decoder.flush().expect("flush the decoder"));
2572
2573 let expected: Vec<(u32, u32)> = sizes
2574 .iter()
2575 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
2576 .collect();
2577 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2578 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2579
2580 for picture in &decoded {
2581 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2582 assert_eq!(
2583 picture.data.len(),
2584 expected_len,
2585 "a picture was read back at the wrong size"
2586 );
2587 }
2588 }
2589
2590 #[test]
2597 #[ignore = "requires a VA-API render node"]
2598 fn a_new_sequence_decodes_at_its_own_size() {
2599 const PER_SEQUENCE: u32 = 6;
2600 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2601
2602 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2603
2604 let mut decoded = Vec::new();
2605 let mut timestamp = 0u64;
2606 for &(width, height) in &sizes {
2607 let mut encoder =
2608 crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2609 for step in 0..PER_SEQUENCE {
2610 let unit = encoder
2611 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2612 .expect("encode a picture");
2613 decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
2614 timestamp += 1;
2615 }
2616 }
2617 decoded.extend(decoder.flush().expect("flush the decoder"));
2618
2619 let expected: Vec<(u32, u32)> = sizes
2620 .iter()
2621 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
2622 .collect();
2623 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2624 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2625
2626 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2627 assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());
2628
2629 for picture in &decoded {
2630 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2631 assert_eq!(
2632 picture.data.len(),
2633 expected_len,
2634 "a picture was read back at the wrong size"
2635 );
2636 }
2637 }
2638
2639 fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2642 let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
2643 if !output.status.success() {
2644 eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
2645 return None;
2646 }
2647 Some(output.stdout)
2648 }
2649
2650 fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
2654 let source = format!("testsrc2=size={width}x{height}:rate=30");
2655 let pictures = pictures.to_string();
2656 let mut args = vec![
2657 "-f",
2658 "lavfi",
2659 "-i",
2660 &source,
2661 "-frames:v",
2662 &pictures,
2663 "-pix_fmt",
2664 "yuv420p",
2665 ];
2666
2667 let x265;
2668 match codec {
2669 Codec::H264 => args.extend([
2670 "-c:v",
2671 "libx264",
2672 "-profile:v",
2673 "main",
2674 "-bf",
2675 if reorder { "2" } else { "0" },
2676 "-refs",
2677 if reorder { "3" } else { "1" },
2678 "-g",
2679 "15",
2680 "-f",
2681 "h264",
2682 ]),
2683 Codec::H265 => {
2684 x265 = if reorder {
2687 "bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
2688 } else {
2689 "bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
2690 };
2691 args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
2692 }
2693 }
2694 args.push("-");
2695 ffmpeg(&args)
2696 }
2697
2698 fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
2700 static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2703 let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2704 let extension = match codec {
2705 Codec::H264 => "264",
2706 Codec::H265 => "265",
2707 };
2708 let path = std::env::temp_dir().join(format!(
2709 "kodecs-vaapi-decode-{}-{count}.{extension}",
2710 std::process::id()
2711 ));
2712 std::fs::write(&path, stream).expect("write the elementary stream");
2713 let decoded = ffmpeg(&[
2714 "-i",
2715 path.to_str().expect("a UTF-8 temporary path"),
2716 "-pix_fmt",
2717 "nv12",
2718 "-f",
2719 "rawvideo",
2720 "-",
2721 ]);
2722 let _ = std::fs::remove_file(&path);
2723 decoded.expect("ffmpeg decodes what it just encoded")
2724 }
2725
2726 fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
2731 let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
2732 .filter(|&i| stream[i..i + 3] == [0, 0, 1])
2733 .collect();
2734
2735 let mut units = Vec::new();
2736 let mut current: Vec<u8> = Vec::new();
2737 let mut current_has_picture = false;
2738
2739 for (index, &start) in starts.iter().enumerate() {
2740 let end = starts.get(index + 1).copied().unwrap_or(stream.len());
2741 let nal = &stream[start + 3..end];
2742 let (is_slice, starts_picture, starts_unit) = match codec {
2746 Codec::H264 => {
2747 let nal_type = nal[0] & 0x1f;
2748 let is_slice = (1..=5).contains(&nal_type);
2749 (is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
2750 }
2751 Codec::H265 => {
2752 let nal_type = (nal[0] >> 1) & 0x3f;
2753 let is_slice = nal_type <= 31;
2754 (
2755 is_slice,
2756 is_slice && nal[2] & 0x80 != 0,
2757 matches!(nal_type, 32..=35 | 39),
2758 )
2759 }
2760 };
2761
2762 if current_has_picture && (starts_picture || starts_unit) {
2763 units.push(std::mem::take(&mut current));
2764 current_has_picture = false;
2765 }
2766
2767 current.extend_from_slice(&stream[start..end]);
2768 current_has_picture |= is_slice;
2769 }
2770
2771 if !current.is_empty() {
2772 units.push(current);
2773 }
2774 units
2775 }
2776
2777 fn inode(fd: &OwnedFd) -> u64 {
2780 use std::os::unix::fs::MetadataExt as _;
2781
2782 let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
2785 file.metadata().expect("stat the descriptor").ino()
2786 }
2787}