1use std::path::PathBuf;
44use std::rc::Rc;
45use std::sync::Arc;
46
47use anyhow::{anyhow, bail, Context as _};
48
49use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists};
50use crate::codec::h264::picture::{PictureData, Reference};
51use crate::codec::Codec;
52use crate::pool::{PooledSurface, SurfacePool};
53use crate::{
54 bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields,
55 H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter,
56 PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib,
57 VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
58 VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420,
59 VA_SLICE_DATA_FLAG_ALL,
60};
61use kodecs_h264::{
62 Marking, Matrix, Mmco, Modification, Nalu, NaluHeader, NaluType, Parser, PicOrderCnt, Pps, Profile, SliceHeader,
63 SliceType, Sps, Unit,
64};
65
66mod h265;
67
68#[derive(Clone, Debug)]
70pub struct Config {
71 pub codec: Codec,
73 pub device: Option<PathBuf>,
78}
79
80impl Config {
81 pub fn new() -> Self {
83 Self {
84 codec: Codec::H264,
85 device: None,
86 }
87 }
88}
89
90impl Default for Config {
91 fn default() -> Self {
92 Self::new()
93 }
94}
95
96#[derive(Clone)]
98pub struct Frame {
99 pub timestamp: u64,
102 pub width: u32,
104 pub height: u32,
106 pub data: Vec<u8>,
109}
110
111pub struct ExportedFrame {
136 pub timestamp: u64,
139 pub width: u32,
141 pub height: u32,
143 pub descriptor: DrmPrimeSurfaceDescriptor,
146 surface: Arc<PooledSurface>,
150}
151
152impl ExportedFrame {
153 pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result<Self> {
165 let size = surface.size();
166 Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size)
167 }
168
169 pub(crate) fn export(
175 surface: Arc<PooledSurface>,
176 timestamp: u64,
177 (width, height): (u32, u32),
178 ) -> anyhow::Result<Self> {
179 surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
180 let descriptor = surface
181 .get()
182 .export_prime()
183 .map_err(|e| anyhow!("export the surface: {e:?}"))?;
184 if descriptor.fourcc != VA_FOURCC_NV12 {
185 anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc);
186 }
187 Ok(Self {
188 timestamp,
189 width,
190 height,
191 descriptor,
192 surface,
193 })
194 }
195
196 pub fn download(&self) -> anyhow::Result<Frame> {
205 read_back(self.surface.get(), self.timestamp, self.width, self.height)
206 }
207}
208
209impl std::fmt::Debug for ExportedFrame {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 f.debug_struct("ExportedFrame")
212 .field("timestamp", &self.timestamp)
213 .field("width", &self.width)
214 .field("height", &self.height)
215 .field("fourcc", &self.descriptor.fourcc)
216 .finish()
217 }
218}
219
220impl std::fmt::Debug for Frame {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 f.debug_struct("Frame")
223 .field("timestamp", &self.timestamp)
224 .field("width", &self.width)
225 .field("height", &self.height)
226 .field("bytes", &self.data.len())
227 .finish()
228 }
229}
230
231pub struct Decoder {
253 inner: Inner,
254}
255
256enum Inner {
259 H264(H264),
260 H265(h265::Decoder),
261}
262
263struct H264 {
265 parser: Parser,
266 in_scope: Option<Arc<Sps>>,
269 dpb: Dpb<Handle>,
270 prev_ref_pic_info: PrevReferencePicInfo,
272 prev_pic_info: PrevPicInfo,
274 max_long_term_frame_idx_plus1: u32,
276 sequence: Option<Sequence>,
279 ready: Vec<Handle>,
281 display: Arc<Display>,
283}
284
285impl Decoder {
286 pub fn new(config: Config) -> anyhow::Result<Self> {
296 let codec = config.codec;
297 let (device, display) = match config.device {
298 Some(device) => {
299 let display =
300 Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
301 probe(&display, codec)?;
302 (device, display)
303 }
304 None => crate::display::open_first(|display| probe(display, codec))
305 .map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
306 };
307
308 tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
309 let inner = match codec {
310 Codec::H264 => Inner::H264(H264::new(display)),
311 Codec::H265 => Inner::H265(h265::Decoder::new(display)),
312 };
313 Ok(Self { inner })
314 }
315
316 pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
324 self.submit(access_unit, timestamp)?;
325 self.take_frames()
326 }
327
328 pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
347 self.submit(access_unit, timestamp)?;
348 self.take_exported()
349 }
350
351 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
355 let nalus = match &mut self.inner {
356 Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
357 Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
358 };
359
360 if nalus == 0 && !access_unit.is_empty() {
365 tracing::warn!(
366 "access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
367 access_unit.len()
368 );
369 }
370 Ok(())
371 }
372
373 pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
384 self.reset();
385 self.take_frames()
386 }
387
388 pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
390 self.reset();
391 self.take_exported()
392 }
393
394 fn reset(&mut self) {
397 match &mut self.inner {
398 Inner::H264(decoder) => decoder.reset(),
399 Inner::H265(decoder) => decoder.reset(),
400 }
401 }
402
403 fn ready(&mut self) -> &mut Vec<Handle> {
405 match &mut self.inner {
406 Inner::H264(decoder) => &mut decoder.ready,
407 Inner::H265(decoder) => &mut decoder.ready,
408 }
409 }
410
411 fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
413 std::mem::take(self.ready()).iter().map(download).collect()
414 }
415
416 fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
419 std::mem::take(self.ready()).iter().map(export).collect()
420 }
421
422 #[cfg(test)]
424 fn sequence(&self) -> Option<&Sequence> {
425 match &self.inner {
426 Inner::H264(decoder) => decoder.sequence.as_ref(),
427 Inner::H265(decoder) => decoder.sequence.as_ref(),
428 }
429 }
430}
431
432impl H264 {
433 fn new(display: Arc<Display>) -> Self {
434 Self {
435 parser: Parser::new(usize::MAX),
439 in_scope: None,
440 dpb: Dpb::default(),
441 prev_ref_pic_info: PrevReferencePicInfo::default(),
442 prev_pic_info: PrevPicInfo::default(),
443 max_long_term_frame_idx_plus1: 0,
444 sequence: None,
445 ready: Vec::new(),
446 display,
447 }
448 }
449
450 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
452 let mut stream = access_unit;
453 let mut current: Option<CurrentPicture> = None;
454 let mut nalus = 0usize;
455
456 loop {
457 let before = stream;
458 let Some(nalu) = next_nalu(&mut stream, self.parser.max_nal_bytes())? else {
459 break;
460 };
461 nalus += 1;
462 let nal = nalu.header;
463 match nal.type_ {
464 NaluType::Sps | NaluType::Pps | NaluType::Slice | NaluType::SliceIdr => {}
465 NaluType::SliceDpa => bail!("H.264 data partitioning is outside what VA-API decodes"),
466 other => {
469 tracing::trace!("ignoring NAL unit of type {other:?}");
470 continue;
471 }
472 }
473
474 let mut sent = &before[..before.len() - stream.len()];
479 let unit = self
480 .parser
481 .next(&mut sent)
482 .map_err(|e| anyhow!(e).context(format!("parse a {:?} NAL unit", nal.type_)))?
483 .expect("the unit framed above");
484 let Unit::Slice { header, sps, pps, .. } = unit else {
485 continue;
486 };
487 if !self.in_scope.as_ref().is_some_and(|checked| Arc::ptr_eq(checked, &sps)) {
490 check_scope(&sps)?;
491 self.in_scope = Some(Arc::clone(&sps));
492 }
493 if matches!(header.slice_type, SliceType::Sp | SliceType::Si) {
494 bail!("H.264 {:?} slice: {SCOPE}", header.slice_type);
495 }
496 let start = nalu.payload.as_ptr() as usize - before.as_ptr() as usize - 1;
498 let slice = Slice {
499 header,
500 sps,
501 pps,
502 nal,
503 data: before[start..start + 1 + nalu.payload.len()].to_vec(),
504 };
505
506 let mut picture = match current.take() {
507 Some(picture) if slice.header.first_mb_in_slice == 0 => {
511 self.finish_picture(picture)?;
512 self.begin_picture(&slice, timestamp)?
513 }
514 Some(picture) => picture,
515 None => self.begin_picture(&slice, timestamp)?,
516 };
517
518 self.decode_slice(&mut picture, slice)?;
519 current = Some(picture);
520 }
521
522 if let Some(picture) = current.take() {
525 self.finish_picture(picture)?;
526 }
527
528 Ok(nalus)
529 }
530
531 fn reset(&mut self) {
534 self.drain();
535 self.prev_ref_pic_info = PrevReferencePicInfo::default();
536 self.prev_pic_info = PrevPicInfo::default();
537 self.max_long_term_frame_idx_plus1 = 0;
538 }
539
540 fn drain(&mut self) {
542 self.ready.extend(self.dpb.drain().into_iter().flatten());
543 }
544
545 fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
548 let info = SequenceInfo::new(sps)?;
549 self.dpb
552 .set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));
553
554 let format = Format {
555 codec: Codec::H264,
556 profile: va_profile(info.profile)?,
557 coded: info.coded,
558 visible: info.visible,
559 max_dpb_frames: info.max_dpb_frames,
560 };
561 if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
562 return Ok(());
563 }
564
565 self.drain();
569
570 self.sequence = Some(Sequence::new(&self.display, format)?);
571 Ok(())
572 }
573
574 fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
577 let (sps, pps) = (Arc::clone(&slice.sps), Arc::clone(&slice.pps));
578 self.apply_sps(&sps)?;
579
580 if slice.nal.type_ == NaluType::SliceIdr {
581 self.prev_ref_pic_info.frame_num = 0;
582 }
583
584 let frame_num = slice.header.frame_num;
585 if frame_num != self.prev_ref_pic_info.frame_num
586 && frame_num != (self.prev_ref_pic_info.frame_num + 1) % max_frame_num(&sps)
587 {
588 self.handle_frame_num_gap(&sps, frame_num)?;
589 }
590
591 let pic = self.init_current_pic(slice, &sps)?;
592 let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic, &sps);
593
594 let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
596 let context = Rc::clone(&sequence.context);
597 let handle = sequence.handle(timestamp)?;
598
599 let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
600 let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
601 picture.add_buffer(create_buffer(&context, pic_param)?);
602 picture.add_buffer(create_buffer(&context, build_iq_matrix(&sps, &pps))?);
603
604 tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
605 Ok(CurrentPicture {
606 pic,
607 sps,
608 pps,
609 handle,
610 picture,
611 ref_pic_lists,
612 })
613 }
614
615 fn decode_slice(&mut self, current: &mut CurrentPicture, slice: Slice) -> anyhow::Result<()> {
618 if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
622 bail!(
623 "slice starts at macroblock {}, past what a VA slice parameter addresses",
624 slice.header.first_mb_in_slice
625 );
626 }
627 if slice.header.header_bit_size > usize::from(u16::MAX) {
628 bail!(
629 "slice header is {} bits long, past what a VA slice parameter addresses",
630 slice.header.header_bit_size
631 );
632 }
633
634 if !Arc::ptr_eq(&slice.sps, ¤t.sps) && SequenceInfo::new(&slice.sps)? != SequenceInfo::new(¤t.sps)?
637 {
638 bail!("invalid stream: the sequence changed between slices of one picture");
639 }
640 current.sps = slice.sps;
641 current.pps = slice.pps;
642
643 let (list0, list1) =
644 self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.sps, ¤t.ref_pic_lists)?;
645 let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
646
647 let slice_param = build_slice_param(&slice.header, slice.data.len(), &list0, &list1, ¤t.pps);
648 current.picture.add_buffer(create_buffer(context, slice_param)?);
649 current
650 .picture
651 .add_buffer(create_buffer(context, BufferType::SliceData(slice.data))?);
652
653 Ok(())
654 }
655
656 fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
659 let CurrentPicture {
660 mut pic,
661 sps,
662 handle,
663 picture,
664 ..
665 } = current;
666
667 run(picture)?;
668 tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
669
670 if pic.is_ref() {
671 self.reference_pic_marking(&mut pic, &sps)?;
672 self.prev_ref_pic_info.fill(&pic);
673 }
674 self.prev_pic_info.fill(&pic);
675
676 if pic.has_mmco_5 {
679 self.drain();
680 }
681
682 self.dpb
684 .finish_picture(pic, handle, &mut self.ready)
685 .map_err(|e| anyhow!("store picture in DPB: {e}"))?;
686
687 Ok(())
688 }
689
690 fn init_current_pic(&mut self, slice: &Slice, sps: &Sps) -> anyhow::Result<PictureData> {
692 let mut pic = PictureData::new_from_slice(&slice.header, slice.nal, &sps.pic_order_cnt);
693 self.compute_pic_order_count(&mut pic, sps)?;
694
695 if pic.idr {
696 if matches!(pic.marking, Some(Marking::Idr(true, _))) {
699 self.dpb.clear();
700 } else {
701 self.drain();
702 }
703 }
704
705 self.dpb.update_pic_nums(slice.header.frame_num, max_frame_num(sps));
706
707 Ok(pic)
708 }
709
710 fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> anyhow::Result<()> {
713 if self.dpb.is_empty() {
714 return Ok(());
715 }
716
717 if !sps.gaps_in_frame_num_allowed {
718 bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
719 }
720 tracing::debug!("frame_num gap up to {frame_num}");
721
722 let max_frame_num = max_frame_num(sps);
723 let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
724 while unused != frame_num {
725 let mut pic = PictureData::new_non_existing(unused);
726 self.compute_pic_order_count(&mut pic, sps)?;
727
728 self.dpb.update_pic_nums(unused, max_frame_num);
729 self.dpb.sliding_window_marking(sps);
730 self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
731 self.dpb
732 .store_picture(pic, None)
733 .map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
734
735 unused = (unused + 1) % max_frame_num;
736 }
737
738 Ok(())
739 }
740
741 fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
743 pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
744 }
745
746 fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
748 if pic.idr {
749 self.dpb.mark_all_as_unused_for_ref();
750
751 if matches!(pic.marking, Some(Marking::Idr(_, true))) {
752 pic.set_reference(Reference::LongTerm);
753 pic.long_term_frame_idx = 0;
754 self.max_long_term_frame_idx_plus1 = 1;
755 } else {
756 pic.set_reference(Reference::ShortTerm);
757 self.max_long_term_frame_idx_plus1 = 0;
758 }
759
760 return Ok(());
761 }
762
763 match pic.marking.take() {
764 Some(Marking::Adaptive(mmcos)) => self.handle_memory_management_ops(pic, &mmcos)?,
765 _ => self.dpb.sliding_window_marking(sps),
766 }
767
768 Ok(())
769 }
770
771 fn handle_memory_management_ops(&mut self, pic: &mut PictureData, mmcos: &[Mmco]) -> Result<(), MmcoError> {
773 for &mmco in mmcos {
774 match mmco {
775 Mmco::ForgetShort(difference) => self.dpb.mmco_op_1(pic, difference)?,
776 Mmco::ForgetLong(long_term_pic_num) => self.dpb.mmco_op_2(long_term_pic_num)?,
777 Mmco::ShortToLong(difference, idx) => self.dpb.mmco_op_3(pic, difference, idx)?,
778 Mmco::MaxLong(plus1) => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_4(plus1),
779 Mmco::ForgetAll => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_5(pic),
780 Mmco::CurrentToLong(idx) => self.dpb.mmco_op_6(pic, idx),
781 }
782 }
783
784 Ok(())
785 }
786
787 fn create_ref_pic_lists<'a>(
790 &'a self,
791 pic: &PictureData,
792 hdr: &SliceHeader,
793 sps: &Sps,
794 lists: &ReferencePicLists,
795 ) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
796 let max_pic_num = max_frame_num(sps) as i32;
798 let list0 = match hdr.slice_type {
800 SliceType::P => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0, max_pic_num)?,
801 SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0, max_pic_num)?,
802 SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
803 };
804
805 let list1 = match hdr.slice_type {
806 SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1, max_pic_num)?,
807 SliceType::P | SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
808 };
809
810 Ok((list0, list1))
811 }
812
813 fn modify_ref_pic_list<'a>(
815 &'a self,
816 pic: &PictureData,
817 hdr: &SliceHeader,
818 list1: bool,
819 indices: &[usize],
820 max_pic_num: i32,
821 ) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
822 let (active, modifications) = match list1 {
823 true => (hdr.num_ref_idx_l1_active, &hdr.modification_l1),
824 false => (hdr.num_ref_idx_l0_active, &hdr.modification_l0),
825 };
826 let active = usize::from(active);
827
828 let mut list: DpbPicRefList<'a, Handle> =
829 indices.iter().map(|&i| &self.dpb.entries()[i]).take(active).collect();
830
831 let Some(modifications) = modifications else {
832 return Ok(list);
833 };
834
835 let mut pic_num_pred = pic.pic_num;
836 let mut ref_idx = 0;
837
838 for modification in modifications {
839 match modification.idc {
840 idc @ (0 | 1) => self.short_term_modification(
841 pic,
842 &mut list,
843 active,
844 max_pic_num,
845 idc,
846 modification,
847 &mut pic_num_pred,
848 &mut ref_idx,
849 )?,
850 2 => self.long_term_modification(&mut list, active, modification, &mut ref_idx)?,
851 other => bail!("unexpected modification_of_pic_nums_idc {other}"),
852 }
853 }
854
855 Ok(list)
856 }
857
858 fn short_term_modification<'a>(
860 &'a self,
861 pic: &PictureData,
862 list: &mut DpbPicRefList<'a, Handle>,
863 active: usize,
864 max_pic_num: i32,
865 idc: u8,
866 modification: &Modification,
867 pic_num_pred: &mut i32,
868 ref_idx: &mut usize,
869 ) -> anyhow::Result<()> {
870 let abs_diff_pic_num = modification.value as i32 + 1;
872
873 let pic_num_no_wrap = if idc == 0 {
874 if *pic_num_pred - abs_diff_pic_num < 0 {
875 *pic_num_pred - abs_diff_pic_num + max_pic_num
876 } else {
877 *pic_num_pred - abs_diff_pic_num
878 }
879 } else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
880 *pic_num_pred + abs_diff_pic_num - max_pic_num
881 } else {
882 *pic_num_pred + abs_diff_pic_num
883 };
884
885 *pic_num_pred = pic_num_no_wrap;
886
887 let pic_num = if pic_num_no_wrap > pic.pic_num {
888 pic_num_no_wrap - max_pic_num
889 } else {
890 pic_num_no_wrap
891 };
892
893 let entry = self
894 .dpb
895 .find_short_term_with_pic_num(pic_num)
896 .with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
897
898 Self::insert_modification(list, entry, active, ref_idx, |target| {
899 target.pic_num_f(max_pic_num) != pic_num
900 });
901
902 Ok(())
903 }
904
905 fn long_term_modification<'a>(
907 &'a self,
908 list: &mut DpbPicRefList<'a, Handle>,
909 active: usize,
910 modification: &Modification,
911 ref_idx: &mut usize,
912 ) -> anyhow::Result<()> {
913 let long_term_pic_num = modification.value;
914 let max_long_term_frame_idx_plus1 = self.max_long_term_frame_idx_plus1;
915
916 let entry = self
917 .dpb
918 .find_long_term_with_long_term_pic_num(long_term_pic_num)
919 .with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
920
921 Self::insert_modification(list, entry, active, ref_idx, |target| {
922 target.long_term_pic_num_f(max_long_term_frame_idx_plus1) != u64::from(long_term_pic_num)
923 });
924
925 Ok(())
926 }
927
928 fn insert_modification<'a>(
932 list: &mut DpbPicRefList<'a, Handle>,
933 entry: &'a DpbEntry<Handle>,
934 active: usize,
935 ref_idx: &mut usize,
936 keep: impl Fn(&PictureData) -> bool,
937 ) {
938 let at = (*ref_idx).min(list.len());
941 list.insert(at, entry);
942 *ref_idx = at + 1;
943
944 let mut next = *ref_idx;
945 for current in *ref_idx..=active {
946 if current >= list.len() {
947 break;
948 }
949
950 if keep(&list[current].pic) {
951 list[next] = list[current];
952 next += 1;
953 }
954 }
955
956 list.truncate(active);
957 }
958}
959
960struct Slice {
963 header: SliceHeader,
964 sps: Arc<Sps>,
965 pps: Arc<Pps>,
966 nal: NaluHeader,
967 data: Vec<u8>,
969}
970
971struct CurrentPicture {
973 pic: PictureData,
974 sps: Arc<Sps>,
976 pps: Arc<Pps>,
977 handle: Handle,
979 picture: Picture<crate::PictureNew, Handle>,
980 ref_pic_lists: ReferencePicLists,
982}
983
984#[derive(Clone)]
988struct Handle {
989 surface: Arc<PooledSurface>,
990 timestamp: u64,
991 width: u32,
992 height: u32,
993}
994
995impl std::borrow::Borrow<Surface<()>> for Handle {
996 fn borrow(&self) -> &Surface<()> {
997 self.surface.get()
998 }
999}
1000
1001#[derive(Clone, Debug, PartialEq, Eq)]
1004struct SequenceInfo {
1005 visible: (u32, u32),
1006 coded: (u32, u32),
1007 profile: Profile,
1008 max_dpb_frames: usize,
1009}
1010
1011const SCOPE: &str = "only progressive 8-bit 4:2:0 up to High profile, within its level, decodes";
1013
1014fn check_scope(sps: &Sps) -> anyhow::Result<()> {
1016 sps.check_decoder_scope()
1017 .map_err(|e| anyhow!("H.264 SPS {}: {e}: {SCOPE}", sps.id))
1018}
1019
1020impl SequenceInfo {
1021 fn new(sps: &Sps) -> anyhow::Result<Self> {
1024 let (right, bottom) = match sps.crop {
1025 Some(crop) if crop.left != 0 || crop.top != 0 => bail!("left and top H.264 cropping is not supported"),
1026 Some(crop) => (crop.right, crop.bottom),
1027 None => (0, 0),
1028 };
1029 let coded = (16 * sps.width_mbs, 16 * sps.height_mbs);
1030
1031 Ok(Self {
1032 visible: (coded.0 - right, coded.1 - bottom),
1033 coded,
1034 profile: sps.profile,
1035 max_dpb_frames: max_dpb_frames(sps),
1036 })
1037 }
1038}
1039
1040#[derive(Clone, Debug, PartialEq, Eq)]
1043struct Format {
1044 codec: Codec,
1045 profile: VAProfile::Type,
1046 coded: (u32, u32),
1047 visible: (u32, u32),
1049 max_dpb_frames: usize,
1051}
1052
1053struct Sequence {
1055 format: Format,
1056 pool: SurfacePool,
1057 context: Rc<Context>,
1059 _config: VaConfig,
1060}
1061
1062impl Sequence {
1063 fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
1064 let attrs = vec![VAConfigAttrib {
1065 type_: VAConfigAttribType::VAConfigAttribRTFormat,
1066 value: VA_RT_FORMAT_YUV420,
1067 }];
1068 let config = display
1069 .create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
1070 .map_err(|e| anyhow!("create VA config: {e:?}"))?;
1071
1072 let (coded_width, coded_height) = format.coded;
1073 let context = display
1074 .create_context::<()>(&config, coded_width, coded_height, None, true)
1075 .map_err(|e| anyhow!("create VA context: {e:?}"))?;
1076
1077 let (width, height) = format.visible;
1078 tracing::info!(
1079 "VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
1080 VA profile {}, DPB {} frames",
1081 format.codec,
1082 format.profile,
1083 format.max_dpb_frames
1084 );
1085
1086 let capacity = format.max_dpb_frames + 1;
1091 Ok(Self {
1092 pool: SurfacePool::new(
1093 display,
1094 (coded_width, coded_height),
1095 UsageHint::USAGE_HINT_DECODER,
1096 capacity,
1097 ),
1098 format,
1099 context,
1100 _config: config,
1101 })
1102 }
1103
1104 fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
1106 let (width, height) = self.format.visible;
1107 Ok(Handle {
1108 surface: Arc::new(self.pool.alloc()?),
1109 timestamp,
1110 width,
1111 height,
1112 })
1113 }
1114}
1115
1116fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
1122 let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
1123 let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
1124 let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
1125 drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
1126 Ok(())
1127}
1128
1129fn max_dpb_frames(sps: &Sps) -> usize {
1132 match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1133 Some(restriction) => usize::from(restriction.max_dec_frame_buffering.max(1)),
1134 None => usize::from(sps.max_dpb_frames),
1135 }
1136}
1137
1138fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
1147 if matches!(sps.pic_order_cnt, PicOrderCnt::Decode) {
1148 return 0;
1149 }
1150 let declared = match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1151 Some(restriction) => usize::from(restriction.max_num_reorder_frames),
1152 None if matches!(sps.profile.value(), 44 | 86 | 100 | 110 | 122 | 244) && sps.constraint_flags & 0x10 != 0 => 0,
1154 None => max_dpb_frames,
1155 };
1156 declared.min(max_dpb_frames)
1157}
1158
1159fn max_frame_num(sps: &Sps) -> u32 {
1161 1 << sps.log2_max_frame_num
1162}
1163
1164fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
1166 ExportedFrame::export(
1167 Arc::clone(&handle.surface),
1168 handle.timestamp,
1169 (handle.width, handle.height),
1170 )
1171}
1172
1173fn download(handle: &Handle) -> anyhow::Result<Frame> {
1175 read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
1176}
1177
1178fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
1184 surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
1185
1186 let visible = (width, height);
1187
1188 match unsafe { Image::derive_shared(surface, visible) } {
1195 Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
1196 return pack_nv12(&image, timestamp, width, height);
1197 }
1198 Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
1199 Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
1200 }
1201
1202 let format = surface
1203 .display()
1204 .query_image_formats()
1205 .map_err(|e| anyhow!("query image formats: {e:?}"))?
1206 .into_iter()
1207 .find(|format| format.fourcc == VA_FOURCC_NV12)
1208 .context("driver has no NV12 image format")?;
1209 let image = Image::create_from(surface, format, surface.size(), visible)
1210 .map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
1211
1212 pack_nv12(&image, timestamp, width, height)
1213}
1214
1215fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
1218 let va_image = image.image();
1219 let src: &[u8] = image.as_ref();
1220 let (width, height) = (frame_width as usize, frame_height as usize);
1221 let chroma_rows = height / 2;
1222
1223 let mut data = vec![0u8; width * (height + chroma_rows)];
1224 let (luma, chroma) = data.split_at_mut(width * height);
1225 copy_plane(
1226 luma,
1227 src,
1228 va_image.offsets[0] as usize,
1229 va_image.pitches[0] as usize,
1230 width,
1231 height,
1232 )?;
1233 copy_plane(
1234 chroma,
1235 src,
1236 va_image.offsets[1] as usize,
1237 va_image.pitches[1] as usize,
1238 width,
1239 chroma_rows,
1240 )?;
1241
1242 Ok(Frame {
1243 timestamp,
1244 width: frame_width,
1245 height: frame_height,
1246 data,
1247 })
1248}
1249
1250fn copy_plane(
1252 dst: &mut [u8],
1253 src: &[u8],
1254 offset: usize,
1255 pitch: usize,
1256 width: usize,
1257 rows: usize,
1258) -> anyhow::Result<()> {
1259 if rows == 0 {
1260 return Ok(());
1261 }
1262 let end = offset + pitch * (rows - 1) + width;
1263 if pitch < width || src.len() < end {
1264 bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
1265 }
1266
1267 for row in 0..rows {
1268 let from = offset + row * pitch;
1269 dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
1270 }
1271
1272 Ok(())
1273}
1274
1275pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
1283 let profiles = display
1284 .query_config_profiles()
1285 .map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
1286
1287 let supported = profiles
1288 .into_iter()
1289 .filter(|profile| match codec {
1290 Codec::H264 => matches!(
1291 *profile,
1292 VAProfile::VAProfileH264ConstrainedBaseline
1293 | VAProfile::VAProfileH264Main
1294 | VAProfile::VAProfileH264High
1295 ),
1296 Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
1297 })
1298 .any(|profile| {
1299 display
1300 .query_config_entrypoints(profile)
1301 .is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
1302 });
1303
1304 if !supported {
1305 bail!("driver exposes no {codec:?} decode entrypoint");
1306 }
1307
1308 Ok(())
1309}
1310
1311fn va_profile(profile: Profile) -> anyhow::Result<VAProfile::Type> {
1313 Ok(match profile {
1314 Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
1320 Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
1321 Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
1324 other => bail!("unsupported H.264 profile {other:?}"),
1325 })
1326}
1327
1328fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
1329 context
1330 .create_buffer(buffer)
1331 .map_err(|e| anyhow!("create VA buffer: {e:?}"))
1332}
1333
1334fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
1340 let max_frame_num = max_frame_num(sps);
1341 let first = (prev_frame_num + 1) % max_frame_num;
1342 let missing = (frame_num + max_frame_num - first) % max_frame_num;
1343 let window = u32::from(sps.max_num_ref_frames).max(1);
1345 let skipped = missing.saturating_sub(window);
1346 (first + skipped) % max_frame_num
1347}
1348
1349fn pic_order_count(
1355 prev_ref: &PrevReferencePicInfo,
1356 prev: &mut PrevPicInfo,
1357 pic: &mut PictureData,
1358 sps: &Sps,
1359) -> anyhow::Result<()> {
1360 let overflow = || anyhow!("picture order count overflows");
1361 match &sps.pic_order_cnt {
1362 PicOrderCnt::Lsb { log2_max_lsb } => {
1364 let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if pic.idr {
1365 (0, 0)
1366 } else if prev_ref.has_mmco_5 {
1367 (0, prev_ref.top_field_order_cnt)
1368 } else {
1369 (prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
1370 };
1371
1372 let max_pic_order_cnt_lsb: i32 = 1 << log2_max_lsb;
1373 let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
1376 let half = i64::from(max_pic_order_cnt_lsb / 2);
1377
1378 pic.pic_order_cnt_msb = if lsb_delta >= half {
1379 prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
1380 } else if -lsb_delta > half {
1381 prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
1382 } else {
1383 Some(prev_pic_order_cnt_msb)
1384 }
1385 .ok_or_else(overflow)?;
1386
1387 pic.top_field_order_cnt = pic
1388 .pic_order_cnt_msb
1389 .checked_add(pic.pic_order_cnt_lsb)
1390 .ok_or_else(overflow)?;
1391 pic.bottom_field_order_cnt = pic
1392 .top_field_order_cnt
1393 .checked_add(pic.delta_pic_order_cnt_bottom)
1394 .ok_or_else(overflow)?;
1395 }
1396
1397 PicOrderCnt::Cycle {
1399 offset_for_non_ref_pic,
1400 offset_for_top_to_bottom_field,
1401 offset_for_ref_frame,
1402 ..
1403 } => {
1404 if prev.has_mmco_5 {
1405 prev.frame_num_offset = 0;
1406 }
1407
1408 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1409
1410 let mut abs_frame_num = if !offset_for_ref_frame.is_empty() {
1411 pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
1412 } else {
1413 0
1414 };
1415
1416 if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
1417 abs_frame_num -= 1;
1418 }
1419
1420 let mut expected_pic_order_cnt: i128 = 0;
1423
1424 if abs_frame_num > 0 {
1425 let cycle_len = offset_for_ref_frame.len() as u32;
1427 let cycles = (abs_frame_num - 1) / cycle_len;
1428 let position_in_cycle = (abs_frame_num - 1) % cycle_len;
1431 let expected_delta_per_cycle: i128 =
1432 offset_for_ref_frame.iter().map(|&offset| i128::from(offset)).sum();
1433 expected_pic_order_cnt = i128::from(cycles) * expected_delta_per_cycle;
1434
1435 for &offset in &offset_for_ref_frame[..=position_in_cycle as usize] {
1436 expected_pic_order_cnt += i128::from(offset);
1437 }
1438 }
1439
1440 if pic.nal_ref_idc == 0 {
1441 expected_pic_order_cnt += i128::from(*offset_for_non_ref_pic);
1442 }
1443
1444 let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
1445 let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
1446 let to_bottom = i128::from(*offset_for_top_to_bottom_field);
1447 pic.top_field_order_cnt = count(top)?;
1448 pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
1449 }
1450
1451 PicOrderCnt::Decode => {
1453 if prev.has_mmco_5 {
1454 prev.frame_num_offset = 0;
1455 }
1456
1457 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1458
1459 let pic_order_cnt = if pic.idr {
1460 0
1461 } else {
1462 let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
1463 i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
1464 };
1465
1466 pic.top_field_order_cnt = pic_order_cnt;
1467 pic.bottom_field_order_cnt = pic_order_cnt;
1468 }
1469 }
1470
1471 pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);
1472
1473 Ok(())
1474}
1475
1476fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
1479 Ok(if pic.idr {
1480 0
1481 } else if prev.frame_num > pic.frame_num {
1482 prev.frame_num_offset
1483 .checked_add(max_frame_num(sps))
1484 .context("FrameNumOffset overflows")?
1485 } else {
1486 prev.frame_num_offset
1487 })
1488}
1489
1490#[derive(Debug, Default)]
1492struct PrevReferencePicInfo {
1493 frame_num: u32,
1494 has_mmco_5: bool,
1495 top_field_order_cnt: i32,
1496 pic_order_cnt_msb: i32,
1497 pic_order_cnt_lsb: i32,
1498}
1499
1500impl PrevReferencePicInfo {
1501 fn fill(&mut self, pic: &PictureData) {
1502 self.has_mmco_5 = pic.has_mmco_5;
1503 self.top_field_order_cnt = pic.top_field_order_cnt;
1504 self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
1505 self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
1506 self.frame_num = pic.frame_num;
1507 }
1508}
1509
1510#[derive(Debug, Default)]
1512struct PrevPicInfo {
1513 frame_num: u32,
1514 frame_num_offset: u32,
1515 has_mmco_5: bool,
1516}
1517
1518impl PrevPicInfo {
1519 fn fill(&mut self, pic: &PictureData) {
1520 self.frame_num = pic.frame_num;
1521 self.has_mmco_5 = pic.has_mmco_5;
1522 self.frame_num_offset = pic.frame_num_offset;
1523 }
1524}
1525
1526fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
1529 match handle {
1530 Some(handle) => handle.surface.id(),
1531 None => VA_INVALID_ID,
1532 }
1533}
1534
1535fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
1537 let mut flags = 0;
1538 let frame_idx = match pic.reference() {
1539 Reference::LongTerm => {
1540 flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
1541 pic.long_term_frame_idx
1542 }
1543 Reference::ShortTerm => {
1544 flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1545 pic.frame_num
1546 }
1547 Reference::None => pic.frame_num,
1548 };
1549
1550 PictureH264::new(
1551 surface_id,
1552 frame_idx,
1553 flags,
1554 pic.top_field_order_cnt,
1555 pic.bottom_field_order_cnt,
1556 )
1557}
1558
1559fn build_invalid_va_h264_pic() -> PictureH264 {
1561 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1562}
1563
1564fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType {
1567 const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
1568 #[rustfmt::skip]
1569 const ZIGZAG_8X8: [usize; 64] = [
1570 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,
1571 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
1572 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
1573 ];
1574
1575 let flat = Matrix {
1577 lists_4x4: vec![16; 6 * 16],
1578 lists_8x8: vec![16; 2 * 64],
1579 };
1580 let matrix = pps.scaling.as_ref().or(sps.scaling.as_ref()).unwrap_or(&flat);
1581
1582 let mut scaling_list4x4 = [[0u8; 16]; 6];
1583 for (list, src) in scaling_list4x4.iter_mut().zip(matrix.lists_4x4.chunks_exact(16)) {
1584 for (i, &value) in src.iter().enumerate() {
1585 list[ZIGZAG_4X4[i]] = value;
1586 }
1587 }
1588
1589 let mut scaling_list8x8 = [[0u8; 64]; 2];
1590 for (list, src) in scaling_list8x8.iter_mut().zip(matrix.lists_8x8.chunks_exact(64)) {
1591 for (i, &value) in src.iter().enumerate() {
1592 list[ZIGZAG_8X8[i]] = value;
1593 }
1594 }
1595
1596 BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
1597 scaling_list4x4,
1598 scaling_list8x8,
1599 )))
1600}
1601
1602fn build_pic_param(
1604 hdr: &SliceHeader,
1605 pic: &PictureData,
1606 surface_id: bindings::VASurfaceID,
1607 dpb: &Dpb<Handle>,
1608 sps: &Sps,
1609 pps: &Pps,
1610) -> BufferType {
1611 let curr_pic = fill_va_h264_pic(pic, surface_id);
1612
1613 let short_term = dpb.short_term_refs_iter().filter(|entry| !entry.pic.nonexisting);
1614 let mut refs: Vec<PictureH264> = short_term
1615 .chain(dpb.long_term_refs_iter())
1616 .take(16)
1617 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1618 .collect();
1619 refs.resize_with(16, build_invalid_va_h264_pic);
1620 let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
1621
1622 let (pic_order_cnt_type, log2_max_lsb, delta_always_zero) = match sps.pic_order_cnt {
1623 PicOrderCnt::Lsb { log2_max_lsb } => (0, log2_max_lsb, false),
1624 PicOrderCnt::Cycle { delta_always_zero, .. } => (1, 4, delta_always_zero),
1625 PicOrderCnt::Decode => (2, 4, false),
1626 };
1627 let seq_fields = H264SeqFields::new(
1628 1, 0, sps.gaps_in_frame_num_allowed as u32,
1631 1, 0, sps.direct_8x8_inference as u32,
1634 (sps.level.value() >= 31) as u32,
1636 u32::from(sps.log2_max_frame_num - 4),
1637 pic_order_cnt_type,
1638 u32::from(log2_max_lsb - 4),
1639 delta_always_zero as u32,
1640 );
1641
1642 let pic_fields = H264PicFields::new(
1643 pps.entropy_coding_mode as u32,
1644 pps.weighted_pred as u32,
1645 u32::from(pps.weighted_bipred_idc),
1646 pps.transform_8x8_mode as u32,
1647 0, pps.constrained_intra_pred as u32,
1649 pps.bottom_field_pic_order_in_frame_present as u32,
1650 pps.deblocking_filter_control_present as u32,
1651 pps.redundant_pic_cnt_present as u32,
1652 (pic.nal_ref_idc != 0) as u32,
1653 );
1654
1655 BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
1658 curr_pic,
1659 refs,
1660 (sps.width_mbs - 1) as u16,
1661 (sps.height_mbs - 1) as u16,
1662 0, 0, sps.max_num_ref_frames,
1665 &seq_fields,
1666 0,
1668 0,
1669 0,
1670 (pps.pic_init_qp - 26) as i8,
1671 (pps.pic_init_qs - 26) as i8,
1672 pps.chroma_qp_index_offset as i8,
1673 pps.second_chroma_qp_index_offset as i8,
1674 &pic_fields,
1675 hdr.frame_num as u16,
1676 )))
1677}
1678
1679fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
1681 let mut pics: Vec<PictureH264> = list
1682 .iter()
1683 .take(32)
1684 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1685 .collect();
1686 pics.resize_with(32, build_invalid_va_h264_pic);
1687
1688 pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
1689}
1690
1691fn build_slice_param(
1693 hdr: &SliceHeader,
1694 slice_size: usize,
1695 list0: &[&DpbEntry<Handle>],
1696 list1: &[&DpbEntry<Handle>],
1697 pps: &Pps,
1698) -> BufferType {
1699 let mut luma_weight_l0 = [0i16; 32];
1700 let mut luma_offset_l0 = [0i16; 32];
1701 let mut chroma_weight_l0 = [[0i16; 2]; 32];
1702 let mut chroma_offset_l0 = [[0i16; 2]; 32];
1703
1704 let mut luma_weight_l1 = [0i16; 32];
1705 let mut luma_offset_l1 = [0i16; 32];
1706 let mut chroma_weight_l1 = [[0i16; 2]; 32];
1707 let mut chroma_offset_l1 = [[0i16; 2]; 32];
1708
1709 let weights = hdr.weights.as_ref();
1714 let fill = |weights: &[kodecs_h264::Weight],
1715 luma_weight: &mut [i16; 32],
1716 luma_offset: &mut [i16; 32],
1717 chroma_weight: &mut [[i16; 2]; 32],
1718 chroma_offset: &mut [[i16; 2]; 32]| {
1719 for (i, weight) in weights.iter().take(32).enumerate() {
1720 luma_weight[i] = weight.luma_weight as i16;
1721 luma_offset[i] = weight.luma_offset as i16;
1722 chroma_weight[i] = weight.chroma_weight.map(|w| w as i16);
1723 chroma_offset[i] = weight.chroma_offset.map(|o| o as i16);
1724 }
1725 };
1726 if let Some(weights) = weights {
1727 fill(
1728 &weights.l0,
1729 &mut luma_weight_l0,
1730 &mut luma_offset_l0,
1731 &mut chroma_weight_l0,
1732 &mut chroma_offset_l0,
1733 );
1734 fill(
1735 &weights.l1,
1736 &mut luma_weight_l1,
1737 &mut luma_offset_l1,
1738 &mut chroma_weight_l1,
1739 &mut chroma_offset_l1,
1740 );
1741 }
1742 let fill_l0 = weights.is_some();
1743 let fill_l1 = weights.is_some() && hdr.slice_type == SliceType::B;
1744
1745 BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
1748 slice_size as u32,
1749 0,
1750 VA_SLICE_DATA_FLAG_ALL,
1751 hdr.header_bit_size as u16,
1752 hdr.first_mb_in_slice as u16,
1753 hdr.slice_type_raw % 5,
1754 hdr.direct_spatial_mv_pred as u8,
1755 hdr.num_ref_idx_l0_active.saturating_sub(1),
1756 hdr.num_ref_idx_l1_active.saturating_sub(1),
1757 hdr.cabac_init_idc,
1758 (hdr.slice_qp - pps.pic_init_qp) as i8,
1759 hdr.disable_deblocking_filter_idc,
1760 hdr.slice_alpha_c0_offset_div2 as i8,
1761 hdr.slice_beta_offset_div2 as i8,
1762 fill_ref_pic_list(list0),
1763 fill_ref_pic_list(list1),
1764 weights.map_or(0, |w| w.luma_log2_denom),
1765 weights.map_or(0, |w| w.chroma_log2_denom),
1766 fill_l0 as u8,
1767 luma_weight_l0,
1768 luma_offset_l0,
1769 fill_l0 as u8,
1770 chroma_weight_l0,
1771 chroma_offset_l0,
1772 fill_l1 as u8,
1773 luma_weight_l1,
1774 luma_offset_l1,
1775 fill_l1 as u8,
1776 chroma_weight_l1,
1777 chroma_offset_l1,
1778 )))
1779}
1780
1781fn next_nalu<'a>(stream: &mut &'a [u8], max_bytes: usize) -> anyhow::Result<Option<Nalu<'a>>> {
1784 loop {
1785 let Some(raw) = kodecs_h264::split_annex_b(stream, max_bytes).context("frame a NAL unit")? else {
1786 return Ok(None);
1787 };
1788 if !raw.is_empty() {
1789 return Ok(Some(Nalu::new(raw, max_bytes).context("parse a NAL unit header")?));
1790 }
1791 }
1792}
1793
1794#[cfg(test)]
1795mod tests {
1796 use std::os::fd::OwnedFd;
1797 use std::process::Command;
1798
1799 use super::*;
1800
1801 #[test]
1804 fn a_malformed_header_is_an_error() {
1805 let bytes = [0, 0, 1, 0, 0, 0, 1, 0x09, 0x10, 0, 0, 0, 1, 0x07, 0x42, 0x00, 0x1e];
1807 let mut stream = &bytes[..];
1808 let nalu = next_nalu(&mut stream, usize::MAX).unwrap().expect("a unit");
1809 assert_eq!(nalu.header.type_, NaluType::AuDelimiter);
1810 assert!(next_nalu(&mut stream, usize::MAX).is_err());
1811 assert!(next_nalu(&mut stream, usize::MAX).unwrap().is_none());
1812 }
1813
1814 fn progressive_sps() -> Sps {
1816 kodecs_h264::SpsBuilder::new(Profile::Main, kodecs_h264::Level::L3)
1817 .resolution(320, 240)
1818 .build()
1819 .unwrap()
1820 }
1821
1822 #[test]
1825 fn a_frame_num_gap_invents_only_the_reference_window() {
1826 let mut sps = progressive_sps();
1828 sps.max_num_ref_frames = 2;
1829 assert_eq!(first_invented(3, 4, &sps), 4);
1831 assert_eq!(first_invented(3, 5, &sps), 4);
1833 assert_eq!(first_invented(3, 10, &sps), 8);
1835 assert_eq!(first_invented(14, 3, &sps), 1);
1837 assert_eq!(first_invented(4, 3, &sps), 1);
1839
1840 sps.max_num_ref_frames = 0;
1843 assert_eq!(first_invented(0, 3, &sps), 2);
1844 }
1845
1846 fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
1849 let mut sps = progressive_sps();
1850 sps.pic_order_cnt = PicOrderCnt::Lsb { log2_max_lsb: 8 };
1851 let mut pic = PictureData::default();
1852 pic.pic_order_cnt_lsb = lsb;
1853 pic.nal_ref_idc = 1;
1854 pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
1855 Ok(pic.pic_order_cnt)
1856 }
1857
1858 fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
1859 PrevReferencePicInfo {
1860 pic_order_cnt_msb: msb,
1861 pic_order_cnt_lsb: lsb,
1862 ..Default::default()
1863 }
1864 }
1865
1866 #[test]
1870 fn the_picture_order_count_wraps_and_never_overflows() {
1871 assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
1872 assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
1873 assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
1874 assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
1875 assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
1876
1877 let after_mmco5 = PrevReferencePicInfo {
1880 has_mmco_5: true,
1881 top_field_order_cnt: i32::MIN,
1882 ..Default::default()
1883 };
1884 assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
1885 }
1886
1887 #[test]
1890 fn the_frame_num_offset_never_overflows() {
1891 let mut sps = progressive_sps();
1892 sps.pic_order_cnt = PicOrderCnt::Decode;
1893 let order_count = |frame_num_offset| {
1894 let mut prev = PrevPicInfo {
1895 frame_num: 5,
1896 frame_num_offset,
1897 has_mmco_5: false,
1898 };
1899 let mut pic = PictureData::default();
1900 pic.frame_num = 1;
1901 pic.nal_ref_idc = 1;
1902 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1903 };
1904 assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
1906 assert!(order_count(u32::MAX - 3).is_err());
1907 assert!(order_count(i32::MAX as u32 / 2).is_err());
1909 }
1910
1911 #[test]
1914 fn the_type2_order_count_is_checked_whole() {
1915 let mut sps = progressive_sps();
1916 sps.pic_order_cnt = PicOrderCnt::Decode;
1917 let order_count = |nal_ref_idc| {
1918 let mut prev = PrevPicInfo {
1920 frame_num: 5,
1921 frame_num_offset: (1 << 30) - 17,
1922 has_mmco_5: false,
1923 };
1924 let mut pic = PictureData::default();
1925 pic.frame_num = 1;
1926 pic.nal_ref_idc = nal_ref_idc;
1927 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1928 };
1929 assert_eq!(order_count(0).unwrap(), i32::MAX);
1930 assert!(order_count(1).is_err());
1931 }
1932
1933 #[test]
1936 fn the_type1_bottom_field_is_checked_whole() {
1937 let mut sps = progressive_sps();
1938 sps.pic_order_cnt = PicOrderCnt::Cycle {
1939 delta_always_zero: false,
1940 offset_for_non_ref_pic: 0,
1941 offset_for_top_to_bottom_field: i32::MAX,
1942 offset_for_ref_frame: Vec::new(),
1943 };
1944 let bottom = |delta0, delta1| {
1945 let mut pic = PictureData::default();
1946 pic.nal_ref_idc = 1;
1947 pic.delta_pic_order_cnt0 = delta0;
1948 pic.delta_pic_order_cnt1 = delta1;
1949 pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
1950 .map(|()| pic.bottom_field_order_cnt)
1951 };
1952 assert_eq!(bottom(2, -i32::MAX).unwrap(), 2);
1953 assert!(bottom(2, 0).is_err());
1954 }
1955
1956 #[test]
1957 fn rejects_nonzero_crop_origins() {
1958 for (left, top) in [(2, 0), (0, 2)] {
1959 let mut sps = progressive_sps();
1960 sps.crop = Some(kodecs_h264::Crop {
1961 left,
1962 right: 0,
1963 top,
1964 bottom: 0,
1965 });
1966 assert!(SequenceInfo::new(&sps)
1967 .unwrap_err()
1968 .to_string()
1969 .contains("left and top"));
1970 }
1971 }
1972
1973 #[test]
1974 fn crop_only_updates_change_sequence_identity() {
1975 let original = SequenceInfo::new(&progressive_sps()).unwrap();
1976 for (right, bottom, expected) in [(2, 0, (318, 240)), (0, 2, (320, 238))] {
1977 let mut sps = progressive_sps();
1978 sps.crop = Some(kodecs_h264::Crop {
1979 left: 0,
1980 right,
1981 top: 0,
1982 bottom,
1983 });
1984 let cropped = SequenceInfo::new(&sps).unwrap();
1985 assert_eq!(original.coded, cropped.coded);
1986 assert_eq!(cropped.visible, expected);
1987 assert_ne!(original, cropped);
1988 }
1989 }
1990
1991 fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
1994 crate::encode::Config {
1995 device: Some(crate::testing::device()),
1996 ..crate::encode::Config::new(width, height, 30, 2_000_000, std::num::NonZeroU32::new(30).unwrap())
1997 }
1998 }
1999
2000 fn config() -> Config {
2002 Config {
2003 device: Some(crate::testing::device()),
2004 ..Config::new()
2005 }
2006 }
2007
2008 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
2011 let (w, h) = (width as usize, height as usize);
2012 let mut data = vec![128u8; w * h * 3 / 2];
2013 let x0 = (step * 16) as usize % (w / 2);
2014 for y in h / 4..h / 2 {
2015 for x in x0..x0 + w / 4 {
2016 data[y * w + x] = 235;
2017 }
2018 }
2019 data
2020 }
2021
2022 #[test]
2031 #[ignore = "requires a VA-API render node"]
2032 fn exported_pictures_do_not_share_a_surface() {
2033 let (width, height) = (320u32, 240u32);
2034 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2035 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2036
2037 let mut exported = Vec::new();
2038 for step in 0..8 {
2039 let unit = encoder
2040 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2041 .expect("encode a picture");
2042 exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
2043 }
2044 exported.extend(decoder.flush_exported().expect("flush the decoder"));
2045 assert!(!exported.is_empty(), "the decoder produced no pictures");
2046
2047 let first = &exported[0];
2048 eprintln!(
2049 "exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
2050 exported.len(),
2051 first.width,
2052 first.height,
2053 first.descriptor.fourcc,
2054 first.descriptor.objects[0].drm_format_modifier
2055 );
2056
2057 let mut seen = Vec::new();
2058 for (index, frame) in exported.iter().enumerate() {
2059 assert_eq!((frame.width, frame.height), (width, height));
2060 assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
2061 assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
2062 assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
2063
2064 let inode = inode(&frame.descriptor.objects[0].fd);
2068 assert!(
2069 !seen.contains(&inode),
2070 "picture {index} was decoded into an allocation an earlier one still holds"
2071 );
2072 seen.push(inode);
2073 }
2074 }
2075
2076 #[test]
2079 #[ignore = "requires a VA-API render node"]
2080 fn the_render_node_is_found_or_named() {
2081 if let Err(err) = Decoder::new(Config::new()) {
2082 panic!("no VA-API H.264 decoder: {err:#}");
2083 }
2084 let named = Config {
2085 device: Some(PathBuf::from("/dev/null")),
2086 ..Config::new()
2087 };
2088 assert!(
2089 Decoder::new(named).is_err(),
2090 "a named node that is not a render node was swapped for one that is"
2091 );
2092 }
2093
2094 #[test]
2101 #[ignore = "requires a VA-API render node and FFmpeg"]
2102 fn flush_returns_the_pictures_the_dpb_still_holds() {
2103 const PICTURES: usize = 10;
2104
2105 let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
2106 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2107
2108 let mut streamed = Vec::new();
2109 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2110 streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
2111 }
2112 assert!(
2113 streamed.len() < PICTURES,
2114 "the DPB held nothing back, so this test proves nothing"
2115 );
2116
2117 let flushed = decoder.flush().expect("flush the decoder");
2118 let mut timestamps: Vec<u64> = streamed
2119 .iter()
2120 .chain(&flushed)
2121 .map(|picture| picture.timestamp)
2122 .collect();
2123 timestamps.sort_unstable();
2124 assert_eq!(
2125 timestamps,
2126 (0..PICTURES as u64).collect::<Vec<_>>(),
2127 "the stream lost pictures at its end"
2128 );
2129
2130 assert!(decoder.flush().expect("flush an empty decoder").is_empty());
2133 }
2134
2135 #[test]
2144 #[ignore = "requires a VA-API render node and FFmpeg"]
2145 fn h264_without_reordering_comes_out_as_it_decodes() {
2146 const PICTURES: usize = 10;
2147 let (width, height) = (320u32, 240u32);
2148
2149 let mut streams = Vec::new();
2150 match crate::encode::Encoder::new(encoder_config(width, height)) {
2151 Ok(mut encoder) => {
2152 let units = (0..PICTURES)
2153 .map(|step| {
2154 encoder
2155 .encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
2156 .expect("encode a picture")
2157 })
2158 .collect::<Vec<_>>();
2159 streams.push(("VA-API", units));
2160 }
2161 Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
2162 }
2163 match software_encode(Codec::H264, (width, height), PICTURES, false) {
2164 Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
2165 None => panic!("FFmpeg with libx264 is required"),
2166 }
2167
2168 for (encoder, units) in streams {
2169 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2170 for (index, unit) in units.iter().enumerate() {
2171 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2172 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2173 assert_eq!(
2174 timestamps,
2175 [index as u64],
2176 "{encoder}: access unit {index} was held back"
2177 );
2178 }
2179 assert!(decoder.flush().expect("flush the decoder").is_empty());
2180 }
2181 }
2182
2183 #[test]
2186 fn the_reorder_limit_follows_the_sps() {
2187 let sps = progressive_sps();
2189 assert_eq!(sps.max_dpb_frames, 16);
2190 assert_eq!(max_dpb_frames(&sps), 16);
2191 assert_eq!(
2192 reorder_limit(&sps, 16),
2193 16,
2194 "without a VUI, the inference is the DPB size"
2195 );
2196
2197 let mut intra = progressive_sps();
2198 intra.profile = Profile::High;
2199 intra.constraint_flags = 0x10;
2200 assert_eq!(
2201 reorder_limit(&intra, 16),
2202 0,
2203 "without a VUI, a High intra profile reorders nothing"
2204 );
2205
2206 let restriction = |max_num_reorder_frames, max_dec_frame_buffering| kodecs_h264::Restriction {
2207 motion_vectors_over_pic_boundaries: true,
2208 max_bytes_per_pic_denom: 2,
2209 max_bits_per_mb_denom: 1,
2210 log2_max_mv_length_horizontal: 16,
2211 log2_max_mv_length_vertical: 16,
2212 max_num_reorder_frames,
2213 max_dec_frame_buffering,
2214 };
2215 let mut declared = progressive_sps();
2216 declared.vui = Some(kodecs_h264::Vui {
2217 aspect_ratio: None,
2218 overscan_appropriate: None,
2219 video_signal: None,
2220 chroma_loc: None,
2221 timing: None,
2222 nal_hrd: None,
2223 vcl_hrd: None,
2224 low_delay_hrd: false,
2225 pic_struct_present: false,
2226 restriction: Some(restriction(0, 1)),
2227 });
2228 assert_eq!(max_dpb_frames(&declared), 1, "the VUI's buffering is the DPB size");
2229 assert_eq!(
2230 reorder_limit(&declared, max_dpb_frames(&declared)),
2231 0,
2232 "the VUI's limit applies"
2233 );
2234
2235 if let Some(vui) = declared.vui.as_mut() {
2236 vui.restriction = Some(restriction(5, 2));
2237 }
2238 assert_eq!(
2239 reorder_limit(&declared, max_dpb_frames(&declared)),
2240 2,
2241 "the DPB size bounds the VUI's limit"
2242 );
2243
2244 let mut derived = progressive_sps();
2245 derived.pic_order_cnt = PicOrderCnt::Decode;
2246 assert_eq!(
2247 reorder_limit(&derived, 16),
2248 0,
2249 "an order count from frame_num reorders nothing"
2250 );
2251 }
2252
2253 #[test]
2261 #[ignore = "requires a VA-API render node"]
2262 fn a_dropped_export_is_decoded_into_again() {
2263 const PICTURES: u32 = 60;
2264 let (width, height) = (320u32, 240u32);
2265 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2266 let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
2267 let mut downloading = Decoder::new(config()).expect("a second decoder");
2268
2269 let mut compared = 0;
2270 for step in 0..PICTURES {
2271 let unit = encoder
2272 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2273 .expect("encode a picture");
2274 let exported = exporting
2275 .decode_exported(&unit, step as u64)
2276 .expect("decode to a descriptor");
2277 let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
2278 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2279 for (gpu, cpu) in exported.iter().zip(&downloaded) {
2280 let read_back = gpu.download().expect("read the exported surface back");
2281 assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
2282 compared += 1;
2283 }
2284 }
2285 assert!(compared > 0, "the decoder produced no pictures");
2286
2287 let pool = &exporting.sequence().expect("a sequence").pool;
2288 let allocated = pool.allocated.get();
2289 eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
2290 assert!(
2291 allocated <= pool.free.capacity,
2292 "{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
2293 pool.free.capacity
2294 );
2295 }
2296
2297 #[test]
2300 #[ignore = "requires a VA-API render node"]
2301 fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
2302 const HELD: u32 = 40;
2303 let (width, height) = (320u32, 240u32);
2304 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2305 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2306
2307 let mut step = 0;
2308 let mut decode = |decoder: &mut Decoder| {
2309 let unit = encoder
2310 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2311 .expect("encode a picture");
2312 step += 1;
2313 decoder.decode_exported(&unit, step as u64).expect("decode a picture")
2314 };
2315
2316 let mut held = Vec::new();
2317 for _ in 0..HELD {
2318 held.extend(decode(&mut decoder));
2319 }
2320 let pool = &decoder.sequence().expect("a sequence").pool;
2321 let allocated = pool.allocated.get();
2322 assert!(
2323 allocated >= held.len(),
2324 "{} pictures held on {allocated} surfaces",
2325 held.len()
2326 );
2327
2328 drop(held);
2329 let free = pool.free.surfaces.lock().unwrap().len();
2330 assert!(
2331 free <= pool.free.capacity,
2332 "{free} surfaces left free, more than the capacity of {}",
2333 pool.free.capacity
2334 );
2335
2336 for _ in 0..10 {
2337 drop(decode(&mut decoder));
2338 }
2339 let pool = &decoder.sequence().expect("a sequence").pool;
2340 assert_eq!(
2341 pool.allocated.get(),
2342 allocated,
2343 "pictures after the release did not reuse the free surfaces"
2344 );
2345 }
2346
2347 #[test]
2352 fn an_exported_frame_is_send_and_sync() {
2353 const fn assert_send_sync<T: Send + Sync>() {}
2354 assert_send_sync::<ExportedFrame>();
2355 }
2356
2357 #[test]
2366 #[ignore = "requires a VA-API render node"]
2367 fn an_exported_picture_downloads_to_the_same_pixels() {
2368 let (width, height) = (320u32, 240u32);
2369 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2370 let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
2371 let mut downloading = Decoder::new(config()).expect("a second decoder");
2372
2373 let mut exported = Vec::new();
2374 let mut downloaded = Vec::new();
2375 for step in 0..8 {
2376 let unit = encoder
2377 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2378 .expect("encode a picture");
2379 exported.extend(
2380 exporting
2381 .decode_exported(&unit, step as u64)
2382 .expect("decode to a descriptor"),
2383 );
2384 downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
2385 }
2386 exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
2387 downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
2388
2389 assert!(!exported.is_empty(), "the decoder produced no pictures");
2390 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2391
2392 for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
2393 let read_back = gpu.download().expect("read the exported surface back");
2394 assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
2395 assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
2396 assert!(
2397 read_back.data == cpu.data,
2398 "picture {index} read back differently than it downloaded"
2399 );
2400 }
2401 }
2402
2403 #[test]
2413 #[ignore = "requires a VA-API render node and FFmpeg"]
2414 fn decoded_pictures_match_a_software_decoder() {
2415 const PICTURES: usize = 30;
2416
2417 for codec in [Codec::H264, Codec::H265] {
2418 for (width, height) in [(320u32, 240u32), (852, 478)] {
2419 let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
2420 panic!("no ffmpeg that encodes {codec:?}");
2421 };
2422 let reference = software_decode(codec, &stream);
2423
2424 let picture_len = (width * height * 3 / 2) as usize;
2425 assert_eq!(
2426 reference.len(),
2427 PICTURES * picture_len,
2428 "ffmpeg decoded a different count"
2429 );
2430
2431 let Ok(mut decoder) = Decoder::new(Config { codec, ..config() }) else {
2432 panic!("no VA-API {codec:?} decoder");
2433 };
2434
2435 let units = split_access_units(codec, &stream);
2436 let mut decoded = Vec::new();
2437 for (index, unit) in units.iter().enumerate() {
2438 if index % 2 == 0 {
2439 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2440 } else {
2441 for exported in decoder
2442 .decode_exported(unit, index as u64)
2443 .expect("decode an access unit")
2444 {
2445 decoded.push(exported.download().expect("download an exported picture"));
2446 }
2447 }
2448 }
2449 decoded.extend(decoder.flush().expect("flush the decoder"));
2450 assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
2451
2452 let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2453 assert!(
2454 timestamps.windows(2).any(|pair| pair[0] > pair[1]),
2455 "the {codec:?} stream came out in decode order, so nothing here tests reordering"
2456 );
2457 timestamps.sort_unstable();
2458 assert_eq!(
2459 timestamps,
2460 (0..PICTURES as u64).collect::<Vec<_>>(),
2461 "a {codec:?} picture's timestamp did not survive reordering"
2462 );
2463
2464 for (index, picture) in decoded.iter().enumerate() {
2465 assert_eq!((picture.width, picture.height), (width, height));
2466 assert!(
2467 picture.data == reference[index * picture_len..][..picture_len],
2468 "{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
2469 );
2470 }
2471 }
2472 }
2473 }
2474
2475 #[test]
2480 #[ignore = "requires a VA-API render node and FFmpeg"]
2481 fn h264_coding_tools_match_a_software_decoder() {
2482 const PICTURES: usize = 40;
2483 let (width, height) = (852u32, 478u32);
2484 let source = format!("testsrc2=size={width}x{height}:rate=30,fade=in:0:20,fade=out:25:15");
2485 let pictures = PICTURES.to_string();
2486 #[rustfmt::skip]
2487 let stream = ffmpeg(&[
2488 "-f", "lavfi", "-i", &source, "-frames:v", &pictures, "-pix_fmt", "yuv420p",
2489 "-c:v", "libx264", "-profile:v", "high", "-bf", "3", "-refs", "4", "-g", "20",
2490 "-x264-params", "slices=3:weightp=2:weightb=1:cqm=jvt:b-pyramid=strict:log-level=error",
2491 "-f", "h264", "-",
2492 ])
2493 .expect("no ffmpeg that encodes H.264");
2494 let reference = software_decode(Codec::H264, &stream);
2495 let picture_len = (width * height * 3 / 2) as usize;
2496 assert_eq!(
2497 reference.len(),
2498 PICTURES * picture_len,
2499 "ffmpeg decoded a different count"
2500 );
2501
2502 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2503 let mut decoded = Vec::new();
2504 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2505 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2506 }
2507 decoded.extend(decoder.flush().expect("flush the decoder"));
2508 assert_eq!(decoded.len(), PICTURES, "lost or invented pictures");
2509 for (index, picture) in decoded.iter().enumerate() {
2510 assert!(
2511 picture.data == reference[index * picture_len..][..picture_len],
2512 "picture {index} differs from the software decoder"
2513 );
2514 }
2515 }
2516
2517 #[test]
2521 #[ignore = "requires a VA-API render node and FFmpeg"]
2522 fn h265_without_reordering_comes_out_as_it_decodes() {
2523 const PICTURES: usize = 10;
2524
2525 let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
2526 let mut decoder = Decoder::new(Config {
2527 codec: Codec::H265,
2528 ..config()
2529 })
2530 .expect("no VA-API H.265 decoder");
2531
2532 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2533 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2534 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2535 assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
2536 }
2537 assert!(decoder.flush().expect("flush the decoder").is_empty());
2538 }
2539
2540 #[test]
2544 #[ignore = "requires a VA-API render node and FFmpeg"]
2545 fn a_4k_h265_wavefront_stream_decodes() {
2546 const PICTURES: usize = 2;
2547 let size = (3840, 2160);
2548
2549 let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
2550 let mut decoder = Decoder::new(Config {
2551 codec: Codec::H265,
2552 ..config()
2553 })
2554 .expect("no VA-API H.265 decoder");
2555
2556 let mut decoded = Vec::new();
2557 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2558 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2559 }
2560 decoded.extend(decoder.flush().expect("flush the decoder"));
2561 assert_eq!(decoded.len(), PICTURES);
2562 assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
2563 }
2564
2565 #[test]
2568 #[ignore = "requires a VA-API render node and FFmpeg"]
2569 fn a_new_h265_sequence_decodes_at_its_own_size() {
2570 const PER_SEQUENCE: usize = 6;
2571 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2572
2573 let mut stream = Vec::new();
2574 for &size in &sizes {
2575 let sequence =
2576 software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
2577 stream.extend(sequence);
2578 }
2579 let mut decoder = Decoder::new(Config {
2580 codec: Codec::H265,
2581 ..config()
2582 })
2583 .expect("no VA-API H.265 decoder");
2584
2585 let mut decoded = Vec::new();
2586 let units = split_access_units(Codec::H265, &stream);
2587 for (index, unit) in units.iter().enumerate() {
2588 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2589 }
2590 decoded.extend(decoder.flush().expect("flush the decoder"));
2591
2592 let expected: Vec<(u32, u32)> = sizes
2593 .iter()
2594 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
2595 .collect();
2596 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2597 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2598
2599 for picture in &decoded {
2600 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2601 assert_eq!(
2602 picture.data.len(),
2603 expected_len,
2604 "a picture was read back at the wrong size"
2605 );
2606 }
2607 }
2608
2609 #[test]
2616 #[ignore = "requires a VA-API render node"]
2617 fn a_new_sequence_decodes_at_its_own_size() {
2618 const PER_SEQUENCE: u32 = 6;
2619 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2620
2621 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2622
2623 let mut decoded = Vec::new();
2624 let mut timestamp = 0u64;
2625 for &(width, height) in &sizes {
2626 let mut encoder =
2627 crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2628 for step in 0..PER_SEQUENCE {
2629 let unit = encoder
2630 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2631 .expect("encode a picture");
2632 decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
2633 timestamp += 1;
2634 }
2635 }
2636 decoded.extend(decoder.flush().expect("flush the decoder"));
2637
2638 let expected: Vec<(u32, u32)> = sizes
2639 .iter()
2640 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
2641 .collect();
2642 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2643 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2644
2645 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2646 assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());
2647
2648 for picture in &decoded {
2649 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2650 assert_eq!(
2651 picture.data.len(),
2652 expected_len,
2653 "a picture was read back at the wrong size"
2654 );
2655 }
2656 }
2657
2658 #[test]
2659 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2660 fn a_refused_sequence_resumes_once_sent_again() {
2661 let (width, height) = (320u32, 240u32);
2662 let stream = software_encode(Codec::H264, (width, height), 4, false).expect("no ffmpeg that encodes H.264");
2663 let units = split_access_units(Codec::H264, &stream);
2664 let source = format!("testsrc2=size={width}x{height}:rate=30");
2665 #[rustfmt::skip]
2666 let high422 = ffmpeg(&[
2667 "-f", "lavfi", "-i", &source, "-frames:v", "1", "-pix_fmt", "yuv422p",
2668 "-c:v", "libx264", "-profile:v", "high422", "-f", "h264", "-",
2669 ])
2670 .expect("no ffmpeg that encodes H.264 4:2:2");
2671
2672 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2673 decoder.decode(&units[0], 0).expect("decode the IDR");
2674 let refused = decoder.decode(&high422, 1).expect_err("a 4:2:2 slice decodes");
2675 assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
2676
2677 let stale = decoder
2680 .decode(&units[1], 2)
2681 .expect_err("a slice decoded against a replaced SPS");
2682 assert!(format!("{stale:#}").contains("Slice"), "{stale:#}");
2683
2684 decoder.decode(&units[0], 3).expect("decode the resent IDR");
2686 }
2687
2688 #[test]
2691 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2692 fn sequences_outside_the_scope_are_refused() {
2693 let source = "testsrc2=size=320x240:rate=30";
2694 #[rustfmt::skip]
2695 let streams = [
2696 &["-flags", "+ildct+ilme", "-x264-params", "interlaced=1", "-pix_fmt", "yuv420p"][..],
2697 &["-pix_fmt", "yuv420p10le", "-profile:v", "high10"][..],
2698 ];
2699 for args in streams {
2700 let mut command = vec!["-f", "lavfi", "-i", source, "-frames:v", "2", "-c:v", "libx264"];
2701 command.extend_from_slice(args);
2702 command.extend_from_slice(&["-f", "h264", "-"]);
2703 let stream = ffmpeg(&command).expect("no ffmpeg that encodes H.264");
2704 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2705 let refused = decoder.decode(&stream, 0).expect_err("decoded out of scope");
2706 assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
2707 }
2708 }
2709
2710 #[test]
2713 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2714 fn a_pps_outlasts_a_sequence_that_cant_read_it() {
2715 let annex_b = |nals: &[&[u8]]| {
2716 nals.iter()
2717 .flat_map(|nal| [&[0, 0, 0, 1][..], nal].concat())
2718 .collect::<Vec<u8>>()
2719 };
2720 let nals = |stream: &[u8]| {
2721 let mut rest = stream;
2722 let mut nals = Vec::new();
2723 while let Some(nal) = kodecs_h264::split_annex_b(&mut rest, usize::MAX).unwrap() {
2724 nals.push((Nalu::new(nal, usize::MAX).unwrap().header.type_, nal.to_vec()));
2725 }
2726 nals
2727 };
2728 let of = |nals: &[(NaluType, Vec<u8>)], type_| -> Vec<Vec<u8>> {
2729 nals.iter()
2730 .filter(|(t, _)| *t == type_)
2731 .map(|(_, nal)| nal.clone())
2732 .collect()
2733 };
2734
2735 let encode = |pix_fmt| {
2737 let source = "testsrc2=size=320x240:rate=30";
2738 #[rustfmt::skip]
2739 let args = ["-f", "lavfi", "-i", source, "-frames:v", "1", "-c:v", "libx264", "-pix_fmt", pix_fmt, "-f", "h264", "-"];
2740 nals(&ffmpeg(&args).expect("no ffmpeg that encodes H.264"))
2741 };
2742 let first = encode("yuv420p");
2743 let (sps, pps, idr) = (
2744 &of(&first, NaluType::Sps)[0],
2745 &of(&first, NaluType::Pps)[0],
2746 of(&first, NaluType::SliceIdr),
2747 );
2748 let idr: Vec<&[u8]> = idr.iter().map(Vec::as_slice).collect();
2749
2750 let mut parser = Parser::new(usize::MAX);
2752 parser.parse(sps).unwrap();
2753 parser.parse(pps).unwrap();
2754 let mut scaled = Pps::clone(parser.pps(0).unwrap());
2755 assert!(scaled.transform_8x8_mode);
2756 scaled.scaling = Some(Matrix {
2757 lists_4x4: vec![16; 96],
2758 lists_8x8: vec![16; 128],
2759 });
2760 let mut scaled_pps = Vec::new();
2761 scaled.write(3, &mut scaled_pps).unwrap();
2762
2763 let sps_444 = &of(&encode("yuv444p"), NaluType::Sps)[0];
2764
2765 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2766 let unit = [annex_b(&[sps]), scaled_pps, annex_b(&idr)].concat();
2767 decoder.decode(&unit, 0).expect("decode the IDR");
2768 decoder.decode(&annex_b(&[sps_444]), 1).expect("take the 4:4:4 SPS");
2770 let refused = decoder
2771 .decode(&annex_b(&idr), 2)
2772 .expect_err("decoded against the 4:4:4 SPS");
2773 assert!(format!("{refused:#}").contains("missing parameter set"), "{refused:#}");
2774 decoder
2775 .decode(&[annex_b(&[sps]), annex_b(&idr)].concat(), 3)
2776 .expect("decode the IDR once its sequence is back");
2777 }
2778
2779 #[test]
2780 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2781 fn a_refused_pps_leaves_the_other_sets_usable() {
2782 let stream = software_encode(Codec::H264, (320, 240), 4, false).expect("no ffmpeg that encodes H.264");
2783 let units = split_access_units(Codec::H264, &stream);
2784
2785 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2786 let mut decoded = decoder.decode(&units[0], 0).expect("decode the IDR");
2787 let refused = decoder
2790 .decode(&[0, 0, 0, 1, 0x68, 0b0100_1010], 1)
2791 .expect_err("a PPS naming a missing SPS decodes");
2792 assert!(format!("{refused:#}").contains("Pps"), "{refused:#}");
2793
2794 for (timestamp, unit) in (2..).zip(&units[1..]) {
2796 decoded.extend(
2797 decoder
2798 .decode(unit, timestamp)
2799 .expect("decode a picture after the refused PPS"),
2800 );
2801 }
2802 decoded.extend(decoder.flush().expect("flush the decoder"));
2803 assert_eq!(decoded.len(), units.len());
2804 }
2805
2806 fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2809 let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
2810 if !output.status.success() {
2811 eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
2812 return None;
2813 }
2814 Some(output.stdout)
2815 }
2816
2817 fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
2821 let source = format!("testsrc2=size={width}x{height}:rate=30");
2822 let pictures = pictures.to_string();
2823 let mut args = vec![
2824 "-f",
2825 "lavfi",
2826 "-i",
2827 &source,
2828 "-frames:v",
2829 &pictures,
2830 "-pix_fmt",
2831 "yuv420p",
2832 ];
2833
2834 let x265;
2835 match codec {
2836 Codec::H264 => args.extend([
2837 "-c:v",
2838 "libx264",
2839 "-profile:v",
2840 "main",
2841 "-bf",
2842 if reorder { "2" } else { "0" },
2843 "-refs",
2844 if reorder { "3" } else { "1" },
2845 "-g",
2846 "15",
2847 "-f",
2848 "h264",
2849 ]),
2850 Codec::H265 => {
2851 x265 = if reorder {
2854 "bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
2855 } else {
2856 "bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
2857 };
2858 args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
2859 }
2860 }
2861 args.push("-");
2862 ffmpeg(&args)
2863 }
2864
2865 fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
2867 static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2870 let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2871 let extension = match codec {
2872 Codec::H264 => "264",
2873 Codec::H265 => "265",
2874 };
2875 let path = std::env::temp_dir().join(format!(
2876 "kodecs-vaapi-decode-{}-{count}.{extension}",
2877 std::process::id()
2878 ));
2879 std::fs::write(&path, stream).expect("write the elementary stream");
2880 let decoded = ffmpeg(&[
2881 "-i",
2882 path.to_str().expect("a UTF-8 temporary path"),
2883 "-pix_fmt",
2884 "nv12",
2885 "-f",
2886 "rawvideo",
2887 "-",
2888 ]);
2889 let _ = std::fs::remove_file(&path);
2890 decoded.expect("ffmpeg decodes what it just encoded")
2891 }
2892
2893 fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
2898 let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
2899 .filter(|&i| stream[i..i + 3] == [0, 0, 1])
2900 .collect();
2901
2902 let mut units = Vec::new();
2903 let mut current: Vec<u8> = Vec::new();
2904 let mut current_has_picture = false;
2905
2906 for (index, &start) in starts.iter().enumerate() {
2907 let end = starts.get(index + 1).copied().unwrap_or(stream.len());
2908 let nal = &stream[start + 3..end];
2909 let (is_slice, starts_picture, starts_unit) = match codec {
2913 Codec::H264 => {
2914 let nal_type = nal[0] & 0x1f;
2915 let is_slice = (1..=5).contains(&nal_type);
2916 (is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
2917 }
2918 Codec::H265 => {
2919 let nal_type = (nal[0] >> 1) & 0x3f;
2920 let is_slice = nal_type <= 31;
2921 (
2922 is_slice,
2923 is_slice && nal[2] & 0x80 != 0,
2924 matches!(nal_type, 32..=35 | 39),
2925 )
2926 }
2927 };
2928
2929 if current_has_picture && (starts_picture || starts_unit) {
2930 units.push(std::mem::take(&mut current));
2931 current_has_picture = false;
2932 }
2933
2934 current.extend_from_slice(&stream[start..end]);
2935 current_has_picture |= is_slice;
2936 }
2937
2938 if !current.is_empty() {
2939 units.push(current);
2940 }
2941 units
2942 }
2943
2944 fn inode(fd: &OwnedFd) -> u64 {
2947 use std::os::unix::fs::MetadataExt as _;
2948
2949 let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
2952 file.metadata().expect("stat the descriptor").ino()
2953 }
2954}