forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

vkdec265.rs569 lines, 20.2 KiBHistoryRawDownload
1//! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices.
2
3use std::cell::RefCell;
4use std::collections::{HashMap, VecDeque};
5use std::rc::Rc;
6
7use ec_h265_syntax::{
8 AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps,
9 split_annex_b,
10};
11use ec_vk::{
12 H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265Pcm, H265Pps, H265ProfileTierLevel,
13 H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps,
14};
15
16use crate::error::{Error, Result};
17use crate::hevc_dpb::{
18 self, AMD_VENDOR_ID, Dpb, Mark, hevc_ctb16_broken, is_bla_picture, is_leading_picture,
19 is_rasl_picture, is_reference_picture, peek_pps_id, vui_colour_tags,
20};
21use ec_core::color::{ColorDescription, Tags};
22
23use crate::output::{HwPicture, Ring, Surfaces, VkPicture};
24
25const MAX_SLOTS: u32 = 17;
26
27struct Session {
28 h265: Rc<RefCell<H265DecodeSession>>,
29 ring: Ring,
30 bit_depth: u8,
31 max_width: u32,
32 max_height: u32,
33 slots: u32,
34}
35
36struct Current {
37 slot: u32,
38 sps_id: u8,
39 pps_id: u8,
40 nal_type: NalUnitType,
41 st_rps_bits: u32,
42 short_term_ref_pic_set_sps: bool,
43 poc: i32,
44 timestamp: i64,
45 output: bool,
46 is_tid0_anchor: bool,
47 st_curr_before: Vec<u32>,
48 st_curr_after: Vec<u32>,
49 lt_curr: Vec<u32>,
50 slices: Vec<Vec<u8>>,
51}
52
53/// H.265 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots.
54pub(crate) struct VkH265Decoder {
55 gpu: ec_vk::Gpu,
56 session: Option<Session>,
57 params_dirty: bool,
58 vps_map: Vec<Option<Vps>>,
59 sps_map: Vec<Option<Sps>>,
60 pps_map: Vec<Option<Pps>>,
61 dpb: Dpb<u32>,
62 outputs: HashMap<u32, HwPicture>,
63 current: Option<Current>,
64 ready: VecDeque<HwPicture>,
65 no_rasl_output: bool,
66}
67
68impl VkH265Decoder {
69 pub(crate) fn new() -> Result<Self> {
70 let gpu = crate::hw::vk_gpu()
71 .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?;
72 Ok(VkH265Decoder {
73 gpu,
74 session: None,
75 params_dirty: false,
76 vps_map: vec![None; 16],
77 sps_map: vec![None; 16],
78 pps_map: vec![None; 64],
79 dpb: Dpb::new(),
80 outputs: HashMap::new(),
81 current: None,
82 ready: VecDeque::new(),
83 no_rasl_output: false,
84 })
85 }
86
87 pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
88 for nal in split_annex_b(data) {
89 match nal.header.nal_type {
90 NalUnitType::Vps => {
91 let vps = Vps::parse(&nal.rbsp())?;
92 let id = usize::from(vps.id);
93 if let Some(slot) = self.vps_map.get_mut(id) {
94 self.params_dirty |= store(slot, vps);
95 }
96 }
97 NalUnitType::Sps => {
98 self.finish_picture()?;
99 let sps = Sps::parse(&nal.rbsp())?;
100 self.dpb.max_reorder = sps.max_num_reorder_pics as usize;
101 self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;
102 let id = sps.id as usize;
103 if let Some(slot) = self.sps_map.get_mut(id) {
104 self.params_dirty |= store(slot, sps);
105 }
106 }
107 NalUnitType::Pps => {
108 let pps = Pps::parse(&nal.rbsp())?;
109 let id = pps.id as usize;
110 if let Some(slot) = self.pps_map.get_mut(id) {
111 self.params_dirty |= store(slot, pps);
112 }
113 }
114 t if t.is_vcl() => self.slice(&nal, timestamp)?,
115 _ => {}
116 }
117 }
118 self.finish_picture()
119 }
120
121 pub(crate) fn next_frame(&mut self) -> Option<HwPicture> {
122 self.ready.pop_front()
123 }
124
125 pub(crate) fn reset(&mut self) {
126 self.current = None;
127 self.dpb.pictures.clear();
128 self.dpb.started = false;
129 self.dpb.prev_tid0_poc = 0;
130 self.outputs.clear();
131 self.ready.clear();
132 }
133
134 pub(crate) fn flush(&mut self) -> Result<()> {
135 self.finish_picture()?;
136 self.bump(true);
137 Ok(())
138 }
139
140 fn slice(&mut self, nal: &AnnexBNal, timestamp: i64) -> Result<()> {
141 let rbsp = nal.rbsp();
142 let nal_type = nal.header.nal_type;
143 let pps_id = peek_pps_id(&rbsp, nal_type)?;
144 let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else {
145 return Ok(());
146 };
147 let Some(sps) = self
148 .sps_map
149 .get(pps.sps_id as usize)
150 .and_then(|s| s.clone())
151 else {
152 return Ok(());
153 };
154 let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?;
155 if sh.first_slice_segment_in_pic {
156 self.finish_picture()?;
157 if !(is_rasl_picture(nal_type) && self.no_rasl_output) {
158 self.start_picture(&sps, &sh, pos.st_rps_bits, nal, timestamp)?;
159 }
160 }
161 if let Some(current) = self.current.as_mut() {
162 let mut raw = nal.header.to_bytes().to_vec();
163 raw.extend_from_slice(nal.payload);
164 current.slices.push(raw);
165 }
166 Ok(())
167 }
168
169 fn start_picture(
170 &mut self,
171 sps: &Sps,
172 sh: &SliceHeader,
173 st_rps_bits: u32,
174 nal: &AnnexBNal,
175 timestamp: i64,
176 ) -> Result<()> {
177 let nal_type = nal.header.nal_type;
178 self.ensure_session(sps)?;
179 if self.params_dirty {
180 self.set_parameters()?;
181 }
182 if nal_type.is_irap() {
183 self.no_rasl_output =
184 nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started;
185 }
186 let poc = self.dpb.picture_order_count(sps, sh, nal_type);
187 let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?;
188 let ids = |list: &[usize]| -> Vec<u32> {
189 list.iter().map(|&i| self.dpb.pictures[i].surface).collect()
190 };
191 let (st_curr_before, st_curr_after, lt_curr) = (
192 ids(&rps.st_curr_before),
193 ids(&rps.st_curr_after),
194 ids(&rps.lt_curr),
195 );
196 if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) {
197 self.bump(true);
198 }
199 let slot = self.free_slot()?;
200 let is_reference = is_reference_picture(nal_type);
201 self.current = Some(Current {
202 slot,
203 sps_id: sps.id as u8,
204 pps_id: sh.pps_id as u8,
205 nal_type,
206 st_rps_bits,
207 short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag,
208 poc,
209 timestamp,
210 output: sh.pic_output_flag,
211 is_tid0_anchor: nal.header.temporal_id == 0
212 && is_reference
213 && !is_leading_picture(nal_type),
214 st_curr_before,
215 st_curr_after,
216 lt_curr,
217 slices: Vec::new(),
218 });
219 Ok(())
220 }
221
222 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
223 if hevc_ctb16_broken(sps, || self.gpu.vendor_id() == AMD_VENDOR_ID) {
224 return Err(Error::unsupported(
225 "Vulkan H.265 decode",
226 "16x16 CTBs on AMD decode with wrong chroma",
227 ));
228 }
229 if sps.chroma_format_idc != 1
230 || sps.bit_depth_luma_minus8 != sps.bit_depth_chroma_minus8
231 || !matches!(sps.bit_depth_luma_minus8, 0 | 2)
232 {
233 return Err(Error::unsupported(
234 "Vulkan H.265 decode",
235 "only 8- and 10-bit 4:2:0",
236 ));
237 }
238 let bit_depth = (8 + sps.bit_depth_luma_minus8) as u8;
239 let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS);
240 let (w, h) = (
241 sps.pic_width_in_luma_samples,
242 sps.pic_height_in_luma_samples,
243 );
244 if let Some(s) = &self.session
245 && s.bit_depth == bit_depth
246 && s.max_width == w
247 && s.max_height == h
248 && slots <= s.slots
249 {
250 return Ok(());
251 }
252 self.bump(true);
253 self.current = None;
254 self.dpb.pictures.clear();
255 self.outputs.clear();
256 self.session = None;
257 let h265 = H265DecodeSession::new(
258 &self.gpu,
259 &H265DecodeConfig {
260 max_width: w,
261 max_height: h,
262 max_dpb_slots: slots,
263 bit_depth,
264 },
265 )?;
266 let ring = Ring::new(h265.ring_len());
267 self.session = Some(Session {
268 h265: Rc::new(RefCell::new(h265)),
269 ring,
270 bit_depth,
271 max_width: w,
272 max_height: h,
273 slots,
274 });
275 self.params_dirty = true;
276 Ok(())
277 }
278
279 fn set_parameters(&mut self) -> Result<()> {
280 let vps: Vec<H265Vps> = self.vps_map.iter().flatten().map(vk_vps).collect();
281 let sps: Vec<H265Sps> = self.sps_map.iter().flatten().map(vk_sps).collect();
282 let pps: Vec<H265Pps> = self
283 .pps_map
284 .iter()
285 .flatten()
286 .filter(|p| {
287 self.sps_map
288 .get(p.sps_id as usize)
289 .is_some_and(Option::is_some)
290 })
291 .map(vk_pps)
292 .collect();
293 let session = self
294 .session
295 .as_mut()
296 .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?;
297 session.h265.borrow_mut().set_parameters(&vps, &sps, &pps)?;
298 self.params_dirty = false;
299 Ok(())
300 }
301
302 fn free_slot(&self) -> Result<u32> {
303 let session = self
304 .session
305 .as_ref()
306 .ok_or_else(|| Error::config("H.265 picture before any SPS"))?;
307 (0..session.slots)
308 .find(|slot| self.dpb.pictures.iter().all(|p| p.surface != *slot))
309 .ok_or_else(|| Error::config("H.265 Vulkan decode: every DPB slot is in use"))
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
317 .sps_map
318 .get(usize::from(current.sps_id))
319 .and_then(|s| s.clone())
320 else {
321 return Ok(());
322 };
323 let refs: Vec<H265RefSlot> = self
324 .dpb
325 .pictures
326 .iter()
327 .filter(|p| p.mark != Mark::Unused)
328 .map(|p| H265RefSlot {
329 slot: p.surface,
330 poc: p.poc,
331 long_term: p.mark == Mark::LongTerm,
332 })
333 .collect();
334 let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect();
335 let session = self
336 .session
337 .as_mut()
338 .ok_or_else(|| Error::config("H.265 picture before any SPS"))?;
339 session.h265.borrow_mut().decode(&H265DecodePicture {
340 vps_id: sps.vps_id,
341 sps_id: current.sps_id,
342 pps_id: current.pps_id,
343 irap: current.nal_type.is_irap(),
344 idr: current.nal_type.is_idr(),
345 reference: is_reference_picture(current.nal_type),
346 poc: current.poc,
347 setup_slot: current.slot,
348 short_term_ref_pic_set_sps: current.short_term_ref_pic_set_sps,
349 num_delta_pocs_of_ref_rps_idx: 0,
350 st_rps_bits: current.st_rps_bits,
351 st_curr_before: &current.st_curr_before,
352 st_curr_after: &current.st_curr_after,
353 lt_curr: &current.lt_curr,
354 refs: &refs,
355 slices: &slices,
356 })?;
357 if current.output {
358 let slot = session.ring.take(|| Ok(session.h265.borrow_mut().add_ring_slot()?))?;
359 let (width, height) = sps.display_size();
360 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
361 session.h265.borrow_mut().store_output(
362 slot.index(),
363 (origin.0, origin.1, width, height),
364 )?;
365 let matrix =
366 ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height).matrix;
367 let picture = VkPicture::new(
368 Surfaces::H265(session.h265.clone()),
369 slot,
370 (width, height),
371 (8 + sps.bit_depth_luma_minus8) as u8,
372 matrix,
373 );
374 self.outputs
375 .insert(current.slot, HwPicture::vk(current.timestamp, picture));
376 }
377
378 self.dpb.pictures.push(hevc_dpb::StoredPicture {
379 surface: current.slot,
380 poc: current.poc,
381 timestamp: current.timestamp,
382 mark: if is_reference_picture(current.nal_type) {
383 Mark::ShortTerm
384 } else {
385 Mark::Unused
386 },
387 output: current.output,
388 });
389 if current.is_tid0_anchor {
390 self.dpb.prev_tid0_poc = current.poc;
391 }
392 self.dpb.started = true;
393 self.bump(false);
394 Ok(())
395 }
396
397 fn bump(&mut self, flush: bool) {
398 while let Some(idx) = self.dpb.next_output(flush) {
399 let pic = &self.dpb.pictures[idx];
400 if let Some(frame) = self.outputs.remove(&pic.surface) {
401 self.ready.push_back(frame);
402 }
403 self.dpb.released(idx);
404 }
405 }
406}
407
408fn store<T: PartialEq>(slot: &mut Option<T>, value: T) -> bool {
409 if slot.as_ref() == Some(&value) {
410 return false;
411 }
412 *slot = Some(value);
413 true
414}
415
416fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel {
417 H265ProfileTierLevel {
418 tier_flag: p.tier_flag,
419 progressive_source: p.progressive_source,
420 interlaced_source: p.interlaced_source,
421 non_packed_constraint: p.non_packed_constraint,
422 frame_only_constraint: p.frame_only_constraint,
423 profile_idc: p.profile_idc,
424 level_idc: p.level_idc,
425 }
426}
427
428fn dpbm(
429 max_latency_increase_plus1: u32,
430 max_dec_pic_buffering_minus1: u32,
431 reorder: u32,
432) -> ec_vk::H265DecPicBufMgr {
433 ec_vk::H265DecPicBufMgr {
434 max_latency_increase_plus1: [max_latency_increase_plus1; 7],
435 max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7],
436 max_num_reorder_pics: [reorder as u8; 7],
437 }
438}
439
440fn lists(l: &ScalingList) -> H265ScalingLists {
441 let c = &l.coefficients;
442 H265ScalingLists {
443 list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()),
444 list_8x8: std::array::from_fn(|i| c[1][i]),
445 list_16x16: std::array::from_fn(|i| c[2][i]),
446 list_32x32: std::array::from_fn(|i| c[3][3 * i]),
447 dc_16x16: std::array::from_fn(|i| l.dc[2][i]),
448 dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]),
449 }
450}
451
452fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet {
453 let (n0, n1) = (r.num_negative as usize, r.num_positive as usize);
454 H265ShortTermRefPicSet {
455 delta_poc_s0: r.delta_poc_s0[..n0].to_vec(),
456 used_by_curr_pic_s0: r.used_s0[..n0].to_vec(),
457 delta_poc_s1: r.delta_poc_s1[..n1].to_vec(),
458 used_by_curr_pic_s1: r.used_s1[..n1].to_vec(),
459 }
460}
461
462fn vk_vps(vps: &Vps) -> H265Vps {
463 H265Vps {
464 id: vps.id,
465 max_sub_layers_minus1: 0,
466 profile_tier_level: ptl(&vps.ptl),
467 dec_pic_buf_mgr: dpbm(
468 0,
469 vps.max_dec_pic_buffering_minus1,
470 vps.max_num_reorder_pics,
471 ),
472 }
473}
474
475fn vk_sps(sps: &Sps) -> H265Sps {
476 let c = &sps.conf_win;
477 H265Sps {
478 id: sps.id as u8,
479 vps_id: sps.vps_id,
480 max_sub_layers_minus1: 0,
481 profile_tier_level: ptl(&sps.ptl),
482 chroma_format_idc: sps.chroma_format_idc as u8,
483 pic_width_in_luma_samples: sps.pic_width_in_luma_samples,
484 pic_height_in_luma_samples: sps.pic_height_in_luma_samples,
485 conformance_window: [c.left, c.right, c.top, c.bottom],
486 bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8,
487 bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8,
488 log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8,
489 log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8,
490 log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8,
491 log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8,
492 log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8,
493 max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8,
494 max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8,
495 pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm {
496 bit_depth_luma_minus1: a as u8,
497 bit_depth_chroma_minus1: b as u8,
498 log2_min_luma_coding_block_size_minus3: c as u8,
499 log2_diff_max_min_luma_coding_block_size: d as u8,
500 loop_filter_disabled: e,
501 }),
502 dec_pic_buf_mgr: dpbm(
503 sps.max_latency_increase_plus1,
504 sps.max_dec_pic_buffering_minus1,
505 sps.max_num_reorder_pics,
506 ),
507 scaling_list_enabled: sps.scaling_list_enabled,
508 scaling_lists: sps.scaling_list.as_ref().map(lists),
509 amp_enabled: sps.amp_enabled,
510 sample_adaptive_offset_enabled: sps.sao_enabled,
511 long_term_ref_pics_present: sps.long_term_ref_pics_present,
512 long_term_ref_pics_sps: sps
513 .long_term_ref_pics_sps
514 .iter()
515 .map(
516 |&(poc_lsb, used_by_curr_pic)| ec_vk::H265LongTermRefPicSps {
517 poc_lsb,
518 used_by_curr_pic,
519 },
520 )
521 .collect(),
522 temporal_mvp_enabled: sps.temporal_mvp_enabled,
523 strong_intra_smoothing_enabled: sps.strong_intra_smoothing,
524 short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(),
525 }
526}
527
528fn vk_pps(pps: &Pps) -> H265Pps {
529 H265Pps {
530 id: pps.id as u8,
531 sps_id: pps.sps_id as u8,
532 dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled,
533 output_flag_present: pps.output_flag_present,
534 num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,
535 sign_data_hiding_enabled: pps.sign_data_hiding_enabled,
536 cabac_init_present: pps.cabac_init_present,
537 num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8,
538 num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8,
539 init_qp_minus26: pps.init_qp_minus26 as i8,
540 constrained_intra_pred: pps.constrained_intra_pred,
541 transform_skip_enabled: pps.transform_skip_enabled,
542 cu_qp_delta_enabled: pps.cu_qp_delta_enabled,
543 diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8,
544 cb_qp_offset: pps.cb_qp_offset as i8,
545 cr_qp_offset: pps.cr_qp_offset as i8,
546 slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present,
547 weighted_pred: pps.weighted_pred,
548 weighted_bipred: pps.weighted_bipred,
549 transquant_bypass_enabled: pps.transquant_bypass_enabled,
550 tiles_enabled: pps.tiles_enabled,
551 entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled,
552 num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8,
553 num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8,
554 uniform_spacing: pps.uniform_spacing,
555 column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(),
556 row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(),
557 loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled,
558 loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
559 deblocking_filter_control_present: pps.deblocking_filter_control_present,
560 deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled,
561 deblocking_filter_disabled: pps.deblocking_filter_disabled,
562 beta_offset_div2: pps.beta_offset_div2 as i8,
563 tc_offset_div2: pps.tc_offset_div2 as i8,
564 scaling_lists: pps.scaling_list.as_ref().map(lists),
565 lists_modification_present: pps.lists_modification_present,
566 log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8,
567 slice_segment_header_extension_present: pps.slice_segment_header_extension_present,
568 }
569}