edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·b07f07a·Tahinli·3 months ago·1061 commits
| 1 | //! The slice segment header (7.3.6.1). |
| 2 | |
| 3 | use crate::nal::NalUnitType; |
| 4 | use crate::ps::{Pps, ShortTermRefPicSet, Sps, ceil_log2}; |
| 5 | use ec_core::bitio::{BitReader, BitWriter}; |
| 6 | use ec_core::error::{Error, Result}; |
| 7 | |
| 8 | /// `slice_type`. |
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 10 | pub 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 | |
| 19 | impl 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)] |
| 42 | pub 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)] |
| 55 | pub 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)] |
| 64 | pub 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)] |
| 78 | pub 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 | /// `slice_deblocking_filter_disabled_flag`, after any override. |
| 125 | pub deblocking_filter_disabled: bool, |
| 126 | /// `slice_beta_offset_div2`. |
| 127 | pub beta_offset_div2: i32, |
| 128 | /// `slice_tc_offset_div2`. |
| 129 | pub tc_offset_div2: i32, |
| 130 | /// `slice_loop_filter_across_slices_enabled_flag`. |
| 131 | pub loop_filter_across_slices_enabled: bool, |
| 132 | /// Substream entry points: one per WPP CTB row (or tile) after the first. |
| 133 | pub entry_point_offsets: Vec<u32>, |
| 134 | /// The short-term reference picture set in force, whether it came from the |
| 135 | /// SPS by index or was written out in this header. |
| 136 | /// |
| 137 | /// This and the three fields after it are what a *stateless hardware* |
| 138 | /// decoder needs and a software one derives on the fly: the driver is given |
| 139 | /// `RefPicSetStCurrBefore` / `StCurrAfter` / `LtCurr` as picture lists, so |
| 140 | /// the caller has to turn these deltas into reference pictures itself. |
| 141 | pub short_term_ref_pic_set: ShortTermRefPicSet, |
| 142 | /// True when the set above came from the SPS rather than this header. |
| 143 | pub short_term_ref_pic_set_sps_flag: bool, |
| 144 | /// The long-term reference pictures this slice names, in bitstream order. |
| 145 | pub long_term: Vec<LongTermRef>, |
| 146 | /// `list_entry_l0` / `list_entry_l1`; empty when the list is not modified. |
| 147 | pub list_entry: [Vec<u32>; 2], |
| 148 | /// `pred_weight_table()`, when the PPS turns weighted prediction on. |
| 149 | pub pred_weight_table: Option<PredWeightTable>, |
| 150 | } |
| 151 | |
| 152 | impl SliceHeader { |
| 153 | /// An I slice covering a whole picture at `qp_delta`, filters off. |
| 154 | pub fn intra(pps: &Pps, qp_delta: i32) -> SliceHeader { |
| 155 | SliceHeader { |
| 156 | first_slice_segment_in_pic: true, |
| 157 | no_output_of_prior_pics: false, |
| 158 | pps_id: pps.id, |
| 159 | dependent_slice_segment: false, |
| 160 | segment_address: 0, |
| 161 | slice_type: SliceType::I, |
| 162 | pic_output_flag: true, |
| 163 | poc_lsb: 0, |
| 164 | colour_plane_id: 0, |
| 165 | sao_luma: false, |
| 166 | sao_chroma: false, |
| 167 | num_ref_idx_l0_active_minus1: 0, |
| 168 | num_ref_idx_l1_active_minus1: 0, |
| 169 | mvd_l1_zero: false, |
| 170 | cabac_init: false, |
| 171 | temporal_mvp_enabled: false, |
| 172 | collocated_from_l0: true, |
| 173 | collocated_ref_idx: 0, |
| 174 | five_minus_max_num_merge_cand: 0, |
| 175 | qp_delta, |
| 176 | cb_qp_offset: 0, |
| 177 | cr_qp_offset: 0, |
| 178 | deblocking_filter_disabled: pps.deblocking_filter_disabled, |
| 179 | beta_offset_div2: 0, |
| 180 | tc_offset_div2: 0, |
| 181 | loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, |
| 182 | entry_point_offsets: Vec::new(), |
| 183 | short_term_ref_pic_set: ShortTermRefPicSet::default(), |
| 184 | short_term_ref_pic_set_sps_flag: true, |
| 185 | long_term: Vec::new(), |
| 186 | list_entry: [Vec::new(), Vec::new()], |
| 187 | pred_weight_table: None, |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// Write the header, up to and including `byte_alignment()`. |
| 192 | /// |
| 193 | /// Entry point offsets are written from `self.entry_point_offsets`, so a WPP |
| 194 | /// encoder codes its substreams first and builds the header afterwards — |
| 195 | /// the offsets are not knowable any earlier. |
| 196 | pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) { |
| 197 | self.write_without_alignment(w, sps, pps, nal_type); |
| 198 | // byte_alignment(): a one bit then zeros. |
| 199 | w.write_bit(true); |
| 200 | w.align_to_byte(); |
| 201 | } |
| 202 | |
| 203 | /// The header without its closing `byte_alignment()`. |
| 204 | /// |
| 205 | /// A VA-API encoder wants exactly this: the driver is told how many bits of |
| 206 | /// header the application wrote and appends the alignment itself, so |
| 207 | /// including it here leaves the alignment bit sitting where the driver |
| 208 | /// expects slice data (measured on radeonsi: every P picture then decodes |
| 209 | /// as `alignment_bit_equal_to_one = 0`). |
| 210 | pub fn write_without_alignment( |
| 211 | &self, |
| 212 | w: &mut BitWriter, |
| 213 | sps: &Sps, |
| 214 | pps: &Pps, |
| 215 | nal_type: NalUnitType, |
| 216 | ) { |
| 217 | w.write_bit(self.first_slice_segment_in_pic); |
| 218 | if nal_type.is_irap() { |
| 219 | w.write_bit(self.no_output_of_prior_pics); |
| 220 | } |
| 221 | w.write_ue(self.pps_id); |
| 222 | if !self.first_slice_segment_in_pic { |
| 223 | if pps.dependent_slice_segments_enabled { |
| 224 | w.write_bit(self.dependent_slice_segment); |
| 225 | } |
| 226 | w.write_bits(self.segment_address, sps.slice_address_bits()); |
| 227 | } |
| 228 | if !self.dependent_slice_segment { |
| 229 | for _ in 0..pps.num_extra_slice_header_bits { |
| 230 | w.write_bit(false); |
| 231 | } |
| 232 | w.write_ue(self.slice_type.code()); |
| 233 | if pps.output_flag_present { |
| 234 | w.write_bit(self.pic_output_flag); |
| 235 | } |
| 236 | if !nal_type.is_idr() { |
| 237 | w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4); |
| 238 | w.write_bit(self.short_term_ref_pic_set_sps_flag); |
| 239 | if self.short_term_ref_pic_set_sps_flag { |
| 240 | if sps.num_short_term_ref_pic_sets > 1 { |
| 241 | w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets)); |
| 242 | } |
| 243 | } else { |
| 244 | // Written out here, which is what a stream whose SPS carries |
| 245 | // no sets must do — and what a hardware encoder's driver |
| 246 | // does for its own single reference. |
| 247 | self.short_term_ref_pic_set |
| 248 | .write(w, sps.num_short_term_ref_pic_sets); |
| 249 | } |
| 250 | if sps.temporal_mvp_enabled { |
| 251 | w.write_bit(self.temporal_mvp_enabled); |
| 252 | } |
| 253 | } |
| 254 | if sps.sao_enabled { |
| 255 | w.write_bit(self.sao_luma); |
| 256 | if sps.chroma_format_idc != 0 { |
| 257 | w.write_bit(self.sao_chroma); |
| 258 | } |
| 259 | } |
| 260 | if self.slice_type != SliceType::I { |
| 261 | w.write_bit(false); // num_ref_idx_active_override_flag |
| 262 | if self.slice_type == SliceType::B { |
| 263 | w.write_bit(self.mvd_l1_zero); |
| 264 | } |
| 265 | if pps.cabac_init_present { |
| 266 | w.write_bit(self.cabac_init); |
| 267 | } |
| 268 | w.write_ue(self.five_minus_max_num_merge_cand); |
| 269 | } |
| 270 | w.write_se(self.qp_delta); |
| 271 | if pps.slice_chroma_qp_offsets_present { |
| 272 | w.write_se(self.cb_qp_offset); |
| 273 | w.write_se(self.cr_qp_offset); |
| 274 | } |
| 275 | if pps.deblocking_filter_override_enabled { |
| 276 | w.write_bit(false); // deblocking_filter_override_flag |
| 277 | } |
| 278 | if pps.loop_filter_across_slices_enabled |
| 279 | && (self.sao_luma || self.sao_chroma || !self.deblocking_filter_disabled) |
| 280 | { |
| 281 | w.write_bit(self.loop_filter_across_slices_enabled); |
| 282 | } |
| 283 | } |
| 284 | if pps.tiles_enabled || pps.entropy_coding_sync_enabled { |
| 285 | w.write_ue(self.entry_point_offsets.len() as u32); |
| 286 | if !self.entry_point_offsets.is_empty() { |
| 287 | let max = self.entry_point_offsets.iter().copied().max().unwrap_or(1); |
| 288 | let offset_len = ceil_log2(max + 1).max(1); |
| 289 | w.write_ue(offset_len - 1); |
| 290 | for &offset in &self.entry_point_offsets { |
| 291 | w.write_bits(offset - 1, offset_len); |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | /// Parse a slice segment header out of an unescaped slice NAL payload. |
| 298 | /// |
| 299 | /// Returns the header and the bit position where slice data begins — what |
| 300 | /// `VASliceParameterBufferHEVC::slice_data_byte_offset` is derived from. |
| 301 | pub fn parse( |
| 302 | rbsp: &[u8], |
| 303 | sps: &Sps, |
| 304 | pps: &Pps, |
| 305 | nal_type: NalUnitType, |
| 306 | ) -> Result<(SliceHeader, ParsePositions)> { |
| 307 | let mut r = BitReader::new(rbsp); |
| 308 | let mut h = SliceHeader::intra(pps, 0); |
| 309 | let mut pos = ParsePositions::default(); |
| 310 | h.first_slice_segment_in_pic = r.read_bit()?; |
| 311 | if nal_type.is_irap() { |
| 312 | h.no_output_of_prior_pics = r.read_bit()?; |
| 313 | } |
| 314 | h.pps_id = r.read_ue()?; |
| 315 | if !h.first_slice_segment_in_pic { |
| 316 | if pps.dependent_slice_segments_enabled { |
| 317 | h.dependent_slice_segment = r.read_bit()?; |
| 318 | } |
| 319 | h.segment_address = r.read_bits(sps.slice_address_bits())?; |
| 320 | } |
| 321 | if !h.dependent_slice_segment { |
| 322 | for _ in 0..pps.num_extra_slice_header_bits { |
| 323 | r.read_bit()?; |
| 324 | } |
| 325 | h.slice_type = SliceType::from_code(r.read_ue()?)?; |
| 326 | if pps.output_flag_present { |
| 327 | h.pic_output_flag = r.read_bit()?; |
| 328 | } |
| 329 | if sps.separate_colour_plane { |
| 330 | h.colour_plane_id = r.read_bits(2)? as u8; |
| 331 | } |
| 332 | let mut num_long_term = 0; |
| 333 | if !nal_type.is_idr() { |
| 334 | h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; |
| 335 | let from_sps = r.read_bit()?; |
| 336 | h.short_term_ref_pic_set_sps_flag = from_sps; |
| 337 | let before = r.bit_position(); |
| 338 | if !from_sps { |
| 339 | // Written out here, possibly predicted from the SPS sets — |
| 340 | // hence `num_short_term_ref_pic_sets` as this set's index |
| 341 | // and the SPS sets as the prediction source (7.3.7). |
| 342 | h.short_term_ref_pic_set = ShortTermRefPicSet::parse( |
| 343 | &mut r, |
| 344 | sps.num_short_term_ref_pic_sets, |
| 345 | &sps.short_term_ref_pic_sets, |
| 346 | )?; |
| 347 | } else { |
| 348 | let idx = if sps.num_short_term_ref_pic_sets > 1 { |
| 349 | r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))? |
| 350 | } else { |
| 351 | 0 |
| 352 | }; |
| 353 | h.short_term_ref_pic_set = sps |
| 354 | .short_term_ref_pic_sets |
| 355 | .get(idx as usize) |
| 356 | .copied() |
| 357 | .ok_or_else(|| { |
| 358 | Error::corrupt(format!( |
| 359 | "HEVC slice: short_term_ref_pic_set_idx {idx} is not in the SPS" |
| 360 | )) |
| 361 | })?; |
| 362 | } |
| 363 | // Only a set written *in the header* costs the driver bits to |
| 364 | // skip; for an SPS-indexed one libva wants zero. |
| 365 | pos.st_rps_bits = if from_sps { |
| 366 | 0 |
| 367 | } else { |
| 368 | (r.bit_position() - before) as u32 |
| 369 | }; |
| 370 | if sps.long_term_ref_pics_present { |
| 371 | let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 { |
| 372 | r.read_ue()? |
| 373 | } else { |
| 374 | 0 |
| 375 | }; |
| 376 | let num_long_term_pics = r.read_ue()?; |
| 377 | let mut prev_delta_msb = 0u32; |
| 378 | for i in 0..num_long_term_sps + num_long_term_pics { |
| 379 | let mut entry = LongTermRef::default(); |
| 380 | if i < num_long_term_sps { |
| 381 | let idx = if sps.num_long_term_ref_pics_sps > 1 { |
| 382 | r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))? |
| 383 | } else { |
| 384 | 0 |
| 385 | }; |
| 386 | let (poc_lsb_lt, used) = sps |
| 387 | .long_term_ref_pics_sps |
| 388 | .get(idx as usize) |
| 389 | .copied() |
| 390 | .unwrap_or((0, false)); |
| 391 | entry.poc_lsb_lt = poc_lsb_lt; |
| 392 | entry.used_by_curr = used; |
| 393 | } else { |
| 394 | entry.poc_lsb_lt = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; |
| 395 | entry.used_by_curr = r.read_bit()?; |
| 396 | } |
| 397 | if entry.used_by_curr { |
| 398 | num_long_term += 1; |
| 399 | } |
| 400 | entry.delta_poc_msb_present = r.read_bit()?; |
| 401 | if entry.delta_poc_msb_present { |
| 402 | // 7-52: coded as a delta against the previous entry, |
| 403 | // except for the first of each kind. |
| 404 | let delta = r.read_ue()?; |
| 405 | entry.delta_poc_msb_cycle = if i == 0 || i == num_long_term_sps { |
| 406 | delta |
| 407 | } else { |
| 408 | delta + prev_delta_msb |
| 409 | }; |
| 410 | prev_delta_msb = entry.delta_poc_msb_cycle; |
| 411 | } |
| 412 | h.long_term.push(entry); |
| 413 | } |
| 414 | } |
| 415 | if sps.temporal_mvp_enabled { |
| 416 | h.temporal_mvp_enabled = r.read_bit()?; |
| 417 | } |
| 418 | } |
| 419 | if sps.sao_enabled { |
| 420 | h.sao_luma = r.read_bit()?; |
| 421 | if sps.chroma_format_idc != 0 { |
| 422 | h.sao_chroma = r.read_bit()?; |
| 423 | } |
| 424 | } |
| 425 | if h.slice_type != SliceType::I { |
| 426 | h.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1; |
| 427 | h.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1; |
| 428 | if r.read_bit()? { |
| 429 | h.num_ref_idx_l0_active_minus1 = r.read_ue()?; |
| 430 | if h.slice_type == SliceType::B { |
| 431 | h.num_ref_idx_l1_active_minus1 = r.read_ue()?; |
| 432 | } |
| 433 | // 7.4.7.1: both fields are in range 0..=14. Past that is |
| 434 | // a corrupt stream, not a bigger reference list -- and |
| 435 | // pred_weight_table below sizes a Vec from this value, so |
| 436 | // an unchecked ue(v) is a header-declared allocation an |
| 437 | // attacker fully controls (up to 2^32 entries from a |
| 438 | // handful of bits). |
| 439 | if h.num_ref_idx_l0_active_minus1 > 14 || h.num_ref_idx_l1_active_minus1 > 14 { |
| 440 | return Err(Error::corrupt( |
| 441 | "HEVC slice header: num_ref_idx_lX_active_minus1 out of range", |
| 442 | )); |
| 443 | } |
| 444 | } |
| 445 | let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; |
| 446 | if pps.lists_modification_present && num_pic_total_curr > 1 { |
| 447 | let bits = ceil_log2(num_pic_total_curr); |
| 448 | if r.read_bit()? { |
| 449 | for _ in 0..=h.num_ref_idx_l0_active_minus1 { |
| 450 | let entry = r.read_bits(bits)?; |
| 451 | h.list_entry[0].push(entry); |
| 452 | } |
| 453 | } |
| 454 | if h.slice_type == SliceType::B && r.read_bit()? { |
| 455 | for _ in 0..=h.num_ref_idx_l1_active_minus1 { |
| 456 | let entry = r.read_bits(bits)?; |
| 457 | h.list_entry[1].push(entry); |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | if h.slice_type == SliceType::B { |
| 462 | h.mvd_l1_zero = r.read_bit()?; |
| 463 | } |
| 464 | if pps.cabac_init_present { |
| 465 | h.cabac_init = r.read_bit()?; |
| 466 | } |
| 467 | if h.temporal_mvp_enabled { |
| 468 | if h.slice_type == SliceType::B { |
| 469 | h.collocated_from_l0 = r.read_bit()?; |
| 470 | } |
| 471 | if (h.collocated_from_l0 && h.num_ref_idx_l0_active_minus1 > 0) |
| 472 | || (!h.collocated_from_l0 && h.num_ref_idx_l1_active_minus1 > 0) |
| 473 | { |
| 474 | h.collocated_ref_idx = r.read_ue()?; |
| 475 | } |
| 476 | } |
| 477 | if (pps.weighted_pred && h.slice_type == SliceType::P) |
| 478 | || (pps.weighted_bipred && h.slice_type == SliceType::B) |
| 479 | { |
| 480 | h.pred_weight_table = Some(parse_pred_weight_table(&mut r, &h, sps)?); |
| 481 | } |
| 482 | h.five_minus_max_num_merge_cand = r.read_ue()?; |
| 483 | } |
| 484 | h.qp_delta = r.read_se()?; |
| 485 | if pps.slice_chroma_qp_offsets_present { |
| 486 | h.cb_qp_offset = r.read_se()?; |
| 487 | h.cr_qp_offset = r.read_se()?; |
| 488 | } |
| 489 | h.deblocking_filter_disabled = pps.deblocking_filter_disabled; |
| 490 | h.beta_offset_div2 = pps.beta_offset_div2; |
| 491 | h.tc_offset_div2 = pps.tc_offset_div2; |
| 492 | if pps.deblocking_filter_override_enabled && r.read_bit()? { |
| 493 | h.deblocking_filter_disabled = r.read_bit()?; |
| 494 | if !h.deblocking_filter_disabled { |
| 495 | h.beta_offset_div2 = r.read_se()?; |
| 496 | h.tc_offset_div2 = r.read_se()?; |
| 497 | } |
| 498 | } |
| 499 | h.loop_filter_across_slices_enabled = pps.loop_filter_across_slices_enabled; |
| 500 | if pps.loop_filter_across_slices_enabled |
| 501 | && (h.sao_luma || h.sao_chroma || !h.deblocking_filter_disabled) |
| 502 | { |
| 503 | h.loop_filter_across_slices_enabled = r.read_bit()?; |
| 504 | } |
| 505 | } |
| 506 | if pps.tiles_enabled || pps.entropy_coding_sync_enabled { |
| 507 | let count = r.read_ue()?; |
| 508 | if count > 0 { |
| 509 | if count as u64 > sps.pic_height_in_ctbs() as u64 * sps.pic_width_in_ctbs() as u64 { |
| 510 | return Err(Error::corrupt("HEVC slice: num_entry_point_offsets absurd")); |
| 511 | } |
| 512 | let offset_len = r.read_ue()? + 1; |
| 513 | if offset_len > 32 { |
| 514 | return Err(Error::corrupt("HEVC slice: offset_len_minus1 > 31")); |
| 515 | } |
| 516 | for _ in 0..count { |
| 517 | h.entry_point_offsets.push(r.read_bits(offset_len)? + 1); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | if pps.slice_segment_header_extension_present { |
| 522 | let len = r.read_ue()?; |
| 523 | for _ in 0..len { |
| 524 | r.read_bits(8)?; |
| 525 | } |
| 526 | } |
| 527 | // byte_alignment() |
| 528 | if !r.read_bit()? { |
| 529 | return Err(Error::corrupt("HEVC slice: alignment_bit_equal_to_one = 0")); |
| 530 | } |
| 531 | r.align_to_byte(); |
| 532 | pos.header_bits = r.bit_position(); |
| 533 | Ok((h, pos)) |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | /// Where the slice header ended, in the units a hardware decoder wants. |
| 538 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 539 | pub struct ParsePositions { |
| 540 | /// Bit position in the *unescaped* RBSP where slice data starts; always a |
| 541 | /// multiple of 8. |
| 542 | pub header_bits: u64, |
| 543 | /// `st_rps_bits`: the size of the `st_ref_pic_set()` in the slice header, |
| 544 | /// which `VAPictureParameterBufferHEVC` carries so the driver can skip it. |
| 545 | pub st_rps_bits: u32, |
| 546 | } |
| 547 | |
| 548 | impl ParsePositions { |
| 549 | /// `slice_data_byte_offset`: the offset from the start of the NAL unit |
| 550 | /// (header bytes included) to the first byte of slice data, counted in the |
| 551 | /// *escaped* bytes a driver is handed. |
| 552 | /// |
| 553 | /// The emulation prevention bytes inside the header count, which is why this |
| 554 | /// takes the escaped payload rather than working from `header_bits` alone. |
| 555 | pub fn slice_data_byte_offset(&self, escaped_payload: &[u8]) -> usize { |
| 556 | let rbsp_bytes = (self.header_bits / 8) as usize; |
| 557 | let mut zeros = 0usize; |
| 558 | let mut rbsp_seen = 0usize; |
| 559 | let mut escaped_seen = 0usize; |
| 560 | for &b in escaped_payload { |
| 561 | escaped_seen += 1; |
| 562 | if zeros >= 2 && b == 3 { |
| 563 | zeros = 0; |
| 564 | continue; |
| 565 | } |
| 566 | rbsp_seen += 1; |
| 567 | if b == 0 { |
| 568 | zeros += 1; |
| 569 | } else { |
| 570 | zeros = 0; |
| 571 | } |
| 572 | if rbsp_seen == rbsp_bytes { |
| 573 | break; |
| 574 | } |
| 575 | } |
| 576 | // 2 = the NAL unit header, which the offset is measured from. |
| 577 | 2 + escaped_seen |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /// How many emulation prevention bytes a NAL unit payload carries. |
| 582 | /// |
| 583 | /// `VASliceParameterBufferHEVC::slice_data_num_emu_prevn_bytes` wants this for |
| 584 | /// the slice data a driver is handed, and a caller that has the escaped bytes |
| 585 | /// should not have to unescape them twice to find out. |
| 586 | pub fn count_emulation_prevention_bytes(escaped_payload: &[u8]) -> usize { |
| 587 | let mut zeros = 0usize; |
| 588 | let mut count = 0usize; |
| 589 | for &b in escaped_payload { |
| 590 | if zeros >= 2 && b == 3 { |
| 591 | count += 1; |
| 592 | zeros = 0; |
| 593 | continue; |
| 594 | } |
| 595 | if b == 0 { |
| 596 | zeros += 1; |
| 597 | } else { |
| 598 | zeros = 0; |
| 599 | } |
| 600 | } |
| 601 | count |
| 602 | } |
| 603 | |
| 604 | /// Parse a `pred_weight_table()` (7.3.6.3). |
| 605 | /// |
| 606 | /// The chroma *offset* is derived, not coded: equation 7-56 turns |
| 607 | /// `delta_chroma_offset_lX` into `ChromaOffsetLX` against the weight, and a |
| 608 | /// decoder that forwards the raw delta to hardware shifts every weighted |
| 609 | /// chroma sample. |
| 610 | fn parse_pred_weight_table( |
| 611 | r: &mut BitReader, |
| 612 | h: &SliceHeader, |
| 613 | sps: &Sps, |
| 614 | ) -> Result<PredWeightTable> { |
| 615 | let mut table = PredWeightTable { |
| 616 | luma_log2_weight_denom: r.read_ue()?, |
| 617 | ..PredWeightTable::default() |
| 618 | }; |
| 619 | let chroma = sps.chroma_format_idc != 0; |
| 620 | if chroma { |
| 621 | table.delta_chroma_log2_weight_denom = r.read_se()?; |
| 622 | } |
| 623 | let chroma_log2 = table.luma_log2_weight_denom as i32 + table.delta_chroma_log2_weight_denom; |
| 624 | if !(0..=7).contains(&chroma_log2) { |
| 625 | return Err(Error::corrupt( |
| 626 | "HEVC pred_weight_table: ChromaLog2WeightDenom out of range", |
| 627 | )); |
| 628 | } |
| 629 | // A fuzzed SPS can name any bit depth; the shift below has to survive it. |
| 630 | let half_range = 1i64 << (sps.bit_depth_chroma_minus8.min(8) + 7); |
| 631 | |
| 632 | let lists: &[u32] = if h.slice_type == SliceType::B { |
| 633 | &[ |
| 634 | h.num_ref_idx_l0_active_minus1, |
| 635 | h.num_ref_idx_l1_active_minus1, |
| 636 | ] |
| 637 | } else { |
| 638 | &[h.num_ref_idx_l0_active_minus1] |
| 639 | }; |
| 640 | for (list, &active_minus1) in lists.iter().enumerate() { |
| 641 | let count = (active_minus1 + 1) as usize; |
| 642 | let mut luma_flags = Vec::with_capacity(count); |
| 643 | for _ in 0..count { |
| 644 | luma_flags.push(r.read_bit()?); |
| 645 | } |
| 646 | let mut chroma_flags = vec![false; count]; |
| 647 | if chroma { |
| 648 | for flag in chroma_flags.iter_mut() { |
| 649 | *flag = r.read_bit()?; |
| 650 | } |
| 651 | } |
| 652 | let mut entries = Vec::with_capacity(count); |
| 653 | for i in 0..count { |
| 654 | let mut entry = WeightEntry::default(); |
| 655 | if luma_flags[i] { |
| 656 | let delta_weight = r.read_se()?; |
| 657 | let offset = r.read_se()?; |
| 658 | entry.luma = Some((delta_weight, offset)); |
| 659 | } |
| 660 | if chroma && chroma_flags[i] { |
| 661 | let mut pair = [(0i32, 0i32); 2]; |
| 662 | for component in &mut pair { |
| 663 | let delta_weight = r.read_se()?; |
| 664 | let delta_offset = r.read_se()?; |
| 665 | let weight = (1i64 << chroma_log2) + i64::from(delta_weight); |
| 666 | // 7-56, in 64 bits because both terms come straight off the |
| 667 | // wire and a corrupt stream must not overflow the derivation. |
| 668 | let offset = (half_range + i64::from(delta_offset) |
| 669 | - ((half_range * weight) >> chroma_log2)) |
| 670 | .clamp(-half_range, half_range - 1); |
| 671 | *component = (delta_weight, offset as i32); |
| 672 | } |
| 673 | entry.chroma = Some(pair); |
| 674 | } |
| 675 | entries.push(entry); |
| 676 | } |
| 677 | if list == 0 { |
| 678 | table.l0 = entries; |
| 679 | } else { |
| 680 | table.l1 = entries; |
| 681 | } |
| 682 | } |
| 683 | Ok(table) |
| 684 | } |
| 685 | |
| 686 | #[cfg(test)] |
| 687 | mod tests { |
| 688 | use super::*; |
| 689 | use crate::ps::{ConformanceWindow, ProfileTierLevel}; |
| 690 | |
| 691 | fn sps() -> Sps { |
| 692 | Sps { |
| 693 | vps_id: 0, |
| 694 | id: 0, |
| 695 | chroma_format_idc: 1, |
| 696 | separate_colour_plane: false, |
| 697 | pic_width_in_luma_samples: 1920, |
| 698 | pic_height_in_luma_samples: 1088, |
| 699 | conf_win: ConformanceWindow::default(), |
| 700 | bit_depth_luma_minus8: 0, |
| 701 | bit_depth_chroma_minus8: 0, |
| 702 | log2_max_poc_lsb_minus4: 4, |
| 703 | max_dec_pic_buffering_minus1: 0, |
| 704 | max_num_reorder_pics: 0, |
| 705 | log2_min_cb_size_minus3: 0, |
| 706 | log2_diff_max_min_cb_size: 3, |
| 707 | log2_min_tb_size_minus2: 0, |
| 708 | log2_diff_max_min_tb_size: 3, |
| 709 | max_transform_hierarchy_depth_inter: 0, |
| 710 | max_transform_hierarchy_depth_intra: 0, |
| 711 | scaling_list_enabled: false, |
| 712 | amp_enabled: false, |
| 713 | sao_enabled: false, |
| 714 | pcm_enabled: false, |
| 715 | pcm: None, |
| 716 | num_short_term_ref_pic_sets: 0, |
| 717 | short_term_ref_pic_sets: Vec::new(), |
| 718 | long_term_ref_pics_present: false, |
| 719 | num_long_term_ref_pics_sps: 0, |
| 720 | long_term_ref_pics_sps: Vec::new(), |
| 721 | temporal_mvp_enabled: false, |
| 722 | strong_intra_smoothing: true, |
| 723 | ptl: ProfileTierLevel::main(120), |
| 724 | vui: None, |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn intra_slice_header_round_trips_with_entry_points() { |
| 730 | let pps = Pps { |
| 731 | entropy_coding_sync_enabled: true, |
| 732 | deblocking_filter_control_present: true, |
| 733 | deblocking_filter_disabled: true, |
| 734 | ..Pps::default() |
| 735 | }; |
| 736 | let sps = sps(); |
| 737 | let mut header = SliceHeader::intra(&pps, -3); |
| 738 | header.entry_point_offsets = vec![1234, 9, 65_540]; |
| 739 | let mut w = BitWriter::new(); |
| 740 | header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl); |
| 741 | let rbsp = w.into_bytes(); |
| 742 | let (parsed, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap(); |
| 743 | assert_eq!(parsed, header); |
| 744 | assert_eq!(pos.header_bits % 8, 0); |
| 745 | assert_eq!(pos.header_bits as usize / 8, rbsp.len()); |
| 746 | // No emulation prevention in this header, so the byte offset is the |
| 747 | // NAL header plus the RBSP header bytes. |
| 748 | assert_eq!(pos.slice_data_byte_offset(&rbsp), 2 + rbsp.len()); |
| 749 | } |
| 750 | |
| 751 | #[test] |
| 752 | fn emulation_prevention_bytes_are_counted() { |
| 753 | assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 1, 0xff]), 1); |
| 754 | assert_eq!(count_emulation_prevention_bytes(&[0, 0, 3, 0, 0, 3, 2]), 2); |
| 755 | // A 3 that is not preceded by two zeros is payload, not an escape. |
| 756 | assert_eq!(count_emulation_prevention_bytes(&[0, 3, 3, 3]), 0); |
| 757 | assert_eq!(count_emulation_prevention_bytes(&[]), 0); |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn byte_offset_counts_escape_bytes() { |
| 762 | // RBSP 00 00 01 ... escapes to 00 00 03 01 ...; a header of four RBSP |
| 763 | // bytes therefore ends five escaped bytes in. |
| 764 | let pos = ParsePositions { |
| 765 | header_bits: 4 * 8, |
| 766 | st_rps_bits: 0, |
| 767 | }; |
| 768 | let escaped = [0u8, 0, 3, 1, 0xff]; |
| 769 | assert_eq!(pos.slice_data_byte_offset(&escaped), 2 + 5); |
| 770 | } |
| 771 | } |