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 format = h264_format(sps)?;
549 self.dpb
552 .set_limits(format.max_dpb_frames, reorder_limit(sps, format.max_dpb_frames));
553 if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
554 return Ok(());
555 }
556
557 self.drain();
561
562 self.sequence = Some(Sequence::new(&self.display, format)?);
563 Ok(())
564 }
565
566 fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
569 let (sps, pps) = (Arc::clone(&slice.sps), Arc::clone(&slice.pps));
570 self.apply_sps(&sps)?;
571
572 if slice.nal.type_ == NaluType::SliceIdr {
573 self.prev_ref_pic_info.frame_num = 0;
574 }
575
576 let frame_num = slice.header.frame_num;
577 if frame_num != self.prev_ref_pic_info.frame_num
578 && frame_num != (self.prev_ref_pic_info.frame_num + 1) % max_frame_num(&sps)
579 {
580 self.handle_frame_num_gap(&sps, frame_num)?;
581 }
582
583 let pic = self.init_current_pic(slice, &sps)?;
584 let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic, &sps);
585
586 let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
588 let context = Rc::clone(&sequence.context);
589 let handle = sequence.handle(timestamp)?;
590
591 let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
592 let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
593 picture.add_buffer(create_buffer(&context, pic_param)?);
594 picture.add_buffer(create_buffer(&context, build_iq_matrix(&sps, &pps))?);
595
596 tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
597 Ok(CurrentPicture {
598 pic,
599 sps,
600 pps,
601 handle,
602 picture,
603 ref_pic_lists,
604 })
605 }
606
607 fn decode_slice(&mut self, current: &mut CurrentPicture, slice: Slice) -> anyhow::Result<()> {
610 if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
614 bail!(
615 "slice starts at macroblock {}, past what a VA slice parameter addresses",
616 slice.header.first_mb_in_slice
617 );
618 }
619 if slice.header.header_bit_size > usize::from(u16::MAX) {
620 bail!(
621 "slice header is {} bits long, past what a VA slice parameter addresses",
622 slice.header.header_bit_size
623 );
624 }
625
626 if !Arc::ptr_eq(&slice.sps, ¤t.sps)
629 && (slice.sps.profile != current.sps.profile || h264_format(&slice.sps)? != h264_format(¤t.sps)?)
630 {
631 bail!("invalid stream: the sequence changed between slices of one picture");
632 }
633 current.sps = slice.sps;
634 current.pps = slice.pps;
635
636 let (list0, list1) =
637 self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.sps, ¤t.ref_pic_lists)?;
638 let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
639
640 let slice_param = build_slice_param(&slice.header, slice.data.len(), &list0, &list1, ¤t.pps);
641 current.picture.add_buffer(create_buffer(context, slice_param)?);
642 current
643 .picture
644 .add_buffer(create_buffer(context, BufferType::SliceData(slice.data))?);
645
646 Ok(())
647 }
648
649 fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
652 let CurrentPicture {
653 mut pic,
654 sps,
655 handle,
656 picture,
657 ..
658 } = current;
659
660 run(picture)?;
661 tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
662
663 if pic.is_ref() {
664 self.reference_pic_marking(&mut pic, &sps)?;
665 self.prev_ref_pic_info.fill(&pic);
666 }
667 self.prev_pic_info.fill(&pic);
668
669 if pic.has_mmco_5 {
672 self.drain();
673 }
674
675 self.dpb
677 .finish_picture(pic, handle, &mut self.ready)
678 .map_err(|e| anyhow!("store picture in DPB: {e}"))?;
679
680 Ok(())
681 }
682
683 fn init_current_pic(&mut self, slice: &Slice, sps: &Sps) -> anyhow::Result<PictureData> {
685 let mut pic = PictureData::new_from_slice(&slice.header, slice.nal, &sps.pic_order_cnt);
686 self.compute_pic_order_count(&mut pic, sps)?;
687
688 if pic.idr {
689 if matches!(pic.marking, Some(Marking::Idr(true, _))) {
692 self.dpb.clear();
693 } else {
694 self.drain();
695 }
696 }
697
698 self.dpb.update_pic_nums(slice.header.frame_num, max_frame_num(sps));
699
700 Ok(pic)
701 }
702
703 fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> anyhow::Result<()> {
706 if self.dpb.is_empty() {
707 return Ok(());
708 }
709
710 if !sps.gaps_in_frame_num_allowed {
711 bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
712 }
713 tracing::debug!("frame_num gap up to {frame_num}");
714
715 let max_frame_num = max_frame_num(sps);
716 let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
717 while unused != frame_num {
718 let mut pic = PictureData::new_non_existing(unused);
719 self.compute_pic_order_count(&mut pic, sps)?;
720
721 self.dpb.update_pic_nums(unused, max_frame_num);
722 self.dpb.sliding_window_marking(sps);
723 self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
724 self.dpb
725 .store_picture(pic, None)
726 .map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
727
728 unused = (unused + 1) % max_frame_num;
729 }
730
731 Ok(())
732 }
733
734 fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
736 pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
737 }
738
739 fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
741 if pic.idr {
742 self.dpb.mark_all_as_unused_for_ref();
743
744 if matches!(pic.marking, Some(Marking::Idr(_, true))) {
745 pic.set_reference(Reference::LongTerm);
746 pic.long_term_frame_idx = 0;
747 self.max_long_term_frame_idx_plus1 = 1;
748 } else {
749 pic.set_reference(Reference::ShortTerm);
750 self.max_long_term_frame_idx_plus1 = 0;
751 }
752
753 return Ok(());
754 }
755
756 match pic.marking.take() {
757 Some(Marking::Adaptive(mmcos)) => self.handle_memory_management_ops(pic, &mmcos)?,
758 _ => self.dpb.sliding_window_marking(sps),
759 }
760
761 Ok(())
762 }
763
764 fn handle_memory_management_ops(&mut self, pic: &mut PictureData, mmcos: &[Mmco]) -> Result<(), MmcoError> {
766 for &mmco in mmcos {
767 match mmco {
768 Mmco::ForgetShort(difference) => self.dpb.mmco_op_1(pic, difference)?,
769 Mmco::ForgetLong(long_term_pic_num) => self.dpb.mmco_op_2(long_term_pic_num)?,
770 Mmco::ShortToLong(difference, idx) => self.dpb.mmco_op_3(pic, difference, idx)?,
771 Mmco::MaxLong(plus1) => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_4(plus1),
772 Mmco::ForgetAll => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_5(pic),
773 Mmco::CurrentToLong(idx) => self.dpb.mmco_op_6(pic, idx),
774 }
775 }
776
777 Ok(())
778 }
779
780 fn create_ref_pic_lists<'a>(
783 &'a self,
784 pic: &PictureData,
785 hdr: &SliceHeader,
786 sps: &Sps,
787 lists: &ReferencePicLists,
788 ) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
789 let max_pic_num = max_frame_num(sps) as i32;
791 let list0 = match hdr.slice_type {
793 SliceType::P => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0, max_pic_num)?,
794 SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0, max_pic_num)?,
795 SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
796 };
797
798 let list1 = match hdr.slice_type {
799 SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1, max_pic_num)?,
800 SliceType::P | SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
801 };
802
803 Ok((list0, list1))
804 }
805
806 fn modify_ref_pic_list<'a>(
808 &'a self,
809 pic: &PictureData,
810 hdr: &SliceHeader,
811 list1: bool,
812 indices: &[usize],
813 max_pic_num: i32,
814 ) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
815 let (active, modifications) = match list1 {
816 true => (hdr.num_ref_idx_l1_active, &hdr.modification_l1),
817 false => (hdr.num_ref_idx_l0_active, &hdr.modification_l0),
818 };
819 let active = usize::from(active);
820
821 let mut list: DpbPicRefList<'a, Handle> =
822 indices.iter().map(|&i| &self.dpb.entries()[i]).take(active).collect();
823
824 let Some(modifications) = modifications else {
825 return Ok(list);
826 };
827
828 let mut pic_num_pred = pic.pic_num;
829 let mut ref_idx = 0;
830
831 for modification in modifications {
832 match modification.idc {
833 idc @ (0 | 1) => self.short_term_modification(
834 pic,
835 &mut list,
836 active,
837 max_pic_num,
838 idc,
839 modification,
840 &mut pic_num_pred,
841 &mut ref_idx,
842 )?,
843 2 => self.long_term_modification(&mut list, active, modification, &mut ref_idx)?,
844 other => bail!("unexpected modification_of_pic_nums_idc {other}"),
845 }
846 }
847
848 Ok(list)
849 }
850
851 fn short_term_modification<'a>(
853 &'a self,
854 pic: &PictureData,
855 list: &mut DpbPicRefList<'a, Handle>,
856 active: usize,
857 max_pic_num: i32,
858 idc: u8,
859 modification: &Modification,
860 pic_num_pred: &mut i32,
861 ref_idx: &mut usize,
862 ) -> anyhow::Result<()> {
863 let abs_diff_pic_num = modification.value as i32 + 1;
865
866 let pic_num_no_wrap = if idc == 0 {
867 if *pic_num_pred - abs_diff_pic_num < 0 {
868 *pic_num_pred - abs_diff_pic_num + max_pic_num
869 } else {
870 *pic_num_pred - abs_diff_pic_num
871 }
872 } else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
873 *pic_num_pred + abs_diff_pic_num - max_pic_num
874 } else {
875 *pic_num_pred + abs_diff_pic_num
876 };
877
878 *pic_num_pred = pic_num_no_wrap;
879
880 let pic_num = if pic_num_no_wrap > pic.pic_num {
881 pic_num_no_wrap - max_pic_num
882 } else {
883 pic_num_no_wrap
884 };
885
886 let entry = self
887 .dpb
888 .find_short_term_with_pic_num(pic_num)
889 .with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
890
891 Self::insert_modification(list, entry, active, ref_idx, |target| {
892 target.pic_num_f(max_pic_num) != pic_num
893 });
894
895 Ok(())
896 }
897
898 fn long_term_modification<'a>(
900 &'a self,
901 list: &mut DpbPicRefList<'a, Handle>,
902 active: usize,
903 modification: &Modification,
904 ref_idx: &mut usize,
905 ) -> anyhow::Result<()> {
906 let long_term_pic_num = modification.value;
907 let max_long_term_frame_idx_plus1 = self.max_long_term_frame_idx_plus1;
908
909 let entry = self
910 .dpb
911 .find_long_term_with_long_term_pic_num(long_term_pic_num)
912 .with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
913
914 Self::insert_modification(list, entry, active, ref_idx, |target| {
915 target.long_term_pic_num_f(max_long_term_frame_idx_plus1) != u64::from(long_term_pic_num)
916 });
917
918 Ok(())
919 }
920
921 fn insert_modification<'a>(
925 list: &mut DpbPicRefList<'a, Handle>,
926 entry: &'a DpbEntry<Handle>,
927 active: usize,
928 ref_idx: &mut usize,
929 keep: impl Fn(&PictureData) -> bool,
930 ) {
931 let at = (*ref_idx).min(list.len());
934 list.insert(at, entry);
935 *ref_idx = at + 1;
936
937 let mut next = *ref_idx;
938 for current in *ref_idx..=active {
939 if current >= list.len() {
940 break;
941 }
942
943 if keep(&list[current].pic) {
944 list[next] = list[current];
945 next += 1;
946 }
947 }
948
949 list.truncate(active);
950 }
951}
952
953struct Slice {
956 header: SliceHeader,
957 sps: Arc<Sps>,
958 pps: Arc<Pps>,
959 nal: NaluHeader,
960 data: Vec<u8>,
962}
963
964struct CurrentPicture {
966 pic: PictureData,
967 sps: Arc<Sps>,
969 pps: Arc<Pps>,
970 handle: Handle,
972 picture: Picture<crate::PictureNew, Handle>,
973 ref_pic_lists: ReferencePicLists,
975}
976
977#[derive(Clone)]
981struct Handle {
982 surface: Arc<PooledSurface>,
983 timestamp: u64,
984 width: u32,
985 height: u32,
986}
987
988impl std::borrow::Borrow<Surface<()>> for Handle {
989 fn borrow(&self) -> &Surface<()> {
990 self.surface.get()
991 }
992}
993
994const SCOPE: &str = "only progressive 8-bit 4:2:0 up to High profile, within its level, decodes";
996
997fn check_scope(sps: &Sps) -> anyhow::Result<()> {
999 sps.check_decoder_scope()
1000 .map_err(|e| anyhow!("H.264 SPS {}: {e}: {SCOPE}", sps.id))
1001}
1002
1003fn h264_format(sps: &Sps) -> anyhow::Result<Format> {
1008 let (right, bottom) = match sps.crop {
1009 Some(crop) if crop.left != 0 || crop.top != 0 => bail!("left and top H.264 cropping is not supported"),
1010 Some(crop) => (crop.right, crop.bottom),
1011 None => (0, 0),
1012 };
1013 let coded = (16 * sps.width_mbs, 16 * sps.height_mbs);
1014 Ok(Format {
1015 codec: Codec::H264,
1016 profile: va_profile(sps.profile)?,
1017 coded,
1018 visible: (coded.0 - right, coded.1 - bottom),
1019 max_dpb_frames: max_dpb_frames(sps),
1020 })
1021}
1022
1023#[derive(Clone, Debug, PartialEq, Eq)]
1026struct Format {
1027 codec: Codec,
1028 profile: VAProfile::Type,
1029 coded: (u32, u32),
1030 visible: (u32, u32),
1032 max_dpb_frames: usize,
1034}
1035
1036struct Sequence {
1038 format: Format,
1039 pool: SurfacePool,
1040 context: Rc<Context>,
1042 _config: VaConfig,
1043}
1044
1045impl Sequence {
1046 fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
1047 let attrs = vec![VAConfigAttrib {
1048 type_: VAConfigAttribType::VAConfigAttribRTFormat,
1049 value: VA_RT_FORMAT_YUV420,
1050 }];
1051 let config = display
1052 .create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
1053 .map_err(|e| anyhow!("create VA config: {e:?}"))?;
1054
1055 let (coded_width, coded_height) = format.coded;
1056 let context = display
1057 .create_context::<()>(&config, coded_width, coded_height, None, true)
1058 .map_err(|e| anyhow!("create VA context: {e:?}"))?;
1059
1060 let (width, height) = format.visible;
1061 tracing::info!(
1062 "VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
1063 VA profile {}, DPB {} frames",
1064 format.codec,
1065 format.profile,
1066 format.max_dpb_frames
1067 );
1068
1069 let capacity = format.max_dpb_frames + 1;
1074 Ok(Self {
1075 pool: SurfacePool::new(
1076 display,
1077 (coded_width, coded_height),
1078 UsageHint::USAGE_HINT_DECODER,
1079 capacity,
1080 ),
1081 format,
1082 context,
1083 _config: config,
1084 })
1085 }
1086
1087 fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
1089 let (width, height) = self.format.visible;
1090 Ok(Handle {
1091 surface: Arc::new(self.pool.alloc()?),
1092 timestamp,
1093 width,
1094 height,
1095 })
1096 }
1097}
1098
1099fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
1105 let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
1106 let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
1107 let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
1108 drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
1109 Ok(())
1110}
1111
1112fn max_dpb_frames(sps: &Sps) -> usize {
1115 match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1116 Some(restriction) => usize::from(restriction.max_dec_frame_buffering.max(1)),
1117 None => usize::from(sps.max_dpb_frames),
1118 }
1119}
1120
1121fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
1130 if matches!(sps.pic_order_cnt, PicOrderCnt::Decode) {
1131 return 0;
1132 }
1133 let declared = match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1134 Some(restriction) => usize::from(restriction.max_num_reorder_frames),
1135 None if matches!(sps.profile.value(), 44 | 86 | 100 | 110 | 122 | 244) && sps.constraint_flags & 0x10 != 0 => 0,
1137 None => max_dpb_frames,
1138 };
1139 declared.min(max_dpb_frames)
1140}
1141
1142fn max_frame_num(sps: &Sps) -> u32 {
1144 1 << sps.log2_max_frame_num
1145}
1146
1147fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
1149 ExportedFrame::export(
1150 Arc::clone(&handle.surface),
1151 handle.timestamp,
1152 (handle.width, handle.height),
1153 )
1154}
1155
1156fn download(handle: &Handle) -> anyhow::Result<Frame> {
1158 read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
1159}
1160
1161fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
1167 surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
1168
1169 let visible = (width, height);
1170
1171 match unsafe { Image::derive_shared(surface, visible) } {
1178 Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
1179 return pack_nv12(&image, timestamp, width, height);
1180 }
1181 Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
1182 Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
1183 }
1184
1185 let format = surface
1186 .display()
1187 .query_image_formats()
1188 .map_err(|e| anyhow!("query image formats: {e:?}"))?
1189 .into_iter()
1190 .find(|format| format.fourcc == VA_FOURCC_NV12)
1191 .context("driver has no NV12 image format")?;
1192 let image = Image::create_from(surface, format, surface.size(), visible)
1193 .map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
1194
1195 pack_nv12(&image, timestamp, width, height)
1196}
1197
1198fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
1201 let va_image = image.image();
1202 let src: &[u8] = image.as_ref();
1203 let (width, height) = (frame_width as usize, frame_height as usize);
1204 let chroma_rows = height / 2;
1205
1206 let mut data = vec![0u8; width * (height + chroma_rows)];
1207 let (luma, chroma) = data.split_at_mut(width * height);
1208 copy_plane(
1209 luma,
1210 src,
1211 va_image.offsets[0] as usize,
1212 va_image.pitches[0] as usize,
1213 width,
1214 height,
1215 )?;
1216 copy_plane(
1217 chroma,
1218 src,
1219 va_image.offsets[1] as usize,
1220 va_image.pitches[1] as usize,
1221 width,
1222 chroma_rows,
1223 )?;
1224
1225 Ok(Frame {
1226 timestamp,
1227 width: frame_width,
1228 height: frame_height,
1229 data,
1230 })
1231}
1232
1233fn copy_plane(
1235 dst: &mut [u8],
1236 src: &[u8],
1237 offset: usize,
1238 pitch: usize,
1239 width: usize,
1240 rows: usize,
1241) -> anyhow::Result<()> {
1242 if rows == 0 {
1243 return Ok(());
1244 }
1245 let end = offset + pitch * (rows - 1) + width;
1246 if pitch < width || src.len() < end {
1247 bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
1248 }
1249
1250 for row in 0..rows {
1251 let from = offset + row * pitch;
1252 dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
1253 }
1254
1255 Ok(())
1256}
1257
1258pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
1266 let profiles = display
1267 .query_config_profiles()
1268 .map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
1269
1270 let supported = profiles
1271 .into_iter()
1272 .filter(|profile| match codec {
1273 Codec::H264 => matches!(
1274 *profile,
1275 VAProfile::VAProfileH264ConstrainedBaseline
1276 | VAProfile::VAProfileH264Main
1277 | VAProfile::VAProfileH264High
1278 ),
1279 Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
1280 })
1281 .any(|profile| {
1282 display
1283 .query_config_entrypoints(profile)
1284 .is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
1285 });
1286
1287 if !supported {
1288 bail!("driver exposes no {codec:?} decode entrypoint");
1289 }
1290
1291 Ok(())
1292}
1293
1294fn va_profile(profile: Profile) -> anyhow::Result<VAProfile::Type> {
1296 Ok(match profile {
1297 Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
1303 Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
1304 Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
1307 other => bail!("unsupported H.264 profile {other:?}"),
1308 })
1309}
1310
1311fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
1312 context
1313 .create_buffer(buffer)
1314 .map_err(|e| anyhow!("create VA buffer: {e:?}"))
1315}
1316
1317fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
1323 let max_frame_num = max_frame_num(sps);
1324 let first = (prev_frame_num + 1) % max_frame_num;
1325 let missing = (frame_num + max_frame_num - first) % max_frame_num;
1326 let window = u32::from(sps.max_num_ref_frames).max(1);
1328 let skipped = missing.saturating_sub(window);
1329 (first + skipped) % max_frame_num
1330}
1331
1332fn pic_order_count(
1338 prev_ref: &PrevReferencePicInfo,
1339 prev: &mut PrevPicInfo,
1340 pic: &mut PictureData,
1341 sps: &Sps,
1342) -> anyhow::Result<()> {
1343 let overflow = || anyhow!("picture order count overflows");
1344 match &sps.pic_order_cnt {
1345 PicOrderCnt::Lsb { log2_max_lsb } => {
1347 let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if pic.idr {
1348 (0, 0)
1349 } else if prev_ref.has_mmco_5 {
1350 (0, prev_ref.top_field_order_cnt)
1351 } else {
1352 (prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
1353 };
1354
1355 let max_pic_order_cnt_lsb: i32 = 1 << log2_max_lsb;
1356 let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
1359 let half = i64::from(max_pic_order_cnt_lsb / 2);
1360
1361 pic.pic_order_cnt_msb = if lsb_delta >= half {
1362 prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
1363 } else if -lsb_delta > half {
1364 prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
1365 } else {
1366 Some(prev_pic_order_cnt_msb)
1367 }
1368 .ok_or_else(overflow)?;
1369
1370 pic.top_field_order_cnt = pic
1371 .pic_order_cnt_msb
1372 .checked_add(pic.pic_order_cnt_lsb)
1373 .ok_or_else(overflow)?;
1374 pic.bottom_field_order_cnt = pic
1375 .top_field_order_cnt
1376 .checked_add(pic.delta_pic_order_cnt_bottom)
1377 .ok_or_else(overflow)?;
1378 }
1379
1380 PicOrderCnt::Cycle {
1382 offset_for_non_ref_pic,
1383 offset_for_top_to_bottom_field,
1384 offset_for_ref_frame,
1385 ..
1386 } => {
1387 if prev.has_mmco_5 {
1388 prev.frame_num_offset = 0;
1389 }
1390
1391 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1392
1393 let mut abs_frame_num = if !offset_for_ref_frame.is_empty() {
1394 pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
1395 } else {
1396 0
1397 };
1398
1399 if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
1400 abs_frame_num -= 1;
1401 }
1402
1403 let mut expected_pic_order_cnt: i128 = 0;
1406
1407 if abs_frame_num > 0 {
1408 let cycle_len = offset_for_ref_frame.len() as u32;
1410 let cycles = (abs_frame_num - 1) / cycle_len;
1411 let position_in_cycle = (abs_frame_num - 1) % cycle_len;
1414 let expected_delta_per_cycle: i128 =
1415 offset_for_ref_frame.iter().map(|&offset| i128::from(offset)).sum();
1416 expected_pic_order_cnt = i128::from(cycles) * expected_delta_per_cycle;
1417
1418 for &offset in &offset_for_ref_frame[..=position_in_cycle as usize] {
1419 expected_pic_order_cnt += i128::from(offset);
1420 }
1421 }
1422
1423 if pic.nal_ref_idc == 0 {
1424 expected_pic_order_cnt += i128::from(*offset_for_non_ref_pic);
1425 }
1426
1427 let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
1428 let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
1429 let to_bottom = i128::from(*offset_for_top_to_bottom_field);
1430 pic.top_field_order_cnt = count(top)?;
1431 pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
1432 }
1433
1434 PicOrderCnt::Decode => {
1436 if prev.has_mmco_5 {
1437 prev.frame_num_offset = 0;
1438 }
1439
1440 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1441
1442 let pic_order_cnt = if pic.idr {
1443 0
1444 } else {
1445 let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
1446 i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
1447 };
1448
1449 pic.top_field_order_cnt = pic_order_cnt;
1450 pic.bottom_field_order_cnt = pic_order_cnt;
1451 }
1452 }
1453
1454 pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);
1455
1456 Ok(())
1457}
1458
1459fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
1462 Ok(if pic.idr {
1463 0
1464 } else if prev.frame_num > pic.frame_num {
1465 prev.frame_num_offset
1466 .checked_add(max_frame_num(sps))
1467 .context("FrameNumOffset overflows")?
1468 } else {
1469 prev.frame_num_offset
1470 })
1471}
1472
1473#[derive(Debug, Default)]
1475struct PrevReferencePicInfo {
1476 frame_num: u32,
1477 has_mmco_5: bool,
1478 top_field_order_cnt: i32,
1479 pic_order_cnt_msb: i32,
1480 pic_order_cnt_lsb: i32,
1481}
1482
1483impl PrevReferencePicInfo {
1484 fn fill(&mut self, pic: &PictureData) {
1485 self.has_mmco_5 = pic.has_mmco_5;
1486 self.top_field_order_cnt = pic.top_field_order_cnt;
1487 self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
1488 self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
1489 self.frame_num = pic.frame_num;
1490 }
1491}
1492
1493#[derive(Debug, Default)]
1495struct PrevPicInfo {
1496 frame_num: u32,
1497 frame_num_offset: u32,
1498 has_mmco_5: bool,
1499}
1500
1501impl PrevPicInfo {
1502 fn fill(&mut self, pic: &PictureData) {
1503 self.frame_num = pic.frame_num;
1504 self.has_mmco_5 = pic.has_mmco_5;
1505 self.frame_num_offset = pic.frame_num_offset;
1506 }
1507}
1508
1509fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
1512 match handle {
1513 Some(handle) => handle.surface.id(),
1514 None => VA_INVALID_ID,
1515 }
1516}
1517
1518fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
1520 let mut flags = 0;
1521 let frame_idx = match pic.reference() {
1522 Reference::LongTerm => {
1523 flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
1524 pic.long_term_frame_idx
1525 }
1526 Reference::ShortTerm => {
1527 flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1528 pic.frame_num
1529 }
1530 Reference::None => pic.frame_num,
1531 };
1532
1533 PictureH264::new(
1534 surface_id,
1535 frame_idx,
1536 flags,
1537 pic.top_field_order_cnt,
1538 pic.bottom_field_order_cnt,
1539 )
1540}
1541
1542fn build_invalid_va_h264_pic() -> PictureH264 {
1544 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1545}
1546
1547fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType {
1550 const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
1551 #[rustfmt::skip]
1552 const ZIGZAG_8X8: [usize; 64] = [
1553 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,
1554 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
1555 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
1556 ];
1557
1558 let flat = Matrix {
1560 lists_4x4: vec![16; 6 * 16],
1561 lists_8x8: vec![16; 2 * 64],
1562 };
1563 let matrix = pps.scaling.as_ref().or(sps.scaling.as_ref()).unwrap_or(&flat);
1564
1565 let mut scaling_list4x4 = [[0u8; 16]; 6];
1566 for (list, src) in scaling_list4x4.iter_mut().zip(matrix.lists_4x4.chunks_exact(16)) {
1567 for (i, &value) in src.iter().enumerate() {
1568 list[ZIGZAG_4X4[i]] = value;
1569 }
1570 }
1571
1572 let mut scaling_list8x8 = [[0u8; 64]; 2];
1573 for (list, src) in scaling_list8x8.iter_mut().zip(matrix.lists_8x8.chunks_exact(64)) {
1574 for (i, &value) in src.iter().enumerate() {
1575 list[ZIGZAG_8X8[i]] = value;
1576 }
1577 }
1578
1579 BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
1580 scaling_list4x4,
1581 scaling_list8x8,
1582 )))
1583}
1584
1585fn build_pic_param(
1587 hdr: &SliceHeader,
1588 pic: &PictureData,
1589 surface_id: bindings::VASurfaceID,
1590 dpb: &Dpb<Handle>,
1591 sps: &Sps,
1592 pps: &Pps,
1593) -> BufferType {
1594 let curr_pic = fill_va_h264_pic(pic, surface_id);
1595
1596 let short_term = dpb.short_term_refs_iter().filter(|entry| !entry.pic.nonexisting);
1597 let mut refs: Vec<PictureH264> = short_term
1598 .chain(dpb.long_term_refs_iter())
1599 .take(16)
1600 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1601 .collect();
1602 refs.resize_with(16, build_invalid_va_h264_pic);
1603 let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
1604
1605 let (pic_order_cnt_type, log2_max_lsb, delta_always_zero) = match sps.pic_order_cnt {
1606 PicOrderCnt::Lsb { log2_max_lsb } => (0, log2_max_lsb, false),
1607 PicOrderCnt::Cycle { delta_always_zero, .. } => (1, 4, delta_always_zero),
1608 PicOrderCnt::Decode => (2, 4, false),
1609 };
1610 let seq_fields = H264SeqFields::new(
1611 1, 0, sps.gaps_in_frame_num_allowed as u32,
1614 1, 0, sps.direct_8x8_inference as u32,
1617 (sps.level.value() >= 31) as u32,
1619 u32::from(sps.log2_max_frame_num - 4),
1620 pic_order_cnt_type,
1621 u32::from(log2_max_lsb - 4),
1622 delta_always_zero as u32,
1623 );
1624
1625 let pic_fields = H264PicFields::new(
1626 pps.entropy_coding_mode as u32,
1627 pps.weighted_pred as u32,
1628 u32::from(pps.weighted_bipred_idc),
1629 pps.transform_8x8_mode as u32,
1630 0, pps.constrained_intra_pred as u32,
1632 pps.bottom_field_pic_order_in_frame_present as u32,
1633 pps.deblocking_filter_control_present as u32,
1634 pps.redundant_pic_cnt_present as u32,
1635 (pic.nal_ref_idc != 0) as u32,
1636 );
1637
1638 BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
1641 curr_pic,
1642 refs,
1643 (sps.width_mbs - 1) as u16,
1644 (sps.height_mbs - 1) as u16,
1645 0, 0, sps.max_num_ref_frames,
1648 &seq_fields,
1649 0,
1651 0,
1652 0,
1653 (pps.pic_init_qp - 26) as i8,
1654 (pps.pic_init_qs - 26) as i8,
1655 pps.chroma_qp_index_offset as i8,
1656 pps.second_chroma_qp_index_offset as i8,
1657 &pic_fields,
1658 hdr.frame_num as u16,
1659 )))
1660}
1661
1662fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
1664 let mut pics: Vec<PictureH264> = list
1665 .iter()
1666 .take(32)
1667 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1668 .collect();
1669 pics.resize_with(32, build_invalid_va_h264_pic);
1670
1671 pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
1672}
1673
1674fn build_slice_param(
1676 hdr: &SliceHeader,
1677 slice_size: usize,
1678 list0: &[&DpbEntry<Handle>],
1679 list1: &[&DpbEntry<Handle>],
1680 pps: &Pps,
1681) -> BufferType {
1682 let mut luma_weight_l0 = [0i16; 32];
1683 let mut luma_offset_l0 = [0i16; 32];
1684 let mut chroma_weight_l0 = [[0i16; 2]; 32];
1685 let mut chroma_offset_l0 = [[0i16; 2]; 32];
1686
1687 let mut luma_weight_l1 = [0i16; 32];
1688 let mut luma_offset_l1 = [0i16; 32];
1689 let mut chroma_weight_l1 = [[0i16; 2]; 32];
1690 let mut chroma_offset_l1 = [[0i16; 2]; 32];
1691
1692 let weights = hdr.weights.as_ref();
1697 let fill = |weights: &[kodecs_h264::Weight],
1698 luma_weight: &mut [i16; 32],
1699 luma_offset: &mut [i16; 32],
1700 chroma_weight: &mut [[i16; 2]; 32],
1701 chroma_offset: &mut [[i16; 2]; 32]| {
1702 for (i, weight) in weights.iter().take(32).enumerate() {
1703 luma_weight[i] = weight.luma_weight as i16;
1704 luma_offset[i] = weight.luma_offset as i16;
1705 chroma_weight[i] = weight.chroma_weight.map(|w| w as i16);
1706 chroma_offset[i] = weight.chroma_offset.map(|o| o as i16);
1707 }
1708 };
1709 if let Some(weights) = weights {
1710 fill(
1711 &weights.l0,
1712 &mut luma_weight_l0,
1713 &mut luma_offset_l0,
1714 &mut chroma_weight_l0,
1715 &mut chroma_offset_l0,
1716 );
1717 fill(
1718 &weights.l1,
1719 &mut luma_weight_l1,
1720 &mut luma_offset_l1,
1721 &mut chroma_weight_l1,
1722 &mut chroma_offset_l1,
1723 );
1724 }
1725 let fill_l0 = weights.is_some();
1726 let fill_l1 = weights.is_some() && hdr.slice_type == SliceType::B;
1727
1728 BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
1731 slice_size as u32,
1732 0,
1733 VA_SLICE_DATA_FLAG_ALL,
1734 hdr.header_bit_size as u16,
1735 hdr.first_mb_in_slice as u16,
1736 hdr.slice_type_raw % 5,
1737 hdr.direct_spatial_mv_pred as u8,
1738 hdr.num_ref_idx_l0_active.saturating_sub(1),
1739 hdr.num_ref_idx_l1_active.saturating_sub(1),
1740 hdr.cabac_init_idc,
1741 (hdr.slice_qp - pps.pic_init_qp) as i8,
1742 hdr.disable_deblocking_filter_idc,
1743 hdr.slice_alpha_c0_offset_div2 as i8,
1744 hdr.slice_beta_offset_div2 as i8,
1745 fill_ref_pic_list(list0),
1746 fill_ref_pic_list(list1),
1747 weights.map_or(0, |w| w.luma_log2_denom),
1748 weights.map_or(0, |w| w.chroma_log2_denom),
1749 fill_l0 as u8,
1750 luma_weight_l0,
1751 luma_offset_l0,
1752 fill_l0 as u8,
1753 chroma_weight_l0,
1754 chroma_offset_l0,
1755 fill_l1 as u8,
1756 luma_weight_l1,
1757 luma_offset_l1,
1758 fill_l1 as u8,
1759 chroma_weight_l1,
1760 chroma_offset_l1,
1761 )))
1762}
1763
1764fn next_nalu<'a>(stream: &mut &'a [u8], max_bytes: usize) -> anyhow::Result<Option<Nalu<'a>>> {
1767 loop {
1768 let Some(raw) = kodecs_h264::split_annex_b(stream, max_bytes).context("frame a NAL unit")? else {
1769 return Ok(None);
1770 };
1771 if !raw.is_empty() {
1772 return Ok(Some(Nalu::new(raw, max_bytes).context("parse a NAL unit header")?));
1773 }
1774 }
1775}
1776
1777#[cfg(test)]
1778mod tests {
1779 use std::process::Command;
1780
1781 use super::*;
1782 use crate::testing::{ffmpeg_decode, inode, nv12_frame};
1783
1784 #[test]
1787 fn a_malformed_header_is_an_error() {
1788 let bytes = [0, 0, 1, 0, 0, 0, 1, 0x09, 0x10, 0, 0, 0, 1, 0x07, 0x42, 0x00, 0x1e];
1790 let mut stream = &bytes[..];
1791 let nalu = next_nalu(&mut stream, usize::MAX).unwrap().expect("a unit");
1792 assert_eq!(nalu.header.type_, NaluType::AuDelimiter);
1793 assert!(next_nalu(&mut stream, usize::MAX).is_err());
1794 assert!(next_nalu(&mut stream, usize::MAX).unwrap().is_none());
1795 }
1796
1797 fn progressive_sps() -> Sps {
1799 kodecs_h264::SpsBuilder::new(Profile::Main, kodecs_h264::Level::L3)
1800 .resolution(320, 240)
1801 .build()
1802 .unwrap()
1803 }
1804
1805 #[test]
1808 fn a_frame_num_gap_invents_only_the_reference_window() {
1809 let mut sps = progressive_sps();
1811 sps.max_num_ref_frames = 2;
1812 assert_eq!(first_invented(3, 4, &sps), 4);
1814 assert_eq!(first_invented(3, 5, &sps), 4);
1816 assert_eq!(first_invented(3, 10, &sps), 8);
1818 assert_eq!(first_invented(14, 3, &sps), 1);
1820 assert_eq!(first_invented(4, 3, &sps), 1);
1822
1823 sps.max_num_ref_frames = 0;
1826 assert_eq!(first_invented(0, 3, &sps), 2);
1827 }
1828
1829 fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
1832 let mut sps = progressive_sps();
1833 sps.pic_order_cnt = PicOrderCnt::Lsb { log2_max_lsb: 8 };
1834 let mut pic = PictureData::default();
1835 pic.pic_order_cnt_lsb = lsb;
1836 pic.nal_ref_idc = 1;
1837 pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
1838 Ok(pic.pic_order_cnt)
1839 }
1840
1841 fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
1842 PrevReferencePicInfo {
1843 pic_order_cnt_msb: msb,
1844 pic_order_cnt_lsb: lsb,
1845 ..Default::default()
1846 }
1847 }
1848
1849 #[test]
1853 fn the_picture_order_count_wraps_and_never_overflows() {
1854 assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
1855 assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
1856 assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
1857 assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
1858 assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
1859
1860 let after_mmco5 = PrevReferencePicInfo {
1863 has_mmco_5: true,
1864 top_field_order_cnt: i32::MIN,
1865 ..Default::default()
1866 };
1867 assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
1868 }
1869
1870 #[test]
1873 fn the_frame_num_offset_never_overflows() {
1874 let mut sps = progressive_sps();
1875 sps.pic_order_cnt = PicOrderCnt::Decode;
1876 let order_count = |frame_num_offset| {
1877 let mut prev = PrevPicInfo {
1878 frame_num: 5,
1879 frame_num_offset,
1880 has_mmco_5: false,
1881 };
1882 let mut pic = PictureData::default();
1883 pic.frame_num = 1;
1884 pic.nal_ref_idc = 1;
1885 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1886 };
1887 assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
1889 assert!(order_count(u32::MAX - 3).is_err());
1890 assert!(order_count(i32::MAX as u32 / 2).is_err());
1892 }
1893
1894 #[test]
1897 fn the_type2_order_count_is_checked_whole() {
1898 let mut sps = progressive_sps();
1899 sps.pic_order_cnt = PicOrderCnt::Decode;
1900 let order_count = |nal_ref_idc| {
1901 let mut prev = PrevPicInfo {
1903 frame_num: 5,
1904 frame_num_offset: (1 << 30) - 17,
1905 has_mmco_5: false,
1906 };
1907 let mut pic = PictureData::default();
1908 pic.frame_num = 1;
1909 pic.nal_ref_idc = nal_ref_idc;
1910 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1911 };
1912 assert_eq!(order_count(0).unwrap(), i32::MAX);
1913 assert!(order_count(1).is_err());
1914 }
1915
1916 #[test]
1919 fn the_type1_bottom_field_is_checked_whole() {
1920 let mut sps = progressive_sps();
1921 sps.pic_order_cnt = PicOrderCnt::Cycle {
1922 delta_always_zero: false,
1923 offset_for_non_ref_pic: 0,
1924 offset_for_top_to_bottom_field: i32::MAX,
1925 offset_for_ref_frame: Vec::new(),
1926 };
1927 let bottom = |delta0, delta1| {
1928 let mut pic = PictureData::default();
1929 pic.nal_ref_idc = 1;
1930 pic.delta_pic_order_cnt0 = delta0;
1931 pic.delta_pic_order_cnt1 = delta1;
1932 pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
1933 .map(|()| pic.bottom_field_order_cnt)
1934 };
1935 assert_eq!(bottom(2, -i32::MAX).unwrap(), 2);
1936 assert!(bottom(2, 0).is_err());
1937 }
1938
1939 #[test]
1940 fn rejects_nonzero_crop_origins() {
1941 for (left, top) in [(2, 0), (0, 2)] {
1942 let mut sps = progressive_sps();
1943 sps.crop = Some(kodecs_h264::Crop {
1944 left,
1945 right: 0,
1946 top,
1947 bottom: 0,
1948 });
1949 assert!(h264_format(&sps).unwrap_err().to_string().contains("left and top"));
1950 }
1951 }
1952
1953 #[test]
1954 fn crop_only_updates_change_sequence_identity() {
1955 let original = h264_format(&progressive_sps()).unwrap();
1956 for (right, bottom, expected) in [(2, 0, (318, 240)), (0, 2, (320, 238))] {
1957 let mut sps = progressive_sps();
1958 sps.crop = Some(kodecs_h264::Crop {
1959 left: 0,
1960 right,
1961 top: 0,
1962 bottom,
1963 });
1964 let cropped = h264_format(&sps).unwrap();
1965 assert_eq!(original.coded, cropped.coded);
1966 assert_eq!(cropped.visible, expected);
1967 assert_ne!(original, cropped);
1968 }
1969 }
1970
1971 fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
1974 crate::encode::Config {
1975 device: Some(crate::testing::device()),
1976 ..crate::encode::Config::new(width, height, 30, 2_000_000, std::num::NonZeroU32::new(30).unwrap())
1977 }
1978 }
1979
1980 fn config() -> Config {
1982 Config {
1983 device: Some(crate::testing::device()),
1984 ..Config::new()
1985 }
1986 }
1987
1988 #[test]
1997 #[ignore = "requires a VA-API render node"]
1998 fn exported_pictures_do_not_share_a_surface() {
1999 let (width, height) = (320u32, 240u32);
2000 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2001 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2002
2003 let mut exported = Vec::new();
2004 for step in 0..8 {
2005 let unit = encoder
2006 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2007 .expect("encode a picture");
2008 exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
2009 }
2010 exported.extend(decoder.flush_exported().expect("flush the decoder"));
2011 assert!(!exported.is_empty(), "the decoder produced no pictures");
2012
2013 let first = &exported[0];
2014 eprintln!(
2015 "exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
2016 exported.len(),
2017 first.width,
2018 first.height,
2019 first.descriptor.fourcc,
2020 first.descriptor.objects[0].drm_format_modifier
2021 );
2022
2023 let mut seen = Vec::new();
2024 for (index, frame) in exported.iter().enumerate() {
2025 assert_eq!((frame.width, frame.height), (width, height));
2026 assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
2027 assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
2028 assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
2029
2030 let inode = inode(&frame.descriptor.objects[0].fd);
2034 assert!(
2035 !seen.contains(&inode),
2036 "picture {index} was decoded into an allocation an earlier one still holds"
2037 );
2038 seen.push(inode);
2039 }
2040 }
2041
2042 #[test]
2045 #[ignore = "requires a VA-API render node"]
2046 fn the_render_node_is_found_or_named() {
2047 if let Err(err) = Decoder::new(Config::new()) {
2048 panic!("no VA-API H.264 decoder: {err:#}");
2049 }
2050 let named = Config {
2051 device: Some(PathBuf::from("/dev/null")),
2052 ..Config::new()
2053 };
2054 assert!(
2055 Decoder::new(named).is_err(),
2056 "a named node that is not a render node was swapped for one that is"
2057 );
2058 }
2059
2060 #[test]
2067 #[ignore = "requires a VA-API render node and FFmpeg"]
2068 fn flush_returns_the_pictures_the_dpb_still_holds() {
2069 const PICTURES: usize = 10;
2070
2071 let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
2072 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2073
2074 let mut streamed = Vec::new();
2075 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2076 streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
2077 }
2078 assert!(
2079 streamed.len() < PICTURES,
2080 "the DPB held nothing back, so this test proves nothing"
2081 );
2082
2083 let flushed = decoder.flush().expect("flush the decoder");
2084 let mut timestamps: Vec<u64> = streamed
2085 .iter()
2086 .chain(&flushed)
2087 .map(|picture| picture.timestamp)
2088 .collect();
2089 timestamps.sort_unstable();
2090 assert_eq!(
2091 timestamps,
2092 (0..PICTURES as u64).collect::<Vec<_>>(),
2093 "the stream lost pictures at its end"
2094 );
2095
2096 assert!(decoder.flush().expect("flush an empty decoder").is_empty());
2099 }
2100
2101 #[test]
2111 #[ignore = "requires a VA-API render node and FFmpeg"]
2112 fn a_stream_without_reordering_comes_out_as_it_decodes() {
2113 const PICTURES: usize = 10;
2114 let (width, height) = (320u32, 240u32);
2115
2116 let mut streams = Vec::new();
2117 match crate::encode::Encoder::new(encoder_config(width, height)) {
2118 Ok(mut encoder) => {
2119 let units = (0..PICTURES)
2120 .map(|step| {
2121 encoder
2122 .encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
2123 .expect("encode a picture")
2124 })
2125 .collect::<Vec<_>>();
2126 streams.push(("VA-API", Codec::H264, units));
2127 }
2128 Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
2129 }
2130 for (encoder, codec) in [("libx264", Codec::H264), ("libx265", Codec::H265)] {
2131 let stream = software_encode(codec, (width, height), PICTURES, false).expect("no ffmpeg that encodes it");
2132 streams.push((encoder, codec, split_access_units(codec, &stream)));
2133 }
2134
2135 for (encoder, codec, units) in streams {
2136 let mut decoder = Decoder::new(Config { codec, ..config() }).expect("no VA-API decoder");
2137 for (index, unit) in units.iter().enumerate() {
2138 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2139 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2140 assert_eq!(
2141 timestamps,
2142 [index as u64],
2143 "{encoder}: access unit {index} was held back"
2144 );
2145 }
2146 assert!(decoder.flush().expect("flush the decoder").is_empty());
2147 }
2148 }
2149
2150 #[test]
2153 fn the_reorder_limit_follows_the_sps() {
2154 let sps = progressive_sps();
2156 assert_eq!(sps.max_dpb_frames, 16);
2157 assert_eq!(max_dpb_frames(&sps), 16);
2158 assert_eq!(
2159 reorder_limit(&sps, 16),
2160 16,
2161 "without a VUI, the inference is the DPB size"
2162 );
2163
2164 let mut intra = progressive_sps();
2165 intra.profile = Profile::High;
2166 intra.constraint_flags = 0x10;
2167 assert_eq!(
2168 reorder_limit(&intra, 16),
2169 0,
2170 "without a VUI, a High intra profile reorders nothing"
2171 );
2172
2173 let restriction = |max_num_reorder_frames, max_dec_frame_buffering| kodecs_h264::Restriction {
2174 motion_vectors_over_pic_boundaries: true,
2175 max_bytes_per_pic_denom: 2,
2176 max_bits_per_mb_denom: 1,
2177 log2_max_mv_length_horizontal: 16,
2178 log2_max_mv_length_vertical: 16,
2179 max_num_reorder_frames,
2180 max_dec_frame_buffering,
2181 };
2182 let mut declared = progressive_sps();
2183 declared.vui = Some(kodecs_h264::Vui {
2184 aspect_ratio: None,
2185 overscan_appropriate: None,
2186 video_signal: None,
2187 chroma_loc: None,
2188 timing: None,
2189 nal_hrd: None,
2190 vcl_hrd: None,
2191 low_delay_hrd: false,
2192 pic_struct_present: false,
2193 restriction: Some(restriction(0, 1)),
2194 });
2195 assert_eq!(max_dpb_frames(&declared), 1, "the VUI's buffering is the DPB size");
2196 assert_eq!(
2197 reorder_limit(&declared, max_dpb_frames(&declared)),
2198 0,
2199 "the VUI's limit applies"
2200 );
2201
2202 if let Some(vui) = declared.vui.as_mut() {
2203 vui.restriction = Some(restriction(5, 2));
2204 }
2205 assert_eq!(
2206 reorder_limit(&declared, max_dpb_frames(&declared)),
2207 2,
2208 "the DPB size bounds the VUI's limit"
2209 );
2210
2211 let mut derived = progressive_sps();
2212 derived.pic_order_cnt = PicOrderCnt::Decode;
2213 assert_eq!(
2214 reorder_limit(&derived, 16),
2215 0,
2216 "an order count from frame_num reorders nothing"
2217 );
2218 }
2219
2220 #[test]
2228 #[ignore = "requires a VA-API render node"]
2229 fn a_dropped_export_is_decoded_into_again() {
2230 const PICTURES: u32 = 60;
2231 let (width, height) = (320u32, 240u32);
2232 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2233 let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
2234 let mut downloading = Decoder::new(config()).expect("a second decoder");
2235
2236 let mut compared = 0;
2237 for step in 0..PICTURES {
2238 let unit = encoder
2239 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2240 .expect("encode a picture");
2241 let exported = exporting
2242 .decode_exported(&unit, step as u64)
2243 .expect("decode to a descriptor");
2244 let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
2245 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2246 for (gpu, cpu) in exported.iter().zip(&downloaded) {
2247 let read_back = gpu.download().expect("read the exported surface back");
2248 assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
2249 compared += 1;
2250 }
2251 }
2252 assert!(compared > 0, "the decoder produced no pictures");
2253
2254 let pool = &exporting.sequence().expect("a sequence").pool;
2255 let allocated = pool.allocated.get();
2256 eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
2257 assert!(
2258 allocated <= pool.free.capacity,
2259 "{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
2260 pool.free.capacity
2261 );
2262 }
2263
2264 #[test]
2267 #[ignore = "requires a VA-API render node"]
2268 fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
2269 const HELD: u32 = 40;
2270 let (width, height) = (320u32, 240u32);
2271 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2272 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2273
2274 let mut step = 0;
2275 let mut decode = |decoder: &mut Decoder| {
2276 let unit = encoder
2277 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2278 .expect("encode a picture");
2279 step += 1;
2280 decoder.decode_exported(&unit, step as u64).expect("decode a picture")
2281 };
2282
2283 let mut held = Vec::new();
2284 for _ in 0..HELD {
2285 held.extend(decode(&mut decoder));
2286 }
2287 let pool = &decoder.sequence().expect("a sequence").pool;
2288 let allocated = pool.allocated.get();
2289 assert!(
2290 allocated >= held.len(),
2291 "{} pictures held on {allocated} surfaces",
2292 held.len()
2293 );
2294
2295 drop(held);
2296 let free = pool.free.surfaces.lock().unwrap().len();
2297 assert!(
2298 free <= pool.free.capacity,
2299 "{free} surfaces left free, more than the capacity of {}",
2300 pool.free.capacity
2301 );
2302
2303 for _ in 0..10 {
2304 drop(decode(&mut decoder));
2305 }
2306 let pool = &decoder.sequence().expect("a sequence").pool;
2307 assert_eq!(
2308 pool.allocated.get(),
2309 allocated,
2310 "pictures after the release did not reuse the free surfaces"
2311 );
2312 }
2313
2314 #[test]
2319 fn an_exported_frame_is_send_and_sync() {
2320 const fn assert_send_sync<T: Send + Sync>() {}
2321 assert_send_sync::<ExportedFrame>();
2322 }
2323
2324 #[test]
2333 #[ignore = "requires a VA-API render node"]
2334 fn an_exported_picture_downloads_to_the_same_pixels() {
2335 let (width, height) = (320u32, 240u32);
2336 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2337 let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
2338 let mut downloading = Decoder::new(config()).expect("a second decoder");
2339
2340 let mut exported = Vec::new();
2341 let mut downloaded = Vec::new();
2342 for step in 0..8 {
2343 let unit = encoder
2344 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2345 .expect("encode a picture");
2346 exported.extend(
2347 exporting
2348 .decode_exported(&unit, step as u64)
2349 .expect("decode to a descriptor"),
2350 );
2351 downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
2352 }
2353 exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
2354 downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
2355
2356 assert!(!exported.is_empty(), "the decoder produced no pictures");
2357 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2358
2359 for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
2360 let read_back = gpu.download().expect("read the exported surface back");
2361 assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
2362 assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
2363 assert!(
2364 read_back.data == cpu.data,
2365 "picture {index} read back differently than it downloaded"
2366 );
2367 }
2368 }
2369
2370 #[test]
2380 #[ignore = "requires a VA-API render node and FFmpeg"]
2381 fn decoded_pictures_match_a_software_decoder() {
2382 const PICTURES: usize = 30;
2383
2384 for codec in [Codec::H264, Codec::H265] {
2385 for (width, height) in [(320u32, 240u32), (852, 478)] {
2386 let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
2387 panic!("no ffmpeg that encodes {codec:?}");
2388 };
2389 let reference = ffmpeg_decode(codec, &stream);
2390
2391 let picture_len = (width * height * 3 / 2) as usize;
2392 assert_eq!(
2393 reference.len(),
2394 PICTURES * picture_len,
2395 "ffmpeg decoded a different count"
2396 );
2397
2398 let Ok(mut decoder) = Decoder::new(Config { codec, ..config() }) else {
2399 panic!("no VA-API {codec:?} decoder");
2400 };
2401
2402 let units = split_access_units(codec, &stream);
2403 let mut decoded = Vec::new();
2404 for (index, unit) in units.iter().enumerate() {
2405 if index % 2 == 0 {
2406 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2407 } else {
2408 for exported in decoder
2409 .decode_exported(unit, index as u64)
2410 .expect("decode an access unit")
2411 {
2412 decoded.push(exported.download().expect("download an exported picture"));
2413 }
2414 }
2415 }
2416 decoded.extend(decoder.flush().expect("flush the decoder"));
2417 assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
2418
2419 let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2420 assert!(
2421 timestamps.windows(2).any(|pair| pair[0] > pair[1]),
2422 "the {codec:?} stream came out in decode order, so nothing here tests reordering"
2423 );
2424 timestamps.sort_unstable();
2425 assert_eq!(
2426 timestamps,
2427 (0..PICTURES as u64).collect::<Vec<_>>(),
2428 "a {codec:?} picture's timestamp did not survive reordering"
2429 );
2430
2431 for (index, picture) in decoded.iter().enumerate() {
2432 assert_eq!((picture.width, picture.height), (width, height));
2433 assert!(
2434 picture.data == reference[index * picture_len..][..picture_len],
2435 "{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
2436 );
2437 }
2438 }
2439 }
2440 }
2441
2442 #[test]
2447 #[ignore = "requires a VA-API render node and FFmpeg"]
2448 fn h264_coding_tools_match_a_software_decoder() {
2449 const PICTURES: usize = 40;
2450 let (width, height) = (852u32, 478u32);
2451 let source = format!("testsrc2=size={width}x{height}:rate=30,fade=in:0:20,fade=out:25:15");
2452 let pictures = PICTURES.to_string();
2453 #[rustfmt::skip]
2454 let stream = ffmpeg(&[
2455 "-f", "lavfi", "-i", &source, "-frames:v", &pictures, "-pix_fmt", "yuv420p",
2456 "-c:v", "libx264", "-profile:v", "high", "-bf", "3", "-refs", "4", "-g", "20",
2457 "-x264-params", "slices=3:weightp=2:weightb=1:cqm=jvt:b-pyramid=strict:log-level=error",
2458 "-f", "h264", "-",
2459 ])
2460 .expect("no ffmpeg that encodes H.264");
2461 let reference = ffmpeg_decode(Codec::H264, &stream);
2462 let picture_len = (width * height * 3 / 2) as usize;
2463 assert_eq!(
2464 reference.len(),
2465 PICTURES * picture_len,
2466 "ffmpeg decoded a different count"
2467 );
2468
2469 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2470 let mut decoded = Vec::new();
2471 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2472 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2473 }
2474 decoded.extend(decoder.flush().expect("flush the decoder"));
2475 assert_eq!(decoded.len(), PICTURES, "lost or invented pictures");
2476 for (index, picture) in decoded.iter().enumerate() {
2477 assert!(
2478 picture.data == reference[index * picture_len..][..picture_len],
2479 "picture {index} differs from the software decoder"
2480 );
2481 }
2482 }
2483
2484 #[test]
2488 #[ignore = "requires a VA-API render node and FFmpeg"]
2489 fn a_4k_h265_wavefront_stream_decodes() {
2490 const PICTURES: usize = 2;
2491 let size = (3840, 2160);
2492
2493 let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
2494 let mut decoder = Decoder::new(Config {
2495 codec: Codec::H265,
2496 ..config()
2497 })
2498 .expect("no VA-API H.265 decoder");
2499
2500 let mut decoded = Vec::new();
2501 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2502 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2503 }
2504 decoded.extend(decoder.flush().expect("flush the decoder"));
2505 assert_eq!(decoded.len(), PICTURES);
2506 assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
2507 }
2508
2509 #[test]
2516 #[ignore = "requires a VA-API render node and FFmpeg"]
2517 fn a_new_sequence_decodes_at_its_own_size() {
2518 const PER_SEQUENCE: usize = 6;
2519 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2520
2521 for codec in [Codec::H264, Codec::H265] {
2522 let mut stream = Vec::new();
2523 for &size in &sizes {
2524 stream.extend(software_encode(codec, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes it"));
2525 }
2526 let mut decoder = Decoder::new(Config { codec, ..config() }).expect("no VA-API decoder");
2527
2528 let mut decoded = Vec::new();
2529 let units = split_access_units(codec, &stream);
2530 for (index, unit) in units.iter().enumerate() {
2531 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2532 }
2533 decoded.extend(decoder.flush().expect("flush the decoder"));
2534
2535 let expected: Vec<(u32, u32)> = sizes
2536 .iter()
2537 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
2538 .collect();
2539 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2540 assert_eq!(
2541 actual, expected,
2542 "{codec:?}: a picture came out at the wrong size or out of order"
2543 );
2544
2545 for picture in &decoded {
2546 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2547 assert_eq!(
2548 picture.data.len(),
2549 expected_len,
2550 "a picture was read back at the wrong size"
2551 );
2552 }
2553 }
2554 }
2555
2556 #[test]
2557 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2558 fn a_refused_sequence_resumes_once_sent_again() {
2559 let (width, height) = (320u32, 240u32);
2560 let stream = software_encode(Codec::H264, (width, height), 4, false).expect("no ffmpeg that encodes H.264");
2561 let units = split_access_units(Codec::H264, &stream);
2562 let source = format!("testsrc2=size={width}x{height}:rate=30");
2563 #[rustfmt::skip]
2564 let high422 = ffmpeg(&[
2565 "-f", "lavfi", "-i", &source, "-frames:v", "1", "-pix_fmt", "yuv422p",
2566 "-c:v", "libx264", "-profile:v", "high422", "-f", "h264", "-",
2567 ])
2568 .expect("no ffmpeg that encodes H.264 4:2:2");
2569
2570 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2571 decoder.decode(&units[0], 0).expect("decode the IDR");
2572 let refused = decoder.decode(&high422, 1).expect_err("a 4:2:2 slice decodes");
2573 assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
2574
2575 let stale = decoder
2578 .decode(&units[1], 2)
2579 .expect_err("a slice decoded against a replaced SPS");
2580 assert!(format!("{stale:#}").contains("Slice"), "{stale:#}");
2581
2582 decoder.decode(&units[0], 3).expect("decode the resent IDR");
2584 }
2585
2586 #[test]
2589 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2590 fn sequences_outside_the_scope_are_refused() {
2591 let source = "testsrc2=size=320x240:rate=30";
2592 #[rustfmt::skip]
2593 let streams = [
2594 &["-flags", "+ildct+ilme", "-x264-params", "interlaced=1", "-pix_fmt", "yuv420p"][..],
2595 &["-pix_fmt", "yuv420p10le", "-profile:v", "high10"][..],
2596 ];
2597 for args in streams {
2598 let mut command = vec!["-f", "lavfi", "-i", source, "-frames:v", "2", "-c:v", "libx264"];
2599 command.extend_from_slice(args);
2600 command.extend_from_slice(&["-f", "h264", "-"]);
2601 let stream = ffmpeg(&command).expect("no ffmpeg that encodes H.264");
2602 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2603 let refused = decoder.decode(&stream, 0).expect_err("decoded out of scope");
2604 assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
2605 }
2606 }
2607
2608 #[test]
2611 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2612 fn a_pps_outlasts_a_sequence_that_cant_read_it() {
2613 let annex_b = |nals: &[&[u8]]| {
2614 nals.iter()
2615 .flat_map(|nal| [&[0, 0, 0, 1][..], nal].concat())
2616 .collect::<Vec<u8>>()
2617 };
2618 let nals = |stream: &[u8]| {
2619 let mut rest = stream;
2620 let mut nals = Vec::new();
2621 while let Some(nal) = kodecs_h264::split_annex_b(&mut rest, usize::MAX).unwrap() {
2622 nals.push((Nalu::new(nal, usize::MAX).unwrap().header.type_, nal.to_vec()));
2623 }
2624 nals
2625 };
2626 let of = |nals: &[(NaluType, Vec<u8>)], type_| -> Vec<Vec<u8>> {
2627 nals.iter()
2628 .filter(|(t, _)| *t == type_)
2629 .map(|(_, nal)| nal.clone())
2630 .collect()
2631 };
2632
2633 let encode = |pix_fmt| {
2635 let source = "testsrc2=size=320x240:rate=30";
2636 #[rustfmt::skip]
2637 let args = ["-f", "lavfi", "-i", source, "-frames:v", "1", "-c:v", "libx264", "-pix_fmt", pix_fmt, "-f", "h264", "-"];
2638 nals(&ffmpeg(&args).expect("no ffmpeg that encodes H.264"))
2639 };
2640 let first = encode("yuv420p");
2641 let (sps, pps, idr) = (
2642 &of(&first, NaluType::Sps)[0],
2643 &of(&first, NaluType::Pps)[0],
2644 of(&first, NaluType::SliceIdr),
2645 );
2646 let idr: Vec<&[u8]> = idr.iter().map(Vec::as_slice).collect();
2647
2648 let mut parser = Parser::new(usize::MAX);
2650 parser.parse(sps).unwrap();
2651 parser.parse(pps).unwrap();
2652 let mut scaled = Pps::clone(parser.pps(0).unwrap());
2653 assert!(scaled.transform_8x8_mode);
2654 scaled.scaling = Some(Matrix {
2655 lists_4x4: vec![16; 96],
2656 lists_8x8: vec![16; 128],
2657 });
2658 let mut scaled_pps = Vec::new();
2659 scaled.write(3, &mut scaled_pps).unwrap();
2660
2661 let sps_444 = &of(&encode("yuv444p"), NaluType::Sps)[0];
2662
2663 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2664 let unit = [annex_b(&[sps]), scaled_pps, annex_b(&idr)].concat();
2665 decoder.decode(&unit, 0).expect("decode the IDR");
2666 decoder.decode(&annex_b(&[sps_444]), 1).expect("take the 4:4:4 SPS");
2668 let refused = decoder
2669 .decode(&annex_b(&idr), 2)
2670 .expect_err("decoded against the 4:4:4 SPS");
2671 assert!(format!("{refused:#}").contains("missing parameter set"), "{refused:#}");
2672 decoder
2673 .decode(&[annex_b(&[sps]), annex_b(&idr)].concat(), 3)
2674 .expect("decode the IDR once its sequence is back");
2675 }
2676
2677 #[test]
2678 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2679 fn a_refused_pps_leaves_the_other_sets_usable() {
2680 let stream = software_encode(Codec::H264, (320, 240), 4, false).expect("no ffmpeg that encodes H.264");
2681 let units = split_access_units(Codec::H264, &stream);
2682
2683 let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
2684 let mut decoded = decoder.decode(&units[0], 0).expect("decode the IDR");
2685 let refused = decoder
2688 .decode(&[0, 0, 0, 1, 0x68, 0b0100_1010], 1)
2689 .expect_err("a PPS naming a missing SPS decodes");
2690 assert!(format!("{refused:#}").contains("Pps"), "{refused:#}");
2691
2692 for (timestamp, unit) in (2..).zip(&units[1..]) {
2694 decoded.extend(
2695 decoder
2696 .decode(unit, timestamp)
2697 .expect("decode a picture after the refused PPS"),
2698 );
2699 }
2700 decoded.extend(decoder.flush().expect("flush the decoder"));
2701 assert_eq!(decoded.len(), units.len());
2702 }
2703
2704 fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2707 let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
2708 if !output.status.success() {
2709 eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
2710 return None;
2711 }
2712 Some(output.stdout)
2713 }
2714
2715 fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
2719 let source = format!("testsrc2=size={width}x{height}:rate=30");
2720 let pictures = pictures.to_string();
2721 let mut args = vec![
2722 "-f",
2723 "lavfi",
2724 "-i",
2725 &source,
2726 "-frames:v",
2727 &pictures,
2728 "-pix_fmt",
2729 "yuv420p",
2730 ];
2731
2732 let x265;
2733 match codec {
2734 Codec::H264 => args.extend([
2735 "-c:v",
2736 "libx264",
2737 "-profile:v",
2738 "main",
2739 "-bf",
2740 if reorder { "2" } else { "0" },
2741 "-refs",
2742 if reorder { "3" } else { "1" },
2743 "-g",
2744 "15",
2745 "-f",
2746 "h264",
2747 ]),
2748 Codec::H265 => {
2749 x265 = if reorder {
2752 "bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
2753 } else {
2754 "bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
2755 };
2756 args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
2757 }
2758 }
2759 args.push("-");
2760 ffmpeg(&args)
2761 }
2762
2763 fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
2768 let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
2769 .filter(|&i| stream[i..i + 3] == [0, 0, 1])
2770 .collect();
2771
2772 let mut units = Vec::new();
2773 let mut current: Vec<u8> = Vec::new();
2774 let mut current_has_picture = false;
2775
2776 for (index, &start) in starts.iter().enumerate() {
2777 let end = starts.get(index + 1).copied().unwrap_or(stream.len());
2778 let nal = &stream[start + 3..end];
2779 let (is_slice, starts_picture, starts_unit) = match codec {
2783 Codec::H264 => {
2784 let nal_type = nal[0] & 0x1f;
2785 let is_slice = (1..=5).contains(&nal_type);
2786 (is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
2787 }
2788 Codec::H265 => {
2789 let nal_type = (nal[0] >> 1) & 0x3f;
2790 let is_slice = nal_type <= 31;
2791 (
2792 is_slice,
2793 is_slice && nal[2] & 0x80 != 0,
2794 matches!(nal_type, 32..=35 | 39),
2795 )
2796 }
2797 };
2798
2799 if current_has_picture && (starts_picture || starts_unit) {
2800 units.push(std::mem::take(&mut current));
2801 current_has_picture = false;
2802 }
2803
2804 current.extend_from_slice(&stream[start..end]);
2805 current_has_picture |= is_slice;
2806 }
2807
2808 if !current.is_empty() {
2809 units.push(current);
2810 }
2811 units
2812 }
2813}