forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBabd41b6Tahinli3 months ago75 commits

slice.rs593 lines, 22.6 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/// A slice segment header, as far as an intra encoder writes one and a
41/// stateless hardware decoder reads one.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct SliceHeader {
44 /// `first_slice_segment_in_pic_flag`.
45 pub first_slice_segment_in_pic: bool,
46 /// `no_output_of_prior_pics_flag`, present on IRAP pictures only.
47 pub no_output_of_prior_pics: bool,
48 /// `slice_pic_parameter_set_id`.
49 pub pps_id: u32,
50 /// `dependent_slice_segment_flag`.
51 pub dependent_slice_segment: bool,
52 /// `slice_segment_address` in CTB raster order.
53 pub segment_address: u32,
54 /// `slice_type`.
55 pub slice_type: SliceType,
56 /// `pic_output_flag`, when the PPS says it is present.
57 pub pic_output_flag: bool,
58 /// `slice_pic_order_cnt_lsb`; absent (0) on IDR pictures.
59 pub poc_lsb: u32,
60 /// `colour_plane_id`, present only when the sequence codes its three
61 /// planes as separate pictures.
62 pub colour_plane_id: u8,
63 /// `slice_sao_luma_flag`.
64 pub sao_luma: bool,
65 /// `slice_sao_chroma_flag`.
66 pub sao_chroma: bool,
67 /// `num_ref_idx_l0_active_minus1` in force for this slice.
68 pub num_ref_idx_l0_active_minus1: u32,
69 /// `num_ref_idx_l1_active_minus1` in force for this slice.
70 pub num_ref_idx_l1_active_minus1: u32,
71 /// `mvd_l1_zero_flag`.
72 pub mvd_l1_zero: bool,
73 /// `cabac_init_flag`.
74 pub cabac_init: bool,
75 /// `slice_temporal_mvp_enabled_flag`.
76 pub temporal_mvp_enabled: bool,
77 /// `collocated_from_l0_flag`.
78 pub collocated_from_l0: bool,
79 /// `collocated_ref_idx`.
80 pub collocated_ref_idx: u32,
81 /// `five_minus_max_num_merge_cand`.
82 pub five_minus_max_num_merge_cand: u32,
83 /// `slice_qp_delta`: the slice QP is `26 + init_qp_minus26 + this`.
84 pub qp_delta: i32,
85 /// `slice_cb_qp_offset`.
86 pub cb_qp_offset: i32,
87 /// `slice_cr_qp_offset`.
88 pub cr_qp_offset: i32,
89 /// `slice_deblocking_filter_disabled_flag`, after any override.
90 pub deblocking_filter_disabled: bool,
91 /// `slice_beta_offset_div2`.
92 pub beta_offset_div2: i32,
93 /// `slice_tc_offset_div2`.
94 pub tc_offset_div2: i32,
95 /// `slice_loop_filter_across_slices_enabled_flag`.
96 pub loop_filter_across_slices_enabled: bool,
97 /// Substream entry points: one per WPP CTB row (or tile) after the first.
98 pub entry_point_offsets: Vec<u32>,
99}
100
101impl SliceHeader {
102 /// An I slice covering a whole picture at `qp_delta`, filters off.
103 pub fn intra(pps: &Pps, qp_delta: i32) -> SliceHeader {
104 SliceHeader {
105 first_slice_segment_in_pic: true,
106 no_output_of_prior_pics: false,
107 pps_id: pps.id,
108 dependent_slice_segment: false,
109 segment_address: 0,
110 slice_type: SliceType::I,
111 pic_output_flag: true,
112 poc_lsb: 0,
113 colour_plane_id: 0,
114 sao_luma: false,
115 sao_chroma: false,
116 num_ref_idx_l0_active_minus1: 0,
117 num_ref_idx_l1_active_minus1: 0,
118 mvd_l1_zero: false,
119 cabac_init: false,
120 temporal_mvp_enabled: false,
121 collocated_from_l0: true,
122 collocated_ref_idx: 0,
123 five_minus_max_num_merge_cand: 0,
124 qp_delta,
125 cb_qp_offset: 0,
126 cr_qp_offset: 0,
127 deblocking_filter_disabled: pps.deblocking_filter_disabled,
128 beta_offset_div2: 0,
129 tc_offset_div2: 0,
130 loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
131 entry_point_offsets: Vec::new(),
132 }
133 }
134
135 /// Write the header, up to and including `byte_alignment()`.
136 ///
137 /// Entry point offsets are written from `self.entry_point_offsets`, so a WPP
138 /// encoder codes its substreams first and builds the header afterwards —
139 /// the offsets are not knowable any earlier.
140 pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) {
141 w.write_bit(self.first_slice_segment_in_pic);
142 if nal_type.is_irap() {
143 w.write_bit(self.no_output_of_prior_pics);
144 }
145 w.write_ue(self.pps_id);
146 if !self.first_slice_segment_in_pic {
147 if pps.dependent_slice_segments_enabled {
148 w.write_bit(self.dependent_slice_segment);
149 }
150 w.write_bits(self.segment_address, sps.slice_address_bits());
151 }
152 if !self.dependent_slice_segment {
153 for _ in 0..pps.num_extra_slice_header_bits {
154 w.write_bit(false);
155 }
156 w.write_ue(self.slice_type.code());
157 if pps.output_flag_present {
158 w.write_bit(self.pic_output_flag);
159 }
160 if !nal_type.is_idr() {
161 w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4);
162 // An intra encoder writes no reference picture sets at all; a
163 // non-IDR picture from this family does not exist yet.
164 w.write_bit(true); // short_term_ref_pic_set_sps_flag
165 if sps.num_short_term_ref_pic_sets > 1 {
166 w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets));
167 }
168 if sps.temporal_mvp_enabled {
169 w.write_bit(self.temporal_mvp_enabled);
170 }
171 }
172 if sps.sao_enabled {
173 w.write_bit(self.sao_luma);
174 if sps.chroma_format_idc != 0 {
175 w.write_bit(self.sao_chroma);
176 }
177 }
178 if self.slice_type != SliceType::I {
179 w.write_bit(false); // num_ref_idx_active_override_flag
180 if self.slice_type == SliceType::B {
181 w.write_bit(self.mvd_l1_zero);
182 }
183 if pps.cabac_init_present {
184 w.write_bit(self.cabac_init);
185 }
186 w.write_ue(self.five_minus_max_num_merge_cand);
187 }
188 w.write_se(self.qp_delta);
189 if pps.slice_chroma_qp_offsets_present {
190 w.write_se(self.cb_qp_offset);
191 w.write_se(self.cr_qp_offset);
192 }
193 if pps.deblocking_filter_override_enabled {
194 w.write_bit(false); // deblocking_filter_override_flag
195 }
196 if pps.loop_filter_across_slices_enabled
197 && (self.sao_luma || self.sao_chroma || !self.deblocking_filter_disabled)
198 {
199 w.write_bit(self.loop_filter_across_slices_enabled);
200 }
201 }
202 if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
203 w.write_ue(self.entry_point_offsets.len() as u32);
204 if !self.entry_point_offsets.is_empty() {
205 let max = self.entry_point_offsets.iter().copied().max().unwrap_or(1);
206 let offset_len = ceil_log2(max + 1).max(1);
207 w.write_ue(offset_len - 1);
208 for &offset in &self.entry_point_offsets {
209 w.write_bits(offset - 1, offset_len);
210 }
211 }
212 }
213 // byte_alignment(): a one bit then zeros.
214 w.write_bit(true);
215 w.align_to_byte();
216 }
217
218 /// Parse a slice segment header out of an unescaped slice NAL payload.
219 ///
220 /// Returns the header and the bit position where slice data begins — what
221 /// `VASliceParameterBufferHEVC::slice_data_byte_offset` is derived from.
222 pub fn parse(
223 rbsp: &[u8],
224 sps: &Sps,
225 pps: &Pps,
226 nal_type: NalUnitType,
227 ) -> Result<(SliceHeader, ParsePositions)> {
228 let mut r = BitReader::new(rbsp);
229 let mut h = SliceHeader::intra(pps, 0);
230 let mut pos = ParsePositions::default();
231 h.first_slice_segment_in_pic = r.read_bit()?;
232 if nal_type.is_irap() {
233 h.no_output_of_prior_pics = r.read_bit()?;
234 }
235 h.pps_id = r.read_ue()?;
236 if !h.first_slice_segment_in_pic {
237 if pps.dependent_slice_segments_enabled {
238 h.dependent_slice_segment = r.read_bit()?;
239 }
240 h.segment_address = r.read_bits(sps.slice_address_bits())?;
241 }
242 if !h.dependent_slice_segment {
243 for _ in 0..pps.num_extra_slice_header_bits {
244 r.read_bit()?;
245 }
246 h.slice_type = SliceType::from_code(r.read_ue()?)?;
247 if pps.output_flag_present {
248 h.pic_output_flag = r.read_bit()?;
249 }
250 if sps.separate_colour_plane {
251 h.colour_plane_id = r.read_bits(2)? as u8;
252 }
253 let mut st_rps = ShortTermRefPicSet::default();
254 let mut num_long_term = 0;
255 if !nal_type.is_idr() {
256 h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
257 let from_sps = r.read_bit()?;
258 let before = r.bit_position();
259 if !from_sps {
260 // The sets in the SPS are not kept, so an inter-set
261 // predicted slice set cannot be resolved here.
262 st_rps = ShortTermRefPicSet::parse(&mut r, 0, &[])?;
263 } else if sps.num_short_term_ref_pic_sets > 1 {
264 r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?;
265 }
266 pos.st_rps_bits = (r.bit_position() - before) as u32;
267 if sps.long_term_ref_pics_present {
268 let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 {
269 r.read_ue()?
270 } else {
271 0
272 };
273 let num_long_term_pics = r.read_ue()?;
274 for i in 0..num_long_term_sps + num_long_term_pics {
275 if i < num_long_term_sps {
276 if sps.num_long_term_ref_pics_sps > 1 {
277 r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?;
278 }
279 num_long_term += 1;
280 } else {
281 r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; // poc_lsb_lt
282 if r.read_bit()? {
283 num_long_term += 1; // used_by_curr_pic_lt_flag
284 }
285 }
286 if r.read_bit()? {
287 r.read_ue()?; // delta_poc_msb_cycle_lt
288 }
289 }
290 }
291 if sps.temporal_mvp_enabled {
292 h.temporal_mvp_enabled = r.read_bit()?;
293 }
294 }
295 if sps.sao_enabled {
296 h.sao_luma = r.read_bit()?;
297 if sps.chroma_format_idc != 0 {
298 h.sao_chroma = r.read_bit()?;
299 }
300 }
301 if h.slice_type != SliceType::I {
302 h.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
303 h.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
304 if r.read_bit()? {
305 h.num_ref_idx_l0_active_minus1 = r.read_ue()?;
306 if h.slice_type == SliceType::B {
307 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;
308 }
309 }
310 let num_pic_total_curr = st_rps.num_used_by_curr + num_long_term;
311 if pps.lists_modification_present && num_pic_total_curr > 1 {
312 let bits = ceil_log2(num_pic_total_curr);
313 if r.read_bit()? {
314 for _ in 0..=h.num_ref_idx_l0_active_minus1 {
315 r.read_bits(bits)?;
316 }
317 }
318 if h.slice_type == SliceType::B && r.read_bit()? {
319 for _ in 0..=h.num_ref_idx_l1_active_minus1 {
320 r.read_bits(bits)?;
321 }
322 }
323 }
324 if h.slice_type == SliceType::B {
325 h.mvd_l1_zero = r.read_bit()?;
326 }
327 if pps.cabac_init_present {
328 h.cabac_init = r.read_bit()?;
329 }
330 if h.temporal_mvp_enabled {
331 if h.slice_type == SliceType::B {
332 h.collocated_from_l0 = r.read_bit()?;
333 }
334 if (h.collocated_from_l0 && h.num_ref_idx_l0_active_minus1 > 0)
335 || (!h.collocated_from_l0 && h.num_ref_idx_l1_active_minus1 > 0)
336 {
337 h.collocated_ref_idx = r.read_ue()?;
338 }
339 }
340 if (pps.weighted_pred && h.slice_type == SliceType::P)
341 || (pps.weighted_bipred && h.slice_type == SliceType::B)
342 {
343 skip_pred_weight_table(&mut r, &h, sps)?;
344 }
345 h.five_minus_max_num_merge_cand = r.read_ue()?;
346 }
347 h.qp_delta = r.read_se()?;
348 if pps.slice_chroma_qp_offsets_present {
349 h.cb_qp_offset = r.read_se()?;
350 h.cr_qp_offset = r.read_se()?;
351 }
352 h.deblocking_filter_disabled = pps.deblocking_filter_disabled;
353 h.beta_offset_div2 = pps.beta_offset_div2;
354 h.tc_offset_div2 = pps.tc_offset_div2;
355 if pps.deblocking_filter_override_enabled && r.read_bit()? {
356 h.deblocking_filter_disabled = r.read_bit()?;
357 if !h.deblocking_filter_disabled {
358 h.beta_offset_div2 = r.read_se()?;
359 h.tc_offset_div2 = r.read_se()?;
360 }
361 }
362 h.loop_filter_across_slices_enabled = pps.loop_filter_across_slices_enabled;
363 if pps.loop_filter_across_slices_enabled
364 && (h.sao_luma || h.sao_chroma || !h.deblocking_filter_disabled)
365 {
366 h.loop_filter_across_slices_enabled = r.read_bit()?;
367 }
368 }
369 if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
370 let count = r.read_ue()?;
371 if count > 0 {
372 if count as u64 > sps.pic_height_in_ctbs() as u64 * sps.pic_width_in_ctbs() as u64 {
373 return Err(Error::corrupt("HEVC slice: num_entry_point_offsets absurd"));
374 }
375 let offset_len = r.read_ue()? + 1;
376 if offset_len > 32 {
377 return Err(Error::corrupt("HEVC slice: offset_len_minus1 > 31"));
378 }
379 for _ in 0..count {
380 h.entry_point_offsets.push(r.read_bits(offset_len)? + 1);
381 }
382 }
383 }
384 if pps.slice_segment_header_extension_present {
385 let len = r.read_ue()?;
386 for _ in 0..len {
387 r.read_bits(8)?;
388 }
389 }
390 // byte_alignment()
391 if !r.read_bit()? {
392 return Err(Error::corrupt("HEVC slice: alignment_bit_equal_to_one = 0"));
393 }
394 r.align_to_byte();
395 pos.header_bits = r.bit_position();
396 Ok((h, pos))
397 }
398}
399
400/// Where the slice header ended, in the units a hardware decoder wants.
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
402pub struct ParsePositions {
403 /// Bit position in the *unescaped* RBSP where slice data starts; always a
404 /// multiple of 8.
405 pub header_bits: u64,
406 /// `st_rps_bits`: the size of the `st_ref_pic_set()` in the slice header,
407 /// which `VAPictureParameterBufferHEVC` carries so the driver can skip it.
408 pub st_rps_bits: u32,
409}
410
411impl ParsePositions {
412 /// `slice_data_byte_offset`: the offset from the start of the NAL unit
413 /// (header bytes included) to the first byte of slice data, counted in the
414 /// *escaped* bytes a driver is handed.
415 ///
416 /// The emulation prevention bytes inside the header count, which is why this
417 /// takes the escaped payload rather than working from `header_bits` alone.
418 pub fn slice_data_byte_offset(&self, escaped_payload: &[u8]) -> usize {
419 let rbsp_bytes = (self.header_bits / 8) as usize;
420 let mut zeros = 0usize;
421 let mut rbsp_seen = 0usize;
422 let mut escaped_seen = 0usize;
423 for &b in escaped_payload {
424 escaped_seen += 1;
425 if zeros >= 2 && b == 3 {
426 zeros = 0;
427 continue;
428 }
429 rbsp_seen += 1;
430 if b == 0 {
431 zeros += 1;
432 } else {
433 zeros = 0;
434 }
435 if rbsp_seen == rbsp_bytes {
436 break;
437 }
438 }
439 // 2 = the NAL unit header, which the offset is measured from.
440 2 + escaped_seen
441 }
442}
443
444/// How many emulation prevention bytes a NAL unit payload carries.
445///
446/// `VASliceParameterBufferHEVC::slice_data_num_emu_prevn_bytes` wants this for
447/// the slice data a driver is handed, and a caller that has the escaped bytes
448/// should not have to unescape them twice to find out.
449pub fn count_emulation_prevention_bytes(escaped_payload: &[u8]) -> usize {
450 let mut zeros = 0usize;
451 let mut count = 0usize;
452 for &b in escaped_payload {
453 if zeros >= 2 && b == 3 {
454 count += 1;
455 zeros = 0;
456 continue;
457 }
458 if b == 0 {
459 zeros += 1;
460 } else {
461 zeros = 0;
462 }
463 }
464 count
465}
466
467/// Walk past a `pred_weight_table()` (7.3.6.3).
468fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Result<()> {
469 r.read_ue()?; // luma_log2_weight_denom
470 let chroma = sps.chroma_format_idc != 0;
471 if chroma {
472 r.read_se()?; // delta_chroma_log2_weight_denom
473 }
474 let lists: &[u32] = if h.slice_type == SliceType::B {
475 &[
476 h.num_ref_idx_l0_active_minus1,
477 h.num_ref_idx_l1_active_minus1,
478 ]
479 } else {
480 &[h.num_ref_idx_l0_active_minus1]
481 };
482 for &active_minus1 in lists {
483 let count = active_minus1 + 1;
484 let mut luma_flags = Vec::with_capacity(count as usize);
485 for _ in 0..count {
486 luma_flags.push(r.read_bit()?);
487 }
488 let mut chroma_flags = Vec::with_capacity(count as usize);
489 if chroma {
490 for _ in 0..count {
491 chroma_flags.push(r.read_bit()?);
492 }
493 }
494 for i in 0..count as usize {
495 if luma_flags[i] {
496 r.read_se()?; // delta_luma_weight
497 r.read_se()?; // luma_offset
498 }
499 if chroma && chroma_flags[i] {
500 for _ in 0..2 {
501 r.read_se()?; // delta_chroma_weight
502 r.read_se()?; // delta_chroma_offset
503 }
504 }
505 }
506 }
507 Ok(())
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513 use crate::ps::{ConformanceWindow, ProfileTierLevel};
514
515 fn sps() -> Sps {
516 Sps {
517 vps_id: 0,
518 id: 0,
519 chroma_format_idc: 1,
520 separate_colour_plane: false,
521 pic_width_in_luma_samples: 1920,
522 pic_height_in_luma_samples: 1088,
523 conf_win: ConformanceWindow::default(),
524 bit_depth_luma_minus8: 0,
525 bit_depth_chroma_minus8: 0,
526 log2_max_poc_lsb_minus4: 4,
527 max_dec_pic_buffering_minus1: 0,
528 max_num_reorder_pics: 0,
529 log2_min_cb_size_minus3: 0,
530 log2_diff_max_min_cb_size: 3,
531 log2_min_tb_size_minus2: 0,
532 log2_diff_max_min_tb_size: 3,
533 max_transform_hierarchy_depth_inter: 0,
534 max_transform_hierarchy_depth_intra: 0,
535 scaling_list_enabled: false,
536 amp_enabled: false,
537 sao_enabled: false,
538 pcm_enabled: false,
539 pcm: None,
540 num_short_term_ref_pic_sets: 0,
541 long_term_ref_pics_present: false,
542 num_long_term_ref_pics_sps: 0,
543 temporal_mvp_enabled: false,
544 strong_intra_smoothing: true,
545 ptl: ProfileTierLevel::main(120),
546 vui: None,
547 }
548 }
549
550 #[test]
551 fn intra_slice_header_round_trips_with_entry_points() {
552 let pps = Pps {
553 entropy_coding_sync_enabled: true,
554 deblocking_filter_control_present: true,
555 deblocking_filter_disabled: true,
556 ..Pps::default()
557 };
558 let sps = sps();
559 let mut header = SliceHeader::intra(&pps, -3);
560 header.entry_point_offsets = vec![1234, 9, 65_540];
561 let mut w = BitWriter::new();
562 header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl);
563 let rbsp = w.into_bytes();
564 let (parsed, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap();
565 assert_eq!(parsed, header);
566 assert_eq!(pos.header_bits % 8, 0);
567 assert_eq!(pos.header_bits as usize / 8, rbsp.len());
568 // No emulation prevention in this header, so the byte offset is the
569 // NAL header plus the RBSP header bytes.
570 assert_eq!(pos.slice_data_byte_offset(&rbsp), 2 + rbsp.len());
571 }
572
573 #[test]
574 fn emulation_prevention_bytes_are_counted() {
575 assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 1, 0xff]), 1);
576 assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 0, 0, 3, 2]), 2);
577 // A 3 that is not preceded by two zeros is payload, not an escape.
578 assert_eq!(count_emulation_prevention_bytes(&[0, 3, 3, 3]), 0);
579 assert_eq!(count_emulation_prevention_bytes(&[]), 0);
580 }
581
582 #[test]
583 fn byte_offset_counts_escape_bytes() {
584 // RBSP 00 00 01 ... escapes to 00 00 03 01 ...; a header of four RBSP
585 // bytes therefore ends five escaped bytes in.
586 let pos = ParsePositions {
587 header_bits: 4 * 8,
588 st_rps_bits: 0,
589 };
590 let escaped = [0u8, 0, 3, 1, 0xff];
591 assert_eq!(pos.slice_data_byte_offset(&escaped), 2 + 5);
592 }
593}