forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

hevc.rs967 lines, 36.9 KiBHistoryRawDownload
1//! Stateless HEVC decoding.
2//!
3//! HEVC keeps no `frame_num` and no sliding window: every picture states its
4//! whole reference picture set, and anything the set does not name stops being
5//! a reference there and then (8.3.2). That makes the DPB smaller than H.264's
6//! but the *derivation* larger, and all of it has to happen here — a stateless
7//! driver is handed `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as
8//! finished picture lists.
9
10use std::sync::Arc;
11
12use ec_core::color::{ColorDescription, ContentLight, Tags};
13use ec_h265_syntax::{
14 NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b,
15 unescape_rbsp,
16};
17use ec_va::caps::Profile;
18use ec_va::{Buffer, Display, sys};
19
20use super::{ReadyFrames, Session, StreamInfo};
21use crate::error::{Error, Result};
22use crate::frame::{Colour, Frame};
23use crate::params::hevc::{
24 IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR,
25 PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC,
26 SliceParameterBufferHEVC, VAPictureHEVC,
27};
28use crate::params::param_buffer;
29use crate::pool::PooledSurface;
30
31/// Beyond `sps_max_dec_pic_buffering`: the picture being decoded plus the ones
32/// a caller is still holding.
33const EXTRA_SURFACES: usize = 6;
34
35/// Reference marking of a stored picture (8.3.2).
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37enum Mark {
38 Unused,
39 ShortTerm,
40 LongTerm,
41}
42
43struct StoredPicture {
44 surface: Arc<PooledSurface>,
45 poc: i32,
46 timestamp: i64,
47 mark: Mark,
48 /// Still to be handed to the caller.
49 output: bool,
50}
51
52impl StoredPicture {
53 fn stored(&self) -> bool {
54 self.output || self.mark != Mark::Unused
55 }
56}
57
58/// The reference picture set of the picture being decoded, as DPB indices.
59#[derive(Debug, Default, Clone)]
60struct Rps {
61 st_curr_before: Vec<usize>,
62 st_curr_after: Vec<usize>,
63 lt_curr: Vec<usize>,
64}
65
66/// The picture being assembled from its slices.
67struct Current {
68 surface: Arc<PooledSurface>,
69 sps_id: u32,
70 poc: i32,
71 timestamp: i64,
72 is_reference: bool,
73 /// True when this picture may be `prevTid0Pic` for the next one (8.3.1).
74 is_tid0_anchor: bool,
75 output: bool,
76 rps: Rps,
77 buffers: Vec<Buffer>,
78 slices: usize,
79 /// Index into `PictureParameterBufferHEVC::reference_frames` per DPB index.
80 va_index: Vec<u8>,
81}
82
83/// A stateless HEVC decoder.
84pub struct HevcDecoder {
85 display: Arc<Display>,
86 vps_map: Vec<Option<Vps>>,
87 sps_map: Vec<Option<Sps>>,
88 pps_map: Vec<Option<Pps>>,
89 session: Option<Session>,
90 dpb: Vec<StoredPicture>,
91 ready: ReadyFrames,
92 current: Option<Current>,
93 /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1.
94 prev_tid0_poc: i32,
95 /// Set once a picture has been decoded since the last reset.
96 started: bool,
97 /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures
98 /// associated with it must not be decoded or output when set, because
99 /// they predict from pictures before a random-access point this decoder
100 /// never saw.
101 no_rasl_output: bool,
102 max_reorder: usize,
103 max_dec_pic_buffering: usize,
104 /// The most recent SPS's VUI colour tags, sticky across pictures.
105 colour_tags: Tags,
106 /// The prefix SEI HDR peak seen so far, merged so a later access unit that
107 /// says nothing does not erase what an earlier IRAP declared.
108 colour_light: ContentLight,
109}
110
111impl HevcDecoder {
112 /// A decoder with no stream state.
113 pub fn new(display: &Arc<Display>) -> HevcDecoder {
114 HevcDecoder {
115 display: Arc::clone(display),
116 vps_map: (0..16).map(|_| None).collect(),
117 sps_map: (0..16).map(|_| None).collect(),
118 pps_map: (0..64).map(|_| None).collect(),
119 session: None,
120 dpb: Vec::new(),
121 ready: ReadyFrames::default(),
122 current: None,
123 prev_tid0_poc: 0,
124 started: false,
125 no_rasl_output: false,
126 max_reorder: 1,
127 max_dec_pic_buffering: 6,
128 colour_tags: Tags::default(),
129 colour_light: ContentLight::default(),
130 }
131 }
132
133 /// Decode one Annex B access unit.
134 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
135 for nal in split_annex_b(data) {
136 match nal.header.nal_type {
137 NalUnitType::Vps => {
138 let vps = Vps::parse(&nal.rbsp())?;
139 let id = usize::from(vps.id);
140 if id < self.vps_map.len() {
141 self.vps_map[id] = Some(vps);
142 }
143 }
144 NalUnitType::Sps => {
145 let sps = Sps::parse(&nal.rbsp())?;
146 self.max_reorder = sps.max_num_reorder_pics as usize;
147 self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;
148 self.colour_tags = vui_colour_tags(&sps);
149 let id = sps.id as usize;
150 if id < self.sps_map.len() {
151 self.sps_map[id] = Some(sps);
152 }
153 }
154 NalUnitType::Pps => {
155 let pps = Pps::parse(&nal.rbsp())?;
156 let id = pps.id as usize;
157 if id < self.pps_map.len() {
158 self.pps_map[id] = Some(pps);
159 }
160 }
161 t if t.is_vcl() => {
162 self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?;
163 }
164 _ => {}
165 }
166 }
167 // The HDR SEI messages (mastering display, content light level) live
168 // outside the slice loop above and are read on the whole access unit:
169 // an encoder writes them once, ahead of the IRAP they describe, and
170 // they otherwise say nothing (`ContentLight::default()`), so a later
171 // access unit that carries neither never overwrites what an earlier
172 // one declared.
173 let light = ec_core::color::hevc_sei_light(data);
174 if light != ContentLight::default() {
175 self.colour_light = light.over(self.colour_light);
176 }
177 self.finish_picture()?;
178 Ok(())
179 }
180
181 /// This stream's colour metadata, once its first SPS has been seen.
182 pub fn colour(&self) -> Option<Colour> {
183 let session = self.session.as_ref()?;
184 Some(Colour {
185 description: ColorDescription::resolve(
186 Tags::default(),
187 self.colour_tags,
188 session.display_size.1,
189 ),
190 light: self.colour_light,
191 })
192 }
193
194 /// The next frame in output order.
195 pub fn next_frame(&mut self) -> Option<Frame> {
196 self.ready.pop()
197 }
198
199 /// Push every buffered picture out (end of stream).
200 pub fn flush(&mut self) {
201 let _ = self.finish_picture();
202 self.bump(true);
203 }
204
205 /// Drop all picture state after a seek; parameter sets survive.
206 pub fn reset(&mut self) {
207 self.current = None;
208 self.dpb.clear();
209 self.ready.clear();
210 self.prev_tid0_poc = 0;
211 self.started = false;
212 self.no_rasl_output = false;
213 }
214
215 /// What the stream turned out to be.
216 pub fn stream_info(&self) -> Option<StreamInfo> {
217 self.session.as_ref().map(Session::info)
218 }
219
220 fn slice(
221 &mut self,
222 nal_type: NalUnitType,
223 temporal_id: u8,
224 payload: &[u8],
225 timestamp: i64,
226 ) -> Result<()> {
227 let rbsp = unescape_rbsp(payload);
228 // The header cannot be parsed without its PPS, and the PPS names the SPS.
229 let pps_id = peek_pps_id(&rbsp, nal_type)?;
230 let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else {
231 return Ok(());
232 };
233 let Some(sps) = self
234 .sps_map
235 .get(pps.sps_id as usize)
236 .and_then(|s| s.clone())
237 else {
238 return Ok(());
239 };
240 let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?;
241
242 if sh.first_slice_segment_in_pic {
243 self.finish_picture()?;
244 // 8.1.3 / C.5.2.2: a RASL picture associated with an IRAP whose
245 // NoRaslOutputFlag is 1 predicts from pictures before that IRAP,
246 // which a mid-stream start never decoded. It is not output and
247 // is not guaranteed decodable, so it is dropped whole rather than
248 // handed to the driver.
249 if !(is_rasl_picture(nal_type) && self.no_rasl_output) {
250 self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?;
251 }
252 }
253 if self.current.is_none() {
254 return Ok(());
255 }
256 self.render_slice(&sps, &pps, &sh, &pos, payload, nal_type)
257 }
258
259 fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
260 let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8;
261 let profile = match (sps.chroma_format_idc, bit_depth) {
262 (1, 8) => Profile::HEVCMain,
263 (1, 10) => Profile::HEVCMain10,
264 (chroma, depth) => {
265 return Err(Error::unsupported(
266 format!("HEVC chroma_format_idc {chroma} at {depth} bits"),
267 "only Main and Main10 (4:2:0, 8 or 10 bit) are decoded in hardware",
268 ));
269 }
270 };
271 let coded = (
272 sps.pic_width_in_luma_samples,
273 sps.pic_height_in_luma_samples,
274 );
275 if let Some(session) = &self.session
276 && session.coded_size == coded
277 && session.bit_depth == bit_depth
278 && session.profile == profile
279 {
280 return Ok(());
281 }
282 self.current = None;
283 self.dpb.clear();
284 self.session = Some(Session::new(
285 &self.display,
286 profile,
287 coded,
288 sps.display_size(),
289 bit_depth,
290 self.max_dec_pic_buffering + EXTRA_SURFACES,
291 )?);
292 Ok(())
293 }
294
295 fn start_picture(
296 &mut self,
297 sps: &Sps,
298 sh: &SliceHeader,
299 nal_type: NalUnitType,
300 temporal_id: u8,
301 timestamp: i64,
302 ) -> Result<()> {
303 self.ensure_session(sps)?;
304
305 if nal_type.is_irap() {
306 // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded
307 // video sequence — which a mid-stream start's first IRAP always
308 // is, `self.started` still being false at that point.
309 self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started;
310 }
311
312 let poc = self.picture_order_count(sps, sh, nal_type);
313 // 8.3.2 runs before the picture is decoded and after its POC is known:
314 // every stored picture the set does not name stops being a reference.
315 let rps = self.apply_rps(sps, sh, nal_type, poc);
316
317 if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) {
318 // An IRAP that restarts output order: everything ahead of it in the
319 // buffer belongs ahead of it on screen too.
320 self.bump(true);
321 }
322
323 if std::env::var_os("EC_HW_DEBUG").is_some() {
324 eprintln!(
325 "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}",
326 nal_type,
327 sh.poc_lsb,
328 self.dpb.len(),
329 self.ready.len(),
330 rps.st_curr_before.len(),
331 rps.st_curr_after.len(),
332 rps.lt_curr.len(),
333 self.session
334 .as_ref()
335 .map(|s| s.pool.available())
336 .unwrap_or(0),
337 );
338 }
339 let session = self
340 .session
341 .as_ref()
342 .ok_or_else(|| Error::config("HEVC picture before any SPS"))?;
343 let surface = session
344 .pool
345 .acquire()
346 .ok_or_else(|| Error::config("HEVC decode: every surface is still in use"))?;
347
348 // The driver indexes RefPicList into `reference_frames`, so the mapping
349 // from DPB slot to that array is fixed once, here.
350 let mut va_index = vec![0xffu8; self.dpb.len()];
351 let mut n = 0u8;
352 for (i, pic) in self.dpb.iter().enumerate() {
353 if pic.mark != Mark::Unused && n < 15 {
354 va_index[i] = n;
355 n += 1;
356 }
357 }
358
359 self.current = Some(Current {
360 surface,
361 sps_id: sps.id,
362 poc,
363 timestamp,
364 // A "_N" picture (an even NAL type below 16) is a sub-layer
365 // non-reference: nothing in its own sub-layer may predict from it,
366 // and a decoder that stores it as a reference lets the next
367 // picture's reference picture set match the wrong picture by POC.
368 is_reference: is_reference_picture(nal_type),
369 // 8.3.1: `prevTid0Pic` is the previous picture with TemporalId 0
370 // that is neither RASL, RADL nor sub-layer non-reference. Taking
371 // the previous picture instead — which a stream with temporal
372 // sub-layers immediately punishes — puts the picture order count
373 // MSB one wrap out and hands the driver the wrong references.
374 is_tid0_anchor: temporal_id == 0
375 && is_reference_picture(nal_type)
376 && !is_leading_picture(nal_type),
377 output: sh.pic_output_flag,
378 rps,
379 buffers: Vec::new(),
380 slices: 0,
381 va_index,
382 });
383 Ok(())
384 }
385
386 /// `PicOrderCntVal` (8.3.1).
387 fn picture_order_count(&self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType) -> i32 {
388 if nal_type.is_idr() {
389 return 0;
390 }
391 let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
392 let lsb = sh.poc_lsb as i32;
393 let (prev_msb, prev_lsb) = if !self.started {
394 (0, 0)
395 } else {
396 (
397 self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)),
398 self.prev_tid0_poc.rem_euclid(max_lsb),
399 )
400 };
401 // An IRAP that starts a new coded video sequence has no predecessor.
402 if nal_type.is_irap() && !self.started {
403 return lsb;
404 }
405 let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
406 prev_msb + max_lsb
407 } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
408 prev_msb - max_lsb
409 } else {
410 prev_msb
411 };
412 msb + lsb
413 }
414
415 /// Reference picture set derivation and marking (8.3.2).
416 fn apply_rps(&mut self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, poc: i32) -> Rps {
417 if nal_type.is_irap() && (nal_type.is_idr() || !self.started) {
418 for pic in &mut self.dpb {
419 pic.mark = Mark::Unused;
420 }
421 self.dpb.retain(|p| p.stored());
422 return Rps::default();
423 }
424
425 let set = &sh.short_term_ref_pic_set;
426 let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
427 let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term)
428 for i in 0..set.num_negative as usize {
429 wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false));
430 }
431 for i in 0..set.num_positive as usize {
432 wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false));
433 }
434 for lt in &sh.long_term {
435 // 8.3.2: a long-term entry without an MSB cycle is matched on its
436 // POC low bits alone, which is how a stream survives an MSB wrap.
437 let target = if lt.delta_poc_msb_present {
438 poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb)
439 + lt.poc_lsb_lt as i32
440 } else {
441 lt.poc_lsb_lt as i32
442 };
443 wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present));
444 }
445
446 let mut rps = Rps::default();
447 let mut keep = vec![false; self.dpb.len()];
448 for (target, used, lsb_only) in wanted {
449 let found = self.dpb.iter().position(|p| {
450 if lsb_only {
451 p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb)
452 } else {
453 p.poc == target
454 }
455 });
456 let Some(idx) = found else { continue };
457 keep[idx] = true;
458 if !used {
459 continue;
460 }
461 // The three "current" lists are what the reference lists are built
462 // from, in POC order relative to the current picture.
463 if self.dpb[idx].mark == Mark::LongTerm || lsb_only {
464 rps.lt_curr.push(idx);
465 } else if self.dpb[idx].poc < poc {
466 rps.st_curr_before.push(idx);
467 } else {
468 rps.st_curr_after.push(idx);
469 }
470 }
471 rps.st_curr_before
472 .sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc));
473 rps.st_curr_after.sort_by_key(|&i| self.dpb[i].poc);
474
475 for (i, pic) in self.dpb.iter_mut().enumerate() {
476 if !keep[i] {
477 pic.mark = Mark::Unused;
478 }
479 }
480 // Dropping unreferenced, already-output pictures here is what returns
481 // their surfaces to the pool; the indices in `rps` are recomputed after.
482 let mut remap = vec![usize::MAX; self.dpb.len()];
483 let mut next = 0usize;
484 for (i, pic) in self.dpb.iter().enumerate() {
485 if pic.stored() {
486 remap[i] = next;
487 next += 1;
488 }
489 }
490 self.dpb.retain(|p| p.stored());
491 for list in [
492 &mut rps.st_curr_before,
493 &mut rps.st_curr_after,
494 &mut rps.lt_curr,
495 ] {
496 list.retain(|&i| remap[i] != usize::MAX);
497 for entry in list.iter_mut() {
498 *entry = remap[*entry];
499 }
500 }
501 rps
502 }
503
504 fn render_slice(
505 &mut self,
506 sps: &Sps,
507 pps: &Pps,
508 sh: &SliceHeader,
509 pos: &ParsePositions,
510 payload: &[u8],
511 nal_type: NalUnitType,
512 ) -> Result<()> {
513 let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else {
514 return Ok(());
515 };
516 if current.sps_id != sps.id {
517 return Err(Error::Stream(ec_core::Error::corrupt(
518 "HEVC SPS changed mid-picture",
519 )));
520 }
521
522 if current.slices == 0 {
523 let pic_param = picture_parameters(sps, pps, sh, pos, nal_type, current, &self.dpb);
524 current
525 .buffers
526 .push(param_buffer(&session.context, &pic_param)?);
527 if sps.scaling_list_enabled {
528 // The syntax crate refuses a stream that codes its own lists, so
529 // "enabled" here always means the flat default matrices.
530 current.buffers.push(param_buffer(
531 &session.context,
532 &IQMatrixBufferHEVC::default(),
533 )?);
534 }
535 }
536
537 // The NAL unit header is part of the slice data the driver is handed,
538 // and every offset it is given is measured from there.
539 let nal_bytes = payload.len() + 2;
540 let mut slice_param = SliceParameterBufferHEVC {
541 slice_data_size: nal_bytes as u32,
542 slice_data_offset: 0,
543 slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL
544 slice_data_byte_offset: pos.slice_data_byte_offset(payload) as u32,
545 slice_segment_address: sh.segment_address,
546 collocated_ref_idx: if sh.temporal_mvp_enabled {
547 sh.collocated_ref_idx as u8
548 } else {
549 0xff
550 },
551 num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active_minus1 as u8,
552 num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active_minus1 as u8,
553 slice_qp_delta: sh.qp_delta as i8,
554 slice_cb_qp_offset: sh.cb_qp_offset as i8,
555 slice_cr_qp_offset: sh.cr_qp_offset as i8,
556 slice_beta_offset_div2: sh.beta_offset_div2 as i8,
557 slice_tc_offset_div2: sh.tc_offset_div2 as i8,
558 five_minus_max_num_merge_cand: sh.five_minus_max_num_merge_cand as u8,
559 num_entry_point_offsets: sh.entry_point_offsets.len().min(u16::MAX as usize) as u16,
560 slice_data_num_emu_prevn_bytes: ec_h265_syntax::count_emulation_prevention_bytes(
561 payload,
562 )
563 .min(u16::MAX as usize) as u16,
564 ..SliceParameterBufferHEVC::default()
565 };
566 slice_param.long_slice_flags = slice_param
567 .long_slice_flags
568 .last_slice_of_pic(0)
569 .dependent_slice_segment_flag(u32::from(sh.dependent_slice_segment))
570 .slice_type(sh.slice_type.code())
571 .color_plane_id(u32::from(sh.colour_plane_id))
572 .slice_sao_luma_flag(u32::from(sh.sao_luma))
573 .slice_sao_chroma_flag(u32::from(sh.sao_chroma))
574 .mvd_l1_zero_flag(u32::from(sh.mvd_l1_zero))
575 .cabac_init_flag(u32::from(sh.cabac_init))
576 .slice_temporal_mvp_enabled_flag(u32::from(sh.temporal_mvp_enabled))
577 .slice_deblocking_filter_disabled_flag(u32::from(sh.deblocking_filter_disabled))
578 .collocated_from_l0_flag(u32::from(sh.collocated_from_l0))
579 .slice_loop_filter_across_slices_enabled_flag(u32::from(
580 sh.loop_filter_across_slices_enabled,
581 ));
582
583 if sh.slice_type != SliceType::I {
584 let lists = reference_lists(sh, &current.rps);
585 for (x, list) in lists.iter().enumerate() {
586 for (i, &dpb_idx) in list.iter().take(15).enumerate() {
587 slice_param.ref_pic_list[x][i] =
588 current.va_index.get(dpb_idx).copied().unwrap_or(0xff);
589 }
590 }
591 }
592 write_weights(&mut slice_param, sh);
593
594 current
595 .buffers
596 .push(param_buffer(&session.context, &slice_param)?);
597 // Rebuild the NAL unit: `split_annex_b` hands over the payload without
598 // its two header bytes, and the driver counts from them.
599 let mut nal = Vec::with_capacity(nal_bytes);
600 nal.extend_from_slice(&ec_h265_syntax::NalHeader::new(nal_type).to_bytes());
601 nal.extend_from_slice(payload);
602 current.buffers.push(Buffer::from_bytes(
603 &session.context,
604 sys::VASliceDataBufferType,
605 &nal,
606 )?);
607 current.slices += 1;
608 Ok(())
609 }
610
611 fn finish_picture(&mut self) -> Result<()> {
612 let Some(current) = self.current.take() else {
613 return Ok(());
614 };
615 let Some(session) = self.session.as_ref() else {
616 return Ok(());
617 };
618 if current.slices == 0 {
619 return Ok(());
620 }
621 session.submit(&current.surface, current.buffers)?;
622
623 self.dpb.push(StoredPicture {
624 surface: Arc::clone(&current.surface),
625 poc: current.poc,
626 timestamp: current.timestamp,
627 mark: if current.is_reference {
628 Mark::ShortTerm
629 } else {
630 Mark::Unused
631 },
632 output: current.output,
633 });
634 if current.is_tid0_anchor {
635 self.prev_tid0_poc = current.poc;
636 }
637 self.started = true;
638 self.bump(false);
639 Ok(())
640 }
641
642 /// The bumping process (C.5.2.4): output while the buffer holds more than
643 /// its reordering or storage limit allows.
644 fn bump(&mut self, flush: bool) {
645 let Some(session) = self.session.as_ref() else {
646 return;
647 };
648 loop {
649 let pending = self.dpb.iter().filter(|p| p.output).count();
650 let stored = self.dpb.iter().filter(|p| p.stored()).count();
651 if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering {
652 return;
653 }
654 let Some(idx) = self
655 .dpb
656 .iter()
657 .enumerate()
658 .filter(|(_, p)| p.output)
659 .min_by_key(|(_, p)| p.poc)
660 .map(|(i, _)| i)
661 else {
662 return;
663 };
664 let pic = &self.dpb[idx];
665 self.ready.push(Frame::new(
666 Arc::clone(&pic.surface),
667 Arc::clone(&session.images),
668 pic.timestamp,
669 session.display_size,
670 session.coded_size,
671 session.bit_depth,
672 self.colour(),
673 ));
674 self.dpb[idx].output = false;
675 self.dpb.retain(|p| p.stored());
676 }
677 }
678}
679
680/// True unless the NAL type says sub-layer non-reference (`_N`, an even type
681/// below 16).
682fn is_reference_picture(nal_type: NalUnitType) -> bool {
683 let code = nal_type.code();
684 code >= 16 || code % 2 == 1
685}
686
687/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1
688/// excludes from the picture order count prediction.
689fn is_leading_picture(nal_type: NalUnitType) -> bool {
690 (6..=9).contains(&nal_type.code())
691}
692
693/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
694/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
695/// `video_signal_type` at all.
696fn vui_colour_tags(sps: &Sps) -> Tags {
697 let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else {
698 return Tags::default();
699 };
700 let (_primaries, transfer, matrix) = vst
701 .colour_description
702 .map(|cd| {
703 (
704 cd.colour_primaries,
705 cd.transfer_characteristics,
706 cd.matrix_coeffs,
707 )
708 })
709 .unwrap_or((0, 0, 0));
710 Tags::from_codes(
711 u64::from(matrix),
712 u64::from(transfer),
713 if vst.video_full_range_flag { 2 } else { 1 },
714 )
715}
716
717/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's
718/// `NoRaslOutputFlag` is 1 (8.1.3).
719fn is_rasl_picture(nal_type: NalUnitType) -> bool {
720 matches!(nal_type.code(), 8 | 9)
721}
722
723/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1
724/// (8.1.3), a broken-link splice point that never has a decodable RASL.
725fn is_bla_picture(nal_type: NalUnitType) -> bool {
726 (16..=18).contains(&nal_type.code())
727}
728
729/// `slice_pic_parameter_set_id`, readable without any parameter set.
730fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
731 let mut r = ec_core::BitReader::new(rbsp);
732 r.read_bit()?; // first_slice_segment_in_pic_flag
733 if nal_type.is_irap() {
734 r.read_bit()?; // no_output_of_prior_pics_flag
735 }
736 Ok(r.read_ue()?)
737}
738
739/// Reference list construction (8.3.4), as DPB indices.
740fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] {
741 let mut out = [Vec::new(), Vec::new()];
742 let counts = [
743 sh.num_ref_idx_l0_active_minus1 as usize + 1,
744 sh.num_ref_idx_l1_active_minus1 as usize + 1,
745 ];
746 for x in 0..2 {
747 if x == 1 && sh.slice_type != SliceType::B {
748 continue;
749 }
750 // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; list 1 swaps the
751 // first two, which is the whole difference between the two lists.
752 let mut temp: Vec<usize> = Vec::new();
753 while temp.len() < counts[x] {
754 let before = if x == 0 {
755 &rps.st_curr_before
756 } else {
757 &rps.st_curr_after
758 };
759 let after = if x == 0 {
760 &rps.st_curr_after
761 } else {
762 &rps.st_curr_before
763 };
764 let round = before.len() + after.len() + rps.lt_curr.len();
765 if round == 0 {
766 break;
767 }
768 temp.extend(before.iter().copied());
769 temp.extend(after.iter().copied());
770 temp.extend(rps.lt_curr.iter().copied());
771 }
772 if temp.is_empty() {
773 continue;
774 }
775 for i in 0..counts[x] {
776 let idx = match sh.list_entry[x].get(i) {
777 Some(&entry) => *temp.get(entry as usize).unwrap_or(&temp[0]),
778 None => temp[i.min(temp.len() - 1)],
779 };
780 out[x].push(idx);
781 }
782 }
783 out
784}
785
786#[allow(clippy::too_many_arguments)]
787fn picture_parameters(
788 sps: &Sps,
789 pps: &Pps,
790 sh: &SliceHeader,
791 pos: &ParsePositions,
792 nal_type: NalUnitType,
793 current: &Current,
794 dpb: &[StoredPicture],
795) -> PictureParameterBufferHEVC {
796 let mut p = PictureParameterBufferHEVC {
797 curr_pic: VAPictureHEVC::new(current.surface.id(), current.poc, 0),
798 pic_width_in_luma_samples: sps.pic_width_in_luma_samples as u16,
799 pic_height_in_luma_samples: sps.pic_height_in_luma_samples as u16,
800 sps_max_dec_pic_buffering_minus1: sps.max_dec_pic_buffering_minus1 as u8,
801 bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8,
802 bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8,
803 pcm_sample_bit_depth_luma_minus1: sps.pcm.map(|p| p.0 as u8).unwrap_or(0),
804 pcm_sample_bit_depth_chroma_minus1: sps.pcm.map(|p| p.1 as u8).unwrap_or(0),
805 log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8,
806 log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8,
807 log2_min_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8,
808 log2_diff_max_min_transform_block_size: sps.log2_diff_max_min_tb_size as u8,
809 log2_min_pcm_luma_coding_block_size_minus3: sps.pcm.map(|p| p.2 as u8).unwrap_or(0),
810 log2_diff_max_min_pcm_luma_coding_block_size: sps.pcm.map(|p| p.3 as u8).unwrap_or(0),
811 max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8,
812 max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8,
813 init_qp_minus26: pps.init_qp_minus26 as i8,
814 diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8,
815 pps_cb_qp_offset: pps.cb_qp_offset as i8,
816 pps_cr_qp_offset: pps.cr_qp_offset as i8,
817 log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8,
818 num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8,
819 num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8,
820 log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8,
821 num_short_term_ref_pic_sets: sps.num_short_term_ref_pic_sets as u8,
822 num_long_term_ref_pic_sps: sps.num_long_term_ref_pics_sps as u8,
823 num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8,
824 num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8,
825 pps_beta_offset_div2: pps.beta_offset_div2 as i8,
826 pps_tc_offset_div2: pps.tc_offset_div2 as i8,
827 num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,
828 // The size of an `st_ref_pic_set()` the slice header carried itself,
829 // so the driver can skip it; zero when the slice named an SPS set,
830 // which is what the parser reports.
831 st_rps_bits: pos.st_rps_bits,
832 ..PictureParameterBufferHEVC::default()
833 };
834
835 // Tile geometry: uniform spacing is expanded here because libva wants the
836 // widths either way (`va_dec_hevc.h:125`).
837 let (cols, rows) = (
838 pps.num_tile_columns_minus1 as usize + 1,
839 pps.num_tile_rows_minus1 as usize + 1,
840 );
841 if pps.tiles_enabled {
842 let ctb_cols = sps.pic_width_in_ctbs();
843 let ctb_rows = sps.pic_height_in_ctbs();
844 for i in 0..cols.min(p.column_width_minus1.len()) {
845 let width = if pps.uniform_spacing {
846 ((i + 1) as u32 * ctb_cols) / cols as u32 - (i as u32 * ctb_cols) / cols as u32
847 } else {
848 pps.column_width_minus1.get(i).copied().unwrap_or(0) + 1
849 };
850 p.column_width_minus1[i] = width.saturating_sub(1) as u16;
851 }
852 for i in 0..rows.min(p.row_height_minus1.len()) {
853 let height = if pps.uniform_spacing {
854 ((i + 1) as u32 * ctb_rows) / rows as u32 - (i as u32 * ctb_rows) / rows as u32
855 } else {
856 pps.row_height_minus1.get(i).copied().unwrap_or(0) + 1
857 };
858 p.row_height_minus1[i] = height.saturating_sub(1) as u16;
859 }
860 }
861
862 let mut n = 0usize;
863 for (i, pic) in dpb.iter().enumerate() {
864 if pic.mark == Mark::Unused || n >= p.reference_frames.len() {
865 continue;
866 }
867 let mut flags = 0;
868 if pic.mark == Mark::LongTerm {
869 flags |= PICTURE_LONG_TERM_REFERENCE;
870 }
871 if current.rps.st_curr_before.contains(&i) {
872 flags |= PICTURE_RPS_ST_CURR_BEFORE;
873 } else if current.rps.st_curr_after.contains(&i) {
874 flags |= PICTURE_RPS_ST_CURR_AFTER;
875 } else if current.rps.lt_curr.contains(&i) {
876 flags |= PICTURE_RPS_LT_CURR;
877 }
878 p.reference_frames[n] = VAPictureHEVC::new(pic.surface.id(), pic.poc, flags);
879 n += 1;
880 }
881 for entry in p.reference_frames.iter_mut().skip(n) {
882 *entry = VAPictureHEVC::new(ec_va::sys::VA_INVALID_SURFACE, 0, PICTURE_INVALID);
883 }
884
885 p.pic_fields = p
886 .pic_fields
887 .chroma_format_idc(sps.chroma_format_idc)
888 .separate_colour_plane_flag(u32::from(sps.separate_colour_plane))
889 .pcm_enabled_flag(u32::from(sps.pcm_enabled))
890 .scaling_list_enabled_flag(u32::from(sps.scaling_list_enabled))
891 .transform_skip_enabled_flag(u32::from(pps.transform_skip_enabled))
892 .amp_enabled_flag(u32::from(sps.amp_enabled))
893 .strong_intra_smoothing_enabled_flag(u32::from(sps.strong_intra_smoothing))
894 .sign_data_hiding_enabled_flag(u32::from(pps.sign_data_hiding_enabled))
895 .constrained_intra_pred_flag(u32::from(pps.constrained_intra_pred))
896 .cu_qp_delta_enabled_flag(u32::from(pps.cu_qp_delta_enabled))
897 .weighted_pred_flag(u32::from(pps.weighted_pred))
898 .weighted_bipred_flag(u32::from(pps.weighted_bipred))
899 .transquant_bypass_enabled_flag(u32::from(pps.transquant_bypass_enabled))
900 .tiles_enabled_flag(u32::from(pps.tiles_enabled))
901 .entropy_coding_sync_enabled_flag(u32::from(pps.entropy_coding_sync_enabled))
902 .pps_loop_filter_across_slices_enabled_flag(u32::from(
903 pps.loop_filter_across_slices_enabled,
904 ))
905 .loop_filter_across_tiles_enabled_flag(u32::from(pps.loop_filter_across_tiles_enabled))
906 .pcm_loop_filter_disabled_flag(u32::from(sps.pcm.map(|p| p.4).unwrap_or(false)))
907 .no_pic_reordering_flag(u32::from(sps.max_num_reorder_pics == 0))
908 .no_bi_pred_flag(u32::from(sh.slice_type != SliceType::B));
909
910 p.slice_parsing_fields = p
911 .slice_parsing_fields
912 .lists_modification_present_flag(u32::from(pps.lists_modification_present))
913 .long_term_ref_pics_present_flag(u32::from(sps.long_term_ref_pics_present))
914 .sps_temporal_mvp_enabled_flag(u32::from(sps.temporal_mvp_enabled))
915 .cabac_init_present_flag(u32::from(pps.cabac_init_present))
916 .output_flag_present_flag(u32::from(pps.output_flag_present))
917 .dependent_slice_segments_enabled_flag(u32::from(pps.dependent_slice_segments_enabled))
918 .pps_slice_chroma_qp_offsets_present_flag(u32::from(pps.slice_chroma_qp_offsets_present))
919 .sample_adaptive_offset_enabled_flag(u32::from(sps.sao_enabled))
920 .deblocking_filter_override_enabled_flag(u32::from(pps.deblocking_filter_override_enabled))
921 .pps_disable_deblocking_filter_flag(u32::from(pps.deblocking_filter_disabled))
922 .slice_segment_header_extension_present_flag(u32::from(
923 pps.slice_segment_header_extension_present,
924 ))
925 .rap_pic_flag(u32::from(nal_type.is_irap()))
926 .idr_pic_flag(u32::from(nal_type.is_idr()))
927 .intra_pic_flag(u32::from(sh.slice_type == SliceType::I));
928 p
929}
930
931/// Copy the parsed `pred_weight_table()` into the slice parameter buffer.
932fn write_weights(s: &mut SliceParameterBufferHEVC, sh: &SliceHeader) {
933 let Some(w) = sh.pred_weight_table.as_ref() else {
934 return;
935 };
936 s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8;
937 s.delta_chroma_log2_weight_denom = w.delta_chroma_log2_weight_denom as i8;
938 for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] {
939 let (dlw, lo, dcw, co) = if list == 0 {
940 (
941 &mut s.delta_luma_weight_l0,
942 &mut s.luma_offset_l0,
943 &mut s.delta_chroma_weight_l0,
944 &mut s.chroma_offset_l0,
945 )
946 } else {
947 (
948 &mut s.delta_luma_weight_l1,
949 &mut s.luma_offset_l1,
950 &mut s.delta_chroma_weight_l1,
951 &mut s.chroma_offset_l1,
952 )
953 };
954 for (i, entry) in entries.iter().take(15).enumerate() {
955 if let Some((weight, offset)) = entry.luma {
956 dlw[i] = weight as i8;
957 lo[i] = offset as i8;
958 }
959 if let Some(pair) = entry.chroma {
960 for c in 0..2 {
961 dcw[i][c] = pair[c].0 as i8;
962 co[i][c] = pair[c].1 as i8;
963 }
964 }
965 }
966 }
967}