edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! H.264 decoding over Vulkan Video: the shared DPB over DPB slot indices. |
| 2 | |
| 3 | use std::cell::RefCell; |
| 4 | use std::collections::{HashMap, VecDeque}; |
| 5 | use std::rc::Rc; |
| 6 | |
| 7 | use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; |
| 8 | use ec_h264_syntax::{ |
| 9 | AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, |
| 10 | unescape_rbsp, |
| 11 | }; |
| 12 | use ec_vk::{ |
| 13 | H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, |
| 14 | ScalingLists, |
| 15 | }; |
| 16 | |
| 17 | use crate::dpb264::{self, Mark, PicInfo, Poc}; |
| 18 | use crate::error::{Error, Result}; |
| 19 | use crate::h264_common::{peek_pps_id, vui_colour_tags}; |
| 20 | use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; |
| 21 | use ec_core::color::{ColorDescription, Tags}; |
| 22 | |
| 23 | const MAX_SLOTS: u32 = 17; |
| 24 | |
| 25 | type Dpb = dpb264::Dpb<u32>; |
| 26 | type Picture = dpb264::Picture<u32>; |
| 27 | |
| 28 | struct Session { |
| 29 | h264: Rc<RefCell<H264DecodeSession>>, |
| 30 | ring: Ring, |
| 31 | max_width: u32, |
| 32 | max_height: u32, |
| 33 | slots: u32, |
| 34 | chroma_format_idc: u8, |
| 35 | } |
| 36 | |
| 37 | struct Current { |
| 38 | slot: u32, |
| 39 | id: i32, |
| 40 | sps_id: u8, |
| 41 | pps_id: u8, |
| 42 | info: PicInfo, |
| 43 | poc: Poc, |
| 44 | idr_pic_id: u16, |
| 45 | timestamp: i64, |
| 46 | marking: Option<DecRefPicMarking>, |
| 47 | slices: Vec<Vec<u8>>, |
| 48 | } |
| 49 | |
| 50 | struct Side { |
| 51 | fields: [i32; 2], |
| 52 | output: Option<HwPicture>, |
| 53 | } |
| 54 | |
| 55 | /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. |
| 56 | pub(crate) struct VkH264Decoder { |
| 57 | gpu: ec_vk::Gpu, |
| 58 | session: Option<Session>, |
| 59 | params_dirty: bool, |
| 60 | sps_map: [Option<Sps>; 32], |
| 61 | pps_map: Vec<Option<Pps>>, |
| 62 | dpb: Dpb, |
| 63 | pics: HashMap<i32, Side>, |
| 64 | current: Option<Current>, |
| 65 | ready: VecDeque<HwPicture>, |
| 66 | rbsp: Vec<u8>, |
| 67 | } |
| 68 | |
| 69 | impl VkH264Decoder { |
| 70 | pub(crate) fn new() -> Result<Self> { |
| 71 | let gpu = crate::hw::vk_gpu() |
| 72 | .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; |
| 73 | Ok(VkH264Decoder { |
| 74 | gpu, |
| 75 | session: None, |
| 76 | params_dirty: false, |
| 77 | sps_map: [const { None }; 32], |
| 78 | pps_map: (0..256).map(|_| None).collect(), |
| 79 | dpb: Dpb::default(), |
| 80 | pics: HashMap::new(), |
| 81 | current: None, |
| 82 | ready: VecDeque::new(), |
| 83 | rbsp: Vec::new(), |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 88 | for nal in AnnexBIter::new(data) { |
| 89 | let Some((&first, payload)) = nal.split_first() else { |
| 90 | continue; |
| 91 | }; |
| 92 | let header = NalHeader::parse(first)?; |
| 93 | match header.unit_type { |
| 94 | NalUnitType::Sps => { |
| 95 | self.finish_picture()?; |
| 96 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 97 | unescape_rbsp(payload, &mut rbsp); |
| 98 | let sps = Sps::parse(&rbsp); |
| 99 | self.rbsp = rbsp; |
| 100 | let sps = sps?; |
| 101 | self.dpb.configure(&sps); |
| 102 | let id = usize::from(sps.id); |
| 103 | self.sps_map[id] = Some(sps); |
| 104 | self.params_dirty = true; |
| 105 | } |
| 106 | NalUnitType::Pps => { |
| 107 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 108 | unescape_rbsp(payload, &mut rbsp); |
| 109 | let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref()); |
| 110 | self.rbsp = rbsp; |
| 111 | let pps = pps?; |
| 112 | let id = pps.id as usize; |
| 113 | if id < self.pps_map.len() { |
| 114 | self.pps_map[id] = Some(pps); |
| 115 | self.params_dirty = true; |
| 116 | } |
| 117 | } |
| 118 | NalUnitType::Slice | NalUnitType::SliceIdr => { |
| 119 | self.slice(header, nal, payload, timestamp)?; |
| 120 | } |
| 121 | _ => {} |
| 122 | } |
| 123 | } |
| 124 | self.finish_picture() |
| 125 | } |
| 126 | |
| 127 | pub(crate) fn next_frame(&mut self) -> Option<HwPicture> { |
| 128 | self.ready.pop_front() |
| 129 | } |
| 130 | |
| 131 | pub(crate) fn reset(&mut self) { |
| 132 | self.current = None; |
| 133 | self.dpb.clear(); |
| 134 | self.pics.clear(); |
| 135 | self.ready.clear(); |
| 136 | } |
| 137 | |
| 138 | pub(crate) fn flush(&mut self) -> Result<()> { |
| 139 | self.finish_picture()?; |
| 140 | self.bump(true); |
| 141 | Ok(()) |
| 142 | } |
| 143 | |
| 144 | fn slice( |
| 145 | &mut self, |
| 146 | header: NalHeader, |
| 147 | nal: &[u8], |
| 148 | payload: &[u8], |
| 149 | timestamp: i64, |
| 150 | ) -> Result<()> { |
| 151 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 152 | unescape_rbsp(payload, &mut rbsp); |
| 153 | let result = self.slice_rbsp(header, nal, &rbsp, timestamp); |
| 154 | self.rbsp = rbsp; |
| 155 | result |
| 156 | } |
| 157 | |
| 158 | fn slice_rbsp( |
| 159 | &mut self, |
| 160 | header: NalHeader, |
| 161 | nal: &[u8], |
| 162 | rbsp: &[u8], |
| 163 | timestamp: i64, |
| 164 | ) -> Result<()> { |
| 165 | let pps_id = peek_pps_id(rbsp)?; |
| 166 | let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { |
| 167 | return Ok(()); |
| 168 | }; |
| 169 | let Some(sps) = self.sps_map[usize::from(pps.sps_id)].clone() else { |
| 170 | return Ok(()); |
| 171 | }; |
| 172 | let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?; |
| 173 | if sh.first_mb_in_slice == 0 { |
| 174 | self.finish_picture()?; |
| 175 | self.start_picture(&sps, &sh, header, timestamp)?; |
| 176 | } |
| 177 | if let Some(current) = self.current.as_mut() { |
| 178 | current.slices.push(nal.to_vec()); |
| 179 | } |
| 180 | Ok(()) |
| 181 | } |
| 182 | |
| 183 | fn start_picture( |
| 184 | &mut self, |
| 185 | sps: &Sps, |
| 186 | sh: &SliceHeader, |
| 187 | header: NalHeader, |
| 188 | timestamp: i64, |
| 189 | ) -> Result<()> { |
| 190 | let inter = !matches!(sh.slice_type, SliceType::I | SliceType::Si); |
| 191 | if inter && !header.is_idr() && self.dpb.frames.iter().all(|p| p.mark == Mark::Unused) { |
| 192 | return Err(Error::Stream(ec_core::Error::corrupt( |
| 193 | "H.264 inter picture with no reference picture since the last IDR or reset", |
| 194 | ))); |
| 195 | } |
| 196 | self.ensure_session(sps)?; |
| 197 | if self.params_dirty { |
| 198 | self.set_parameters()?; |
| 199 | } |
| 200 | let info = PicInfo { |
| 201 | is_idr: header.is_idr(), |
| 202 | is_reference: header.ref_idc != 0, |
| 203 | frame_num: sh.frame_num, |
| 204 | pic_order_cnt_lsb: sh.pic_order_cnt_lsb, |
| 205 | delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, |
| 206 | delta_pic_order_cnt: sh.delta_pic_order_cnt, |
| 207 | }; |
| 208 | if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { |
| 209 | self.fill_gap(sps, sh.frame_num)?; |
| 210 | } |
| 211 | let poc = self.dpb.picture_order_count(sps, &info)?; |
| 212 | let slot = self.free_slot()?; |
| 213 | let id = self.dpb.next_id(); |
| 214 | self.current = Some(Current { |
| 215 | slot, |
| 216 | id, |
| 217 | sps_id: sps.id, |
| 218 | pps_id: sh.pps_id as u8, |
| 219 | info, |
| 220 | poc, |
| 221 | idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16, |
| 222 | timestamp, |
| 223 | marking: sh.dec_ref_pic_marking.clone(), |
| 224 | slices: Vec::new(), |
| 225 | }); |
| 226 | Ok(()) |
| 227 | } |
| 228 | |
| 229 | fn ensure_session(&mut self, sps: &Sps) -> Result<()> { |
| 230 | if !matches!(sps.chroma_format_idc, 0 | 1) |
| 231 | || sps.bit_depth_luma != 8 |
| 232 | || sps.bit_depth_chroma != 8 |
| 233 | { |
| 234 | return Err(Error::unsupported( |
| 235 | "Vulkan H.264 decode", |
| 236 | "only 8-bit 4:0:0 and 4:2:0", |
| 237 | )); |
| 238 | } |
| 239 | let chroma = sps.chroma_format_idc; |
| 240 | let slots = (self.dpb.capacity() as u32 + 1).min(MAX_SLOTS); |
| 241 | let (w, h) = (sps.coded_width, sps.coded_height); |
| 242 | if let Some(s) = &self.session |
| 243 | && s.chroma_format_idc == chroma |
| 244 | && s.max_width == w |
| 245 | && s.max_height == h |
| 246 | && slots <= s.slots |
| 247 | { |
| 248 | return Ok(()); |
| 249 | } |
| 250 | self.bump(true); |
| 251 | self.current = None; |
| 252 | self.dpb.clear(); |
| 253 | self.pics.clear(); |
| 254 | self.session = None; |
| 255 | let h264 = H264DecodeSession::new( |
| 256 | &self.gpu, |
| 257 | &H264DecodeConfig { |
| 258 | max_width: w, |
| 259 | max_height: h, |
| 260 | max_dpb_slots: slots, |
| 261 | profile_idc: sps.profile_idc, |
| 262 | chroma_format_idc: chroma, |
| 263 | }, |
| 264 | ) |
| 265 | ?; |
| 266 | let ring = Ring::new(h264.ring_len()); |
| 267 | self.session = Some(Session { |
| 268 | h264: Rc::new(RefCell::new(h264)), |
| 269 | ring, |
| 270 | max_width: w, |
| 271 | max_height: h, |
| 272 | slots, |
| 273 | chroma_format_idc: chroma, |
| 274 | }); |
| 275 | self.params_dirty = true; |
| 276 | Ok(()) |
| 277 | } |
| 278 | |
| 279 | fn set_parameters(&mut self) -> Result<()> { |
| 280 | let sps: Vec<H264Sps> = self.sps_map.iter().flatten().map(vk_sps).collect(); |
| 281 | let pps: Vec<H264Pps> = self.pps_map.iter().flatten().map(vk_pps).collect(); |
| 282 | let session = self |
| 283 | .session |
| 284 | .as_mut() |
| 285 | .ok_or_else(|| Error::config("H.264 parameters before any SPS"))?; |
| 286 | session.h264.borrow_mut().set_parameters(&sps, &pps)?; |
| 287 | self.params_dirty = false; |
| 288 | Ok(()) |
| 289 | } |
| 290 | |
| 291 | fn free_slot(&self) -> Result<u32> { |
| 292 | let session = self |
| 293 | .session |
| 294 | .as_ref() |
| 295 | .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; |
| 296 | (0..session.slots) |
| 297 | .find(|slot| self.dpb.frames.iter().all(|p| p.surface != *slot)) |
| 298 | .ok_or_else(|| Error::config("H.264 Vulkan decode: every DPB slot is in use")) |
| 299 | } |
| 300 | |
| 301 | fn fill_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> { |
| 302 | let before: Vec<i32> = self.dpb.frames.iter().map(|p| p.id).collect(); |
| 303 | self.dpb.fill_frame_num_gap(sps, frame_num)?; |
| 304 | for i in 0..self.dpb.frames.len() { |
| 305 | if !before.contains(&self.dpb.frames[i].id) { |
| 306 | self.dpb.frames[i].surface = self.free_slot()?; |
| 307 | } |
| 308 | } |
| 309 | Ok(()) |
| 310 | } |
| 311 | |
| 312 | fn finish_picture(&mut self) -> Result<()> { |
| 313 | let Some(current) = self.current.take() else { |
| 314 | return Ok(()); |
| 315 | }; |
| 316 | let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else { |
| 317 | return Ok(()); |
| 318 | }; |
| 319 | let fields = field_pocs(current.poc.value, current.info.delta_pic_order_cnt_bottom); |
| 320 | let refs: Vec<H264RefSlot> = if current.info.is_idr { |
| 321 | Vec::new() |
| 322 | } else { |
| 323 | self.dpb |
| 324 | .frames |
| 325 | .iter() |
| 326 | .filter(|p| p.mark != Mark::Unused) |
| 327 | .map(|p| H264RefSlot { |
| 328 | slot: p.surface, |
| 329 | frame_num: p.frame_num as u16, |
| 330 | poc: self.pics.get(&p.id).map_or([p.poc, p.poc], |s| s.fields), |
| 331 | long_term: p.mark == Mark::Long, |
| 332 | non_existing: p.non_existing, |
| 333 | }) |
| 334 | .collect() |
| 335 | }; |
| 336 | let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect(); |
| 337 | let session = self |
| 338 | .session |
| 339 | .as_mut() |
| 340 | .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; |
| 341 | let slot = session.ring.take(|| Ok(session.h264.borrow_mut().add_ring_slot()?))?; |
| 342 | session.h264.borrow_mut().decode(&H264DecodePicture { |
| 343 | sps_id: current.sps_id, |
| 344 | pps_id: current.pps_id, |
| 345 | idr: current.info.is_idr, |
| 346 | reference: current.info.is_reference, |
| 347 | frame_num: current.info.frame_num as u16, |
| 348 | idr_pic_id: current.idr_pic_id, |
| 349 | poc: fields, |
| 350 | setup_slot: current.slot, |
| 351 | refs: &refs, |
| 352 | slices: &slices, |
| 353 | }) |
| 354 | ?; |
| 355 | let (left, _, top, _) = sps.crop; |
| 356 | session |
| 357 | .h264 |
| 358 | .borrow_mut() |
| 359 | .store_output(slot.index(), (left, top, sps.width, sps.height))?; |
| 360 | let matrix = |
| 361 | ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height).matrix; |
| 362 | let out = HwPicture::vk( |
| 363 | current.timestamp, |
| 364 | VkPicture::new( |
| 365 | Surfaces::H264(session.h264.clone()), |
| 366 | slot, |
| 367 | (sps.width, sps.height), |
| 368 | 8, |
| 369 | matrix, |
| 370 | ), |
| 371 | ); |
| 372 | |
| 373 | let picture = Picture { |
| 374 | id: current.id, |
| 375 | surface: current.slot, |
| 376 | timestamp: current.timestamp, |
| 377 | frame_num: current.info.frame_num, |
| 378 | frame_num_wrap: current.info.frame_num as i32, |
| 379 | pic_num: current.info.frame_num as i32, |
| 380 | long_term_frame_idx: 0, |
| 381 | poc: current.poc.value, |
| 382 | poc_msb: current.poc.msb, |
| 383 | poc_lsb: current.poc.lsb, |
| 384 | frame_num_offset: current.poc.frame_num_offset, |
| 385 | mark: Mark::Unused, |
| 386 | non_existing: false, |
| 387 | output: true, |
| 388 | }; |
| 389 | self.pics.insert( |
| 390 | current.id, |
| 391 | Side { |
| 392 | fields, |
| 393 | output: Some(out), |
| 394 | }, |
| 395 | ); |
| 396 | self.dpb |
| 397 | .store(picture, &sps, ¤t.info, current.marking.as_ref(), true)?; |
| 398 | self.bump(false); |
| 399 | Ok(()) |
| 400 | } |
| 401 | |
| 402 | fn bump(&mut self, flush: bool) { |
| 403 | while let Some(idx) = self.dpb.next_output(flush) { |
| 404 | let id = self.dpb.frames[idx].id; |
| 405 | if let Some(frame) = self.pics.get_mut(&id).and_then(|s| s.output.take()) { |
| 406 | self.ready.push_back(frame); |
| 407 | } |
| 408 | self.dpb.released(idx); |
| 409 | } |
| 410 | let frames = &self.dpb.frames; |
| 411 | self.pics.retain(|id, _| frames.iter().any(|p| p.id == *id)); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | fn field_pocs(poc: i32, delta_bottom: i32) -> [i32; 2] { |
| 416 | [poc - delta_bottom.min(0), poc + delta_bottom.max(0)] |
| 417 | } |
| 418 | |
| 419 | fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists { |
| 420 | let mut out = ScalingLists { |
| 421 | l4x4: [[0; 16]; 6], |
| 422 | l8x8: [[0; 64]; 6], |
| 423 | }; |
| 424 | for i in 0..6 { |
| 425 | out.l4x4[i] = ZIGZAG_4X4.map(|r| l.list_4x4[i][usize::from(r)]); |
| 426 | out.l8x8[i] = ZIGZAG_8X8.map(|r| l.list_8x8[i][usize::from(r)]); |
| 427 | } |
| 428 | out |
| 429 | } |
| 430 | |
| 431 | fn vk_sps(sps: &Sps) -> H264Sps { |
| 432 | let unit_y = if sps.frame_mbs_only { 2 } else { 4 }; |
| 433 | let (left, right, top, bottom) = sps.crop; |
| 434 | H264Sps { |
| 435 | id: sps.id, |
| 436 | profile_idc: sps.profile_idc, |
| 437 | level_idc: sps.level_idc, |
| 438 | chroma_format_idc: sps.chroma_format_idc, |
| 439 | bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8), |
| 440 | bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8), |
| 441 | log2_max_frame_num_minus4: sps.log2_max_frame_num.saturating_sub(4), |
| 442 | pic_order_cnt_type: sps.pic_order_cnt_type, |
| 443 | log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb.saturating_sub(4), |
| 444 | offset_for_non_ref_pic: sps.offset_for_non_ref_pic, |
| 445 | offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field, |
| 446 | offset_for_ref_frame: sps.offsets_for_ref_frame.clone(), |
| 447 | max_num_ref_frames: sps.max_num_ref_frames as u8, |
| 448 | pic_width_in_mbs_minus1: sps.mb_width.saturating_sub(1), |
| 449 | pic_height_in_map_units_minus1: (if sps.frame_mbs_only { |
| 450 | sps.mb_height |
| 451 | } else { |
| 452 | sps.mb_height / 2 |
| 453 | }) |
| 454 | .saturating_sub(1), |
| 455 | frame_mbs_only: sps.frame_mbs_only, |
| 456 | mb_adaptive_frame_field: sps.mb_adaptive_frame_field, |
| 457 | direct_8x8_inference: sps.direct_8x8_inference, |
| 458 | delta_pic_order_always_zero: sps.delta_pic_order_always_zero, |
| 459 | frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y], |
| 460 | qpprime_y_zero_transform_bypass: sps.transform_bypass, |
| 461 | seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists), |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | fn vk_pps(pps: &Pps) -> H264Pps { |
| 466 | H264Pps { |
| 467 | id: pps.id as u8, |
| 468 | sps_id: pps.sps_id, |
| 469 | entropy_coding_mode: pps.entropy_coding_mode, |
| 470 | bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present, |
| 471 | num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8, |
| 472 | num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8, |
| 473 | weighted_pred: pps.weighted_pred, |
| 474 | weighted_bipred_idc: pps.weighted_bipred_idc, |
| 475 | pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, |
| 476 | pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, |
| 477 | chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, |
| 478 | second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, |
| 479 | deblocking_filter_control_present: pps.deblocking_filter_control_present, |
| 480 | constrained_intra_pred: pps.constrained_intra_pred, |
| 481 | redundant_pic_cnt_present: pps.redundant_pic_cnt_present, |
| 482 | transform_8x8_mode: pps.transform_8x8_mode, |
| 483 | pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists), |
| 484 | } |
| 485 | } |