//! Stateless HEVC decoding. //! //! HEVC keeps no `frame_num` and no sliding window: every picture states its //! whole reference picture set, and anything the set does not name stops being //! a reference there and then (8.3.2). That makes the DPB smaller than H.264's //! but the *derivation* larger, and all of it has to happen here — a stateless //! driver is handed `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as //! finished picture lists. use std::rc::Rc; use ec_core::color::{ColorDescription, ContentLight, Tags}; use ec_h265_syntax::{ NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b, unescape_rbsp, }; use ec_va::caps::Profile; use ec_va::{Buffer, Display}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; use crate::frame::{Colour, Frame}; use crate::hevc_dpb::{ Dpb, Mark, Rps, StoredPicture, hevc_ctb16_broken, is_bla_picture, is_rasl_picture, is_reference_picture, is_leading_picture, peek_pps_id, vui_colour_tags, }; use crate::params::hevc::{ IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PicFields, PictureParameterBufferHEVC, SliceParameterBufferHEVC, SliceParsingFields, VAPictureHEVC, }; use crate::pool::PooledSurface; /// Beyond `sps_max_dec_pic_buffering`: the picture being decoded plus the ones /// a caller is still holding. const EXTRA_SURFACES: usize = 6; /// One DPB slot as the parameter builder sees it: its surface, POC and marking. #[derive(Clone, Copy)] struct DpbSlot { id: u32, poc: i32, mark: Mark, } impl DpbSlot { fn of(p: &StoredPicture>) -> DpbSlot { DpbSlot { id: p.surface.id(), poc: p.poc, mark: p.mark, } } } /// The picture being assembled from its slices. struct Current { surface: Rc, sps_id: u32, poc: i32, timestamp: i64, is_reference: bool, /// True when this picture may be `prevTid0Pic` for the next one (8.3.1). is_tid0_anchor: bool, output: bool, rps: Rps, buffers: Vec, slices: usize, /// Index into `PictureParameterBufferHEVC::reference_frames` per DPB index. va_index: Vec, } /// A stateless HEVC decoder. pub struct HevcDecoder { display: Rc, vps_map: Vec>, sps_map: Vec>, pps_map: Vec>, session: Option, dpb: Dpb>, ready: ReadyFrames, current: Option, /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures /// associated with it must not be decoded or output when set, because /// they predict from pictures before a random-access point this decoder /// never saw. no_rasl_output: bool, /// The most recent SPS's VUI colour tags, sticky across pictures. colour_tags: Tags, /// The prefix SEI HDR peak seen so far, merged so a later access unit that /// says nothing does not erase what an earlier IRAP declared. colour_light: ContentLight, } impl HevcDecoder { /// A decoder with no stream state. pub fn new(display: &Rc) -> HevcDecoder { HevcDecoder { display: Rc::clone(display), vps_map: (0..16).map(|_| None).collect(), sps_map: (0..16).map(|_| None).collect(), pps_map: (0..64).map(|_| None).collect(), session: None, dpb: Dpb::new(), ready: ReadyFrames::default(), current: None, no_rasl_output: false, colour_tags: Tags::default(), colour_light: ContentLight::default(), } } /// Decode one Annex B access unit. pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { for nal in split_annex_b(data) { match nal.header.nal_type { NalUnitType::Vps => { let vps = Vps::parse(&nal.rbsp())?; let id = usize::from(vps.id); if id < self.vps_map.len() { self.vps_map[id] = Some(vps); } } NalUnitType::Sps => { let sps = Sps::parse(&nal.rbsp())?; self.dpb.max_reorder = sps.max_num_reorder_pics as usize; self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; self.colour_tags = vui_colour_tags(&sps); let id = sps.id as usize; if id < self.sps_map.len() { self.sps_map[id] = Some(sps); } } NalUnitType::Pps => { let pps = Pps::parse(&nal.rbsp())?; let id = pps.id as usize; if id < self.pps_map.len() { self.pps_map[id] = Some(pps); } } t if t.is_vcl() => { self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?; } _ => {} } } // The HDR SEI messages (mastering display, content light level) live // outside the slice loop above and are read on the whole access unit: // an encoder writes them once, ahead of the IRAP they describe, and // they otherwise say nothing (`ContentLight::default()`), so a later // access unit that carries neither never overwrites what an earlier // one declared. let light = ec_core::color::hevc_sei_light(data); if light != ContentLight::default() { self.colour_light = light.over(self.colour_light); } self.finish_picture()?; Ok(()) } /// This stream's colour metadata, once its first SPS has been seen. pub fn colour(&self) -> Option { let session = self.session.as_ref()?; Some(Colour { description: ColorDescription::resolve( Tags::default(), self.colour_tags, session.display_size.1, ), light: self.colour_light, }) } /// The next frame in output order. pub fn next_frame(&mut self) -> Option { self.ready.pop() } /// Push every buffered picture out (end of stream). pub fn flush(&mut self) { let _ = self.finish_picture(); self.bump(true); } /// Drop all picture state after a seek; parameter sets survive. pub fn reset(&mut self) { self.current = None; self.dpb.pictures.clear(); self.ready.clear(); self.dpb.prev_tid0_poc = 0; self.dpb.started = false; self.no_rasl_output = false; } /// What the stream turned out to be. pub fn stream_info(&self) -> Option { self.session.as_ref().map(Session::info) } fn slice( &mut self, nal_type: NalUnitType, temporal_id: u8, payload: &[u8], timestamp: i64, ) -> Result<()> { let rbsp = unescape_rbsp(payload); // The header cannot be parsed without its PPS, and the PPS names the SPS. let pps_id = peek_pps_id(&rbsp, nal_type)?; let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { return Ok(()); }; let Some(sps) = self .sps_map .get(pps.sps_id as usize) .and_then(|s| s.clone()) else { return Ok(()); }; let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?; if sh.first_slice_segment_in_pic { self.finish_picture()?; // 8.1.3 / C.5.2.2: a RASL picture associated with an IRAP whose // NoRaslOutputFlag is 1 predicts from pictures before that IRAP, // which a mid-stream start never decoded. It is not output and // is not guaranteed decodable, so it is dropped whole rather than // handed to the driver. if !(is_rasl_picture(nal_type) && self.no_rasl_output) { self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?; } } if self.current.is_none() { return Ok(()); } self.render_slice(&sps, &pps, &sh, &pos, payload, nal_type) } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { let amd = || { ec_va::display::vendor(&self.display) .is_ok_and(|v| v.contains("AMD") || v.contains("radeonsi")) }; if hevc_ctb16_broken(sps, amd) { return Err(Error::unsupported( "VA-API H.265 decode", "16x16 CTBs on AMD decode with wrong chroma", )); } let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8; let profile = match (sps.chroma_format_idc, bit_depth) { (1, 8) => Profile::HEVCMain, (1, 10) => Profile::HEVCMain10, (chroma, depth) => { return Err(Error::unsupported( format!("HEVC chroma_format_idc {chroma} at {depth} bits"), "only Main and Main10 (4:2:0, 8 or 10 bit) are decoded in hardware", )); } }; let coded = ( sps.pic_width_in_luma_samples, sps.pic_height_in_luma_samples, ); if let Some(session) = &self.session && session.coded_size == coded && session.bit_depth == bit_depth && session.profile == profile { return Ok(()); } self.current = None; self.dpb.pictures.clear(); self.session = Some(Session::new( &self.display, profile, coded, sps.display_size(), bit_depth, self.dpb.max_dec_pic_buffering + EXTRA_SURFACES, )?); Ok(()) } fn start_picture( &mut self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, temporal_id: u8, timestamp: i64, ) -> Result<()> { self.ensure_session(sps)?; if nal_type.is_irap() { // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded // video sequence — which a mid-stream start's first IRAP always // is, `self.started` still being false at that point. self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; } let poc = self.dpb.picture_order_count(sps, sh, nal_type); // 8.3.2 runs before the picture is decoded and after its POC is known: // every stored picture the set does not name stops being a reference. let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { // An IRAP that restarts output order: everything ahead of it in the // buffer belongs ahead of it on screen too. self.bump(true); } if std::env::var_os("EC_HW_DEBUG").is_some() { eprintln!( "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", nal_type, sh.poc_lsb, self.dpb.pictures.len(), self.ready.len(), rps.st_curr_before.len(), rps.st_curr_after.len(), rps.lt_curr.len(), self.session .as_ref() .map(|s| s.pool.available()) .unwrap_or(0), ); } let session = self .session .as_ref() .ok_or_else(|| Error::config("HEVC picture before any SPS"))?; let surface = session.acquire()?; // The driver indexes RefPicList into `reference_frames`, so the mapping // from DPB slot to that array is fixed once, here. let mut va_index = vec![0xffu8; self.dpb.pictures.len()]; let mut n = 0u8; for (i, pic) in self.dpb.pictures.iter().enumerate() { if pic.mark != Mark::Unused && n < 15 { va_index[i] = n; n += 1; } } self.current = Some(Current { surface, sps_id: sps.id, poc, timestamp, // A "_N" picture (an even NAL type below 16) is a sub-layer // non-reference: nothing in its own sub-layer may predict from it, // and a decoder that stores it as a reference lets the next // picture's reference picture set match the wrong picture by POC. is_reference: is_reference_picture(nal_type), // 8.3.1: `prevTid0Pic` is the previous picture with TemporalId 0 // that is neither RASL, RADL nor sub-layer non-reference. Taking // the previous picture instead — which a stream with temporal // sub-layers immediately punishes — puts the picture order count // MSB one wrap out and hands the driver the wrong references. is_tid0_anchor: temporal_id == 0 && is_reference_picture(nal_type) && !is_leading_picture(nal_type), output: sh.pic_output_flag, rps, buffers: Vec::new(), slices: 0, va_index, }); Ok(()) } fn render_slice( &mut self, sps: &Sps, pps: &Pps, sh: &SliceHeader, pos: &ParsePositions, payload: &[u8], nal_type: NalUnitType, ) -> Result<()> { let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else { return Ok(()); }; if current.sps_id != sps.id { return Err(Error::Stream(ec_core::Error::corrupt( "HEVC SPS changed mid-picture", ))); } if current.slices == 0 { let slots: Vec = self.dpb.pictures.iter().map(DpbSlot::of).collect(); let pic_param = picture_parameters( sps, pps, sh, pos, nal_type, (current.surface.id(), current.poc), ¤t.rps, &slots, ); current.buffers.push(ec_va::picture::buffer( &session.context, pic_param.to_buffer(), )?); if sps.scaling_list_enabled { // The PPS lists override the SPS lists, and with neither sent the // defaults of Tables 7-5 and 7-6 apply. let list = pps .scaling_list .clone() .or_else(|| sps.scaling_list.clone()) .unwrap_or_default(); current.buffers.push(ec_va::picture::buffer( &session.context, iq_matrix(&list).to_buffer(), )?); } } // The NAL unit header is part of the slice data the driver is handed, // and every offset it is given is measured from there. let nal_bytes = payload.len() + 2; let mut slice_param = SliceParameterBufferHEVC { slice_data_size: nal_bytes as u32, slice_data_offset: 0, slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL slice_data_byte_offset: pos.slice_data_byte_offset(payload) as u32, slice_segment_address: sh.segment_address, collocated_ref_idx: if sh.temporal_mvp_enabled { sh.collocated_ref_idx as u8 } else { 0xff }, num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active_minus1 as u8, num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active_minus1 as u8, slice_qp_delta: sh.qp_delta as i8, slice_cb_qp_offset: sh.cb_qp_offset as i8, slice_cr_qp_offset: sh.cr_qp_offset as i8, slice_beta_offset_div2: sh.beta_offset_div2 as i8, slice_tc_offset_div2: sh.tc_offset_div2 as i8, five_minus_max_num_merge_cand: sh.five_minus_max_num_merge_cand as u8, num_entry_point_offsets: entry_point_count(&sh.entry_point_offsets), slice_data_num_emu_prevn_bytes: ec_h265_syntax::count_emulation_prevention_bytes( payload, ) .min(u16::MAX as usize) as u16, ..SliceParameterBufferHEVC::default() }; slice_param.long_slice_flags = LongSliceFlags { last_slice_of_pic: 0, dependent_slice_segment_flag: u32::from(sh.dependent_slice_segment), slice_type: sh.slice_type.code(), color_plane_id: u32::from(sh.colour_plane_id), slice_sao_luma_flag: u32::from(sh.sao_luma), slice_sao_chroma_flag: u32::from(sh.sao_chroma), mvd_l1_zero_flag: u32::from(sh.mvd_l1_zero), cabac_init_flag: u32::from(sh.cabac_init), slice_temporal_mvp_enabled_flag: u32::from(sh.temporal_mvp_enabled), slice_deblocking_filter_disabled_flag: u32::from(sh.deblocking_filter_disabled), collocated_from_l0_flag: u32::from(sh.collocated_from_l0), slice_loop_filter_across_slices_enabled_flag: u32::from( sh.loop_filter_across_slices_enabled, ), }; if sh.slice_type != SliceType::I { let lists = reference_lists(sh, ¤t.rps); // A P or B slice with no reference picture at all is a broken GOP: // its list would name no surface. if lists[0].is_empty() || (sh.slice_type == SliceType::B && lists[1].is_empty()) { return Err(Error::Stream(ec_core::Error::corrupt( "HEVC inter slice with no reference picture in its reference picture set", ))); } for (x, list) in lists.iter().enumerate() { for (i, &dpb_idx) in list.iter().take(15).enumerate() { slice_param.ref_pic_list[x][i] = current.va_index.get(dpb_idx).copied().unwrap_or(0xff); } } } write_weights(&mut slice_param, sh); current.buffers.push(ec_va::picture::buffer( &session.context, slice_param.to_buffer(), )?); // Rebuild the NAL unit: `split_annex_b` hands over the payload without // its two header bytes, and the driver counts from them. let mut nal = Vec::with_capacity(nal_bytes); nal.extend_from_slice(&ec_h265_syntax::NalHeader::new(nal_type).to_bytes()); nal.extend_from_slice(payload); current.buffers.push(ec_va::picture::buffer( &session.context, ec_va::va::BufferType::SliceData(nal), )?); current.slices += 1; Ok(()) } fn finish_picture(&mut self) -> Result<()> { let Some(current) = self.current.take() else { return Ok(()); }; let Some(session) = self.session.as_ref() else { return Ok(()); }; if current.slices == 0 { return Ok(()); } session.submit(¤t.surface, current.buffers)?; self.dpb.pictures.push(StoredPicture { surface: Rc::clone(¤t.surface), poc: current.poc, timestamp: current.timestamp, mark: if current.is_reference { Mark::ShortTerm } else { Mark::Unused }, output: current.output, }); if current.is_tid0_anchor { self.dpb.prev_tid0_poc = current.poc; } self.dpb.started = true; self.bump(false); Ok(()) } /// The bumping process (C.5.2.4): output while the buffer holds more than /// its reordering or storage limit allows. fn bump(&mut self, flush: bool) { let Some(session) = self.session.as_ref() else { return; }; while let Some(idx) = self.dpb.next_output(flush) { let pic = &self.dpb.pictures[idx]; self.ready.push(Frame::new( Rc::clone(&pic.surface), Rc::clone(&self.display), pic.timestamp, session.display_size, session.coded_size, session.bit_depth, self.colour(), )); self.dpb.released(idx); } } } /// Reference list construction (8.3.4), as DPB indices. fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec; 2] { let mut out = [Vec::new(), Vec::new()]; let counts = [ sh.num_ref_idx_l0_active_minus1 as usize + 1, sh.num_ref_idx_l1_active_minus1 as usize + 1, ]; for x in 0..2 { if x == 1 && sh.slice_type != SliceType::B { continue; } // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; list 1 swaps the // first two, which is the whole difference between the two lists. let mut temp: Vec = Vec::new(); while temp.len() < counts[x] { let before = if x == 0 { &rps.st_curr_before } else { &rps.st_curr_after }; let after = if x == 0 { &rps.st_curr_after } else { &rps.st_curr_before }; let round = before.len() + after.len() + rps.lt_curr.len(); if round == 0 { break; } temp.extend(before.iter().copied()); temp.extend(after.iter().copied()); temp.extend(rps.lt_curr.iter().copied()); } if temp.is_empty() { continue; } for i in 0..counts[x] { let idx = match sh.list_entry[x].get(i) { Some(&entry) => *temp.get(entry as usize).unwrap_or(&temp[0]), None => temp[i.min(temp.len() - 1)], }; out[x].push(idx); } } out } #[allow(clippy::too_many_arguments)] fn picture_parameters( sps: &Sps, pps: &Pps, sh: &SliceHeader, pos: &ParsePositions, nal_type: NalUnitType, (curr_id, curr_poc): (u32, i32), rps: &Rps, dpb: &[DpbSlot], ) -> PictureParameterBufferHEVC { let mut p = PictureParameterBufferHEVC { curr_pic: VAPictureHEVC::new(curr_id, curr_poc, 0), pic_width_in_luma_samples: sps.pic_width_in_luma_samples as u16, pic_height_in_luma_samples: sps.pic_height_in_luma_samples as u16, sps_max_dec_pic_buffering_minus1: sps.max_dec_pic_buffering_minus1 as u8, bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, pcm_sample_bit_depth_luma_minus1: sps.pcm.map(|p| p.0 as u8).unwrap_or(0), pcm_sample_bit_depth_chroma_minus1: sps.pcm.map(|p| p.1 as u8).unwrap_or(0), log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, log2_min_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, log2_diff_max_min_transform_block_size: sps.log2_diff_max_min_tb_size as u8, log2_min_pcm_luma_coding_block_size_minus3: sps.pcm.map(|p| p.2 as u8).unwrap_or(0), log2_diff_max_min_pcm_luma_coding_block_size: sps.pcm.map(|p| p.3 as u8).unwrap_or(0), max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, init_qp_minus26: pps.init_qp_minus26 as i8, diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, pps_cb_qp_offset: pps.cb_qp_offset as i8, pps_cr_qp_offset: pps.cr_qp_offset as i8, log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, num_short_term_ref_pic_sets: sps.num_short_term_ref_pic_sets as u8, num_long_term_ref_pic_sps: sps.num_long_term_ref_pics_sps as u8, num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, pps_beta_offset_div2: pps.beta_offset_div2 as i8, pps_tc_offset_div2: pps.tc_offset_div2 as i8, num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, // The size of an `st_ref_pic_set()` the slice header carried itself, // so the driver can skip it; zero when the slice named an SPS set, // which is what the parser reports. st_rps_bits: pos.st_rps_bits, ..PictureParameterBufferHEVC::default() }; // Tile geometry: uniform spacing is expanded here because libva wants the // widths either way (`va_dec_hevc.h:125`). let (cols, rows) = ( pps.num_tile_columns_minus1 as usize + 1, pps.num_tile_rows_minus1 as usize + 1, ); if pps.tiles_enabled { let ctb_cols = sps.pic_width_in_ctbs(); let ctb_rows = sps.pic_height_in_ctbs(); for i in 0..cols.min(p.column_width_minus1.len()) { let width = if pps.uniform_spacing { ((i + 1) as u32 * ctb_cols) / cols as u32 - (i as u32 * ctb_cols) / cols as u32 } else { pps.column_width_minus1.get(i).copied().unwrap_or(0) + 1 }; p.column_width_minus1[i] = width.saturating_sub(1) as u16; } for i in 0..rows.min(p.row_height_minus1.len()) { let height = if pps.uniform_spacing { ((i + 1) as u32 * ctb_rows) / rows as u32 - (i as u32 * ctb_rows) / rows as u32 } else { pps.row_height_minus1.get(i).copied().unwrap_or(0) + 1 }; p.row_height_minus1[i] = height.saturating_sub(1) as u16; } } let mut n = 0usize; for (i, pic) in dpb.iter().enumerate() { if pic.mark == Mark::Unused || n >= p.reference_frames.len() { continue; } let mut flags = 0; if pic.mark == Mark::LongTerm { flags |= PICTURE_LONG_TERM_REFERENCE; } if rps.st_curr_before.contains(&i) { flags |= PICTURE_RPS_ST_CURR_BEFORE; } else if rps.st_curr_after.contains(&i) { flags |= PICTURE_RPS_ST_CURR_AFTER; } else if rps.lt_curr.contains(&i) { flags |= PICTURE_RPS_LT_CURR; } p.reference_frames[n] = VAPictureHEVC::new(pic.id, pic.poc, flags); n += 1; } for entry in p.reference_frames.iter_mut().skip(n) { *entry = VAPictureHEVC::new(ec_va::va::VA_INVALID_SURFACE, 0, PICTURE_INVALID); } p.pic_fields = PicFields { chroma_format_idc: sps.chroma_format_idc, separate_colour_plane_flag: u32::from(sps.separate_colour_plane), pcm_enabled_flag: u32::from(sps.pcm_enabled), scaling_list_enabled_flag: u32::from(sps.scaling_list_enabled), transform_skip_enabled_flag: u32::from(pps.transform_skip_enabled), amp_enabled_flag: u32::from(sps.amp_enabled), strong_intra_smoothing_enabled_flag: u32::from(sps.strong_intra_smoothing), sign_data_hiding_enabled_flag: u32::from(pps.sign_data_hiding_enabled), constrained_intra_pred_flag: u32::from(pps.constrained_intra_pred), cu_qp_delta_enabled_flag: u32::from(pps.cu_qp_delta_enabled), weighted_pred_flag: u32::from(pps.weighted_pred), weighted_bipred_flag: u32::from(pps.weighted_bipred), transquant_bypass_enabled_flag: u32::from(pps.transquant_bypass_enabled), tiles_enabled_flag: u32::from(pps.tiles_enabled), entropy_coding_sync_enabled_flag: u32::from(pps.entropy_coding_sync_enabled), pps_loop_filter_across_slices_enabled_flag: u32::from(pps.loop_filter_across_slices_enabled), loop_filter_across_tiles_enabled_flag: u32::from(pps.loop_filter_across_tiles_enabled), pcm_loop_filter_disabled_flag: u32::from(sps.pcm.map(|p| p.4).unwrap_or(false)), no_pic_reordering_flag: u32::from(sps.max_num_reorder_pics == 0), no_bi_pred_flag: u32::from(sh.slice_type != SliceType::B), }; p.slice_parsing_fields = SliceParsingFields { lists_modification_present_flag: u32::from(pps.lists_modification_present), long_term_ref_pics_present_flag: u32::from(sps.long_term_ref_pics_present), sps_temporal_mvp_enabled_flag: u32::from(sps.temporal_mvp_enabled), cabac_init_present_flag: u32::from(pps.cabac_init_present), output_flag_present_flag: u32::from(pps.output_flag_present), dependent_slice_segments_enabled_flag: u32::from(pps.dependent_slice_segments_enabled), pps_slice_chroma_qp_offsets_present_flag: u32::from(pps.slice_chroma_qp_offsets_present), sample_adaptive_offset_enabled_flag: u32::from(sps.sao_enabled), deblocking_filter_override_enabled_flag: u32::from(pps.deblocking_filter_override_enabled), pps_disable_deblocking_filter_flag: u32::from(pps.deblocking_filter_disabled), slice_segment_header_extension_present_flag: u32::from(pps.slice_segment_header_extension_present), rap_pic_flag: u32::from(nal_type.is_irap()), idr_pic_flag: u32::from(nal_type.is_idr()), intra_pic_flag: u32::from(sh.slice_type == SliceType::I), }; p } /// `num_entry_point_offsets` for the slice parameter buffer. The count comes from /// the stream, not a fixed array: a 4K wavefront HEVC has 33 (one past the 32 a /// fixed `[u32; 32]` holds), and a tiled one can pass 255. fn entry_point_count(offsets: &[u32]) -> u16 { offsets.len().min(u16::MAX as usize) as u16 } /// Copy the parsed `pred_weight_table()` into the slice parameter buffer. fn write_weights(s: &mut SliceParameterBufferHEVC, sh: &SliceHeader) { let Some(w) = sh.pred_weight_table.as_ref() else { return; }; s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8; s.delta_chroma_log2_weight_denom = w.delta_chroma_log2_weight_denom as i8; for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] { let (dlw, lo, dcw, co) = if list == 0 { ( &mut s.delta_luma_weight_l0, &mut s.luma_offset_l0, &mut s.delta_chroma_weight_l0, &mut s.chroma_offset_l0, ) } else { ( &mut s.delta_luma_weight_l1, &mut s.luma_offset_l1, &mut s.delta_chroma_weight_l1, &mut s.chroma_offset_l1, ) }; for (i, entry) in entries.iter().take(15).enumerate() { if let Some((weight, offset)) = entry.luma { dlw[i] = weight as i8; lo[i] = offset as i8; } if let Some(pair) = entry.chroma { for c in 0..2 { dcw[i][c] = pair[c].0 as i8; co[i][c] = pair[c].1 as i8; } } } } } /// The `VAIQMatrixBufferHEVC` for a parsed list set. VA takes the coefficients in /// up-right diagonal order, which is how the syntax crate stores them. For 32x32 /// only matrixId 0 (intra luma) and 3 (inter luma) are coded, so VA's two entries /// are those. fn iq_matrix(list: &ec_h265_syntax::ScalingList) -> IQMatrixBufferHEVC { let mut iq = IQMatrixBufferHEVC::default(); for m in 0..6 { iq.scaling_list_4x4[m].copy_from_slice(&list.coefficients[0][m][..16]); iq.scaling_list_8x8[m] = list.coefficients[1][m]; iq.scaling_list_16x16[m] = list.coefficients[2][m]; iq.scaling_list_dc_16x16[m] = list.dc[2][m]; } for (slot, matrix_id) in [0usize, 3].into_iter().enumerate() { iq.scaling_list_32x32[slot] = list.coefficients[3][matrix_id]; iq.scaling_list_dc_32x32[slot] = list.dc[3][matrix_id]; } iq } /// Fuzzing entry point for the VA-API picture and slice parameter builders. Walks /// the Annex B `data` as a stream: each SPS and PPS replaces the last, and each /// slice that parses against them runs through [`picture_parameters`] and /// [`write_weights`] with a synthetic DPB of up to 15 slots. Returns the number of /// slices built. No GPU: the surface ids are plain numbers here. #[doc(hidden)] pub fn fuzz_build_parameters(data: &[u8]) -> usize { let mut sps: Option = None; let mut pps: Option = None; let mut built = 0usize; for nal in ec_h265_syntax::split_annex_b(data) { let rbsp = nal.rbsp(); match nal.header.nal_type { NalUnitType::Sps => sps = Sps::parse(&rbsp).ok(), NalUnitType::Pps => pps = Pps::parse(&rbsp).ok(), nal_type => { let (Some(s), Some(p)) = (sps.as_ref(), pps.as_ref()) else { continue; }; let Ok((sh, pos)) = SliceHeader::parse(&rbsp, s, p, nal_type) else { continue; }; let n = (data.len() % 16).max(1); let slots: Vec = (0..n) .map(|i| DpbSlot { id: 0x100 + i as u32, poc: i as i32 - (n as i32 / 2), mark: match i % 3 { 0 => Mark::ShortTerm, 1 => Mark::LongTerm, _ => Mark::Unused, }, }) .collect(); let rps = Rps { st_curr_before: (0..n).step_by(2).collect(), st_curr_after: (1..n).step_by(3).collect(), lt_curr: (2..n).step_by(4).collect(), }; let pic = picture_parameters( s, p, &sh, &pos, nal_type, (0x200, data.len() as i32), &rps, &slots, ); let mut slice = SliceParameterBufferHEVC::default(); write_weights(&mut slice, &sh); slice.num_entry_point_offsets = entry_point_count(&sh.entry_point_offsets); std::hint::black_box((pic, slice)); built += 1; } } } built } #[cfg(test)] mod tests { use super::*; #[test] fn entry_points_are_counted_past_32_and_past_u8() { // 33 is a 4K wavefront film (PicHeightInCtbsY - 1); 440 is 20 x 22 tiles. assert_eq!(entry_point_count(&[1; 33]), 33); assert_eq!(entry_point_count(&[1; 440]), 440); // Past u16 saturates rather than wrapping to a small count. assert_eq!(entry_point_count(&vec![1; 70_000]), u16::MAX); assert_eq!(entry_point_count(&[]), 0); } #[test] fn fuzz_entry_is_total_on_garbage() { assert_eq!(fuzz_build_parameters(&[]), 0); assert_eq!(fuzz_build_parameters(&[0, 0, 1, 0x26, 0x01, 0xff, 0xff]), 0); } }