//! HEVC picture management over any surface type: picture order count (8.3.1), //! reference picture sets and marking (8.3.2), and output bumping (C.5.2). //! //! The VA-API and Vulkan Video decoders both build on this. A stored picture //! is only its surface, POC, timestamp, marking and output state; the driver //! sees the reference picture set as DPB indices into [`Dpb::pictures`]. use ec_core::color::Tags; use ec_h265_syntax::{NalUnitType, SliceHeader, Sps}; use crate::error::{Error, Result}; /// PCI vendor ID of AMD. pub(crate) const AMD_VENDOR_ID: u32 = 0x1002; /// AMD's VCN returns wrong chroma for HEVC with 16x16 coding tree blocks, in the /// firmware, so ffmpeg's VA-API and Vulkan decoders get the same wrong picture. Such /// streams go to software. `amd` is only asked when the CTB size is 16. pub(crate) fn hevc_ctb16_broken(sps: &Sps, amd: impl FnOnce() -> bool) -> bool { sps.ctb_size() == 16 && amd() } /// Reference marking of a stored picture (8.3.2). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Mark { Unused, ShortTerm, LongTerm, } /// One stored picture: its surface, POC, marking and whether it is still to be output. pub(crate) struct StoredPicture { pub(crate) surface: S, pub(crate) poc: i32, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) timestamp: i64, pub(crate) mark: Mark, /// Still to be handed to the caller. pub(crate) output: bool, } impl StoredPicture { pub(crate) fn stored(&self) -> bool { self.output || self.mark != Mark::Unused } } /// The reference picture set of the picture being decoded, as DPB indices. #[derive(Debug, Default, Clone)] pub(crate) struct Rps { pub(crate) st_curr_before: Vec, pub(crate) st_curr_after: Vec, pub(crate) lt_curr: Vec, } /// The decoded picture buffer and the cross-picture state of 8.3.1 and C.5.2. pub(crate) struct Dpb { pub(crate) pictures: Vec>, /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. pub(crate) prev_tid0_poc: i32, /// Set once a picture has been decoded since the last reset. pub(crate) started: bool, pub(crate) max_reorder: usize, pub(crate) max_dec_pic_buffering: usize, } impl Dpb { pub(crate) fn new() -> Dpb { Dpb { pictures: Vec::new(), prev_tid0_poc: 0, started: false, max_reorder: 1, max_dec_pic_buffering: 6, } } /// `PicOrderCntVal` (8.3.1). pub(crate) fn picture_order_count( &self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, ) -> i32 { if nal_type.is_idr() { return 0; } let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); let lsb = sh.poc_lsb as i32; let (prev_msb, prev_lsb) = if !self.started { (0, 0) } else { ( self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), self.prev_tid0_poc.rem_euclid(max_lsb), ) }; // An IRAP that starts a new coded video sequence has no predecessor. if nal_type.is_irap() && !self.started { return lsb; } let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { prev_msb + max_lsb } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { prev_msb - max_lsb } else { prev_msb }; msb + lsb } /// Reference picture set derivation and marking (8.3.2). pub(crate) fn apply_rps( &mut self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, poc: i32, ) -> Result { if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { for pic in &mut self.pictures { pic.mark = Mark::Unused; } self.pictures.retain(|p| p.stored()); return Ok(Rps::default()); } let set = &sh.short_term_ref_pic_set; let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) for i in 0..set.num_negative as usize { wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); } for i in 0..set.num_positive as usize { wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); } for lt in &sh.long_term { // 8.3.2: a long-term entry without an MSB cycle is matched on its // POC low bits alone, which is how a stream survives an MSB wrap. let target = if lt.delta_poc_msb_present { poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) + lt.poc_lsb_lt as i32 } else { lt.poc_lsb_lt as i32 }; wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); } let mut rps = Rps::default(); let mut keep = vec![false; self.pictures.len()]; let mut missing_used = false; for (target, used, lsb_only) in wanted { let found = self.pictures.iter().position(|p| { if lsb_only { p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) } else { p.poc == target } }); let Some(idx) = found else { // 8.3.2: a picture the current one predicts from must be in the // buffer. One that is not is a broken GOP, and a reference list // built without it would name a surface that was never decoded. missing_used |= used; continue; }; keep[idx] = true; if !used { continue; } // The three "current" lists are what the reference lists are built // from, in POC order relative to the current picture. if self.pictures[idx].mark == Mark::LongTerm || lsb_only { rps.lt_curr.push(idx); } else if self.pictures[idx].poc < poc { rps.st_curr_before.push(idx); } else { rps.st_curr_after.push(idx); } } rps.st_curr_before .sort_by_key(|&i| std::cmp::Reverse(self.pictures[i].poc)); rps.st_curr_after.sort_by_key(|&i| self.pictures[i].poc); for (i, pic) in self.pictures.iter_mut().enumerate() { if !keep[i] { pic.mark = Mark::Unused; } } // Dropping unreferenced, already-output pictures here is what returns // their surfaces to the pool; the indices in `rps` are recomputed after. let mut remap = vec![usize::MAX; self.pictures.len()]; let mut next = 0usize; for (i, pic) in self.pictures.iter().enumerate() { if pic.stored() { remap[i] = next; next += 1; } } self.pictures.retain(|p| p.stored()); if missing_used { return Err(Error::Stream(ec_core::Error::corrupt( "HEVC reference picture set names a picture used for prediction that was never decoded", ))); } for list in [ &mut rps.st_curr_before, &mut rps.st_curr_after, &mut rps.lt_curr, ] { list.retain(|&i| remap[i] != usize::MAX); for entry in list.iter_mut() { *entry = remap[*entry]; } } Ok(rps) } /// The next picture to output (C.5.2.4), while the buffer holds more than /// its reordering or storage limit allows; `flush` outputs every one. pub(crate) fn next_output(&self, flush: bool) -> Option { let pending = self.pictures.iter().filter(|p| p.output).count(); let stored = self.pictures.iter().filter(|p| p.stored()).count(); if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { return None; } self.pictures .iter() .enumerate() .filter(|(_, p)| p.output) .min_by_key(|(_, p)| p.poc) .map(|(i, _)| i) } /// Marks the picture at `idx` as output and drops it once it is not stored. pub(crate) fn released(&mut self, idx: usize) { self.pictures[idx].output = false; self.pictures.retain(|p| p.stored()); } } /// True unless the NAL type says sub-layer non-reference (`_N`, an even type /// below 16). pub(crate) fn is_reference_picture(nal_type: NalUnitType) -> bool { let code = nal_type.code(); code >= 16 || code % 2 == 1 } /// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1 /// excludes from the picture order count prediction. pub(crate) fn is_leading_picture(nal_type: NalUnitType) -> bool { (6..=9).contains(&nal_type.code()) } /// An SPS's VUI `colour_description` and range flag, as [`Tags`] for /// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no /// `video_signal_type` at all. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) fn vui_colour_tags(sps: &Sps) -> Tags { let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { return Tags::default(); }; let (_primaries, transfer, matrix) = vst .colour_description .map(|cd| { ( cd.colour_primaries, cd.transfer_characteristics, cd.matrix_coeffs, ) }) .unwrap_or((0, 0, 0)); Tags::from_codes( u64::from(matrix), u64::from(transfer), if vst.video_full_range_flag { 2 } else { 1 }, ) } /// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's /// `NoRaslOutputFlag` is 1 (8.1.3). pub(crate) fn is_rasl_picture(nal_type: NalUnitType) -> bool { matches!(nal_type.code(), 8 | 9) } /// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 /// (8.1.3), a broken-link splice point that never has a decodable RASL. pub(crate) fn is_bla_picture(nal_type: NalUnitType) -> bool { (16..=18).contains(&nal_type.code()) } /// `slice_pic_parameter_set_id`, readable without any parameter set. pub(crate) fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result { let mut r = ec_core::BitReader::new(rbsp); r.read_bit()?; // first_slice_segment_in_pic_flag if nal_type.is_irap() { r.read_bit()?; // no_output_of_prior_pics_flag } Ok(r.read_ue()?) }