forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe2fa4f0Tahinli2 months ago3028 commits

slice.rs608 lines, 20.7 KiBHistoryRawDownload
1//! Slice header (spec 7.3.3, 7.4.3) for all five slice types.
2
3use ec_core::BitReader;
4use ec_core::error::{Error, Result};
5
6use crate::nal::NalHeader;
7use crate::pps::Pps;
8use crate::sps::Sps;
9
10/// `slice_type` % 5 (spec Table 7-6).
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum SliceType {
13 /// Predicted slice.
14 P,
15 /// Bi-predicted slice.
16 B,
17 /// Intra slice.
18 I,
19 /// Switching-predicted slice.
20 Sp,
21 /// Switching-intra slice.
22 Si,
23}
24
25impl SliceType {
26 /// Map `slice_type` (0..=9); values 5..=9 assert the type for the whole
27 /// picture but decode identically.
28 pub fn from_code(code: u32) -> Result<SliceType> {
29 Ok(match code % 5 {
30 0 => SliceType::P,
31 1 => SliceType::B,
32 2 => SliceType::I,
33 3 => SliceType::Sp,
34 4 => SliceType::Si,
35 _ => unreachable!(),
36 })
37 }
38
39 /// True for I and SI.
40 pub fn is_intra(&self) -> bool {
41 matches!(self, SliceType::I | SliceType::Si)
42 }
43}
44
45/// One `ref_pic_list_modification` operation (spec 7.3.3.1).
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum RefPicListMod {
48 /// `modification_of_pic_nums_idc` 0/1: `abs_diff_pic_num_minus1`,
49 /// subtract (idc 0) or add (idc 1).
50 ShortTerm {
51 /// `abs_diff_pic_num_minus1`.
52 abs_diff_pic_num_minus1: u32,
53 /// idc 1 = add, idc 0 = subtract.
54 add: bool,
55 },
56 /// idc 2: `long_term_pic_num`.
57 LongTerm(u32),
58}
59
60/// One explicit weight entry of the `pred_weight_table` (spec 7.3.3.2).
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct WeightEntry {
63 /// `(luma_weight, luma_offset)` when `luma_weight_flag`.
64 pub luma: Option<(i32, i32)>,
65 /// `[(cb_weight, cb_offset), (cr_weight, cr_offset)]` when signalled.
66 pub chroma: Option<[(i32, i32); 2]>,
67}
68
69/// `pred_weight_table` (spec 7.3.3.2).
70#[derive(Debug, Clone, PartialEq, Eq, Default)]
71pub struct PredWeightTable {
72 /// `luma_log2_weight_denom`.
73 pub luma_log2_weight_denom: u32,
74 /// `chroma_log2_weight_denom` (chroma formats only).
75 pub chroma_log2_weight_denom: u32,
76 /// Per-reference weights, list 0.
77 pub l0: Vec<WeightEntry>,
78 /// Per-reference weights, list 1 (B slices).
79 pub l1: Vec<WeightEntry>,
80}
81
82/// One memory-management control operation (spec 7.3.3.3, Table 7-9).
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct Mmco {
85 /// `memory_management_control_operation` (1..=6).
86 pub op: u32,
87 /// First operand (difference_of_pic_nums_minus1 / long_term_pic_num /
88 /// long_term_frame_idx / max_long_term_frame_idx_plus1), op-dependent.
89 pub arg1: u32,
90 /// Second operand (op 3: `long_term_frame_idx`).
91 pub arg2: u32,
92}
93
94/// `dec_ref_pic_marking` (spec 7.3.3.3).
95#[derive(Debug, Clone, PartialEq, Eq, Default)]
96pub struct DecRefPicMarking {
97 /// IDR: `no_output_of_prior_pics_flag`.
98 pub no_output_of_prior_pics: bool,
99 /// IDR: `long_term_reference_flag`.
100 pub long_term_reference: bool,
101 /// Non-IDR: `adaptive_ref_pic_marking_mode_flag`.
102 pub adaptive: bool,
103 /// Adaptive-mode operations, in order.
104 pub mmcos: Vec<Mmco>,
105}
106
107/// Deblocking-filter control from the slice header (spec 7.4.3).
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109pub struct DeblockControl {
110 /// `disable_deblocking_filter_idc`: 0 = on, 1 = off, 2 = on but not
111 /// across slice boundaries.
112 pub disable_idc: u8,
113 /// `slice_alpha_c0_offset_div2` * 2.
114 pub alpha_c0_offset: i32,
115 /// `slice_beta_offset_div2` * 2.
116 pub beta_offset: i32,
117}
118
119/// Parsed slice header.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct SliceHeader {
122 /// `first_mb_in_slice` (macroblock address; frame coding).
123 pub first_mb_in_slice: u32,
124 /// Slice type (already reduced mod 5).
125 pub slice_type: SliceType,
126 /// True when `slice_type` was 5..=9: every slice of the picture has
127 /// this type.
128 pub all_slices_same_type: bool,
129 /// `pic_parameter_set_id`.
130 pub pps_id: u32,
131 /// `colour_plane_id` (separate colour planes only).
132 pub colour_plane_id: u8,
133 /// `frame_num`.
134 pub frame_num: u32,
135 /// `field_pic_flag`.
136 pub field_pic: bool,
137 /// `bottom_field_flag`.
138 pub bottom_field: bool,
139 /// `idr_pic_id` for IDR slices.
140 pub idr_pic_id: Option<u32>,
141 /// `pic_order_cnt_lsb` (POC type 0).
142 pub pic_order_cnt_lsb: u32,
143 /// `delta_pic_order_cnt_bottom` (POC type 0 + PPS flag).
144 pub delta_pic_order_cnt_bottom: i32,
145 /// `delta_pic_order_cnt[0..2]` (POC type 1).
146 pub delta_pic_order_cnt: [i32; 2],
147 /// `redundant_pic_cnt` when present.
148 pub redundant_pic_cnt: u32,
149 /// B: `direct_spatial_mv_pred_flag`.
150 pub direct_spatial_mv_pred: bool,
151 /// Active reference count, list 0 (P/SP/B; PPS default applied).
152 pub num_ref_idx_l0_active: u32,
153 /// Active reference count, list 1 (B; PPS default applied).
154 pub num_ref_idx_l1_active: u32,
155 /// Reference list modifications, list 0.
156 pub ref_pic_list_mod_l0: Vec<RefPicListMod>,
157 /// Reference list modifications, list 1.
158 pub ref_pic_list_mod_l1: Vec<RefPicListMod>,
159 /// Prediction weight table when signalled.
160 pub pred_weight_table: Option<PredWeightTable>,
161 /// Reference-picture marking when `nal_ref_idc != 0`.
162 pub dec_ref_pic_marking: Option<DecRefPicMarking>,
163 /// `cabac_init_idc` (CABAC, non-intra slices).
164 pub cabac_init_idc: u32,
165 /// `SliceQPY` = 26 + pic_init_qp_minus26 + slice_qp_delta.
166 pub slice_qp: i32,
167 /// SP: `sp_for_switch_flag`.
168 pub sp_for_switch: bool,
169 /// SP/SI: `SliceQSY`.
170 pub slice_qs: i32,
171 /// Deblocking control (defaults when the PPS does not signal it).
172 pub deblock: DeblockControl,
173 /// `slice_group_change_cycle` (FMO map types 3..=5).
174 pub slice_group_change_cycle: u32,
175 /// Bits consumed by the header — slice data starts here.
176 pub header_bits: u64,
177}
178
179impl SliceHeader {
180 /// Parse a slice header from the RBSP after the NAL header byte.
181 pub fn parse(rbsp: &[u8], nal: NalHeader, sps: &Sps, pps: &Pps) -> Result<SliceHeader> {
182 let mut reader = BitReader::new(rbsp);
183 let r = &mut reader;
184 let first_mb_in_slice = r.read_ue()?;
185 let slice_type_code = r.read_ue()?;
186 if slice_type_code > 9 {
187 return Err(Error::corrupt("slice_type > 9"));
188 }
189 let slice_type = SliceType::from_code(slice_type_code)?;
190 let all_slices_same_type = slice_type_code > 4;
191 let pps_id = r.read_ue()?;
192 if pps_id != pps.id {
193 return Err(Error::corrupt("slice parsed against the wrong PPS"));
194 }
195 let colour_plane_id = if sps.separate_colour_plane {
196 r.read_bits(2)? as u8
197 } else {
198 0
199 };
200 let frame_num = r.read_bits(sps.log2_max_frame_num as u32)?;
201 let mut field_pic = false;
202 let mut bottom_field = false;
203 if !sps.frame_mbs_only {
204 field_pic = r.read_bit()?;
205 if field_pic {
206 bottom_field = r.read_bit()?;
207 }
208 }
209 let idr_pic_id = if nal.is_idr() {
210 let v = r.read_ue()?;
211 if v > 65535 {
212 return Err(Error::corrupt("idr_pic_id > 65535"));
213 }
214 Some(v)
215 } else {
216 None
217 };
218 let mut pic_order_cnt_lsb = 0;
219 let mut delta_pic_order_cnt_bottom = 0;
220 let mut delta_pic_order_cnt = [0i32; 2];
221 match sps.pic_order_cnt_type {
222 0 => {
223 pic_order_cnt_lsb = r.read_bits(sps.log2_max_pic_order_cnt_lsb as u32)?;
224 if pps.bottom_field_pic_order_in_frame_present && !field_pic {
225 delta_pic_order_cnt_bottom = r.read_se()?;
226 }
227 }
228 1 if !sps.delta_pic_order_always_zero => {
229 delta_pic_order_cnt[0] = r.read_se()?;
230 if pps.bottom_field_pic_order_in_frame_present && !field_pic {
231 delta_pic_order_cnt[1] = r.read_se()?;
232 }
233 }
234 _ => {}
235 }
236 let redundant_pic_cnt = if pps.redundant_pic_cnt_present {
237 r.read_ue()?
238 } else {
239 0
240 };
241 let direct_spatial_mv_pred = if slice_type == SliceType::B {
242 r.read_bit()?
243 } else {
244 false
245 };
246
247 let mut num_ref_idx_l0_active = pps.num_ref_idx_l0_default_active;
248 let mut num_ref_idx_l1_active = pps.num_ref_idx_l1_default_active;
249 if matches!(slice_type, SliceType::P | SliceType::Sp | SliceType::B) {
250 if r.read_bit()? {
251 // num_ref_idx_active_override_flag
252 num_ref_idx_l0_active = r.read_ue()? + 1;
253 if slice_type == SliceType::B {
254 num_ref_idx_l1_active = r.read_ue()? + 1;
255 }
256 }
257 if num_ref_idx_l0_active > 32 || num_ref_idx_l1_active > 32 {
258 return Err(Error::corrupt("num_ref_idx_active > 32"));
259 }
260 }
261
262 // ref_pic_list_modification (7.3.3.1) — not for I/SI.
263 let mut ref_pic_list_mod_l0 = Vec::new();
264 let mut ref_pic_list_mod_l1 = Vec::new();
265 if !slice_type.is_intra() {
266 Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l0)?;
267 }
268 if slice_type == SliceType::B {
269 Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l1)?;
270 }
271
272 // pred_weight_table (7.3.3.2).
273 let pred_weight_table = if (pps.weighted_pred
274 && matches!(slice_type, SliceType::P | SliceType::Sp))
275 || (pps.weighted_bipred_idc == 1 && slice_type == SliceType::B)
276 {
277 Some(Self::parse_pred_weight_table(
278 r,
279 sps,
280 slice_type,
281 num_ref_idx_l0_active,
282 num_ref_idx_l1_active,
283 )?)
284 } else {
285 None
286 };
287
288 // dec_ref_pic_marking (7.3.3.3).
289 let dec_ref_pic_marking = if nal.ref_idc != 0 {
290 let mut m = DecRefPicMarking::default();
291 if nal.is_idr() {
292 m.no_output_of_prior_pics = r.read_bit()?;
293 m.long_term_reference = r.read_bit()?;
294 } else {
295 m.adaptive = r.read_bit()?;
296 if m.adaptive {
297 loop {
298 let op = r.read_ue()?;
299 if op == 0 {
300 break;
301 }
302 if op > 6 {
303 return Err(Error::corrupt("memory_management_control_operation > 6"));
304 }
305 if m.mmcos.len() >= 64 {
306 return Err(Error::corrupt("more than 64 MMCO operations"));
307 }
308 let arg1 = match op {
309 1..=4 => r.read_ue()?,
310 6 => r.read_ue()?,
311 _ => 0,
312 };
313 let arg2 = if op == 3 { r.read_ue()? } else { 0 };
314 m.mmcos.push(Mmco { op, arg1, arg2 });
315 }
316 }
317 }
318 Some(m)
319 } else {
320 None
321 };
322
323 let cabac_init_idc = if pps.entropy_coding_mode && !slice_type.is_intra() {
324 let v = r.read_ue()?;
325 if v > 2 {
326 return Err(Error::corrupt("cabac_init_idc > 2"));
327 }
328 v
329 } else {
330 0
331 };
332
333 let slice_qp_delta = r.read_se()?;
334 let slice_qp = pps.pic_init_qp + slice_qp_delta;
335 if !(-(sps.bit_depth_luma as i32 - 8) * 6..=51).contains(&slice_qp) {
336 return Err(Error::corrupt("SliceQPY out of range"));
337 }
338
339 let mut sp_for_switch = false;
340 let mut slice_qs = pps.pic_init_qs;
341 if matches!(slice_type, SliceType::Sp | SliceType::Si) {
342 if slice_type == SliceType::Sp {
343 sp_for_switch = r.read_bit()?;
344 }
345 slice_qs = pps.pic_init_qs + r.read_se()?;
346 if !(0..=51).contains(&slice_qs) {
347 return Err(Error::corrupt("SliceQSY out of range"));
348 }
349 }
350
351 let mut deblock = DeblockControl::default();
352 if pps.deblocking_filter_control_present {
353 let idc = r.read_ue()?;
354 if idc > 2 {
355 return Err(Error::corrupt("disable_deblocking_filter_idc > 2"));
356 }
357 deblock.disable_idc = idc as u8;
358 if idc != 1 {
359 let a = r.read_se()?;
360 let b = r.read_se()?;
361 if !(-6..=6).contains(&a) || !(-6..=6).contains(&b) {
362 return Err(Error::corrupt("deblocking offset div2 outside [-6, 6]"));
363 }
364 deblock.alpha_c0_offset = a * 2;
365 deblock.beta_offset = b * 2;
366 }
367 }
368
369 let mut slice_group_change_cycle = 0;
370 if pps.num_slice_groups > 1
371 && let Some(crate::pps::SliceGroupMap::Changing {
372 change_rate_minus1, ..
373 }) = &pps.slice_group_map
374 {
375 // u(v) with v = Ceil(Log2(PicSizeInMapUnits / SliceGroupChangeRate + 1)).
376 let pic_size_in_map_units =
377 sps.mb_width * (sps.mb_height / if sps.frame_mbs_only { 1 } else { 2 });
378 let rate = change_rate_minus1 + 1;
379 let max = pic_size_in_map_units.div_ceil(rate) + 1;
380 let bits = 32 - (max - 1).leading_zeros();
381 slice_group_change_cycle = r.read_bits(bits.max(1))?;
382 }
383
384 Ok(SliceHeader {
385 first_mb_in_slice,
386 slice_type,
387 all_slices_same_type,
388 pps_id,
389 colour_plane_id,
390 frame_num,
391 field_pic,
392 bottom_field,
393 idr_pic_id,
394 pic_order_cnt_lsb,
395 delta_pic_order_cnt_bottom,
396 delta_pic_order_cnt,
397 redundant_pic_cnt,
398 direct_spatial_mv_pred,
399 num_ref_idx_l0_active,
400 num_ref_idx_l1_active,
401 ref_pic_list_mod_l0,
402 ref_pic_list_mod_l1,
403 pred_weight_table,
404 dec_ref_pic_marking,
405 cabac_init_idc,
406 slice_qp,
407 sp_for_switch,
408 slice_qs,
409 deblock,
410 slice_group_change_cycle,
411 header_bits: reader.bit_position(),
412 })
413 }
414
415 fn parse_ref_list_mod(r: &mut BitReader<'_>, out: &mut Vec<RefPicListMod>) -> Result<()> {
416 if !r.read_bit()? {
417 return Ok(()); // ref_pic_list_modification_flag == 0
418 }
419 loop {
420 let idc = r.read_ue()?;
421 match idc {
422 0 | 1 => out.push(RefPicListMod::ShortTerm {
423 abs_diff_pic_num_minus1: r.read_ue()?,
424 add: idc == 1,
425 }),
426 2 => out.push(RefPicListMod::LongTerm(r.read_ue()?)),
427 3 => return Ok(()),
428 _ => return Err(Error::corrupt("modification_of_pic_nums_idc > 3")),
429 }
430 if out.len() > 64 {
431 return Err(Error::corrupt("more than 64 ref list modifications"));
432 }
433 }
434 }
435
436 fn parse_pred_weight_table(
437 r: &mut BitReader<'_>,
438 sps: &Sps,
439 slice_type: SliceType,
440 l0_count: u32,
441 l1_count: u32,
442 ) -> Result<PredWeightTable> {
443 let mut t = PredWeightTable {
444 luma_log2_weight_denom: r.read_ue()?,
445 ..Default::default()
446 };
447 if t.luma_log2_weight_denom > 7 {
448 return Err(Error::corrupt("luma_log2_weight_denom > 7"));
449 }
450 let has_chroma = sps.chroma_format_idc != 0 && !sps.separate_colour_plane;
451 if has_chroma {
452 t.chroma_log2_weight_denom = r.read_ue()?;
453 if t.chroma_log2_weight_denom > 7 {
454 return Err(Error::corrupt("chroma_log2_weight_denom > 7"));
455 }
456 }
457 let parse_list = |r: &mut BitReader<'_>, count: u32| -> Result<Vec<WeightEntry>> {
458 let mut list = Vec::with_capacity(count as usize);
459 for _ in 0..count {
460 let luma = if r.read_bit()? {
461 Some((r.read_se()?, r.read_se()?))
462 } else {
463 None
464 };
465 let chroma = if has_chroma && r.read_bit()? {
466 Some([(r.read_se()?, r.read_se()?), (r.read_se()?, r.read_se()?)])
467 } else {
468 None
469 };
470 list.push(WeightEntry { luma, chroma });
471 }
472 Ok(list)
473 };
474 t.l0 = parse_list(r, l0_count)?;
475 if slice_type == SliceType::B {
476 t.l1 = parse_list(r, l1_count)?;
477 }
478 Ok(t)
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use crate::nal::NalHeader;
486 use crate::pps::Pps;
487 use crate::sps::Sps;
488 use ec_core::BitWriter;
489
490 fn qcif_sps() -> Sps {
491 let mut w = BitWriter::new();
492 w.write_bits(66, 8);
493 w.write_bits(0xC0, 8);
494 w.write_bits(10, 8);
495 w.write_ue(0);
496 w.write_ue(0); // log2_max_frame_num = 4
497 w.write_ue(0); // poc type 0, log2 lsb next
498 w.write_ue(0);
499 w.write_ue(1);
500 w.write_bit(false);
501 w.write_ue(10);
502 w.write_ue(8);
503 w.write_bit(true);
504 w.write_bit(true);
505 w.write_bit(false);
506 w.write_bit(false);
507 w.write_bit(true);
508 w.align_to_byte();
509 Sps::parse(w.as_bytes()).unwrap()
510 }
511
512 fn simple_pps() -> Pps {
513 let mut w = BitWriter::new();
514 w.write_ue(0);
515 w.write_ue(0);
516 w.write_bit(false);
517 w.write_bit(false);
518 w.write_ue(0);
519 w.write_ue(0);
520 w.write_ue(0);
521 w.write_bit(false);
522 w.write_bits(0, 2);
523 w.write_se(0);
524 w.write_se(0);
525 w.write_se(0);
526 w.write_bit(false); // no deblocking control in header
527 w.write_bit(false);
528 w.write_bit(false);
529 w.write_bit(true);
530 w.align_to_byte();
531 Pps::parse(w.as_bytes(), |_| None).unwrap()
532 }
533
534 #[test]
535 fn idr_i_slice_header() {
536 let sps = qcif_sps();
537 let pps = simple_pps();
538 let mut w = BitWriter::new();
539 w.write_ue(0); // first_mb_in_slice
540 w.write_ue(7); // slice_type: I, all slices
541 w.write_ue(0); // pps id
542 w.write_bits(0, 4); // frame_num
543 w.write_ue(3); // idr_pic_id
544 w.write_bits(0, 4); // pic_order_cnt_lsb
545 w.write_bit(false); // no_output_of_prior_pics (nal_ref_idc != 0)
546 w.write_bit(false); // long_term_reference
547 w.write_se(4); // slice_qp_delta -> QP 30
548 w.write_bit(true); // first slice-data bit, not part of header
549 w.align_to_byte();
550 let nal = NalHeader::parse(0x65).unwrap();
551 let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap();
552 assert_eq!(h.slice_type, SliceType::I);
553 assert!(h.all_slices_same_type);
554 assert_eq!(h.idr_pic_id, Some(3));
555 assert_eq!(h.slice_qp, 30);
556 assert_eq!(h.deblock.disable_idc, 0);
557 // Header ends right before the trailing data bit we appended.
558 assert_eq!(h.header_bits, w.bit_len() - 8 + 7); // wrote 1 bit + 7 pad
559 }
560
561 #[test]
562 fn p_slice_fields_parse() {
563 let sps = qcif_sps();
564 let pps = simple_pps();
565 let mut w = BitWriter::new();
566 w.write_ue(2); // first_mb_in_slice
567 w.write_ue(0); // slice_type: P
568 w.write_ue(0); // pps id
569 w.write_bits(1, 4); // frame_num
570 w.write_bits(2, 4); // pic_order_cnt_lsb
571 w.write_bit(true); // num_ref_idx_active_override
572 w.write_ue(1); // l0 active = 2
573 w.write_bit(true); // ref_pic_list_modification_flag_l0
574 w.write_ue(0); // idc 0: short term subtract
575 w.write_ue(4); // abs_diff_pic_num_minus1
576 w.write_ue(3); // idc 3: end
577 w.write_bit(false); // adaptive_ref_pic_marking (nal_ref_idc != 0)
578 w.write_se(-2); // slice_qp_delta -> 24
579 w.write_bit(true);
580 w.align_to_byte();
581 let nal = NalHeader::parse(0x41).unwrap(); // non-IDR slice, ref
582 let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap();
583 assert_eq!(h.slice_type, SliceType::P);
584 assert_eq!(h.first_mb_in_slice, 2);
585 assert_eq!(h.num_ref_idx_l0_active, 2);
586 assert_eq!(
587 h.ref_pic_list_mod_l0,
588 vec![RefPicListMod::ShortTerm {
589 abs_diff_pic_num_minus1: 4,
590 add: false
591 }]
592 );
593 assert_eq!(h.slice_qp, 24);
594 assert!(h.dec_ref_pic_marking.is_some());
595 }
596
597 #[test]
598 fn truncated_header_is_need_more() {
599 let sps = qcif_sps();
600 let pps = simple_pps();
601 let nal = NalHeader::parse(0x65).unwrap();
602 assert!(
603 SliceHeader::parse(&[0x88], nal, &sps, &pps)
604 .unwrap_err()
605 .is_need_more()
606 );
607 }
608}