//! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices. use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use ec_h265_syntax::{ AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, split_annex_b, }; use ec_vk::{ H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, }; use crate::error::{Error, Result}; use crate::hevc_dpb::{ self, AMD_VENDOR_ID, Dpb, Mark, hevc_ctb16_broken, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, peek_pps_id, vui_colour_tags, }; use ec_core::color::{ColorDescription, Tags}; use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; const MAX_SLOTS: u32 = 17; struct Session { h265: Rc>, ring: Ring, bit_depth: u8, max_width: u32, max_height: u32, slots: u32, } struct Current { slot: u32, sps_id: u8, pps_id: u8, nal_type: NalUnitType, st_rps_bits: u32, short_term_ref_pic_set_sps: bool, poc: i32, timestamp: i64, output: bool, is_tid0_anchor: bool, st_curr_before: Vec, st_curr_after: Vec, lt_curr: Vec, slices: Vec>, } /// H.265 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. pub(crate) struct VkH265Decoder { gpu: ec_vk::Gpu, session: Option, params_dirty: bool, vps_map: Vec>, sps_map: Vec>, pps_map: Vec>, dpb: Dpb, outputs: HashMap, current: Option, ready: VecDeque, no_rasl_output: bool, } impl VkH265Decoder { pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; Ok(VkH265Decoder { gpu, session: None, params_dirty: false, vps_map: vec![None; 16], sps_map: vec![None; 16], pps_map: vec![None; 64], dpb: Dpb::new(), outputs: HashMap::new(), current: None, ready: VecDeque::new(), no_rasl_output: false, }) } pub(crate) 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 let Some(slot) = self.vps_map.get_mut(id) { self.params_dirty |= store(slot, vps); } } NalUnitType::Sps => { self.finish_picture()?; 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; let id = sps.id as usize; if let Some(slot) = self.sps_map.get_mut(id) { self.params_dirty |= store(slot, sps); } } NalUnitType::Pps => { let pps = Pps::parse(&nal.rbsp())?; let id = pps.id as usize; if let Some(slot) = self.pps_map.get_mut(id) { self.params_dirty |= store(slot, pps); } } t if t.is_vcl() => self.slice(&nal, timestamp)?, _ => {} } } self.finish_picture() } pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } pub(crate) fn reset(&mut self) { self.current = None; self.dpb.pictures.clear(); self.dpb.started = false; self.dpb.prev_tid0_poc = 0; self.outputs.clear(); self.ready.clear(); } pub(crate) fn flush(&mut self) -> Result<()> { self.finish_picture()?; self.bump(true); Ok(()) } fn slice(&mut self, nal: &AnnexBNal, timestamp: i64) -> Result<()> { let rbsp = nal.rbsp(); let nal_type = nal.header.nal_type; 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()?; if !(is_rasl_picture(nal_type) && self.no_rasl_output) { self.start_picture(&sps, &sh, pos.st_rps_bits, nal, timestamp)?; } } if let Some(current) = self.current.as_mut() { let mut raw = nal.header.to_bytes().to_vec(); raw.extend_from_slice(nal.payload); current.slices.push(raw); } Ok(()) } fn start_picture( &mut self, sps: &Sps, sh: &SliceHeader, st_rps_bits: u32, nal: &AnnexBNal, timestamp: i64, ) -> Result<()> { let nal_type = nal.header.nal_type; self.ensure_session(sps)?; if self.params_dirty { self.set_parameters()?; } if nal_type.is_irap() { 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); let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; let ids = |list: &[usize]| -> Vec { list.iter().map(|&i| self.dpb.pictures[i].surface).collect() }; let (st_curr_before, st_curr_after, lt_curr) = ( ids(&rps.st_curr_before), ids(&rps.st_curr_after), ids(&rps.lt_curr), ); if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { self.bump(true); } let slot = self.free_slot()?; let is_reference = is_reference_picture(nal_type); self.current = Some(Current { slot, sps_id: sps.id as u8, pps_id: sh.pps_id as u8, nal_type, st_rps_bits, short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, poc, timestamp, output: sh.pic_output_flag, is_tid0_anchor: nal.header.temporal_id == 0 && is_reference && !is_leading_picture(nal_type), st_curr_before, st_curr_after, lt_curr, slices: Vec::new(), }); Ok(()) } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { if hevc_ctb16_broken(sps, || self.gpu.vendor_id() == AMD_VENDOR_ID) { return Err(Error::unsupported( "Vulkan H.265 decode", "16x16 CTBs on AMD decode with wrong chroma", )); } if sps.chroma_format_idc != 1 || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8 || !matches!(sps.bit_depth_luma_minus8, 0 | 2) { return Err(Error::unsupported( "Vulkan H.265 decode", "only 8- and 10-bit 4:2:0", )); } let bit_depth = (8 + sps.bit_depth_luma_minus8) as u8; let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS); let (w, h) = ( sps.pic_width_in_luma_samples, sps.pic_height_in_luma_samples, ); if let Some(s) = &self.session && s.bit_depth == bit_depth && s.max_width == w && s.max_height == h && slots <= s.slots { return Ok(()); } self.bump(true); self.current = None; self.dpb.pictures.clear(); self.outputs.clear(); self.session = None; let h265 = H265DecodeSession::new( &self.gpu, &H265DecodeConfig { max_width: w, max_height: h, max_dpb_slots: slots, bit_depth, }, )?; let ring = Ring::new(h265.ring_len()); self.session = Some(Session { h265: Rc::new(RefCell::new(h265)), ring, bit_depth, max_width: w, max_height: h, slots, }); self.params_dirty = true; Ok(()) } fn set_parameters(&mut self) -> Result<()> { let vps: Vec = self.vps_map.iter().flatten().map(vk_vps).collect(); let sps: Vec = self.sps_map.iter().flatten().map(vk_sps).collect(); let pps: Vec = self .pps_map .iter() .flatten() .filter(|p| { self.sps_map .get(p.sps_id as usize) .is_some_and(Option::is_some) }) .map(vk_pps) .collect(); let session = self .session .as_mut() .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?; session.h265.borrow_mut().set_parameters(&vps, &sps, &pps)?; self.params_dirty = false; Ok(()) } fn free_slot(&self) -> Result { let session = self .session .as_ref() .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; (0..session.slots) .find(|slot| self.dpb.pictures.iter().all(|p| p.surface != *slot)) .ok_or_else(|| Error::config("H.265 Vulkan decode: every DPB slot is in use")) } fn finish_picture(&mut self) -> Result<()> { let Some(current) = self.current.take() else { return Ok(()); }; let Some(sps) = self .sps_map .get(usize::from(current.sps_id)) .and_then(|s| s.clone()) else { return Ok(()); }; let refs: Vec = self .dpb .pictures .iter() .filter(|p| p.mark != Mark::Unused) .map(|p| H265RefSlot { slot: p.surface, poc: p.poc, long_term: p.mark == Mark::LongTerm, }) .collect(); let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect(); let session = self .session .as_mut() .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; session.h265.borrow_mut().decode(&H265DecodePicture { vps_id: sps.vps_id, sps_id: current.sps_id, pps_id: current.pps_id, irap: current.nal_type.is_irap(), idr: current.nal_type.is_idr(), reference: is_reference_picture(current.nal_type), poc: current.poc, setup_slot: current.slot, short_term_ref_pic_set_sps: current.short_term_ref_pic_set_sps, num_delta_pocs_of_ref_rps_idx: 0, st_rps_bits: current.st_rps_bits, st_curr_before: ¤t.st_curr_before, st_curr_after: ¤t.st_curr_after, lt_curr: ¤t.lt_curr, refs: &refs, slices: &slices, })?; if current.output { let slot = session.ring.take(|| Ok(session.h265.borrow_mut().add_ring_slot()?))?; let (width, height) = sps.display_size(); let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); session.h265.borrow_mut().store_output( slot.index(), (origin.0, origin.1, width, height), )?; let matrix = ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height).matrix; let picture = VkPicture::new( Surfaces::H265(session.h265.clone()), slot, (width, height), (8 + sps.bit_depth_luma_minus8) as u8, matrix, ); self.outputs .insert(current.slot, HwPicture::vk(current.timestamp, picture)); } self.dpb.pictures.push(hevc_dpb::StoredPicture { surface: current.slot, poc: current.poc, timestamp: current.timestamp, mark: if is_reference_picture(current.nal_type) { 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(()) } fn bump(&mut self, flush: bool) { while let Some(idx) = self.dpb.next_output(flush) { let pic = &self.dpb.pictures[idx]; if let Some(frame) = self.outputs.remove(&pic.surface) { self.ready.push_back(frame); } self.dpb.released(idx); } } } fn store(slot: &mut Option, value: T) -> bool { if slot.as_ref() == Some(&value) { return false; } *slot = Some(value); true } fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel { H265ProfileTierLevel { tier_flag: p.tier_flag, progressive_source: p.progressive_source, interlaced_source: p.interlaced_source, non_packed_constraint: p.non_packed_constraint, frame_only_constraint: p.frame_only_constraint, profile_idc: p.profile_idc, level_idc: p.level_idc, } } fn dpbm( max_latency_increase_plus1: u32, max_dec_pic_buffering_minus1: u32, reorder: u32, ) -> ec_vk::H265DecPicBufMgr { ec_vk::H265DecPicBufMgr { max_latency_increase_plus1: [max_latency_increase_plus1; 7], max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], max_num_reorder_pics: [reorder as u8; 7], } } fn lists(l: &ScalingList) -> H265ScalingLists { let c = &l.coefficients; H265ScalingLists { list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), list_8x8: std::array::from_fn(|i| c[1][i]), list_16x16: std::array::from_fn(|i| c[2][i]), list_32x32: std::array::from_fn(|i| c[3][3 * i]), dc_16x16: std::array::from_fn(|i| l.dc[2][i]), dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), } } fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); H265ShortTermRefPicSet { delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), } } fn vk_vps(vps: &Vps) -> H265Vps { H265Vps { id: vps.id, max_sub_layers_minus1: 0, profile_tier_level: ptl(&vps.ptl), dec_pic_buf_mgr: dpbm( 0, vps.max_dec_pic_buffering_minus1, vps.max_num_reorder_pics, ), } } fn vk_sps(sps: &Sps) -> H265Sps { let c = &sps.conf_win; H265Sps { id: sps.id as u8, vps_id: sps.vps_id, max_sub_layers_minus1: 0, profile_tier_level: ptl(&sps.ptl), chroma_format_idc: sps.chroma_format_idc as u8, pic_width_in_luma_samples: sps.pic_width_in_luma_samples, pic_height_in_luma_samples: sps.pic_height_in_luma_samples, conformance_window: [c.left, c.right, c.top, c.bottom], bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, 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_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { bit_depth_luma_minus1: a as u8, bit_depth_chroma_minus1: b as u8, log2_min_luma_coding_block_size_minus3: c as u8, log2_diff_max_min_luma_coding_block_size: d as u8, loop_filter_disabled: e, }), dec_pic_buf_mgr: dpbm( sps.max_latency_increase_plus1, sps.max_dec_pic_buffering_minus1, sps.max_num_reorder_pics, ), scaling_list_enabled: sps.scaling_list_enabled, scaling_lists: sps.scaling_list.as_ref().map(lists), amp_enabled: sps.amp_enabled, sample_adaptive_offset_enabled: sps.sao_enabled, long_term_ref_pics_present: sps.long_term_ref_pics_present, long_term_ref_pics_sps: sps .long_term_ref_pics_sps .iter() .map( |&(poc_lsb, used_by_curr_pic)| ec_vk::H265LongTermRefPicSps { poc_lsb, used_by_curr_pic, }, ) .collect(), temporal_mvp_enabled: sps.temporal_mvp_enabled, strong_intra_smoothing_enabled: sps.strong_intra_smoothing, short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), } } fn vk_pps(pps: &Pps) -> H265Pps { H265Pps { id: pps.id as u8, sps_id: pps.sps_id as u8, dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, output_flag_present: pps.output_flag_present, num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, sign_data_hiding_enabled: pps.sign_data_hiding_enabled, cabac_init_present: pps.cabac_init_present, 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, init_qp_minus26: pps.init_qp_minus26 as i8, constrained_intra_pred: pps.constrained_intra_pred, transform_skip_enabled: pps.transform_skip_enabled, cu_qp_delta_enabled: pps.cu_qp_delta_enabled, diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, cb_qp_offset: pps.cb_qp_offset as i8, cr_qp_offset: pps.cr_qp_offset as i8, slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, weighted_pred: pps.weighted_pred, weighted_bipred: pps.weighted_bipred, transquant_bypass_enabled: pps.transquant_bypass_enabled, tiles_enabled: pps.tiles_enabled, entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, uniform_spacing: pps.uniform_spacing, column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, deblocking_filter_control_present: pps.deblocking_filter_control_present, deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, deblocking_filter_disabled: pps.deblocking_filter_disabled, beta_offset_div2: pps.beta_offset_div2 as i8, tc_offset_div2: pps.tc_offset_div2 as i8, scaling_lists: pps.scaling_list.as_ref().map(lists), lists_modification_present: pps.lists_modification_present, log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, slice_segment_header_extension_present: pps.slice_segment_header_extension_present, } }