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 dpb: Dpb<Handle>,
267 prev_ref_pic_info: PrevReferencePicInfo,
269 prev_pic_info: PrevPicInfo,
271 max_long_term_frame_idx_plus1: u32,
273 sequence: Option<Sequence>,
276 ready: Vec<Handle>,
278 display: Arc<Display>,
280}
281
282impl Decoder {
283 pub fn new(config: Config) -> anyhow::Result<Self> {
293 let codec = config.codec;
294 let (device, display) = match config.device {
295 Some(device) => {
296 let display =
297 Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
298 probe(&display, codec)?;
299 (device, display)
300 }
301 None => crate::display::open_first(|display| probe(display, codec))
302 .map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
303 };
304
305 tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
306 let inner = match codec {
307 Codec::H264 => Inner::H264(H264::new(display)),
308 Codec::H265 => Inner::H265(h265::Decoder::new(display)),
309 };
310 Ok(Self { inner })
311 }
312
313 pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
321 self.submit(access_unit, timestamp)?;
322 self.take_frames()
323 }
324
325 pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
344 self.submit(access_unit, timestamp)?;
345 self.take_exported()
346 }
347
348 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
352 let nalus = match &mut self.inner {
353 Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
354 Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
355 };
356
357 if nalus == 0 && !access_unit.is_empty() {
362 tracing::warn!(
363 "access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
364 access_unit.len()
365 );
366 }
367 Ok(())
368 }
369
370 pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
381 self.reset();
382 self.take_frames()
383 }
384
385 pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
387 self.reset();
388 self.take_exported()
389 }
390
391 fn reset(&mut self) {
394 match &mut self.inner {
395 Inner::H264(decoder) => decoder.reset(),
396 Inner::H265(decoder) => decoder.reset(),
397 }
398 }
399
400 fn ready(&mut self) -> &mut Vec<Handle> {
402 match &mut self.inner {
403 Inner::H264(decoder) => &mut decoder.ready,
404 Inner::H265(decoder) => &mut decoder.ready,
405 }
406 }
407
408 fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
410 std::mem::take(self.ready()).iter().map(download).collect()
411 }
412
413 fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
416 std::mem::take(self.ready()).iter().map(export).collect()
417 }
418
419 #[cfg(test)]
421 fn sequence(&self) -> Option<&Sequence> {
422 match &self.inner {
423 Inner::H264(decoder) => decoder.sequence.as_ref(),
424 Inner::H265(decoder) => decoder.sequence.as_ref(),
425 }
426 }
427}
428
429impl H264 {
430 fn new(display: Arc<Display>) -> Self {
431 Self {
432 parser: Parser::new(usize::MAX),
436 dpb: Dpb::default(),
437 prev_ref_pic_info: PrevReferencePicInfo::default(),
438 prev_pic_info: PrevPicInfo::default(),
439 max_long_term_frame_idx_plus1: 0,
440 sequence: None,
441 ready: Vec::new(),
442 display,
443 }
444 }
445
446 fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
448 let mut stream = access_unit;
449 let mut current: Option<CurrentPicture> = None;
450 let mut nalus = 0usize;
451
452 loop {
453 let before = stream;
454 let Some(nalu) = next_nalu(&mut stream, self.parser.max_nal_bytes())? else {
455 break;
456 };
457 nalus += 1;
458 let nal = nalu.header;
459 match nal.type_ {
460 NaluType::Sps | NaluType::Pps | NaluType::Slice | NaluType::SliceIdr | NaluType::SliceDpa => {}
462 other => {
465 tracing::trace!("ignoring NAL unit of type {other:?}");
466 continue;
467 }
468 }
469
470 let mut sent = &before[..before.len() - stream.len()];
474 let unit = self
475 .parser
476 .next(&mut sent)
477 .map_err(|e| match e {
478 kodecs_h264::Error::Unsupported => anyhow!(
479 "{:?} NAL unit: {e}: only progressive 8-bit 4:2:0 up to High profile decodes",
480 nal.type_
481 ),
482 e => anyhow!(e).context(format!("parse a {:?} NAL unit", nal.type_)),
483 })?
484 .expect("the unit framed above");
485 let Unit::Slice(header) = unit else {
486 continue;
487 };
488 let start = nalu.payload.as_ptr() as usize - before.as_ptr() as usize - 1;
490 let data = before[start..start + 1 + nalu.payload.len()].to_vec();
491 let slice = Slice { header, nal, data };
492
493 let mut picture = match current.take() {
494 Some(picture) if slice.header.first_mb_in_slice == 0 => {
498 self.finish_picture(picture)?;
499 self.begin_picture(&slice, timestamp)?
500 }
501 Some(picture) => picture,
502 None => self.begin_picture(&slice, timestamp)?,
503 };
504
505 self.decode_slice(&mut picture, slice)?;
506 current = Some(picture);
507 }
508
509 if let Some(picture) = current.take() {
512 self.finish_picture(picture)?;
513 }
514
515 Ok(nalus)
516 }
517
518 fn reset(&mut self) {
521 self.drain();
522 self.prev_ref_pic_info = PrevReferencePicInfo::default();
523 self.prev_pic_info = PrevPicInfo::default();
524 self.max_long_term_frame_idx_plus1 = 0;
525 }
526
527 fn drain(&mut self) {
529 self.ready.extend(self.dpb.drain().into_iter().flatten());
530 }
531
532 fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
535 let info = SequenceInfo::new(sps)?;
536 self.dpb
539 .set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));
540
541 let format = Format {
542 codec: Codec::H264,
543 profile: va_profile(info.profile)?,
544 coded: info.coded,
545 visible: info.visible,
546 max_dpb_frames: info.max_dpb_frames,
547 };
548 if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
549 return Ok(());
550 }
551
552 self.drain();
556
557 self.sequence = Some(Sequence::new(&self.display, format)?);
558 Ok(())
559 }
560
561 fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
564 let (sps, pps) = self.parameter_sets(&slice.header)?;
565 self.apply_sps(&sps)?;
566
567 if slice.nal.type_ == NaluType::SliceIdr {
568 self.prev_ref_pic_info.frame_num = 0;
569 }
570
571 let frame_num = slice.header.frame_num;
572 if frame_num != self.prev_ref_pic_info.frame_num
573 && frame_num != (self.prev_ref_pic_info.frame_num + 1) % max_frame_num(&sps)
574 {
575 self.handle_frame_num_gap(&sps, frame_num)?;
576 }
577
578 let pic = self.init_current_pic(slice, &sps)?;
579 let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic, &sps);
580
581 let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
583 let context = Rc::clone(&sequence.context);
584 let handle = sequence.handle(timestamp)?;
585
586 let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
587 let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
588 picture.add_buffer(create_buffer(&context, pic_param)?);
589 picture.add_buffer(create_buffer(&context, build_iq_matrix(&sps, &pps))?);
590
591 tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
592 Ok(CurrentPicture {
593 pic,
594 sps,
595 pps,
596 handle,
597 picture,
598 ref_pic_lists,
599 })
600 }
601
602 fn parameter_sets(&self, header: &SliceHeader) -> anyhow::Result<(Sps, Pps)> {
604 let pps = self
605 .parser
606 .pps(header.pps_id)
607 .context("slice refers to an unknown PPS")?;
608 let sps = self.parser.sps(pps.sps_id).context("PPS refers to an unknown SPS")?;
609 Ok((sps.clone(), pps.clone()))
610 }
611
612 fn decode_slice(&mut self, current: &mut CurrentPicture, slice: Slice) -> anyhow::Result<()> {
615 if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
619 bail!(
620 "slice starts at macroblock {}, past what a VA slice parameter addresses",
621 slice.header.first_mb_in_slice
622 );
623 }
624 if slice.header.header_bit_size > usize::from(u16::MAX) {
625 bail!(
626 "slice header is {} bits long, past what a VA slice parameter addresses",
627 slice.header.header_bit_size
628 );
629 }
630
631 let (sps, pps) = self.parameter_sets(&slice.header)?;
634 if SequenceInfo::new(&sps)? != SequenceInfo::new(¤t.sps)? {
635 bail!("invalid stream: the sequence changed between slices of one picture");
636 }
637 current.sps = sps;
638 current.pps = pps;
639
640 let (list0, list1) =
641 self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.sps, ¤t.ref_pic_lists)?;
642 let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
643
644 let slice_param = build_slice_param(&slice.header, slice.data.len(), &list0, &list1, ¤t.pps);
645 current.picture.add_buffer(create_buffer(context, slice_param)?);
646 current
647 .picture
648 .add_buffer(create_buffer(context, BufferType::SliceData(slice.data))?);
649
650 Ok(())
651 }
652
653 fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
656 let CurrentPicture {
657 mut pic,
658 sps,
659 handle,
660 picture,
661 ..
662 } = current;
663
664 run(picture)?;
665 tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
666
667 if pic.is_ref() {
668 self.reference_pic_marking(&mut pic, &sps)?;
669 self.prev_ref_pic_info.fill(&pic);
670 }
671 self.prev_pic_info.fill(&pic);
672
673 if pic.has_mmco_5 {
676 self.drain();
677 }
678
679 self.dpb
681 .finish_picture(pic, handle, &mut self.ready)
682 .map_err(|e| anyhow!("store picture in DPB: {e}"))?;
683
684 Ok(())
685 }
686
687 fn init_current_pic(&mut self, slice: &Slice, sps: &Sps) -> anyhow::Result<PictureData> {
689 let mut pic = PictureData::new_from_slice(&slice.header, slice.nal, &sps.pic_order_cnt);
690 self.compute_pic_order_count(&mut pic, sps)?;
691
692 if pic.idr {
693 if matches!(pic.marking, Some(Marking::Idr(true, _))) {
696 self.dpb.clear();
697 } else {
698 self.drain();
699 }
700 }
701
702 self.dpb.update_pic_nums(slice.header.frame_num, max_frame_num(sps));
703
704 Ok(pic)
705 }
706
707 fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> anyhow::Result<()> {
710 if self.dpb.is_empty() {
711 return Ok(());
712 }
713
714 if !sps.gaps_in_frame_num_allowed {
715 bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
716 }
717 tracing::debug!("frame_num gap up to {frame_num}");
718
719 let max_frame_num = max_frame_num(sps);
720 let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
721 while unused != frame_num {
722 let mut pic = PictureData::new_non_existing(unused);
723 self.compute_pic_order_count(&mut pic, sps)?;
724
725 self.dpb.update_pic_nums(unused, max_frame_num);
726 self.dpb.sliding_window_marking(sps);
727 self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
728 self.dpb
729 .store_picture(pic, None)
730 .map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
731
732 unused = (unused + 1) % max_frame_num;
733 }
734
735 Ok(())
736 }
737
738 fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
740 pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
741 }
742
743 fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
745 if pic.idr {
746 self.dpb.mark_all_as_unused_for_ref();
747
748 if matches!(pic.marking, Some(Marking::Idr(_, true))) {
749 pic.set_reference(Reference::LongTerm);
750 pic.long_term_frame_idx = 0;
751 self.max_long_term_frame_idx_plus1 = 1;
752 } else {
753 pic.set_reference(Reference::ShortTerm);
754 self.max_long_term_frame_idx_plus1 = 0;
755 }
756
757 return Ok(());
758 }
759
760 match pic.marking.take() {
761 Some(Marking::Adaptive(mmcos)) => self.handle_memory_management_ops(pic, &mmcos)?,
762 _ => self.dpb.sliding_window_marking(sps),
763 }
764
765 Ok(())
766 }
767
768 fn handle_memory_management_ops(&mut self, pic: &mut PictureData, mmcos: &[Mmco]) -> Result<(), MmcoError> {
770 for &mmco in mmcos {
771 match mmco {
772 Mmco::ForgetShort(difference) => self.dpb.mmco_op_1(pic, difference)?,
773 Mmco::ForgetLong(long_term_pic_num) => self.dpb.mmco_op_2(long_term_pic_num)?,
774 Mmco::ShortToLong(difference, idx) => self.dpb.mmco_op_3(pic, difference, idx)?,
775 Mmco::MaxLong(plus1) => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_4(plus1),
776 Mmco::ForgetAll => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_5(pic),
777 Mmco::CurrentToLong(idx) => self.dpb.mmco_op_6(pic, idx),
778 }
779 }
780
781 Ok(())
782 }
783
784 fn create_ref_pic_lists<'a>(
787 &'a self,
788 pic: &PictureData,
789 hdr: &SliceHeader,
790 sps: &Sps,
791 lists: &ReferencePicLists,
792 ) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
793 let max_pic_num = max_frame_num(sps) as i32;
795 let list0 = match hdr.slice_type {
796 SliceType::P => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0, max_pic_num)?,
797 SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0, max_pic_num)?,
798 SliceType::I => Vec::new(),
799 };
800
801 let list1 = match hdr.slice_type {
802 SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1, max_pic_num)?,
803 SliceType::P | SliceType::I => Vec::new(),
804 };
805
806 Ok((list0, list1))
807 }
808
809 fn modify_ref_pic_list<'a>(
811 &'a self,
812 pic: &PictureData,
813 hdr: &SliceHeader,
814 list1: bool,
815 indices: &[usize],
816 max_pic_num: i32,
817 ) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
818 let (active, modifications) = match list1 {
819 true => (hdr.num_ref_idx_l1_active, &hdr.modification_l1),
820 false => (hdr.num_ref_idx_l0_active, &hdr.modification_l0),
821 };
822 let active = usize::from(active);
823
824 let mut list: DpbPicRefList<'a, Handle> =
825 indices.iter().map(|&i| &self.dpb.entries()[i]).take(active).collect();
826
827 let Some(modifications) = modifications else {
828 return Ok(list);
829 };
830
831 let mut pic_num_pred = pic.pic_num;
832 let mut ref_idx = 0;
833
834 for modification in modifications {
835 match modification.idc {
836 idc @ (0 | 1) => self.short_term_modification(
837 pic,
838 &mut list,
839 active,
840 max_pic_num,
841 idc,
842 modification,
843 &mut pic_num_pred,
844 &mut ref_idx,
845 )?,
846 2 => self.long_term_modification(&mut list, active, modification, &mut ref_idx)?,
847 other => bail!("unexpected modification_of_pic_nums_idc {other}"),
848 }
849 }
850
851 Ok(list)
852 }
853
854 fn short_term_modification<'a>(
856 &'a self,
857 pic: &PictureData,
858 list: &mut DpbPicRefList<'a, Handle>,
859 active: usize,
860 max_pic_num: i32,
861 idc: u8,
862 modification: &Modification,
863 pic_num_pred: &mut i32,
864 ref_idx: &mut usize,
865 ) -> anyhow::Result<()> {
866 let abs_diff_pic_num = modification.value as i32 + 1;
868
869 let pic_num_no_wrap = if idc == 0 {
870 if *pic_num_pred - abs_diff_pic_num < 0 {
871 *pic_num_pred - abs_diff_pic_num + max_pic_num
872 } else {
873 *pic_num_pred - abs_diff_pic_num
874 }
875 } else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
876 *pic_num_pred + abs_diff_pic_num - max_pic_num
877 } else {
878 *pic_num_pred + abs_diff_pic_num
879 };
880
881 *pic_num_pred = pic_num_no_wrap;
882
883 let pic_num = if pic_num_no_wrap > pic.pic_num {
884 pic_num_no_wrap - max_pic_num
885 } else {
886 pic_num_no_wrap
887 };
888
889 let entry = self
890 .dpb
891 .find_short_term_with_pic_num(pic_num)
892 .with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
893
894 Self::insert_modification(list, entry, active, ref_idx, |target| {
895 target.pic_num_f(max_pic_num) != pic_num
896 });
897
898 Ok(())
899 }
900
901 fn long_term_modification<'a>(
903 &'a self,
904 list: &mut DpbPicRefList<'a, Handle>,
905 active: usize,
906 modification: &Modification,
907 ref_idx: &mut usize,
908 ) -> anyhow::Result<()> {
909 let long_term_pic_num = modification.value;
910 let max_long_term_frame_idx_plus1 = self.max_long_term_frame_idx_plus1;
911
912 let entry = self
913 .dpb
914 .find_long_term_with_long_term_pic_num(long_term_pic_num)
915 .with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
916
917 Self::insert_modification(list, entry, active, ref_idx, |target| {
918 target.long_term_pic_num_f(max_long_term_frame_idx_plus1) != u64::from(long_term_pic_num)
919 });
920
921 Ok(())
922 }
923
924 fn insert_modification<'a>(
928 list: &mut DpbPicRefList<'a, Handle>,
929 entry: &'a DpbEntry<Handle>,
930 active: usize,
931 ref_idx: &mut usize,
932 keep: impl Fn(&PictureData) -> bool,
933 ) {
934 let at = (*ref_idx).min(list.len());
937 list.insert(at, entry);
938 *ref_idx = at + 1;
939
940 let mut next = *ref_idx;
941 for current in *ref_idx..=active {
942 if current >= list.len() {
943 break;
944 }
945
946 if keep(&list[current].pic) {
947 list[next] = list[current];
948 next += 1;
949 }
950 }
951
952 list.truncate(active);
953 }
954}
955
956struct Slice {
958 header: SliceHeader,
959 nal: NaluHeader,
960 data: Vec<u8>,
962}
963
964struct CurrentPicture {
966 pic: PictureData,
967 sps: Sps,
969 pps: 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
994#[derive(Clone, Debug, PartialEq, Eq)]
997struct SequenceInfo {
998 visible: (u32, u32),
999 coded: (u32, u32),
1000 profile: Profile,
1001 max_dpb_frames: usize,
1002}
1003
1004impl SequenceInfo {
1005 fn new(sps: &Sps) -> anyhow::Result<Self> {
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
1015 Ok(Self {
1016 visible: (coded.0 - right, coded.1 - bottom),
1017 coded,
1018 profile: sps.profile,
1019 max_dpb_frames: max_dpb_frames(sps),
1020 })
1021 }
1022}
1023
1024#[derive(Clone, Debug, PartialEq, Eq)]
1027struct Format {
1028 codec: Codec,
1029 profile: VAProfile::Type,
1030 coded: (u32, u32),
1031 visible: (u32, u32),
1033 max_dpb_frames: usize,
1035}
1036
1037struct Sequence {
1039 format: Format,
1040 pool: SurfacePool,
1041 context: Rc<Context>,
1043 _config: VaConfig,
1044}
1045
1046impl Sequence {
1047 fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
1048 let attrs = vec![VAConfigAttrib {
1049 type_: VAConfigAttribType::VAConfigAttribRTFormat,
1050 value: VA_RT_FORMAT_YUV420,
1051 }];
1052 let config = display
1053 .create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
1054 .map_err(|e| anyhow!("create VA config: {e:?}"))?;
1055
1056 let (coded_width, coded_height) = format.coded;
1057 let context = display
1058 .create_context::<()>(&config, coded_width, coded_height, None, true)
1059 .map_err(|e| anyhow!("create VA context: {e:?}"))?;
1060
1061 let (width, height) = format.visible;
1062 tracing::info!(
1063 "VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
1064 VA profile {}, DPB {} frames",
1065 format.codec,
1066 format.profile,
1067 format.max_dpb_frames
1068 );
1069
1070 let capacity = format.max_dpb_frames + 1;
1075 Ok(Self {
1076 pool: SurfacePool::new(
1077 display,
1078 (coded_width, coded_height),
1079 UsageHint::USAGE_HINT_DECODER,
1080 capacity,
1081 ),
1082 format,
1083 context,
1084 _config: config,
1085 })
1086 }
1087
1088 fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
1090 let (width, height) = self.format.visible;
1091 Ok(Handle {
1092 surface: Arc::new(self.pool.alloc()?),
1093 timestamp,
1094 width,
1095 height,
1096 })
1097 }
1098}
1099
1100fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
1106 let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
1107 let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
1108 let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
1109 drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
1110 Ok(())
1111}
1112
1113fn max_dpb_frames(sps: &Sps) -> usize {
1116 match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1117 Some(restriction) => usize::from(restriction.max_dec_frame_buffering.max(1)),
1118 None => usize::from(sps.max_dpb_frames),
1119 }
1120}
1121
1122fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
1131 if matches!(sps.pic_order_cnt, PicOrderCnt::Decode) {
1132 return 0;
1133 }
1134 let declared = match sps.vui.as_ref().and_then(|vui| vui.restriction) {
1135 Some(restriction) => usize::from(restriction.max_num_reorder_frames),
1136 None if matches!(sps.profile.value(), 44 | 86 | 100 | 110 | 122 | 244) && sps.constraint_flags & 0x10 != 0 => 0,
1138 None => max_dpb_frames,
1139 };
1140 declared.min(max_dpb_frames)
1141}
1142
1143fn max_frame_num(sps: &Sps) -> u32 {
1145 1 << sps.log2_max_frame_num
1146}
1147
1148fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
1150 ExportedFrame::export(
1151 Arc::clone(&handle.surface),
1152 handle.timestamp,
1153 (handle.width, handle.height),
1154 )
1155}
1156
1157fn download(handle: &Handle) -> anyhow::Result<Frame> {
1159 read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
1160}
1161
1162fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
1168 surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
1169
1170 let visible = (width, height);
1171
1172 match unsafe { Image::derive_shared(surface, visible) } {
1179 Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
1180 return pack_nv12(&image, timestamp, width, height);
1181 }
1182 Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
1183 Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
1184 }
1185
1186 let format = surface
1187 .display()
1188 .query_image_formats()
1189 .map_err(|e| anyhow!("query image formats: {e:?}"))?
1190 .into_iter()
1191 .find(|format| format.fourcc == VA_FOURCC_NV12)
1192 .context("driver has no NV12 image format")?;
1193 let image = Image::create_from(surface, format, surface.size(), visible)
1194 .map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
1195
1196 pack_nv12(&image, timestamp, width, height)
1197}
1198
1199fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
1202 let va_image = image.image();
1203 let src: &[u8] = image.as_ref();
1204 let (width, height) = (frame_width as usize, frame_height as usize);
1205 let chroma_rows = height / 2;
1206
1207 let mut data = vec![0u8; width * (height + chroma_rows)];
1208 let (luma, chroma) = data.split_at_mut(width * height);
1209 copy_plane(
1210 luma,
1211 src,
1212 va_image.offsets[0] as usize,
1213 va_image.pitches[0] as usize,
1214 width,
1215 height,
1216 )?;
1217 copy_plane(
1218 chroma,
1219 src,
1220 va_image.offsets[1] as usize,
1221 va_image.pitches[1] as usize,
1222 width,
1223 chroma_rows,
1224 )?;
1225
1226 Ok(Frame {
1227 timestamp,
1228 width: frame_width,
1229 height: frame_height,
1230 data,
1231 })
1232}
1233
1234fn copy_plane(
1236 dst: &mut [u8],
1237 src: &[u8],
1238 offset: usize,
1239 pitch: usize,
1240 width: usize,
1241 rows: usize,
1242) -> anyhow::Result<()> {
1243 if rows == 0 {
1244 return Ok(());
1245 }
1246 let end = offset + pitch * (rows - 1) + width;
1247 if pitch < width || src.len() < end {
1248 bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
1249 }
1250
1251 for row in 0..rows {
1252 let from = offset + row * pitch;
1253 dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
1254 }
1255
1256 Ok(())
1257}
1258
1259pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
1267 let profiles = display
1268 .query_config_profiles()
1269 .map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
1270
1271 let supported = profiles
1272 .into_iter()
1273 .filter(|profile| match codec {
1274 Codec::H264 => matches!(
1275 *profile,
1276 VAProfile::VAProfileH264ConstrainedBaseline
1277 | VAProfile::VAProfileH264Main
1278 | VAProfile::VAProfileH264High
1279 ),
1280 Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
1281 })
1282 .any(|profile| {
1283 display
1284 .query_config_entrypoints(profile)
1285 .is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
1286 });
1287
1288 if !supported {
1289 bail!("driver exposes no {codec:?} decode entrypoint");
1290 }
1291
1292 Ok(())
1293}
1294
1295fn va_profile(profile: Profile) -> anyhow::Result<VAProfile::Type> {
1297 Ok(match profile {
1298 Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
1304 Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
1305 Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
1308 other => bail!("unsupported H.264 profile {other:?}"),
1309 })
1310}
1311
1312fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
1313 context
1314 .create_buffer(buffer)
1315 .map_err(|e| anyhow!("create VA buffer: {e:?}"))
1316}
1317
1318fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
1324 let max_frame_num = max_frame_num(sps);
1325 let first = (prev_frame_num + 1) % max_frame_num;
1326 let missing = (frame_num + max_frame_num - first) % max_frame_num;
1327 let window = u32::from(sps.max_num_ref_frames).max(1);
1329 let skipped = missing.saturating_sub(window);
1330 (first + skipped) % max_frame_num
1331}
1332
1333fn pic_order_count(
1339 prev_ref: &PrevReferencePicInfo,
1340 prev: &mut PrevPicInfo,
1341 pic: &mut PictureData,
1342 sps: &Sps,
1343) -> anyhow::Result<()> {
1344 let overflow = || anyhow!("picture order count overflows");
1345 match &sps.pic_order_cnt {
1346 PicOrderCnt::Lsb { log2_max_lsb } => {
1348 let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if pic.idr {
1349 (0, 0)
1350 } else if prev_ref.has_mmco_5 {
1351 (0, prev_ref.top_field_order_cnt)
1352 } else {
1353 (prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
1354 };
1355
1356 let max_pic_order_cnt_lsb: i32 = 1 << log2_max_lsb;
1357 let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
1360 let half = i64::from(max_pic_order_cnt_lsb / 2);
1361
1362 pic.pic_order_cnt_msb = if lsb_delta >= half {
1363 prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
1364 } else if -lsb_delta > half {
1365 prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
1366 } else {
1367 Some(prev_pic_order_cnt_msb)
1368 }
1369 .ok_or_else(overflow)?;
1370
1371 pic.top_field_order_cnt = pic
1372 .pic_order_cnt_msb
1373 .checked_add(pic.pic_order_cnt_lsb)
1374 .ok_or_else(overflow)?;
1375 pic.bottom_field_order_cnt = pic
1376 .top_field_order_cnt
1377 .checked_add(pic.delta_pic_order_cnt_bottom)
1378 .ok_or_else(overflow)?;
1379 }
1380
1381 PicOrderCnt::Cycle {
1383 offset_for_non_ref_pic,
1384 offset_for_top_to_bottom_field,
1385 offset_for_ref_frame,
1386 ..
1387 } => {
1388 if prev.has_mmco_5 {
1389 prev.frame_num_offset = 0;
1390 }
1391
1392 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1393
1394 let mut abs_frame_num = if !offset_for_ref_frame.is_empty() {
1395 pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
1396 } else {
1397 0
1398 };
1399
1400 if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
1401 abs_frame_num -= 1;
1402 }
1403
1404 let mut expected_pic_order_cnt: i128 = 0;
1407
1408 if abs_frame_num > 0 {
1409 let cycle_len = offset_for_ref_frame.len() as u32;
1411 let cycles = (abs_frame_num - 1) / cycle_len;
1412 let position_in_cycle = (abs_frame_num - 1) % cycle_len;
1415 let expected_delta_per_cycle: i128 =
1416 offset_for_ref_frame.iter().map(|&offset| i128::from(offset)).sum();
1417 expected_pic_order_cnt = i128::from(cycles) * expected_delta_per_cycle;
1418
1419 for &offset in &offset_for_ref_frame[..=position_in_cycle as usize] {
1420 expected_pic_order_cnt += i128::from(offset);
1421 }
1422 }
1423
1424 if pic.nal_ref_idc == 0 {
1425 expected_pic_order_cnt += i128::from(*offset_for_non_ref_pic);
1426 }
1427
1428 let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
1429 let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
1430 let to_bottom = i128::from(*offset_for_top_to_bottom_field);
1431 pic.top_field_order_cnt = count(top)?;
1432 pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
1433 }
1434
1435 PicOrderCnt::Decode => {
1437 if prev.has_mmco_5 {
1438 prev.frame_num_offset = 0;
1439 }
1440
1441 pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1442
1443 let pic_order_cnt = if pic.idr {
1444 0
1445 } else {
1446 let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
1447 i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
1448 };
1449
1450 pic.top_field_order_cnt = pic_order_cnt;
1451 pic.bottom_field_order_cnt = pic_order_cnt;
1452 }
1453 }
1454
1455 pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);
1456
1457 Ok(())
1458}
1459
1460fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
1463 Ok(if pic.idr {
1464 0
1465 } else if prev.frame_num > pic.frame_num {
1466 prev.frame_num_offset
1467 .checked_add(max_frame_num(sps))
1468 .context("FrameNumOffset overflows")?
1469 } else {
1470 prev.frame_num_offset
1471 })
1472}
1473
1474#[derive(Debug, Default)]
1476struct PrevReferencePicInfo {
1477 frame_num: u32,
1478 has_mmco_5: bool,
1479 top_field_order_cnt: i32,
1480 pic_order_cnt_msb: i32,
1481 pic_order_cnt_lsb: i32,
1482}
1483
1484impl PrevReferencePicInfo {
1485 fn fill(&mut self, pic: &PictureData) {
1486 self.has_mmco_5 = pic.has_mmco_5;
1487 self.top_field_order_cnt = pic.top_field_order_cnt;
1488 self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
1489 self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
1490 self.frame_num = pic.frame_num;
1491 }
1492}
1493
1494#[derive(Debug, Default)]
1496struct PrevPicInfo {
1497 frame_num: u32,
1498 frame_num_offset: u32,
1499 has_mmco_5: bool,
1500}
1501
1502impl PrevPicInfo {
1503 fn fill(&mut self, pic: &PictureData) {
1504 self.frame_num = pic.frame_num;
1505 self.has_mmco_5 = pic.has_mmco_5;
1506 self.frame_num_offset = pic.frame_num_offset;
1507 }
1508}
1509
1510fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
1513 match handle {
1514 Some(handle) => handle.surface.id(),
1515 None => VA_INVALID_ID,
1516 }
1517}
1518
1519fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
1521 let mut flags = 0;
1522 let frame_idx = match pic.reference() {
1523 Reference::LongTerm => {
1524 flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
1525 pic.long_term_frame_idx
1526 }
1527 Reference::ShortTerm => {
1528 flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1529 pic.frame_num
1530 }
1531 Reference::None => pic.frame_num,
1532 };
1533
1534 PictureH264::new(
1535 surface_id,
1536 frame_idx,
1537 flags,
1538 pic.top_field_order_cnt,
1539 pic.bottom_field_order_cnt,
1540 )
1541}
1542
1543fn build_invalid_va_h264_pic() -> PictureH264 {
1545 PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1546}
1547
1548fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType {
1551 const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
1552 #[rustfmt::skip]
1553 const ZIGZAG_8X8: [usize; 64] = [
1554 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,
1555 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
1556 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
1557 ];
1558
1559 let flat = Matrix {
1561 lists_4x4: vec![16; 6 * 16],
1562 lists_8x8: vec![16; 2 * 64],
1563 };
1564 let matrix = pps.scaling.as_ref().or(sps.scaling.as_ref()).unwrap_or(&flat);
1565
1566 let mut scaling_list4x4 = [[0u8; 16]; 6];
1567 for (list, src) in scaling_list4x4.iter_mut().zip(matrix.lists_4x4.chunks_exact(16)) {
1568 for (i, &value) in src.iter().enumerate() {
1569 list[ZIGZAG_4X4[i]] = value;
1570 }
1571 }
1572
1573 let mut scaling_list8x8 = [[0u8; 64]; 2];
1574 for (list, src) in scaling_list8x8.iter_mut().zip(matrix.lists_8x8.chunks_exact(64)) {
1575 for (i, &value) in src.iter().enumerate() {
1576 list[ZIGZAG_8X8[i]] = value;
1577 }
1578 }
1579
1580 BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
1581 scaling_list4x4,
1582 scaling_list8x8,
1583 )))
1584}
1585
1586fn build_pic_param(
1588 hdr: &SliceHeader,
1589 pic: &PictureData,
1590 surface_id: bindings::VASurfaceID,
1591 dpb: &Dpb<Handle>,
1592 sps: &Sps,
1593 pps: &Pps,
1594) -> BufferType {
1595 let curr_pic = fill_va_h264_pic(pic, surface_id);
1596
1597 let short_term = dpb.short_term_refs_iter().filter(|entry| !entry.pic.nonexisting);
1598 let mut refs: Vec<PictureH264> = short_term
1599 .chain(dpb.long_term_refs_iter())
1600 .take(16)
1601 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1602 .collect();
1603 refs.resize_with(16, build_invalid_va_h264_pic);
1604 let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
1605
1606 let (pic_order_cnt_type, log2_max_lsb, delta_always_zero) = match sps.pic_order_cnt {
1607 PicOrderCnt::Lsb { log2_max_lsb } => (0, log2_max_lsb, false),
1608 PicOrderCnt::Cycle { delta_always_zero, .. } => (1, 4, delta_always_zero),
1609 PicOrderCnt::Decode => (2, 4, false),
1610 };
1611 let seq_fields = H264SeqFields::new(
1612 1, 0, sps.gaps_in_frame_num_allowed as u32,
1615 1, 0, sps.direct_8x8_inference as u32,
1618 (sps.level.value() >= 31) as u32,
1620 u32::from(sps.log2_max_frame_num - 4),
1621 pic_order_cnt_type,
1622 u32::from(log2_max_lsb - 4),
1623 delta_always_zero as u32,
1624 );
1625
1626 let pic_fields = H264PicFields::new(
1627 pps.entropy_coding_mode as u32,
1628 pps.weighted_pred as u32,
1629 u32::from(pps.weighted_bipred_idc),
1630 pps.transform_8x8_mode as u32,
1631 0, pps.constrained_intra_pred as u32,
1633 pps.bottom_field_pic_order_in_frame_present as u32,
1634 pps.deblocking_filter_control_present as u32,
1635 pps.redundant_pic_cnt_present as u32,
1636 (pic.nal_ref_idc != 0) as u32,
1637 );
1638
1639 BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
1642 curr_pic,
1643 refs,
1644 (sps.width_mbs - 1) as u16,
1645 (sps.height_mbs - 1) as u16,
1646 0, 0, sps.max_num_ref_frames,
1649 &seq_fields,
1650 0,
1652 0,
1653 0,
1654 (pps.pic_init_qp - 26) as i8,
1655 (pps.pic_init_qs - 26) as i8,
1656 pps.chroma_qp_index_offset as i8,
1657 pps.second_chroma_qp_index_offset as i8,
1658 &pic_fields,
1659 hdr.frame_num as u16,
1660 )))
1661}
1662
1663fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
1665 let mut pics: Vec<PictureH264> = list
1666 .iter()
1667 .take(32)
1668 .map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
1669 .collect();
1670 pics.resize_with(32, build_invalid_va_h264_pic);
1671
1672 pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
1673}
1674
1675fn build_slice_param(
1677 hdr: &SliceHeader,
1678 slice_size: usize,
1679 list0: &[&DpbEntry<Handle>],
1680 list1: &[&DpbEntry<Handle>],
1681 pps: &Pps,
1682) -> BufferType {
1683 let mut luma_weight_l0 = [0i16; 32];
1684 let mut luma_offset_l0 = [0i16; 32];
1685 let mut chroma_weight_l0 = [[0i16; 2]; 32];
1686 let mut chroma_offset_l0 = [[0i16; 2]; 32];
1687
1688 let mut luma_weight_l1 = [0i16; 32];
1689 let mut luma_offset_l1 = [0i16; 32];
1690 let mut chroma_weight_l1 = [[0i16; 2]; 32];
1691 let mut chroma_offset_l1 = [[0i16; 2]; 32];
1692
1693 let weights = hdr.weights.as_ref();
1698 let fill = |weights: &[kodecs_h264::Weight],
1699 luma_weight: &mut [i16; 32],
1700 luma_offset: &mut [i16; 32],
1701 chroma_weight: &mut [[i16; 2]; 32],
1702 chroma_offset: &mut [[i16; 2]; 32]| {
1703 for (i, weight) in weights.iter().take(32).enumerate() {
1704 luma_weight[i] = weight.luma_weight as i16;
1705 luma_offset[i] = weight.luma_offset as i16;
1706 chroma_weight[i] = weight.chroma_weight.map(|w| w as i16);
1707 chroma_offset[i] = weight.chroma_offset.map(|o| o as i16);
1708 }
1709 };
1710 if let Some(weights) = weights {
1711 fill(
1712 &weights.l0,
1713 &mut luma_weight_l0,
1714 &mut luma_offset_l0,
1715 &mut chroma_weight_l0,
1716 &mut chroma_offset_l0,
1717 );
1718 fill(
1719 &weights.l1,
1720 &mut luma_weight_l1,
1721 &mut luma_offset_l1,
1722 &mut chroma_weight_l1,
1723 &mut chroma_offset_l1,
1724 );
1725 }
1726 let fill_l0 = weights.is_some();
1727 let fill_l1 = weights.is_some() && hdr.slice_type == SliceType::B;
1728
1729 BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
1732 slice_size as u32,
1733 0,
1734 VA_SLICE_DATA_FLAG_ALL,
1735 hdr.header_bit_size as u16,
1736 hdr.first_mb_in_slice as u16,
1737 hdr.slice_type_raw % 5,
1738 hdr.direct_spatial_mv_pred as u8,
1739 hdr.num_ref_idx_l0_active.saturating_sub(1),
1740 hdr.num_ref_idx_l1_active.saturating_sub(1),
1741 hdr.cabac_init_idc,
1742 (hdr.slice_qp - pps.pic_init_qp) as i8,
1743 hdr.disable_deblocking_filter_idc,
1744 hdr.slice_alpha_c0_offset_div2 as i8,
1745 hdr.slice_beta_offset_div2 as i8,
1746 fill_ref_pic_list(list0),
1747 fill_ref_pic_list(list1),
1748 weights.map_or(0, |w| w.luma_log2_denom),
1749 weights.map_or(0, |w| w.chroma_log2_denom),
1750 fill_l0 as u8,
1751 luma_weight_l0,
1752 luma_offset_l0,
1753 fill_l0 as u8,
1754 chroma_weight_l0,
1755 chroma_offset_l0,
1756 fill_l1 as u8,
1757 luma_weight_l1,
1758 luma_offset_l1,
1759 fill_l1 as u8,
1760 chroma_weight_l1,
1761 chroma_offset_l1,
1762 )))
1763}
1764
1765fn next_nalu<'a>(stream: &mut &'a [u8], max_bytes: usize) -> anyhow::Result<Option<Nalu<'a>>> {
1768 loop {
1769 let Some(raw) = kodecs_h264::split_annex_b(stream, max_bytes).context("frame a NAL unit")? else {
1770 return Ok(None);
1771 };
1772 if !raw.is_empty() {
1773 return Ok(Some(Nalu::new(raw, max_bytes).context("parse a NAL unit header")?));
1774 }
1775 }
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780 use std::os::fd::OwnedFd;
1781 use std::process::Command;
1782
1783 use super::*;
1784
1785 #[test]
1788 fn a_malformed_header_is_an_error() {
1789 let bytes = [0, 0, 1, 0, 0, 0, 1, 0x09, 0x10, 0, 0, 0, 1, 0x07, 0x42, 0x00, 0x1e];
1791 let mut stream = &bytes[..];
1792 let nalu = next_nalu(&mut stream, usize::MAX).unwrap().expect("a unit");
1793 assert_eq!(nalu.header.type_, NaluType::AuDelimiter);
1794 assert!(next_nalu(&mut stream, usize::MAX).is_err());
1795 assert!(next_nalu(&mut stream, usize::MAX).unwrap().is_none());
1796 }
1797
1798 fn progressive_sps() -> Sps {
1800 kodecs_h264::SpsBuilder::new(Profile::Main, kodecs_h264::Level::L3)
1801 .resolution(320, 240)
1802 .build()
1803 .unwrap()
1804 }
1805
1806 #[test]
1809 fn a_frame_num_gap_invents_only_the_reference_window() {
1810 let mut sps = progressive_sps();
1812 sps.max_num_ref_frames = 2;
1813 assert_eq!(first_invented(3, 4, &sps), 4);
1815 assert_eq!(first_invented(3, 5, &sps), 4);
1817 assert_eq!(first_invented(3, 10, &sps), 8);
1819 assert_eq!(first_invented(14, 3, &sps), 1);
1821 assert_eq!(first_invented(4, 3, &sps), 1);
1823
1824 sps.max_num_ref_frames = 0;
1827 assert_eq!(first_invented(0, 3, &sps), 2);
1828 }
1829
1830 fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
1833 let mut sps = progressive_sps();
1834 sps.pic_order_cnt = PicOrderCnt::Lsb { log2_max_lsb: 8 };
1835 let mut pic = PictureData::default();
1836 pic.pic_order_cnt_lsb = lsb;
1837 pic.nal_ref_idc = 1;
1838 pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
1839 Ok(pic.pic_order_cnt)
1840 }
1841
1842 fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
1843 PrevReferencePicInfo {
1844 pic_order_cnt_msb: msb,
1845 pic_order_cnt_lsb: lsb,
1846 ..Default::default()
1847 }
1848 }
1849
1850 #[test]
1854 fn the_picture_order_count_wraps_and_never_overflows() {
1855 assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
1856 assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
1857 assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
1858 assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
1859 assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
1860
1861 let after_mmco5 = PrevReferencePicInfo {
1864 has_mmco_5: true,
1865 top_field_order_cnt: i32::MIN,
1866 ..Default::default()
1867 };
1868 assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
1869 }
1870
1871 #[test]
1874 fn the_frame_num_offset_never_overflows() {
1875 let mut sps = progressive_sps();
1876 sps.pic_order_cnt = PicOrderCnt::Decode;
1877 let order_count = |frame_num_offset| {
1878 let mut prev = PrevPicInfo {
1879 frame_num: 5,
1880 frame_num_offset,
1881 has_mmco_5: false,
1882 };
1883 let mut pic = PictureData::default();
1884 pic.frame_num = 1;
1885 pic.nal_ref_idc = 1;
1886 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1887 };
1888 assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
1890 assert!(order_count(u32::MAX - 3).is_err());
1891 assert!(order_count(i32::MAX as u32 / 2).is_err());
1893 }
1894
1895 #[test]
1898 fn the_type2_order_count_is_checked_whole() {
1899 let mut sps = progressive_sps();
1900 sps.pic_order_cnt = PicOrderCnt::Decode;
1901 let order_count = |nal_ref_idc| {
1902 let mut prev = PrevPicInfo {
1904 frame_num: 5,
1905 frame_num_offset: (1 << 30) - 17,
1906 has_mmco_5: false,
1907 };
1908 let mut pic = PictureData::default();
1909 pic.frame_num = 1;
1910 pic.nal_ref_idc = nal_ref_idc;
1911 pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1912 };
1913 assert_eq!(order_count(0).unwrap(), i32::MAX);
1914 assert!(order_count(1).is_err());
1915 }
1916
1917 #[test]
1920 fn the_type1_bottom_field_is_checked_whole() {
1921 let mut sps = progressive_sps();
1922 sps.pic_order_cnt = PicOrderCnt::Cycle {
1923 delta_always_zero: false,
1924 offset_for_non_ref_pic: 0,
1925 offset_for_top_to_bottom_field: i32::MAX,
1926 offset_for_ref_frame: Vec::new(),
1927 };
1928 let bottom = |delta0, delta1| {
1929 let mut pic = PictureData::default();
1930 pic.nal_ref_idc = 1;
1931 pic.delta_pic_order_cnt0 = delta0;
1932 pic.delta_pic_order_cnt1 = delta1;
1933 pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
1934 .map(|()| pic.bottom_field_order_cnt)
1935 };
1936 assert_eq!(bottom(2, -i32::MAX).unwrap(), 2);
1937 assert!(bottom(2, 0).is_err());
1938 }
1939
1940 #[test]
1941 fn rejects_nonzero_crop_origins() {
1942 for (left, top) in [(2, 0), (0, 2)] {
1943 let mut sps = progressive_sps();
1944 sps.crop = Some(kodecs_h264::Crop {
1945 left,
1946 right: 0,
1947 top,
1948 bottom: 0,
1949 });
1950 assert!(SequenceInfo::new(&sps)
1951 .unwrap_err()
1952 .to_string()
1953 .contains("left and top"));
1954 }
1955 }
1956
1957 #[test]
1958 fn crop_only_updates_change_sequence_identity() {
1959 let original = SequenceInfo::new(&progressive_sps()).unwrap();
1960 for (right, bottom, expected) in [(2, 0, (318, 240)), (0, 2, (320, 238))] {
1961 let mut sps = progressive_sps();
1962 sps.crop = Some(kodecs_h264::Crop {
1963 left: 0,
1964 right,
1965 top: 0,
1966 bottom,
1967 });
1968 let cropped = SequenceInfo::new(&sps).unwrap();
1969 assert_eq!(original.coded, cropped.coded);
1970 assert_eq!(cropped.visible, expected);
1971 assert_ne!(original, cropped);
1972 }
1973 }
1974
1975 fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
1978 crate::encode::Config {
1979 codec: crate::Codec::H264,
1980 width,
1981 height,
1982 framerate: 30,
1983 bitrate: 2_000_000,
1984 gop: std::num::NonZeroU32::new(30).unwrap(),
1985 color: crate::Color::infer(height),
1986 device: None,
1987 }
1988 }
1989
1990 fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
1993 let (w, h) = (width as usize, height as usize);
1994 let mut data = vec![128u8; w * h * 3 / 2];
1995 let x0 = (step * 16) as usize % (w / 2);
1996 for y in h / 4..h / 2 {
1997 for x in x0..x0 + w / 4 {
1998 data[y * w + x] = 235;
1999 }
2000 }
2001 data
2002 }
2003
2004 #[test]
2013 #[ignore = "requires a VA-API render node"]
2014 fn exported_pictures_do_not_share_a_surface() {
2015 let (width, height) = (320u32, 240u32);
2016 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2017 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2018
2019 let mut exported = Vec::new();
2020 for step in 0..8 {
2021 let unit = encoder
2022 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2023 .expect("encode a picture");
2024 exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
2025 }
2026 exported.extend(decoder.flush_exported().expect("flush the decoder"));
2027 assert!(!exported.is_empty(), "the decoder produced no pictures");
2028
2029 let first = &exported[0];
2030 eprintln!(
2031 "exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
2032 exported.len(),
2033 first.width,
2034 first.height,
2035 first.descriptor.fourcc,
2036 first.descriptor.objects[0].drm_format_modifier
2037 );
2038
2039 let mut seen = Vec::new();
2040 for (index, frame) in exported.iter().enumerate() {
2041 assert_eq!((frame.width, frame.height), (width, height));
2042 assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
2043 assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
2044 assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
2045
2046 let inode = inode(&frame.descriptor.objects[0].fd);
2050 assert!(
2051 !seen.contains(&inode),
2052 "picture {index} was decoded into an allocation an earlier one still holds"
2053 );
2054 seen.push(inode);
2055 }
2056 }
2057
2058 #[test]
2061 #[ignore = "requires a VA-API render node"]
2062 fn the_render_node_is_found_or_named() {
2063 if let Err(err) = Decoder::new(Config::new()) {
2064 panic!("no VA-API H.264 decoder: {err:#}");
2065 }
2066 let named = Config {
2067 device: Some(PathBuf::from("/dev/null")),
2068 ..Config::new()
2069 };
2070 assert!(
2071 Decoder::new(named).is_err(),
2072 "a named node that is not a render node was swapped for one that is"
2073 );
2074 }
2075
2076 #[test]
2083 #[ignore = "requires a VA-API render node and FFmpeg"]
2084 fn flush_returns_the_pictures_the_dpb_still_holds() {
2085 const PICTURES: usize = 10;
2086
2087 let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
2088 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2089
2090 let mut streamed = Vec::new();
2091 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2092 streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
2093 }
2094 assert!(
2095 streamed.len() < PICTURES,
2096 "the DPB held nothing back, so this test proves nothing"
2097 );
2098
2099 let flushed = decoder.flush().expect("flush the decoder");
2100 let mut timestamps: Vec<u64> = streamed
2101 .iter()
2102 .chain(&flushed)
2103 .map(|picture| picture.timestamp)
2104 .collect();
2105 timestamps.sort_unstable();
2106 assert_eq!(
2107 timestamps,
2108 (0..PICTURES as u64).collect::<Vec<_>>(),
2109 "the stream lost pictures at its end"
2110 );
2111
2112 assert!(decoder.flush().expect("flush an empty decoder").is_empty());
2115 }
2116
2117 #[test]
2126 #[ignore = "requires a VA-API render node and FFmpeg"]
2127 fn h264_without_reordering_comes_out_as_it_decodes() {
2128 const PICTURES: usize = 10;
2129 let (width, height) = (320u32, 240u32);
2130
2131 let mut streams = Vec::new();
2132 match crate::encode::Encoder::new(encoder_config(width, height)) {
2133 Ok(mut encoder) => {
2134 let units = (0..PICTURES)
2135 .map(|step| {
2136 encoder
2137 .encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
2138 .expect("encode a picture")
2139 })
2140 .collect::<Vec<_>>();
2141 streams.push(("VA-API", units));
2142 }
2143 Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
2144 }
2145 match software_encode(Codec::H264, (width, height), PICTURES, false) {
2146 Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
2147 None => panic!("FFmpeg with libx264 is required"),
2148 }
2149
2150 for (encoder, units) in streams {
2151 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2152 for (index, unit) in units.iter().enumerate() {
2153 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2154 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2155 assert_eq!(
2156 timestamps,
2157 [index as u64],
2158 "{encoder}: access unit {index} was held back"
2159 );
2160 }
2161 assert!(decoder.flush().expect("flush the decoder").is_empty());
2162 }
2163 }
2164
2165 #[test]
2168 fn the_reorder_limit_follows_the_sps() {
2169 let sps = progressive_sps();
2171 assert_eq!(sps.max_dpb_frames, 16);
2172 assert_eq!(max_dpb_frames(&sps), 16);
2173 assert_eq!(
2174 reorder_limit(&sps, 16),
2175 16,
2176 "without a VUI, the inference is the DPB size"
2177 );
2178
2179 let mut intra = progressive_sps();
2180 intra.profile = Profile::High;
2181 intra.constraint_flags = 0x10;
2182 assert_eq!(
2183 reorder_limit(&intra, 16),
2184 0,
2185 "without a VUI, a High intra profile reorders nothing"
2186 );
2187
2188 let restriction = |max_num_reorder_frames, max_dec_frame_buffering| kodecs_h264::Restriction {
2189 motion_vectors_over_pic_boundaries: true,
2190 max_bytes_per_pic_denom: 2,
2191 max_bits_per_mb_denom: 1,
2192 log2_max_mv_length_horizontal: 16,
2193 log2_max_mv_length_vertical: 16,
2194 max_num_reorder_frames,
2195 max_dec_frame_buffering,
2196 };
2197 let mut declared = progressive_sps();
2198 declared.vui = Some(kodecs_h264::Vui {
2199 aspect_ratio: None,
2200 overscan_appropriate: None,
2201 video_signal: None,
2202 chroma_loc: None,
2203 timing: None,
2204 nal_hrd: None,
2205 vcl_hrd: None,
2206 low_delay_hrd: false,
2207 pic_struct_present: false,
2208 restriction: Some(restriction(0, 1)),
2209 });
2210 assert_eq!(max_dpb_frames(&declared), 1, "the VUI's buffering is the DPB size");
2211 assert_eq!(
2212 reorder_limit(&declared, max_dpb_frames(&declared)),
2213 0,
2214 "the VUI's limit applies"
2215 );
2216
2217 if let Some(vui) = declared.vui.as_mut() {
2218 vui.restriction = Some(restriction(5, 2));
2219 }
2220 assert_eq!(
2221 reorder_limit(&declared, max_dpb_frames(&declared)),
2222 2,
2223 "the DPB size bounds the VUI's limit"
2224 );
2225
2226 let mut derived = progressive_sps();
2227 derived.pic_order_cnt = PicOrderCnt::Decode;
2228 assert_eq!(
2229 reorder_limit(&derived, 16),
2230 0,
2231 "an order count from frame_num reorders nothing"
2232 );
2233 }
2234
2235 #[test]
2243 #[ignore = "requires a VA-API render node"]
2244 fn a_dropped_export_is_decoded_into_again() {
2245 const PICTURES: u32 = 60;
2246 let (width, height) = (320u32, 240u32);
2247 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2248 let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2249 let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2250
2251 let mut compared = 0;
2252 for step in 0..PICTURES {
2253 let unit = encoder
2254 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2255 .expect("encode a picture");
2256 let exported = exporting
2257 .decode_exported(&unit, step as u64)
2258 .expect("decode to a descriptor");
2259 let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
2260 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2261 for (gpu, cpu) in exported.iter().zip(&downloaded) {
2262 let read_back = gpu.download().expect("read the exported surface back");
2263 assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
2264 compared += 1;
2265 }
2266 }
2267 assert!(compared > 0, "the decoder produced no pictures");
2268
2269 let pool = &exporting.sequence().expect("a sequence").pool;
2270 let allocated = pool.allocated.get();
2271 eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
2272 assert!(
2273 allocated <= pool.free.capacity,
2274 "{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
2275 pool.free.capacity
2276 );
2277 }
2278
2279 #[test]
2282 #[ignore = "requires a VA-API render node"]
2283 fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
2284 const HELD: u32 = 40;
2285 let (width, height) = (320u32, 240u32);
2286 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2287 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2288
2289 let mut step = 0;
2290 let mut decode = |decoder: &mut Decoder| {
2291 let unit = encoder
2292 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2293 .expect("encode a picture");
2294 step += 1;
2295 decoder.decode_exported(&unit, step as u64).expect("decode a picture")
2296 };
2297
2298 let mut held = Vec::new();
2299 for _ in 0..HELD {
2300 held.extend(decode(&mut decoder));
2301 }
2302 let pool = &decoder.sequence().expect("a sequence").pool;
2303 let allocated = pool.allocated.get();
2304 assert!(
2305 allocated >= held.len(),
2306 "{} pictures held on {allocated} surfaces",
2307 held.len()
2308 );
2309
2310 drop(held);
2311 let free = pool.free.surfaces.lock().unwrap().len();
2312 assert!(
2313 free <= pool.free.capacity,
2314 "{free} surfaces left free, more than the capacity of {}",
2315 pool.free.capacity
2316 );
2317
2318 for _ in 0..10 {
2319 drop(decode(&mut decoder));
2320 }
2321 let pool = &decoder.sequence().expect("a sequence").pool;
2322 assert_eq!(
2323 pool.allocated.get(),
2324 allocated,
2325 "pictures after the release did not reuse the free surfaces"
2326 );
2327 }
2328
2329 #[test]
2334 fn an_exported_frame_is_send_and_sync() {
2335 const fn assert_send_sync<T: Send + Sync>() {}
2336 assert_send_sync::<ExportedFrame>();
2337 }
2338
2339 #[test]
2348 #[ignore = "requires a VA-API render node"]
2349 fn an_exported_picture_downloads_to_the_same_pixels() {
2350 let (width, height) = (320u32, 240u32);
2351 let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2352 let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2353 let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2354
2355 let mut exported = Vec::new();
2356 let mut downloaded = Vec::new();
2357 for step in 0..8 {
2358 let unit = encoder
2359 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2360 .expect("encode a picture");
2361 exported.extend(
2362 exporting
2363 .decode_exported(&unit, step as u64)
2364 .expect("decode to a descriptor"),
2365 );
2366 downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
2367 }
2368 exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
2369 downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
2370
2371 assert!(!exported.is_empty(), "the decoder produced no pictures");
2372 assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2373
2374 for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
2375 let read_back = gpu.download().expect("read the exported surface back");
2376 assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
2377 assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
2378 assert!(
2379 read_back.data == cpu.data,
2380 "picture {index} read back differently than it downloaded"
2381 );
2382 }
2383 }
2384
2385 #[test]
2395 #[ignore = "requires a VA-API render node and FFmpeg"]
2396 fn decoded_pictures_match_a_software_decoder() {
2397 const PICTURES: usize = 30;
2398
2399 for codec in [Codec::H264, Codec::H265] {
2400 for (width, height) in [(320u32, 240u32), (852, 478)] {
2401 let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
2402 panic!("no ffmpeg that encodes {codec:?}");
2403 };
2404 let reference = software_decode(codec, &stream);
2405
2406 let picture_len = (width * height * 3 / 2) as usize;
2407 assert_eq!(
2408 reference.len(),
2409 PICTURES * picture_len,
2410 "ffmpeg decoded a different count"
2411 );
2412
2413 let Ok(mut decoder) = Decoder::new(Config { codec, ..Config::new() }) else {
2414 panic!("no VA-API {codec:?} decoder");
2415 };
2416
2417 let units = split_access_units(codec, &stream);
2418 let mut decoded = Vec::new();
2419 for (index, unit) in units.iter().enumerate() {
2420 if index % 2 == 0 {
2421 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2422 } else {
2423 for exported in decoder
2424 .decode_exported(unit, index as u64)
2425 .expect("decode an access unit")
2426 {
2427 decoded.push(exported.download().expect("download an exported picture"));
2428 }
2429 }
2430 }
2431 decoded.extend(decoder.flush().expect("flush the decoder"));
2432 assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
2433
2434 let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2435 assert!(
2436 timestamps.windows(2).any(|pair| pair[0] > pair[1]),
2437 "the {codec:?} stream came out in decode order, so nothing here tests reordering"
2438 );
2439 timestamps.sort_unstable();
2440 assert_eq!(
2441 timestamps,
2442 (0..PICTURES as u64).collect::<Vec<_>>(),
2443 "a {codec:?} picture's timestamp did not survive reordering"
2444 );
2445
2446 for (index, picture) in decoded.iter().enumerate() {
2447 assert_eq!((picture.width, picture.height), (width, height));
2448 assert!(
2449 picture.data == reference[index * picture_len..][..picture_len],
2450 "{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
2451 );
2452 }
2453 }
2454 }
2455 }
2456
2457 #[test]
2462 #[ignore = "requires a VA-API render node and FFmpeg"]
2463 fn h264_coding_tools_match_a_software_decoder() {
2464 const PICTURES: usize = 40;
2465 let (width, height) = (852u32, 478u32);
2466 let source = format!("testsrc2=size={width}x{height}:rate=30,fade=in:0:20,fade=out:25:15");
2467 let pictures = PICTURES.to_string();
2468 #[rustfmt::skip]
2469 let stream = ffmpeg(&[
2470 "-f", "lavfi", "-i", &source, "-frames:v", &pictures, "-pix_fmt", "yuv420p",
2471 "-c:v", "libx264", "-profile:v", "high", "-bf", "3", "-refs", "4", "-g", "20",
2472 "-x264-params", "slices=3:weightp=2:weightb=1:cqm=jvt:b-pyramid=strict:log-level=error",
2473 "-f", "h264", "-",
2474 ])
2475 .expect("no ffmpeg that encodes H.264");
2476 let reference = software_decode(Codec::H264, &stream);
2477 let picture_len = (width * height * 3 / 2) as usize;
2478 assert_eq!(
2479 reference.len(),
2480 PICTURES * picture_len,
2481 "ffmpeg decoded a different count"
2482 );
2483
2484 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2485 let mut decoded = Vec::new();
2486 for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2487 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2488 }
2489 decoded.extend(decoder.flush().expect("flush the decoder"));
2490 assert_eq!(decoded.len(), PICTURES, "lost or invented pictures");
2491 for (index, picture) in decoded.iter().enumerate() {
2492 assert!(
2493 picture.data == reference[index * picture_len..][..picture_len],
2494 "picture {index} differs from the software decoder"
2495 );
2496 }
2497 }
2498
2499 #[test]
2503 #[ignore = "requires a VA-API render node and FFmpeg"]
2504 fn h265_without_reordering_comes_out_as_it_decodes() {
2505 const PICTURES: usize = 10;
2506
2507 let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
2508 let mut decoder = Decoder::new(Config {
2509 codec: Codec::H265,
2510 ..Config::new()
2511 })
2512 .expect("no VA-API H.265 decoder");
2513
2514 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2515 let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2516 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2517 assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
2518 }
2519 assert!(decoder.flush().expect("flush the decoder").is_empty());
2520 }
2521
2522 #[test]
2526 #[ignore = "requires a VA-API render node and FFmpeg"]
2527 fn a_4k_h265_wavefront_stream_decodes() {
2528 const PICTURES: usize = 2;
2529 let size = (3840, 2160);
2530
2531 let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
2532 let mut decoder = Decoder::new(Config {
2533 codec: Codec::H265,
2534 ..Config::new()
2535 })
2536 .expect("no VA-API H.265 decoder");
2537
2538 let mut decoded = Vec::new();
2539 for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2540 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2541 }
2542 decoded.extend(decoder.flush().expect("flush the decoder"));
2543 assert_eq!(decoded.len(), PICTURES);
2544 assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
2545 }
2546
2547 #[test]
2550 #[ignore = "requires a VA-API render node and FFmpeg"]
2551 fn a_new_h265_sequence_decodes_at_its_own_size() {
2552 const PER_SEQUENCE: usize = 6;
2553 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2554
2555 let mut stream = Vec::new();
2556 for &size in &sizes {
2557 let sequence =
2558 software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
2559 stream.extend(sequence);
2560 }
2561 let mut decoder = Decoder::new(Config {
2562 codec: Codec::H265,
2563 ..Config::new()
2564 })
2565 .expect("no VA-API H.265 decoder");
2566
2567 let mut decoded = Vec::new();
2568 let units = split_access_units(Codec::H265, &stream);
2569 for (index, unit) in units.iter().enumerate() {
2570 decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2571 }
2572 decoded.extend(decoder.flush().expect("flush the decoder"));
2573
2574 let expected: Vec<(u32, u32)> = sizes
2575 .iter()
2576 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
2577 .collect();
2578 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2579 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2580
2581 for picture in &decoded {
2582 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2583 assert_eq!(
2584 picture.data.len(),
2585 expected_len,
2586 "a picture was read back at the wrong size"
2587 );
2588 }
2589 }
2590
2591 #[test]
2598 #[ignore = "requires a VA-API render node"]
2599 fn a_new_sequence_decodes_at_its_own_size() {
2600 const PER_SEQUENCE: u32 = 6;
2601 let sizes = [(320u32, 240u32), (192u32, 144u32)];
2602
2603 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2604
2605 let mut decoded = Vec::new();
2606 let mut timestamp = 0u64;
2607 for &(width, height) in &sizes {
2608 let mut encoder =
2609 crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2610 for step in 0..PER_SEQUENCE {
2611 let unit = encoder
2612 .encode_nv12(&nv12_frame(width, height, step), step == 0)
2613 .expect("encode a picture");
2614 decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
2615 timestamp += 1;
2616 }
2617 }
2618 decoded.extend(decoder.flush().expect("flush the decoder"));
2619
2620 let expected: Vec<(u32, u32)> = sizes
2621 .iter()
2622 .flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
2623 .collect();
2624 let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2625 assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2626
2627 let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2628 assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());
2629
2630 for picture in &decoded {
2631 let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2632 assert_eq!(
2633 picture.data.len(),
2634 expected_len,
2635 "a picture was read back at the wrong size"
2636 );
2637 }
2638 }
2639
2640 #[test]
2641 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2642 fn a_refused_sps_leaves_no_stale_set_behind() {
2643 let (width, height) = (320u32, 240u32);
2644 let stream = software_encode(Codec::H264, (width, height), 4, false).expect("no ffmpeg that encodes H.264");
2645 let units = split_access_units(Codec::H264, &stream);
2646 let source = format!("testsrc2=size={width}x{height}:rate=30");
2647 #[rustfmt::skip]
2648 let high422 = ffmpeg(&[
2649 "-f", "lavfi", "-i", &source, "-frames:v", "1", "-pix_fmt", "yuv422p",
2650 "-c:v", "libx264", "-profile:v", "high422", "-f", "h264", "-",
2651 ])
2652 .expect("no ffmpeg that encodes H.264 4:2:2");
2653
2654 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2655 decoder.decode(&units[0], 0).expect("decode the IDR");
2656 let refused = decoder.decode(&high422, 1).expect_err("a 4:2:2 SPS decodes");
2657 assert!(format!("{refused:#}").contains("unsupported"), "{refused:#}");
2658
2659 let stale = decoder
2661 .decode(&units[1], 2)
2662 .expect_err("a slice decoded against a replaced SPS");
2663 assert!(format!("{stale:#}").contains("Slice"), "{stale:#}");
2664
2665 decoder.decode(&units[0], 3).expect("decode the resent IDR");
2667 }
2668
2669 #[test]
2670 #[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
2671 fn a_refused_pps_leaves_the_other_sets_usable() {
2672 let stream = software_encode(Codec::H264, (320, 240), 4, false).expect("no ffmpeg that encodes H.264");
2673 let units = split_access_units(Codec::H264, &stream);
2674
2675 let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2676 let mut decoded = decoder.decode(&units[0], 0).expect("decode the IDR");
2677 let refused = decoder
2680 .decode(&[0, 0, 0, 1, 0x68, 0b0100_1010], 1)
2681 .expect_err("a PPS naming a missing SPS decodes");
2682 assert!(format!("{refused:#}").contains("Pps"), "{refused:#}");
2683
2684 for (timestamp, unit) in (2..).zip(&units[1..]) {
2686 decoded.extend(
2687 decoder
2688 .decode(unit, timestamp)
2689 .expect("decode a picture after the refused PPS"),
2690 );
2691 }
2692 decoded.extend(decoder.flush().expect("flush the decoder"));
2693 assert_eq!(decoded.len(), units.len());
2694 }
2695
2696 fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2699 let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
2700 if !output.status.success() {
2701 eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
2702 return None;
2703 }
2704 Some(output.stdout)
2705 }
2706
2707 fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
2711 let source = format!("testsrc2=size={width}x{height}:rate=30");
2712 let pictures = pictures.to_string();
2713 let mut args = vec![
2714 "-f",
2715 "lavfi",
2716 "-i",
2717 &source,
2718 "-frames:v",
2719 &pictures,
2720 "-pix_fmt",
2721 "yuv420p",
2722 ];
2723
2724 let x265;
2725 match codec {
2726 Codec::H264 => args.extend([
2727 "-c:v",
2728 "libx264",
2729 "-profile:v",
2730 "main",
2731 "-bf",
2732 if reorder { "2" } else { "0" },
2733 "-refs",
2734 if reorder { "3" } else { "1" },
2735 "-g",
2736 "15",
2737 "-f",
2738 "h264",
2739 ]),
2740 Codec::H265 => {
2741 x265 = if reorder {
2744 "bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
2745 } else {
2746 "bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
2747 };
2748 args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
2749 }
2750 }
2751 args.push("-");
2752 ffmpeg(&args)
2753 }
2754
2755 fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
2757 static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2760 let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2761 let extension = match codec {
2762 Codec::H264 => "264",
2763 Codec::H265 => "265",
2764 };
2765 let path = std::env::temp_dir().join(format!(
2766 "kodecs-vaapi-decode-{}-{count}.{extension}",
2767 std::process::id()
2768 ));
2769 std::fs::write(&path, stream).expect("write the elementary stream");
2770 let decoded = ffmpeg(&[
2771 "-i",
2772 path.to_str().expect("a UTF-8 temporary path"),
2773 "-pix_fmt",
2774 "nv12",
2775 "-f",
2776 "rawvideo",
2777 "-",
2778 ]);
2779 let _ = std::fs::remove_file(&path);
2780 decoded.expect("ffmpeg decodes what it just encoded")
2781 }
2782
2783 fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
2788 let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
2789 .filter(|&i| stream[i..i + 3] == [0, 0, 1])
2790 .collect();
2791
2792 let mut units = Vec::new();
2793 let mut current: Vec<u8> = Vec::new();
2794 let mut current_has_picture = false;
2795
2796 for (index, &start) in starts.iter().enumerate() {
2797 let end = starts.get(index + 1).copied().unwrap_or(stream.len());
2798 let nal = &stream[start + 3..end];
2799 let (is_slice, starts_picture, starts_unit) = match codec {
2803 Codec::H264 => {
2804 let nal_type = nal[0] & 0x1f;
2805 let is_slice = (1..=5).contains(&nal_type);
2806 (is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
2807 }
2808 Codec::H265 => {
2809 let nal_type = (nal[0] >> 1) & 0x3f;
2810 let is_slice = nal_type <= 31;
2811 (
2812 is_slice,
2813 is_slice && nal[2] & 0x80 != 0,
2814 matches!(nal_type, 32..=35 | 39),
2815 )
2816 }
2817 };
2818
2819 if current_has_picture && (starts_picture || starts_unit) {
2820 units.push(std::mem::take(&mut current));
2821 current_has_picture = false;
2822 }
2823
2824 current.extend_from_slice(&stream[start..end]);
2825 current_has_picture |= is_slice;
2826 }
2827
2828 if !current.is_empty() {
2829 units.push(current);
2830 }
2831 units
2832 }
2833
2834 fn inode(fd: &OwnedFd) -> u64 {
2837 use std::os::unix::fs::MetadataExt as _;
2838
2839 let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
2842 file.metadata().expect("stat the descriptor").ino()
2843 }
2844}