forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

slice.rs868 lines, 35.4 KiBHistoryRawDownload
1//! The slice segment header (7.3.6.1).
2
3use crate::nal::NalUnitType;
4use crate::ps::{Pps, ShortTermRefPicSet, Sps, ceil_log2};
5use ec_core::bitio::{BitReader, BitWriter};
6use ec_core::error::{Error, Result};
7
8/// `slice_type`.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum SliceType {
11 /// Bi-predictive.
12 B,
13 /// Predictive.
14 P,
15 /// Intra — the only kind this family's HEVC encoder writes.
16 I,
17}
18
19impl SliceType {
20 /// The wire value (`B` = 0, `P` = 1, `I` = 2).
21 pub fn code(self) -> u32 {
22 match self {
23 SliceType::B => 0,
24 SliceType::P => 1,
25 SliceType::I => 2,
26 }
27 }
28
29 /// The type for a wire value.
30 pub fn from_code(code: u32) -> Result<SliceType> {
31 match code {
32 0 => Ok(SliceType::B),
33 1 => Ok(SliceType::P),
34 2 => Ok(SliceType::I),
35 v => Err(Error::corrupt(format!("HEVC slice: slice_type = {v}"))),
36 }
37 }
38}
39
40/// One long-term reference picture named by a slice header (7.3.6.1).
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct LongTermRef {
43 /// `PocLsbLt`: the low bits of the reference's picture order count.
44 pub poc_lsb_lt: u32,
45 /// `UsedByCurrPicLt`: whether the current picture may predict from it.
46 pub used_by_curr: bool,
47 /// `delta_poc_msb_present_flag`.
48 pub delta_poc_msb_present: bool,
49 /// `DeltaPocMsbCycleLt`, accumulated as equation 7-52 requires.
50 pub delta_poc_msb_cycle: u32,
51}
52
53/// One entry of a `pred_weight_table()` (7.3.6.3).
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub struct WeightEntry {
56 /// `(delta_luma_weight, luma_offset)`, absent when the flag was 0.
57 pub luma: Option<(i32, i32)>,
58 /// `(delta_chroma_weight, ChromaOffset)` per chroma component.
59 pub chroma: Option<[(i32, i32); 2]>,
60}
61
62/// A parsed `pred_weight_table()` (7.3.6.3).
63#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct PredWeightTable {
65 /// `luma_log2_weight_denom`.
66 pub luma_log2_weight_denom: u32,
67 /// `delta_chroma_log2_weight_denom`.
68 pub delta_chroma_log2_weight_denom: i32,
69 /// One entry per active list 0 reference.
70 pub l0: Vec<WeightEntry>,
71 /// One entry per active list 1 reference.
72 pub l1: Vec<WeightEntry>,
73}
74
75/// A slice segment header, as far as an intra encoder writes one and a
76/// stateless hardware decoder reads one.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct SliceHeader {
79 /// `first_slice_segment_in_pic_flag`.
80 pub first_slice_segment_in_pic: bool,
81 /// `no_output_of_prior_pics_flag`, present on IRAP pictures only.
82 pub no_output_of_prior_pics: bool,
83 /// `slice_pic_parameter_set_id`.
84 pub pps_id: u32,
85 /// `dependent_slice_segment_flag`.
86 pub dependent_slice_segment: bool,
87 /// `slice_segment_address` in CTB raster order.
88 pub segment_address: u32,
89 /// `slice_type`.
90 pub slice_type: SliceType,
91 /// `pic_output_flag`, when the PPS says it is present.
92 pub pic_output_flag: bool,
93 /// `slice_pic_order_cnt_lsb`; absent (0) on IDR pictures.
94 pub poc_lsb: u32,
95 /// `colour_plane_id`, present only when the sequence codes its three
96 /// planes as separate pictures.
97 pub colour_plane_id: u8,
98 /// `slice_sao_luma_flag`.
99 pub sao_luma: bool,
100 /// `slice_sao_chroma_flag`.
101 pub sao_chroma: bool,
102 /// `num_ref_idx_l0_active_minus1` in force for this slice.
103 pub num_ref_idx_l0_active_minus1: u32,
104 /// `num_ref_idx_l1_active_minus1` in force for this slice.
105 pub num_ref_idx_l1_active_minus1: u32,
106 /// `mvd_l1_zero_flag`.
107 pub mvd_l1_zero: bool,
108 /// `cabac_init_flag`.
109 pub cabac_init: bool,
110 /// `slice_temporal_mvp_enabled_flag`.
111 pub temporal_mvp_enabled: bool,
112 /// `collocated_from_l0_flag`.
113 pub collocated_from_l0: bool,
114 /// `collocated_ref_idx`.
115 pub collocated_ref_idx: u32,
116 /// `five_minus_max_num_merge_cand`.
117 pub five_minus_max_num_merge_cand: u32,
118 /// `slice_qp_delta`: the slice QP is `26 + init_qp_minus26 + this`.
119 pub qp_delta: i32,
120 /// `slice_cb_qp_offset`.
121 pub cb_qp_offset: i32,
122 /// `slice_cr_qp_offset`.
123 pub cr_qp_offset: i32,
124 /// `cu_chroma_qp_offset_enabled_flag` (7.3.6.1): CUs may carry a chroma QP offset.
125 pub cu_chroma_qp_offset_enabled: bool,
126 /// `slice_deblocking_filter_disabled_flag`, after any override.
127 pub deblocking_filter_disabled: bool,
128 /// `slice_beta_offset_div2`.
129 pub beta_offset_div2: i32,
130 /// `slice_tc_offset_div2`.
131 pub tc_offset_div2: i32,
132 /// `slice_loop_filter_across_slices_enabled_flag`.
133 pub loop_filter_across_slices_enabled: bool,
134 /// Substream entry points: one per WPP CTB row (or tile) after the first.
135 pub entry_point_offsets: Vec<u32>,
136 /// The short-term reference picture set in force, whether it came from the
137 /// SPS by index or was written out in this header.
138 ///
139 /// This and the three fields after it are what a *stateless hardware*
140 /// decoder needs and a software one derives on the fly: the driver is given
141 /// `RefPicSetStCurrBefore` / `StCurrAfter` / `LtCurr` as picture lists, so
142 /// the caller has to turn these deltas into reference pictures itself.
143 pub short_term_ref_pic_set: ShortTermRefPicSet,
144 /// True when the set above came from the SPS rather than this header.
145 pub short_term_ref_pic_set_sps_flag: bool,
146 /// The long-term reference pictures this slice names, in bitstream order.
147 pub long_term: Vec<LongTermRef>,
148 /// `list_entry_l0` / `list_entry_l1`; empty when the list is not modified.
149 pub list_entry: [Vec<u32>; 2],
150 /// `pred_weight_table()`, when the PPS turns weighted prediction on.
151 pub pred_weight_table: Option<PredWeightTable>,
152}
153
154impl SliceHeader {
155 /// An I slice covering a whole picture at `qp_delta`, filters off.
156 pub fn intra(pps: &Pps, qp_delta: i32) -> SliceHeader {
157 SliceHeader {
158 first_slice_segment_in_pic: true,
159 no_output_of_prior_pics: false,
160 pps_id: pps.id,
161 dependent_slice_segment: false,
162 segment_address: 0,
163 slice_type: SliceType::I,
164 pic_output_flag: true,
165 poc_lsb: 0,
166 colour_plane_id: 0,
167 sao_luma: false,
168 sao_chroma: false,
169 num_ref_idx_l0_active_minus1: 0,
170 num_ref_idx_l1_active_minus1: 0,
171 mvd_l1_zero: false,
172 cabac_init: false,
173 temporal_mvp_enabled: false,
174 collocated_from_l0: true,
175 collocated_ref_idx: 0,
176 five_minus_max_num_merge_cand: 0,
177 qp_delta,
178 cb_qp_offset: 0,
179 cr_qp_offset: 0,
180 cu_chroma_qp_offset_enabled: false,
181 deblocking_filter_disabled: pps.deblocking_filter_disabled,
182 beta_offset_div2: 0,
183 tc_offset_div2: 0,
184 loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
185 entry_point_offsets: Vec::new(),
186 short_term_ref_pic_set: ShortTermRefPicSet::default(),
187 short_term_ref_pic_set_sps_flag: true,
188 long_term: Vec::new(),
189 list_entry: [Vec::new(), Vec::new()],
190 pred_weight_table: None,
191 }
192 }
193
194 /// Write the header, up to and including `byte_alignment()`.
195 ///
196 /// Entry point offsets are written from `self.entry_point_offsets`, so a WPP
197 /// encoder codes its substreams first and builds the header afterwards —
198 /// the offsets are not knowable any earlier.
199 pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) {
200 self.write_without_alignment(w, sps, pps, nal_type);
201 // byte_alignment(): a one bit then zeros.
202 w.write_bit(true);
203 w.align_to_byte();
204 }
205
206 /// The header without its closing `byte_alignment()`.
207 ///
208 /// A VA-API encoder wants exactly this: the driver is told how many bits of
209 /// header the application wrote and appends the alignment itself, so
210 /// including it here leaves the alignment bit sitting where the driver
211 /// expects slice data (measured on radeonsi: every P picture then decodes
212 /// as `alignment_bit_equal_to_one = 0`).
213 pub fn write_without_alignment(
214 &self,
215 w: &mut BitWriter,
216 sps: &Sps,
217 pps: &Pps,
218 nal_type: NalUnitType,
219 ) {
220 w.write_bit(self.first_slice_segment_in_pic);
221 if nal_type.is_irap() {
222 w.write_bit(self.no_output_of_prior_pics);
223 }
224 w.write_ue(self.pps_id);
225 if !self.first_slice_segment_in_pic {
226 if pps.dependent_slice_segments_enabled {
227 w.write_bit(self.dependent_slice_segment);
228 }
229 w.write_bits(self.segment_address, sps.slice_address_bits());
230 }
231 if !self.dependent_slice_segment {
232 for _ in 0..pps.num_extra_slice_header_bits {
233 w.write_bit(false);
234 }
235 w.write_ue(self.slice_type.code());
236 if pps.output_flag_present {
237 w.write_bit(self.pic_output_flag);
238 }
239 if !nal_type.is_idr() {
240 w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4);
241 w.write_bit(self.short_term_ref_pic_set_sps_flag);
242 if self.short_term_ref_pic_set_sps_flag {
243 if sps.num_short_term_ref_pic_sets > 1 {
244 w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets));
245 }
246 } else {
247 // Written out here, which is what a stream whose SPS carries
248 // no sets must do — and what a hardware encoder's driver
249 // does for its own single reference.
250 self.short_term_ref_pic_set
251 .write(w, sps.num_short_term_ref_pic_sets);
252 }
253 if sps.temporal_mvp_enabled {
254 w.write_bit(self.temporal_mvp_enabled);
255 }
256 }
257 if sps.sao_enabled {
258 w.write_bit(self.sao_luma);
259 if sps.chroma_format_idc != 0 {
260 w.write_bit(self.sao_chroma);
261 }
262 }
263 if self.slice_type != SliceType::I {
264 w.write_bit(false); // num_ref_idx_active_override_flag
265 if self.slice_type == SliceType::B {
266 w.write_bit(self.mvd_l1_zero);
267 }
268 if pps.cabac_init_present {
269 w.write_bit(self.cabac_init);
270 }
271 w.write_ue(self.five_minus_max_num_merge_cand);
272 }
273 w.write_se(self.qp_delta);
274 if pps.slice_chroma_qp_offsets_present {
275 w.write_se(self.cb_qp_offset);
276 w.write_se(self.cr_qp_offset);
277 }
278 if pps.deblocking_filter_override_enabled {
279 w.write_bit(false); // deblocking_filter_override_flag
280 }
281 if pps.loop_filter_across_slices_enabled
282 && (self.sao_luma || self.sao_chroma || !self.deblocking_filter_disabled)
283 {
284 w.write_bit(self.loop_filter_across_slices_enabled);
285 }
286 }
287 if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
288 w.write_ue(self.entry_point_offsets.len() as u32);
289 if !self.entry_point_offsets.is_empty() {
290 let max = self.entry_point_offsets.iter().copied().max().unwrap_or(1);
291 let offset_len = ceil_log2(max + 1).max(1);
292 w.write_ue(offset_len - 1);
293 for &offset in &self.entry_point_offsets {
294 w.write_bits(offset - 1, offset_len);
295 }
296 }
297 }
298 }
299
300 /// Parse a slice segment header out of an unescaped slice NAL payload.
301 ///
302 /// Returns the header and the bit position where slice data begins — what
303 /// `VASliceParameterBufferHEVC::slice_data_byte_offset` is derived from.
304 pub fn parse(
305 rbsp: &[u8],
306 sps: &Sps,
307 pps: &Pps,
308 nal_type: NalUnitType,
309 ) -> Result<(SliceHeader, ParsePositions)> {
310 let mut r = BitReader::new(rbsp);
311 let mut h = SliceHeader::intra(pps, 0);
312 let mut pos = ParsePositions::default();
313 h.first_slice_segment_in_pic = r.read_bit()?;
314 if nal_type.is_irap() {
315 h.no_output_of_prior_pics = r.read_bit()?;
316 }
317 h.pps_id = r.read_ue()?;
318 if !h.first_slice_segment_in_pic {
319 if pps.dependent_slice_segments_enabled {
320 h.dependent_slice_segment = r.read_bit()?;
321 }
322 h.segment_address = r.read_bits(sps.slice_address_bits())?;
323 }
324 if !h.dependent_slice_segment {
325 for _ in 0..pps.num_extra_slice_header_bits {
326 r.read_bit()?;
327 }
328 h.slice_type = SliceType::from_code(r.read_ue()?)?;
329 if pps.output_flag_present {
330 h.pic_output_flag = r.read_bit()?;
331 }
332 if sps.separate_colour_plane {
333 h.colour_plane_id = r.read_bits(2)? as u8;
334 }
335 let mut num_long_term = 0;
336 if !nal_type.is_idr() {
337 h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
338 let from_sps = r.read_bit()?;
339 h.short_term_ref_pic_set_sps_flag = from_sps;
340 let before = r.bit_position();
341 if !from_sps {
342 // Written out here, possibly predicted from the SPS sets —
343 // hence `num_short_term_ref_pic_sets` as this set's index
344 // and the SPS sets as the prediction source (7.3.7).
345 h.short_term_ref_pic_set = ShortTermRefPicSet::parse(
346 &mut r,
347 sps.num_short_term_ref_pic_sets,
348 sps.num_short_term_ref_pic_sets,
349 &sps.short_term_ref_pic_sets,
350 )?;
351 } else {
352 let idx = if sps.num_short_term_ref_pic_sets > 1 {
353 r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?
354 } else {
355 0
356 };
357 h.short_term_ref_pic_set = sps
358 .short_term_ref_pic_sets
359 .get(idx as usize)
360 .copied()
361 .ok_or_else(|| {
362 Error::corrupt(format!(
363 "HEVC slice: short_term_ref_pic_set_idx {idx} is not in the SPS"
364 ))
365 })?;
366 }
367 // Only a set written *in the header* costs the driver bits to
368 // skip; for an SPS-indexed one libva wants zero.
369 pos.st_rps_bits = if from_sps {
370 0
371 } else {
372 (r.bit_position() - before) as u32
373 };
374 if sps.long_term_ref_pics_present {
375 let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 {
376 r.read_ue()?
377 } else {
378 0
379 };
380 let num_long_term_pics = r.read_ue()?;
381 // 7-52 and 7.4.7.1: num_long_term_sps is at most the SPS count, and the
382 // long-term pictures of a slice are bounded by the DPB (32 is the ceiling).
383 // Checked before the loop sum, which would overflow on u32::MAX inputs.
384 if num_long_term_sps > sps.num_long_term_ref_pics_sps
385 || num_long_term_sps.saturating_add(num_long_term_pics) > 32
386 {
387 return Err(Error::corrupt(
388 "HEVC slice header: too many long-term pictures",
389 ));
390 }
391 let mut prev_delta_msb = 0u32;
392 for i in 0..num_long_term_sps + num_long_term_pics {
393 let mut entry = LongTermRef::default();
394 if i < num_long_term_sps {
395 let idx = if sps.num_long_term_ref_pics_sps > 1 {
396 r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?
397 } else {
398 0
399 };
400 let (poc_lsb_lt, used) = sps
401 .long_term_ref_pics_sps
402 .get(idx as usize)
403 .copied()
404 .unwrap_or((0, false));
405 entry.poc_lsb_lt = poc_lsb_lt;
406 entry.used_by_curr = used;
407 } else {
408 entry.poc_lsb_lt = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
409 entry.used_by_curr = r.read_bit()?;
410 }
411 if entry.used_by_curr {
412 num_long_term += 1;
413 }
414 entry.delta_poc_msb_present = r.read_bit()?;
415 if entry.delta_poc_msb_present {
416 // 7-52: coded as a delta against the previous entry,
417 // except for the first of each kind.
418 let delta = r.read_ue()?;
419 entry.delta_poc_msb_cycle = if i == 0 || i == num_long_term_sps {
420 delta
421 } else {
422 // Saturating: the accumulated cycle is only ever compared, and a
423 // corrupt run of ue(v) values must not overflow the sum.
424 delta.saturating_add(prev_delta_msb)
425 };
426 prev_delta_msb = entry.delta_poc_msb_cycle;
427 }
428 h.long_term.push(entry);
429 }
430 }
431 if sps.temporal_mvp_enabled {
432 h.temporal_mvp_enabled = r.read_bit()?;
433 }
434 }
435 if sps.sao_enabled {
436 h.sao_luma = r.read_bit()?;
437 if sps.chroma_format_idc != 0 {
438 h.sao_chroma = r.read_bit()?;
439 }
440 }
441 if h.slice_type != SliceType::I {
442 h.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
443 h.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
444 if r.read_bit()? {
445 h.num_ref_idx_l0_active_minus1 = r.read_ue()?;
446 if h.slice_type == SliceType::B {
447 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;
448 }
449 // 7.4.7.1: both fields are in range 0..=14. Past that is
450 // a corrupt stream, not a bigger reference list -- and
451 // pred_weight_table below sizes a Vec from this value, so
452 // an unchecked ue(v) is a header-declared allocation an
453 // attacker fully controls (up to 2^32 entries from a
454 // handful of bits).
455 }
456 // The PPS defaults are checked too: they reach the same sizes.
457 if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 {
458 return Err(Error::corrupt(
459 "HEVC slice header: num_ref_idx_lX_active_minus1 out of range",
460 ));
461 }
462 let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term;
463 if pps.lists_modification_present && num_pic_total_curr > 1 {
464 let bits = ceil_log2(num_pic_total_curr);
465 if r.read_bit()? {
466 for _ in 0..=h.num_ref_idx_l0_active_minus1 {
467 let entry = r.read_bits(bits)?;
468 h.list_entry[0].push(entry);
469 }
470 }
471 if h.slice_type == SliceType::B && r.read_bit()? {
472 for _ in 0..=h.num_ref_idx_l1_active_minus1 {
473 let entry = r.read_bits(bits)?;
474 h.list_entry[1].push(entry);
475 }
476 }
477 }
478 if h.slice_type == SliceType::B {
479 h.mvd_l1_zero = r.read_bit()?;
480 }
481 if pps.cabac_init_present {
482 h.cabac_init = r.read_bit()?;
483 }
484 if h.temporal_mvp_enabled {
485 if h.slice_type == SliceType::B {
486 h.collocated_from_l0 = r.read_bit()?;
487 }
488 if (h.collocated_from_l0 && h.num_ref_idx_l0_active_minus1 > 0)
489 || (!h.collocated_from_l0 && h.num_ref_idx_l1_active_minus1 > 0)
490 {
491 h.collocated_ref_idx = r.read_ue()?;
492 }
493 }
494 if (pps.weighted_pred && h.slice_type == SliceType::P)
495 || (pps.weighted_bipred && h.slice_type == SliceType::B)
496 {
497 h.pred_weight_table = Some(parse_pred_weight_table(&mut r, &h, sps)?);
498 }
499 h.five_minus_max_num_merge_cand = r.read_ue()?;
500 }
501 h.qp_delta = r.read_se()?;
502 if pps.slice_chroma_qp_offsets_present {
503 h.cb_qp_offset = r.read_se()?;
504 h.cr_qp_offset = r.read_se()?;
505 }
506 if pps.range.chroma_qp_offset_list_enabled {
507 h.cu_chroma_qp_offset_enabled = r.read_bit()?;
508 }
509 h.deblocking_filter_disabled = pps.deblocking_filter_disabled;
510 h.beta_offset_div2 = pps.beta_offset_div2;
511 h.tc_offset_div2 = pps.tc_offset_div2;
512 if pps.deblocking_filter_override_enabled && r.read_bit()? {
513 h.deblocking_filter_disabled = r.read_bit()?;
514 if !h.deblocking_filter_disabled {
515 h.beta_offset_div2 = r.read_se()?;
516 h.tc_offset_div2 = r.read_se()?;
517 }
518 }
519 h.loop_filter_across_slices_enabled = pps.loop_filter_across_slices_enabled;
520 if pps.loop_filter_across_slices_enabled
521 && (h.sao_luma || h.sao_chroma || !h.deblocking_filter_disabled)
522 {
523 h.loop_filter_across_slices_enabled = r.read_bit()?;
524 }
525 }
526 if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
527 let count = r.read_ue()?;
528 if count > 0 {
529 if count as u64 > sps.pic_height_in_ctbs() as u64 * sps.pic_width_in_ctbs() as u64 {
530 return Err(Error::corrupt("HEVC slice: num_entry_point_offsets absurd"));
531 }
532 let offset_len = r.read_ue()?.saturating_add(1);
533 if offset_len > 32 {
534 return Err(Error::corrupt("HEVC slice: offset_len_minus1 > 31"));
535 }
536 for _ in 0..count {
537 h.entry_point_offsets
538 .push(r.read_bits(offset_len)?.saturating_add(1));
539 }
540 }
541 }
542 if pps.slice_segment_header_extension_present {
543 let len = r.read_ue()?;
544 for _ in 0..len {
545 r.read_bits(8)?;
546 }
547 }
548 // byte_alignment()
549 if !r.read_bit()? {
550 return Err(Error::corrupt("HEVC slice: alignment_bit_equal_to_one = 0"));
551 }
552 r.align_to_byte();
553 pos.header_bits = r.bit_position();
554 Ok((h, pos))
555 }
556}
557
558/// Where the slice header ended, in the units a hardware decoder wants.
559#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
560pub struct ParsePositions {
561 /// Bit position in the *unescaped* RBSP where slice data starts; always a
562 /// multiple of 8.
563 pub header_bits: u64,
564 /// `st_rps_bits`: the size of the `st_ref_pic_set()` in the slice header,
565 /// which `VAPictureParameterBufferHEVC` carries so the driver can skip it.
566 pub st_rps_bits: u32,
567}
568
569impl ParsePositions {
570 /// `slice_data_byte_offset`: the offset from the start of the NAL unit
571 /// (header bytes included) to the first byte of slice data, counted in the
572 /// *escaped* bytes a driver is handed.
573 ///
574 /// The emulation prevention bytes inside the header count, which is why this
575 /// takes the escaped payload rather than working from `header_bits` alone.
576 pub fn slice_data_byte_offset(&self, escaped_payload: &[u8]) -> usize {
577 let rbsp_bytes = (self.header_bits / 8) as usize;
578 let mut zeros = 0usize;
579 let mut rbsp_seen = 0usize;
580 let mut escaped_seen = 0usize;
581 for &b in escaped_payload {
582 escaped_seen += 1;
583 if zeros >= 2 && b == 3 {
584 zeros = 0;
585 continue;
586 }
587 rbsp_seen += 1;
588 if b == 0 {
589 zeros += 1;
590 } else {
591 zeros = 0;
592 }
593 if rbsp_seen == rbsp_bytes {
594 break;
595 }
596 }
597 // 2 = the NAL unit header, which the offset is measured from.
598 2 + escaped_seen
599 }
600}
601
602/// How many emulation prevention bytes a NAL unit payload carries.
603///
604/// `VASliceParameterBufferHEVC::slice_data_num_emu_prevn_bytes` wants this for
605/// the slice data a driver is handed, and a caller that has the escaped bytes
606/// should not have to unescape them twice to find out.
607pub fn count_emulation_prevention_bytes(escaped_payload: &[u8]) -> usize {
608 let mut zeros = 0usize;
609 let mut count = 0usize;
610 for &b in escaped_payload {
611 if zeros >= 2 && b == 3 {
612 count += 1;
613 zeros = 0;
614 continue;
615 }
616 if b == 0 {
617 zeros += 1;
618 } else {
619 zeros = 0;
620 }
621 }
622 count
623}
624
625/// Parse a `pred_weight_table()` (7.3.6.3).
626///
627/// The chroma *offset* is derived, not coded: equation 7-56 turns
628/// `delta_chroma_offset_lX` into `ChromaOffsetLX` against the weight, and a
629/// decoder that forwards the raw delta to hardware shifts every weighted
630/// chroma sample.
631fn parse_pred_weight_table(
632 r: &mut BitReader,
633 h: &SliceHeader,
634 sps: &Sps,
635) -> Result<PredWeightTable> {
636 let mut table = PredWeightTable {
637 luma_log2_weight_denom: r.read_ue()?,
638 ..PredWeightTable::default()
639 };
640 let chroma = sps.chroma_format_idc != 0;
641 if chroma {
642 table.delta_chroma_log2_weight_denom = r.read_se()?;
643 }
644 // 7-56: luma_log2_weight_denom is in 0..=7. Checked before the chroma sum below.
645 if table.luma_log2_weight_denom > 7 {
646 return Err(Error::corrupt(
647 "HEVC pred_weight_table: luma_log2_weight_denom out of range",
648 ));
649 }
650 let chroma_log2 =
651 (table.luma_log2_weight_denom as i32).saturating_add(table.delta_chroma_log2_weight_denom);
652 if !(0..=7).contains(&chroma_log2) {
653 return Err(Error::corrupt(
654 "HEVC pred_weight_table: ChromaLog2WeightDenom out of range",
655 ));
656 }
657 // wpOffsetHalfRangeC = 1 << (high_precision_offsets_enabled_flag ? (BitDepthC - 1) : 7).
658 // The offset scaling by BitDepthC happens in weighted prediction.
659 let half_range = 1i64
660 << if sps.range.high_precision_offsets_enabled {
661 sps.bit_depth_chroma_minus8 + 7
662 } else {
663 7
664 };
665
666 let lists: &[u32] = if h.slice_type == SliceType::B {
667 &[
668 h.num_ref_idx_l0_active_minus1,
669 h.num_ref_idx_l1_active_minus1,
670 ]
671 } else {
672 &[h.num_ref_idx_l0_active_minus1]
673 };
674 for (list, &active_minus1) in lists.iter().enumerate() {
675 let count = (active_minus1 + 1) as usize;
676 let mut luma_flags = Vec::with_capacity(count);
677 for _ in 0..count {
678 luma_flags.push(r.read_bit()?);
679 }
680 let mut chroma_flags = vec![false; count];
681 if chroma {
682 for flag in chroma_flags.iter_mut() {
683 *flag = r.read_bit()?;
684 }
685 }
686 let mut entries = Vec::with_capacity(count);
687 for i in 0..count {
688 let mut entry = WeightEntry::default();
689 if luma_flags[i] {
690 let delta_weight = r.read_se()?;
691 let offset = r.read_se()?;
692 entry.luma = Some((delta_weight, offset));
693 }
694 if chroma && chroma_flags[i] {
695 let mut pair = [(0i32, 0i32); 2];
696 for component in &mut pair {
697 let delta_weight = r.read_se()?;
698 let delta_offset = r.read_se()?;
699 let weight = (1i64 << chroma_log2) + i64::from(delta_weight);
700 // 7-56, in 64 bits because both terms come straight off the
701 // wire and a corrupt stream must not overflow the derivation.
702 let offset = (half_range + i64::from(delta_offset)
703 - ((half_range * weight) >> chroma_log2))
704 .clamp(-half_range, half_range - 1);
705 *component = (delta_weight, offset as i32);
706 }
707 entry.chroma = Some(pair);
708 }
709 entries.push(entry);
710 }
711 if list == 0 {
712 table.l0 = entries;
713 } else {
714 table.l1 = entries;
715 }
716 }
717 Ok(table)
718}
719
720#[cfg(test)]
721mod tests {
722 use super::*;
723 use crate::ps::{ConformanceWindow, ProfileTierLevel};
724
725 fn sps() -> Sps {
726 Sps {
727 vps_id: 0,
728 id: 0,
729 chroma_format_idc: 1,
730 separate_colour_plane: false,
731 pic_width_in_luma_samples: 1920,
732 pic_height_in_luma_samples: 1088,
733 conf_win: ConformanceWindow::default(),
734 bit_depth_luma_minus8: 0,
735 bit_depth_chroma_minus8: 0,
736 log2_max_poc_lsb_minus4: 4,
737 max_dec_pic_buffering_minus1: 0,
738 max_num_reorder_pics: 0,
739 log2_min_cb_size_minus3: 0,
740 log2_diff_max_min_cb_size: 3,
741 log2_min_tb_size_minus2: 0,
742 log2_diff_max_min_tb_size: 3,
743 max_transform_hierarchy_depth_inter: 0,
744 max_transform_hierarchy_depth_intra: 0,
745 scaling_list_enabled: false,
746 scaling_list: None,
747 amp_enabled: false,
748 sao_enabled: false,
749 pcm_enabled: false,
750 pcm: None,
751 num_short_term_ref_pic_sets: 0,
752 short_term_ref_pic_sets: Vec::new(),
753 long_term_ref_pics_present: false,
754 num_long_term_ref_pics_sps: 0,
755 long_term_ref_pics_sps: Vec::new(),
756 temporal_mvp_enabled: false,
757 strong_intra_smoothing: true,
758 ptl: ProfileTierLevel::main(120),
759 vui: None,
760 max_latency_increase_plus1: 0,
761 extension_flags: 0,
762 range: Default::default(),
763 }
764 }
765
766 #[test]
767 fn intra_slice_header_round_trips_with_entry_points() {
768 let pps = Pps {
769 entropy_coding_sync_enabled: true,
770 deblocking_filter_control_present: true,
771 deblocking_filter_disabled: true,
772 ..Pps::default()
773 };
774 let sps = sps();
775 let mut header = SliceHeader::intra(&pps, -3);
776 header.entry_point_offsets = vec![1234, 9, 65_540];
777 let mut w = BitWriter::new();
778 header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl);
779 let rbsp = w.into_bytes();
780 let (parsed, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap();
781 assert_eq!(parsed, header);
782 assert_eq!(pos.header_bits % 8, 0);
783 assert_eq!(pos.header_bits as usize / 8, rbsp.len());
784 // No emulation prevention in this header, so the byte offset is the
785 // NAL header plus the RBSP header bytes.
786 assert_eq!(pos.slice_data_byte_offset(&rbsp), 2 + rbsp.len());
787 }
788
789 #[test]
790 fn entry_point_counts_past_32_and_past_u8_round_trip() {
791 // A 4K wavefront film has 33 (PicHeightInCtbsY - 1), past the [u32; 32]
792 // the parser once held; 20 x 22 tiles give 440, past what a u8 product holds.
793 let pps = Pps {
794 entropy_coding_sync_enabled: true,
795 tiles_enabled: true,
796 deblocking_filter_control_present: true,
797 deblocking_filter_disabled: true,
798 ..Pps::default()
799 };
800 let sps = sps();
801 assert!(sps.pic_width_in_ctbs() as usize * sps.pic_height_in_ctbs() as usize >= 440);
802 for count in [33usize, 440] {
803 let mut header = SliceHeader::intra(&pps, 0);
804 header.entry_point_offsets = (0..count as u32).map(|i| 100 + i).collect();
805 let mut w = BitWriter::new();
806 header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl);
807 let rbsp = w.into_bytes();
808 let (parsed, _) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap();
809 assert_eq!(parsed.entry_point_offsets.len(), count);
810 assert_eq!(parsed, header);
811 }
812 }
813
814 #[test]
815 fn emulation_prevention_bytes_are_counted() {
816 assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 1, 0xff]), 1);
817 assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 0, 0, 3, 2]), 2);
818 // A 3 that is not preceded by two zeros is payload, not an escape.
819 assert_eq!(count_emulation_prevention_bytes(&[0, 3, 3, 3]), 0);
820 assert_eq!(count_emulation_prevention_bytes(&[]), 0);
821 }
822
823 #[test]
824 fn byte_offset_counts_escape_bytes() {
825 // RBSP 00 00 01 ... escapes to 00 00 03 01 ...; a header of four RBSP
826 // bytes therefore ends five escaped bytes in.
827 let pos = ParsePositions {
828 header_bits: 4 * 8,
829 st_rps_bits: 0,
830 };
831 let escaped = [0u8, 0, 3, 1, 0xff];
832 assert_eq!(pos.slice_data_byte_offset(&escaped), 2 + 5);
833 }
834
835 #[test]
836 fn chroma_offset_uses_half_range_128_at_10_bits() {
837 // 10-bit Main10 SPS, P slice with one reference, chroma denom 1 (luma 0 + delta 1).
838 // Cb: delta weight 2 gives ChromaWeight 2 + 2 = 4, delta offset 10.
839 // 7-56: 128 + 10 - ((128 * 4) >> 1) = 138 - 256 = -118.
840 // Cr: delta weight -1 gives ChromaWeight 2 - 1 = 1, delta offset 0.
841 // 7-56: 128 + 0 - ((128 * 1) >> 1) = 128 - 64 = 64.
842 // The old 1 << (BitDepthC - 1) = 512 half range would give -502 and 256 instead.
843 let pps = Pps::default();
844 let mut sps = sps();
845 sps.bit_depth_chroma_minus8 = 2;
846 let mut h = SliceHeader::intra(&pps, 0);
847 h.slice_type = SliceType::P;
848 h.num_ref_idx_l0_active_minus1 = 0;
849
850 let mut w = BitWriter::new();
851 w.write_ue(0); // luma_log2_weight_denom
852 w.write_se(1); // delta_chroma_log2_weight_denom
853 w.write_bit(false); // luma_weight_l0_flag[0]
854 w.write_bit(true); // chroma_weight_l0_flag[0]
855 w.write_se(2); // delta_chroma_weight_l0[0][Cb]
856 w.write_se(10); // delta_chroma_offset_l0[0][Cb]
857 w.write_se(-1); // delta_chroma_weight_l0[0][Cr]
858 w.write_se(0); // delta_chroma_offset_l0[0][Cr]
859 let bytes = w.into_bytes();
860
861 let mut r = BitReader::new(&bytes);
862 let table = parse_pred_weight_table(&mut r, &h, &sps).unwrap();
863 assert_eq!(table.delta_chroma_log2_weight_denom, 1);
864 assert_eq!(table.l0.len(), 1);
865 assert_eq!(table.l0[0].luma, None);
866 assert_eq!(table.l0[0].chroma, Some([(2, -118), (-1, 64)]));
867 }
868}