//! H.264 decoding over Vulkan Video: the shared DPB over DPB slot indices. use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; use ec_h264_syntax::{ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp, }; use ec_vk::{ H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, ScalingLists, }; use crate::dpb264::{self, Mark, PicInfo, Poc}; use crate::error::{Error, Result}; use crate::h264_common::{peek_pps_id, vui_colour_tags}; use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; use ec_core::color::{ColorDescription, Tags}; const MAX_SLOTS: u32 = 17; type Dpb = dpb264::Dpb; type Picture = dpb264::Picture; struct Session { h264: Rc>, ring: Ring, max_width: u32, max_height: u32, slots: u32, chroma_format_idc: u8, } struct Current { slot: u32, id: i32, sps_id: u8, pps_id: u8, info: PicInfo, poc: Poc, idr_pic_id: u16, timestamp: i64, marking: Option, slices: Vec>, } struct Side { fields: [i32; 2], output: Option, } /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. pub(crate) struct VkH264Decoder { gpu: ec_vk::Gpu, session: Option, params_dirty: bool, sps_map: [Option; 32], pps_map: Vec>, dpb: Dpb, pics: HashMap, current: Option, ready: VecDeque, rbsp: Vec, } impl VkH264Decoder { pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; Ok(VkH264Decoder { gpu, session: None, params_dirty: false, sps_map: [const { None }; 32], pps_map: (0..256).map(|_| None).collect(), dpb: Dpb::default(), pics: HashMap::new(), current: None, ready: VecDeque::new(), rbsp: Vec::new(), }) } pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { for nal in AnnexBIter::new(data) { let Some((&first, payload)) = nal.split_first() else { continue; }; let header = NalHeader::parse(first)?; match header.unit_type { NalUnitType::Sps => { self.finish_picture()?; let mut rbsp = std::mem::take(&mut self.rbsp); unescape_rbsp(payload, &mut rbsp); let sps = Sps::parse(&rbsp); self.rbsp = rbsp; let sps = sps?; self.dpb.configure(&sps); let id = usize::from(sps.id); self.sps_map[id] = Some(sps); self.params_dirty = true; } NalUnitType::Pps => { let mut rbsp = std::mem::take(&mut self.rbsp); unescape_rbsp(payload, &mut rbsp); let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref()); self.rbsp = rbsp; let pps = pps?; let id = pps.id as usize; if id < self.pps_map.len() { self.pps_map[id] = Some(pps); self.params_dirty = true; } } NalUnitType::Slice | NalUnitType::SliceIdr => { self.slice(header, nal, payload, 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.clear(); self.pics.clear(); self.ready.clear(); } pub(crate) fn flush(&mut self) -> Result<()> { self.finish_picture()?; self.bump(true); Ok(()) } fn slice( &mut self, header: NalHeader, nal: &[u8], payload: &[u8], timestamp: i64, ) -> Result<()> { let mut rbsp = std::mem::take(&mut self.rbsp); unescape_rbsp(payload, &mut rbsp); let result = self.slice_rbsp(header, nal, &rbsp, timestamp); self.rbsp = rbsp; result } fn slice_rbsp( &mut self, header: NalHeader, nal: &[u8], rbsp: &[u8], timestamp: i64, ) -> Result<()> { let pps_id = peek_pps_id(rbsp)?; 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[usize::from(pps.sps_id)].clone() else { return Ok(()); }; let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?; if sh.first_mb_in_slice == 0 { self.finish_picture()?; self.start_picture(&sps, &sh, header, timestamp)?; } if let Some(current) = self.current.as_mut() { current.slices.push(nal.to_vec()); } Ok(()) } fn start_picture( &mut self, sps: &Sps, sh: &SliceHeader, header: NalHeader, timestamp: i64, ) -> Result<()> { let inter = !matches!(sh.slice_type, SliceType::I | SliceType::Si); if inter && !header.is_idr() && self.dpb.frames.iter().all(|p| p.mark == Mark::Unused) { return Err(Error::Stream(ec_core::Error::corrupt( "H.264 inter picture with no reference picture since the last IDR or reset", ))); } self.ensure_session(sps)?; if self.params_dirty { self.set_parameters()?; } let info = PicInfo { is_idr: header.is_idr(), is_reference: header.ref_idc != 0, frame_num: sh.frame_num, pic_order_cnt_lsb: sh.pic_order_cnt_lsb, delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, delta_pic_order_cnt: sh.delta_pic_order_cnt, }; if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { self.fill_gap(sps, sh.frame_num)?; } let poc = self.dpb.picture_order_count(sps, &info)?; let slot = self.free_slot()?; let id = self.dpb.next_id(); self.current = Some(Current { slot, id, sps_id: sps.id, pps_id: sh.pps_id as u8, info, poc, idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16, timestamp, marking: sh.dec_ref_pic_marking.clone(), slices: Vec::new(), }); Ok(()) } fn ensure_session(&mut self, sps: &Sps) -> Result<()> { if !matches!(sps.chroma_format_idc, 0 | 1) || sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 { return Err(Error::unsupported( "Vulkan H.264 decode", "only 8-bit 4:0:0 and 4:2:0", )); } let chroma = sps.chroma_format_idc; let slots = (self.dpb.capacity() as u32 + 1).min(MAX_SLOTS); let (w, h) = (sps.coded_width, sps.coded_height); if let Some(s) = &self.session && s.chroma_format_idc == chroma && s.max_width == w && s.max_height == h && slots <= s.slots { return Ok(()); } self.bump(true); self.current = None; self.dpb.clear(); self.pics.clear(); self.session = None; let h264 = H264DecodeSession::new( &self.gpu, &H264DecodeConfig { max_width: w, max_height: h, max_dpb_slots: slots, profile_idc: sps.profile_idc, chroma_format_idc: chroma, }, ) ?; let ring = Ring::new(h264.ring_len()); self.session = Some(Session { h264: Rc::new(RefCell::new(h264)), ring, max_width: w, max_height: h, slots, chroma_format_idc: chroma, }); self.params_dirty = true; Ok(()) } fn set_parameters(&mut self) -> Result<()> { let sps: Vec = self.sps_map.iter().flatten().map(vk_sps).collect(); let pps: Vec = self.pps_map.iter().flatten().map(vk_pps).collect(); let session = self .session .as_mut() .ok_or_else(|| Error::config("H.264 parameters before any SPS"))?; session.h264.borrow_mut().set_parameters(&sps, &pps)?; self.params_dirty = false; Ok(()) } fn free_slot(&self) -> Result { let session = self .session .as_ref() .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; (0..session.slots) .find(|slot| self.dpb.frames.iter().all(|p| p.surface != *slot)) .ok_or_else(|| Error::config("H.264 Vulkan decode: every DPB slot is in use")) } fn fill_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> { let before: Vec = self.dpb.frames.iter().map(|p| p.id).collect(); self.dpb.fill_frame_num_gap(sps, frame_num)?; for i in 0..self.dpb.frames.len() { if !before.contains(&self.dpb.frames[i].id) { self.dpb.frames[i].surface = self.free_slot()?; } } Ok(()) } fn finish_picture(&mut self) -> Result<()> { let Some(current) = self.current.take() else { return Ok(()); }; let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else { return Ok(()); }; let fields = field_pocs(current.poc.value, current.info.delta_pic_order_cnt_bottom); let refs: Vec = if current.info.is_idr { Vec::new() } else { self.dpb .frames .iter() .filter(|p| p.mark != Mark::Unused) .map(|p| H264RefSlot { slot: p.surface, frame_num: p.frame_num as u16, poc: self.pics.get(&p.id).map_or([p.poc, p.poc], |s| s.fields), long_term: p.mark == Mark::Long, non_existing: p.non_existing, }) .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.264 picture before any SPS"))?; let slot = session.ring.take(|| Ok(session.h264.borrow_mut().add_ring_slot()?))?; session.h264.borrow_mut().decode(&H264DecodePicture { sps_id: current.sps_id, pps_id: current.pps_id, idr: current.info.is_idr, reference: current.info.is_reference, frame_num: current.info.frame_num as u16, idr_pic_id: current.idr_pic_id, poc: fields, setup_slot: current.slot, refs: &refs, slices: &slices, }) ?; let (left, _, top, _) = sps.crop; session .h264 .borrow_mut() .store_output(slot.index(), (left, top, sps.width, sps.height))?; let matrix = ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height).matrix; let out = HwPicture::vk( current.timestamp, VkPicture::new( Surfaces::H264(session.h264.clone()), slot, (sps.width, sps.height), 8, matrix, ), ); let picture = Picture { id: current.id, surface: current.slot, timestamp: current.timestamp, frame_num: current.info.frame_num, frame_num_wrap: current.info.frame_num as i32, pic_num: current.info.frame_num as i32, long_term_frame_idx: 0, poc: current.poc.value, poc_msb: current.poc.msb, poc_lsb: current.poc.lsb, frame_num_offset: current.poc.frame_num_offset, mark: Mark::Unused, non_existing: false, output: true, }; self.pics.insert( current.id, Side { fields, output: Some(out), }, ); self.dpb .store(picture, &sps, ¤t.info, current.marking.as_ref(), true)?; self.bump(false); Ok(()) } fn bump(&mut self, flush: bool) { while let Some(idx) = self.dpb.next_output(flush) { let id = self.dpb.frames[idx].id; if let Some(frame) = self.pics.get_mut(&id).and_then(|s| s.output.take()) { self.ready.push_back(frame); } self.dpb.released(idx); } let frames = &self.dpb.frames; self.pics.retain(|id, _| frames.iter().any(|p| p.id == *id)); } } fn field_pocs(poc: i32, delta_bottom: i32) -> [i32; 2] { [poc - delta_bottom.min(0), poc + delta_bottom.max(0)] } fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists { let mut out = ScalingLists { l4x4: [[0; 16]; 6], l8x8: [[0; 64]; 6], }; for i in 0..6 { out.l4x4[i] = ZIGZAG_4X4.map(|r| l.list_4x4[i][usize::from(r)]); out.l8x8[i] = ZIGZAG_8X8.map(|r| l.list_8x8[i][usize::from(r)]); } out } fn vk_sps(sps: &Sps) -> H264Sps { let unit_y = if sps.frame_mbs_only { 2 } else { 4 }; let (left, right, top, bottom) = sps.crop; H264Sps { id: sps.id, profile_idc: sps.profile_idc, level_idc: sps.level_idc, chroma_format_idc: sps.chroma_format_idc, bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8), bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8), log2_max_frame_num_minus4: sps.log2_max_frame_num.saturating_sub(4), pic_order_cnt_type: sps.pic_order_cnt_type, log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb.saturating_sub(4), offset_for_non_ref_pic: sps.offset_for_non_ref_pic, offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field, offset_for_ref_frame: sps.offsets_for_ref_frame.clone(), max_num_ref_frames: sps.max_num_ref_frames as u8, pic_width_in_mbs_minus1: sps.mb_width.saturating_sub(1), pic_height_in_map_units_minus1: (if sps.frame_mbs_only { sps.mb_height } else { sps.mb_height / 2 }) .saturating_sub(1), frame_mbs_only: sps.frame_mbs_only, mb_adaptive_frame_field: sps.mb_adaptive_frame_field, direct_8x8_inference: sps.direct_8x8_inference, delta_pic_order_always_zero: sps.delta_pic_order_always_zero, frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y], qpprime_y_zero_transform_bypass: sps.transform_bypass, seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists), } } fn vk_pps(pps: &Pps) -> H264Pps { H264Pps { id: pps.id as u8, sps_id: pps.sps_id, entropy_coding_mode: pps.entropy_coding_mode, bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present, num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8, num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8, weighted_pred: pps.weighted_pred, weighted_bipred_idc: pps.weighted_bipred_idc, pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, deblocking_filter_control_present: pps.deblocking_filter_control_present, constrained_intra_pred: pps.constrained_intra_pred, redundant_pic_cnt_present: pps.redundant_pic_cnt_present, transform_8x8_mode: pps.transform_8x8_mode, pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists), } }