edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! Parameter sets: VPS, SPS and PPS, written and parsed. |
| 2 | //! |
| 3 | //! The field sets here are sized by what a *stateless hardware decoder* asks |
| 4 | //! for, not by what this family's own encoder writes: everything in |
| 5 | //! `VAPictureParameterBufferHEVC` is either a field on [`Sps`]/[`Pps`] or |
| 6 | //! derivable from one by a named method. Anything the parser walks past but does |
| 7 | //! not model (scaling lists, HRD, the multilayer and 3D extensions) is a thing |
| 8 | //! no consumer in this family reads, and each such skip says so where it happens. |
| 9 | |
| 10 | use crate::scaling::ScalingList; |
| 11 | use crate::vui::VuiParameters; |
| 12 | use ec_core::bitio::{BitReader, BitWriter}; |
| 13 | use ec_core::error::{Error, Result}; |
| 14 | |
| 15 | /// `profile_tier_level()` for a single-sub-layer stream (7.3.3). |
| 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 17 | pub struct ProfileTierLevel { |
| 18 | /// `general_profile_space`, 0 for everything in the wild. |
| 19 | pub profile_space: u8, |
| 20 | /// False = Main tier, true = High tier. |
| 21 | pub tier_flag: bool, |
| 22 | /// 1 = Main, 2 = Main 10, 3 = Main Still Picture, 4 = range extensions. |
| 23 | pub profile_idc: u8, |
| 24 | /// `general_profile_compatibility_flag[0..32]` as a bit set, bit `j` = flag `j`. |
| 25 | pub profile_compatibility: u32, |
| 26 | /// `general_progressive_source_flag`. |
| 27 | pub progressive_source: bool, |
| 28 | /// `general_interlaced_source_flag`. |
| 29 | pub interlaced_source: bool, |
| 30 | /// `general_non_packed_constraint_flag`. |
| 31 | pub non_packed_constraint: bool, |
| 32 | /// `general_frame_only_constraint_flag`. |
| 33 | pub frame_only_constraint: bool, |
| 34 | /// The 44 bits between the source flags and `general_level_idc`: the |
| 35 | /// profile-dependent constraint flags, their reserved padding and |
| 36 | /// `general_inbld_flag`. Kept verbatim so a re-write is byte-identical, |
| 37 | /// because their *meaning* depends on `profile_idc` while their length |
| 38 | /// never does. |
| 39 | pub constraint_bits: u64, |
| 40 | /// `general_level_idc`: 30 x the level number (level 4 = 120). |
| 41 | pub level_idc: u8, |
| 42 | } |
| 43 | |
| 44 | impl ProfileTierLevel { |
| 45 | /// Main profile at `level_idc`, progressive, frame-only — what an intra |
| 46 | /// 8-bit 4:2:0 encoder emits. |
| 47 | pub fn main(level_idc: u8) -> ProfileTierLevel { |
| 48 | ProfileTierLevel { |
| 49 | profile_space: 0, |
| 50 | tier_flag: false, |
| 51 | profile_idc: 1, |
| 52 | // Main is compatible with itself; bit 1 is what every decoder checks. |
| 53 | profile_compatibility: 1 << 1, |
| 54 | progressive_source: true, |
| 55 | interlaced_source: false, |
| 56 | non_packed_constraint: true, |
| 57 | frame_only_constraint: true, |
| 58 | constraint_bits: 0, |
| 59 | level_idc, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Main 10 profile at `level_idc`: 10-bit 4:2:0 with the same flags as |
| 64 | /// [`ProfileTierLevel::main`]. Main 10 decoders also decode Main, so both |
| 65 | /// compatibility bits are set. |
| 66 | pub fn main10(level_idc: u8) -> ProfileTierLevel { |
| 67 | ProfileTierLevel { |
| 68 | profile_idc: 2, |
| 69 | profile_compatibility: (1 << 1) | (1 << 2), |
| 70 | ..ProfileTierLevel::main(level_idc) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// The smallest level whose limits hold for `width x height` at `fps` |
| 75 | /// (Annex A, Table A.8/A.9 luma sample and sample-rate limits). |
| 76 | /// |
| 77 | /// Levels are a decoder's promise about buffer sizes; naming one too small |
| 78 | /// is what makes a hardware decoder refuse a stream it could otherwise play, |
| 79 | /// so this rounds up and stops at 6.2. |
| 80 | pub fn level_for(width: u32, height: u32, fps: f64) -> u8 { |
| 81 | // (level_idc, MaxLumaPs, MaxLumaSr) |
| 82 | const LIMITS: &[(u8, u64, u64)] = &[ |
| 83 | (30, 36_864, 552_960), |
| 84 | (60, 122_880, 3_686_400), |
| 85 | (63, 245_760, 7_372_800), |
| 86 | (90, 552_960, 16_588_800), |
| 87 | (93, 983_040, 33_177_600), |
| 88 | (120, 2_228_224, 66_846_720), |
| 89 | (123, 2_228_224, 133_693_440), |
| 90 | (126, 2_228_224, 267_386_880), |
| 91 | (150, 8_912_896, 534_773_760), |
| 92 | (153, 8_912_896, 1_069_547_520), |
| 93 | (156, 8_912_896, 1_069_547_520), |
| 94 | (180, 35_651_584, 2_139_095_040), |
| 95 | (183, 35_651_584, 4_278_190_080), |
| 96 | (186, 35_651_584, 4_278_190_080), |
| 97 | ]; |
| 98 | let samples = u64::from(width) * u64::from(height); |
| 99 | let rate = (samples as f64 * fps.max(1.0)) as u64; |
| 100 | for &(idc, max_ps, max_sr) in LIMITS { |
| 101 | if samples <= max_ps && rate <= max_sr { |
| 102 | return idc; |
| 103 | } |
| 104 | } |
| 105 | 186 |
| 106 | } |
| 107 | |
| 108 | /// Write `profile_tier_level(1, 0)` — 96 bits, always. |
| 109 | pub fn write(&self, w: &mut BitWriter) { |
| 110 | w.write_bits(u32::from(self.profile_space), 2); |
| 111 | w.write_bit(self.tier_flag); |
| 112 | w.write_bits(u32::from(self.profile_idc), 5); |
| 113 | for j in 0..32 { |
| 114 | w.write_bit(self.profile_compatibility & (1 << j) != 0); |
| 115 | } |
| 116 | w.write_bit(self.progressive_source); |
| 117 | w.write_bit(self.interlaced_source); |
| 118 | w.write_bit(self.non_packed_constraint); |
| 119 | w.write_bit(self.frame_only_constraint); |
| 120 | w.write_bits64(self.constraint_bits, 44); |
| 121 | w.write_bits(u32::from(self.level_idc), 8); |
| 122 | } |
| 123 | |
| 124 | /// Parse `profile_tier_level(1, max_sub_layers_minus1)`. |
| 125 | pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result<ProfileTierLevel> { |
| 126 | let profile_space = r.read_bits(2)? as u8; |
| 127 | let tier_flag = r.read_bit()?; |
| 128 | let profile_idc = r.read_bits(5)? as u8; |
| 129 | let mut profile_compatibility = 0u32; |
| 130 | for j in 0..32 { |
| 131 | if r.read_bit()? { |
| 132 | profile_compatibility |= 1 << j; |
| 133 | } |
| 134 | } |
| 135 | let progressive_source = r.read_bit()?; |
| 136 | let interlaced_source = r.read_bit()?; |
| 137 | let non_packed_constraint = r.read_bit()?; |
| 138 | let frame_only_constraint = r.read_bit()?; |
| 139 | let constraint_bits = r.read_bits64(44)?; |
| 140 | let level_idc = r.read_bits(8)? as u8; |
| 141 | let mut sub_layer_profile = Vec::new(); |
| 142 | let mut sub_layer_level = Vec::new(); |
| 143 | for _ in 0..max_sub_layers_minus1 { |
| 144 | sub_layer_profile.push(r.read_bit()?); |
| 145 | sub_layer_level.push(r.read_bit()?); |
| 146 | } |
| 147 | if max_sub_layers_minus1 > 0 { |
| 148 | for _ in max_sub_layers_minus1..8 { |
| 149 | r.read_bits(2)?; |
| 150 | } |
| 151 | } |
| 152 | for i in 0..max_sub_layers_minus1 as usize { |
| 153 | if sub_layer_profile[i] { |
| 154 | r.skip_bits(88)?; |
| 155 | } |
| 156 | if sub_layer_level[i] { |
| 157 | r.read_bits(8)?; |
| 158 | } |
| 159 | } |
| 160 | Ok(ProfileTierLevel { |
| 161 | profile_space, |
| 162 | tier_flag, |
| 163 | profile_idc, |
| 164 | profile_compatibility, |
| 165 | progressive_source, |
| 166 | interlaced_source, |
| 167 | non_packed_constraint, |
| 168 | frame_only_constraint, |
| 169 | constraint_bits, |
| 170 | level_idc, |
| 171 | }) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /// The video parameter set (7.3.2.1). |
| 176 | /// |
| 177 | /// A single-layer stream needs one and nothing in it varies, but a decoder that |
| 178 | /// never sees a VPS refuses the stream, so it is written all the same. |
| 179 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 180 | pub struct Vps { |
| 181 | /// `vps_video_parameter_set_id`. |
| 182 | pub id: u8, |
| 183 | /// Profile, tier and level of the base layer. |
| 184 | pub ptl: ProfileTierLevel, |
| 185 | /// `vps_max_dec_pic_buffering_minus1[0]`. |
| 186 | pub max_dec_pic_buffering_minus1: u32, |
| 187 | /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream. |
| 188 | pub max_num_reorder_pics: u32, |
| 189 | /// `(vps_num_units_in_tick, vps_time_scale)` when `vps_timing_info_present_flag` is set. |
| 190 | pub timing: Option<(u32, u32)>, |
| 191 | } |
| 192 | |
| 193 | impl Vps { |
| 194 | /// The RBSP, trailing bits included. |
| 195 | pub fn to_rbsp(&self) -> Vec<u8> { |
| 196 | let mut w = BitWriter::with_capacity(32); |
| 197 | w.write_bits(u32::from(self.id), 4); |
| 198 | w.write_bit(true); // vps_base_layer_internal_flag |
| 199 | w.write_bit(true); // vps_base_layer_available_flag |
| 200 | w.write_bits(0, 6); // vps_max_layers_minus1 |
| 201 | w.write_bits(0, 3); // vps_max_sub_layers_minus1 |
| 202 | w.write_bit(true); // vps_temporal_id_nesting_flag |
| 203 | w.write_bits(0xffff, 16); // vps_reserved_0xffff_16bits |
| 204 | self.ptl.write(&mut w); |
| 205 | w.write_bit(true); // vps_sub_layer_ordering_info_present_flag |
| 206 | w.write_ue(self.max_dec_pic_buffering_minus1); |
| 207 | w.write_ue(self.max_num_reorder_pics); |
| 208 | w.write_ue(0); // vps_max_latency_increase_plus1 |
| 209 | w.write_bits(0, 6); // vps_max_layer_id |
| 210 | w.write_ue(0); // vps_num_layer_sets_minus1 |
| 211 | match self.timing { |
| 212 | Some((num_units_in_tick, time_scale)) => { |
| 213 | w.write_bit(true); // vps_timing_info_present_flag |
| 214 | w.write_bits(num_units_in_tick, 32); |
| 215 | w.write_bits(time_scale, 32); |
| 216 | w.write_bit(false); // vps_poc_proportional_to_timing_flag |
| 217 | w.write_ue(0); // vps_num_hrd_parameters |
| 218 | } |
| 219 | None => w.write_bit(false), // vps_timing_info_present_flag |
| 220 | } |
| 221 | w.write_bit(false); // vps_extension_flag |
| 222 | rbsp_trailing_bits(&mut w); |
| 223 | w.into_bytes() |
| 224 | } |
| 225 | |
| 226 | /// Parse a VPS RBSP. |
| 227 | pub fn parse(rbsp: &[u8]) -> Result<Vps> { |
| 228 | let mut r = BitReader::new(rbsp); |
| 229 | let id = r.read_bits(4)? as u8; |
| 230 | r.read_bit()?; |
| 231 | r.read_bit()?; |
| 232 | r.read_bits(6)?; // vps_max_layers_minus1 |
| 233 | let max_sub_layers_minus1 = r.read_bits(3)?; |
| 234 | check_range( |
| 235 | "HEVC VPS", |
| 236 | "vps_max_sub_layers_minus1", |
| 237 | i64::from(max_sub_layers_minus1), |
| 238 | 0, |
| 239 | MAX_SUB_LAYERS_MINUS1, |
| 240 | )?; |
| 241 | r.read_bit()?; |
| 242 | r.read_bits(16)?; |
| 243 | let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?; |
| 244 | let ordering_info = r.read_bit()?; |
| 245 | let first = if ordering_info { |
| 246 | 0 |
| 247 | } else { |
| 248 | max_sub_layers_minus1 |
| 249 | }; |
| 250 | let mut max_dec_pic_buffering_minus1 = 0; |
| 251 | let mut max_num_reorder_pics = 0; |
| 252 | for _ in first..=max_sub_layers_minus1 { |
| 253 | max_dec_pic_buffering_minus1 = r.read_ue()?; |
| 254 | check_range( |
| 255 | "HEVC VPS", |
| 256 | "vps_max_dec_pic_buffering_minus1", |
| 257 | i64::from(max_dec_pic_buffering_minus1), |
| 258 | 0, |
| 259 | MAX_DPB_PICTURES_MINUS1, |
| 260 | )?; |
| 261 | max_num_reorder_pics = r.read_ue()?; |
| 262 | r.read_ue()?; |
| 263 | } |
| 264 | r.read_bits(6)?; // vps_max_layer_id |
| 265 | let layer_sets_minus1 = r.read_ue()?; |
| 266 | let timing = if layer_sets_minus1 == 0 && r.read_bit()? { |
| 267 | Some((r.read_bits(32)?, r.read_bits(32)?)) |
| 268 | } else { |
| 269 | None |
| 270 | }; |
| 271 | Ok(Vps { |
| 272 | id, |
| 273 | ptl, |
| 274 | max_dec_pic_buffering_minus1, |
| 275 | max_num_reorder_pics, |
| 276 | timing, |
| 277 | }) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /// The conformance window: how many samples to crop off a coded picture. |
| 282 | /// |
| 283 | /// This is how 1920x1080 is coded with 64x64 coding tree blocks — the picture is |
| 284 | /// coded 1920x1088 and eight rows are cropped — and it is a first-class field |
| 285 | /// here rather than a caller's problem, because a caller that pads its own |
| 286 | /// planes has to guess what the encoder does with the padding. |
| 287 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 288 | pub struct ConformanceWindow { |
| 289 | /// `conf_win_left_offset`, in chroma units. |
| 290 | pub left: u32, |
| 291 | /// `conf_win_right_offset`, in chroma units. |
| 292 | pub right: u32, |
| 293 | /// `conf_win_top_offset`, in chroma units. |
| 294 | pub top: u32, |
| 295 | /// `conf_win_bottom_offset`, in chroma units. |
| 296 | pub bottom: u32, |
| 297 | } |
| 298 | |
| 299 | impl ConformanceWindow { |
| 300 | /// True when nothing is cropped. |
| 301 | pub fn is_empty(&self) -> bool { |
| 302 | *self == ConformanceWindow::default() |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | /// The sequence parameter set (7.3.2.2.1). |
| 307 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 308 | pub struct Sps { |
| 309 | /// `sps_video_parameter_set_id`. |
| 310 | pub vps_id: u8, |
| 311 | /// `sps_seq_parameter_set_id`. |
| 312 | pub id: u32, |
| 313 | /// 0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4. |
| 314 | pub chroma_format_idc: u32, |
| 315 | /// `separate_colour_plane_flag`. |
| 316 | pub separate_colour_plane: bool, |
| 317 | /// Coded width — a multiple of the minimum coding block size. |
| 318 | pub pic_width_in_luma_samples: u32, |
| 319 | /// Coded height. |
| 320 | pub pic_height_in_luma_samples: u32, |
| 321 | /// What to crop off the coded picture for display. |
| 322 | pub conf_win: ConformanceWindow, |
| 323 | /// `bit_depth_luma_minus8`. |
| 324 | pub bit_depth_luma_minus8: u32, |
| 325 | /// `bit_depth_chroma_minus8`. |
| 326 | pub bit_depth_chroma_minus8: u32, |
| 327 | /// `log2_max_pic_order_cnt_lsb_minus4`. |
| 328 | pub log2_max_poc_lsb_minus4: u32, |
| 329 | /// `sps_max_dec_pic_buffering_minus1[HighestTid]`. |
| 330 | pub max_dec_pic_buffering_minus1: u32, |
| 331 | /// `sps_max_num_reorder_pics[HighestTid]`. |
| 332 | pub max_num_reorder_pics: u32, |
| 333 | /// `log2_min_luma_coding_block_size_minus3`. |
| 334 | pub log2_min_cb_size_minus3: u32, |
| 335 | /// `log2_diff_max_min_luma_coding_block_size`. |
| 336 | pub log2_diff_max_min_cb_size: u32, |
| 337 | /// `log2_min_luma_transform_block_size_minus2`. |
| 338 | pub log2_min_tb_size_minus2: u32, |
| 339 | /// `log2_diff_max_min_luma_transform_block_size`. |
| 340 | pub log2_diff_max_min_tb_size: u32, |
| 341 | /// `max_transform_hierarchy_depth_inter`. |
| 342 | pub max_transform_hierarchy_depth_inter: u32, |
| 343 | /// `max_transform_hierarchy_depth_intra`. |
| 344 | pub max_transform_hierarchy_depth_intra: u32, |
| 345 | /// `scaling_list_enabled_flag`. |
| 346 | pub scaling_list_enabled: bool, |
| 347 | /// The lists `sps_scaling_list_data_present_flag` sends. `None` with scaling |
| 348 | /// lists enabled means the defaults of Tables 7-5 and 7-6. Meaningful only |
| 349 | /// when `scaling_list_enabled`. |
| 350 | pub scaling_list: Option<ScalingList>, |
| 351 | /// `amp_enabled_flag`. |
| 352 | pub amp_enabled: bool, |
| 353 | /// `sample_adaptive_offset_enabled_flag`. |
| 354 | pub sao_enabled: bool, |
| 355 | /// `pcm_enabled_flag`. |
| 356 | pub pcm_enabled: bool, |
| 357 | /// PCM sample depths and block sizes, present when `pcm_enabled`: |
| 358 | /// `(pcm_sample_bit_depth_luma_minus1, pcm_sample_bit_depth_chroma_minus1, |
| 359 | /// log2_min_pcm_luma_coding_block_size_minus3, |
| 360 | /// log2_diff_max_min_pcm_luma_coding_block_size, pcm_loop_filter_disabled_flag)`. |
| 361 | pub pcm: Option<(u32, u32, u32, u32, bool)>, |
| 362 | /// `num_short_term_ref_pic_sets`. |
| 363 | pub num_short_term_ref_pic_sets: u32, |
| 364 | /// The sets themselves, in bitstream order: a slice header may name one by |
| 365 | /// index instead of carrying it, and a decoder then needs it from here. |
| 366 | pub short_term_ref_pic_sets: Vec<ShortTermRefPicSet>, |
| 367 | /// `long_term_ref_pics_present_flag`. |
| 368 | pub long_term_ref_pics_present: bool, |
| 369 | /// `num_long_term_ref_pics_sps`. |
| 370 | pub num_long_term_ref_pics_sps: u32, |
| 371 | /// `(lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag)` per SPS long |
| 372 | /// term picture, which a slice header names by index. |
| 373 | pub long_term_ref_pics_sps: Vec<(u32, bool)>, |
| 374 | /// `sps_temporal_mvp_enabled_flag`. |
| 375 | pub temporal_mvp_enabled: bool, |
| 376 | /// `strong_intra_smoothing_enabled_flag`. |
| 377 | pub strong_intra_smoothing: bool, |
| 378 | /// Profile, tier, level. |
| 379 | pub ptl: ProfileTierLevel, |
| 380 | /// VUI, when present. |
| 381 | pub vui: Option<VuiParameters>, |
| 382 | /// `sps_max_latency_increase_plus1[HighestTid]`; 0 when there is no latency limit. |
| 383 | pub max_latency_increase_plus1: u32, |
| 384 | /// The extension flags of 7.3.2.2.1, one byte: bit 7 range, 6 multilayer, 5 3D, 4 SCC, |
| 385 | /// bits 0..3 `sps_extension_4bits`. Zero when the SPS carries no extension. |
| 386 | pub extension_flags: u8, |
| 387 | /// The `sps_range_extension()` flags (7.3.2.2.2); all false when absent. |
| 388 | pub range: SpsRangeExt, |
| 389 | } |
| 390 | |
| 391 | impl Sps { |
| 392 | /// Coding tree block size in luma samples (`CtbSizeY`). |
| 393 | pub fn ctb_size(&self) -> u32 { |
| 394 | 1 << (self.log2_min_cb_size_minus3 + 3 + self.log2_diff_max_min_cb_size) |
| 395 | } |
| 396 | |
| 397 | /// `PicWidthInCtbsY`. |
| 398 | pub fn pic_width_in_ctbs(&self) -> u32 { |
| 399 | self.pic_width_in_luma_samples.div_ceil(self.ctb_size()) |
| 400 | } |
| 401 | |
| 402 | /// `PicHeightInCtbsY`. |
| 403 | pub fn pic_height_in_ctbs(&self) -> u32 { |
| 404 | self.pic_height_in_luma_samples.div_ceil(self.ctb_size()) |
| 405 | } |
| 406 | |
| 407 | /// `SubWidthC`, `SubHeightC` for the chroma format. |
| 408 | pub fn chroma_subsampling(&self) -> (u32, u32) { |
| 409 | match self.chroma_format_idc { |
| 410 | 1 => (2, 2), |
| 411 | 2 => (2, 1), |
| 412 | _ => (1, 1), |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | /// Displayed size after the conformance window is applied. |
| 417 | pub fn display_size(&self) -> (u32, u32) { |
| 418 | let (sub_w, sub_h) = self.chroma_subsampling(); |
| 419 | ( |
| 420 | self.pic_width_in_luma_samples - sub_w * (self.conf_win.left + self.conf_win.right), |
| 421 | self.pic_height_in_luma_samples - sub_h * (self.conf_win.top + self.conf_win.bottom), |
| 422 | ) |
| 423 | } |
| 424 | |
| 425 | /// Number of bits `slice_segment_address` occupies in a slice header: |
| 426 | /// `Ceil( Log2( PicSizeInCtbsY ) )`. |
| 427 | pub fn slice_address_bits(&self) -> u32 { |
| 428 | ceil_log2(self.pic_width_in_ctbs() * self.pic_height_in_ctbs()) |
| 429 | } |
| 430 | |
| 431 | /// The RBSP, trailing bits included. |
| 432 | pub fn to_rbsp(&self) -> Vec<u8> { |
| 433 | let mut w = BitWriter::with_capacity(64); |
| 434 | w.write_bits(u32::from(self.vps_id), 4); |
| 435 | w.write_bits(0, 3); // sps_max_sub_layers_minus1 |
| 436 | w.write_bit(true); // sps_temporal_id_nesting_flag |
| 437 | self.ptl.write(&mut w); |
| 438 | w.write_ue(self.id); |
| 439 | w.write_ue(self.chroma_format_idc); |
| 440 | if self.chroma_format_idc == 3 { |
| 441 | w.write_bit(self.separate_colour_plane); |
| 442 | } |
| 443 | w.write_ue(self.pic_width_in_luma_samples); |
| 444 | w.write_ue(self.pic_height_in_luma_samples); |
| 445 | if self.conf_win.is_empty() { |
| 446 | w.write_bit(false); |
| 447 | } else { |
| 448 | w.write_bit(true); |
| 449 | w.write_ue(self.conf_win.left); |
| 450 | w.write_ue(self.conf_win.right); |
| 451 | w.write_ue(self.conf_win.top); |
| 452 | w.write_ue(self.conf_win.bottom); |
| 453 | } |
| 454 | w.write_ue(self.bit_depth_luma_minus8); |
| 455 | w.write_ue(self.bit_depth_chroma_minus8); |
| 456 | w.write_ue(self.log2_max_poc_lsb_minus4); |
| 457 | w.write_bit(true); // sps_sub_layer_ordering_info_present_flag |
| 458 | w.write_ue(self.max_dec_pic_buffering_minus1); |
| 459 | w.write_ue(self.max_num_reorder_pics); |
| 460 | w.write_ue(0); // sps_max_latency_increase_plus1 |
| 461 | w.write_ue(self.log2_min_cb_size_minus3); |
| 462 | w.write_ue(self.log2_diff_max_min_cb_size); |
| 463 | w.write_ue(self.log2_min_tb_size_minus2); |
| 464 | w.write_ue(self.log2_diff_max_min_tb_size); |
| 465 | w.write_ue(self.max_transform_hierarchy_depth_inter); |
| 466 | w.write_ue(self.max_transform_hierarchy_depth_intra); |
| 467 | w.write_bit(self.scaling_list_enabled); |
| 468 | if self.scaling_list_enabled { |
| 469 | match &self.scaling_list { |
| 470 | Some(list) => { |
| 471 | w.write_bit(true); // sps_scaling_list_data_present_flag |
| 472 | list.write(&mut w); |
| 473 | } |
| 474 | None => w.write_bit(false), |
| 475 | } |
| 476 | } |
| 477 | w.write_bit(self.amp_enabled); |
| 478 | w.write_bit(self.sao_enabled); |
| 479 | w.write_bit(self.pcm_enabled); |
| 480 | if let Some((luma, chroma, log2_min, log2_diff, filter_off)) = self.pcm { |
| 481 | w.write_bits(luma, 4); |
| 482 | w.write_bits(chroma, 4); |
| 483 | w.write_ue(log2_min); |
| 484 | w.write_ue(log2_diff); |
| 485 | w.write_bit(filter_off); |
| 486 | } |
| 487 | w.write_ue(self.num_short_term_ref_pic_sets); |
| 488 | for (i, set) in self.short_term_ref_pic_sets.iter().enumerate() { |
| 489 | set.write(&mut w, i as u32); |
| 490 | } |
| 491 | w.write_bit(self.long_term_ref_pics_present); |
| 492 | if self.long_term_ref_pics_present { |
| 493 | w.write_ue(self.num_long_term_ref_pics_sps); |
| 494 | for &(poc_lsb_lt, used_by_curr) in &self.long_term_ref_pics_sps { |
| 495 | w.write_bits(poc_lsb_lt, self.log2_max_poc_lsb_minus4 + 4); |
| 496 | w.write_bit(used_by_curr); |
| 497 | } |
| 498 | } |
| 499 | w.write_bit(self.temporal_mvp_enabled); |
| 500 | w.write_bit(self.strong_intra_smoothing); |
| 501 | match &self.vui { |
| 502 | Some(vui) => { |
| 503 | w.write_bit(true); |
| 504 | vui.write(&mut w); |
| 505 | } |
| 506 | None => w.write_bit(false), |
| 507 | } |
| 508 | write_extension_flags(&mut w, self.extension_flags); |
| 509 | if self.extension_flags & 0x80 != 0 { |
| 510 | let r = &self.range; |
| 511 | for flag in [ |
| 512 | r.transform_skip_rotation_enabled, |
| 513 | r.transform_skip_context_enabled, |
| 514 | r.implicit_rdpcm_enabled, |
| 515 | r.explicit_rdpcm_enabled, |
| 516 | r.extended_precision_processing, |
| 517 | r.intra_smoothing_disabled, |
| 518 | r.high_precision_offsets_enabled, |
| 519 | r.persistent_rice_adaptation_enabled, |
| 520 | r.cabac_bypass_alignment_enabled, |
| 521 | ] { |
| 522 | w.write_bit(flag); |
| 523 | } |
| 524 | } |
| 525 | rbsp_trailing_bits(&mut w); |
| 526 | w.into_bytes() |
| 527 | } |
| 528 | |
| 529 | /// Parse an SPS RBSP. |
| 530 | /// |
| 531 | /// Short-term reference picture sets are walked but not kept: a decoder |
| 532 | /// resolves them from the slice header, and this family's own streams have |
| 533 | /// none. |
| 534 | pub fn parse(rbsp: &[u8]) -> Result<Sps> { |
| 535 | let mut r = BitReader::new(rbsp); |
| 536 | let vps_id = r.read_bits(4)? as u8; |
| 537 | let max_sub_layers_minus1 = r.read_bits(3)?; |
| 538 | check_range( |
| 539 | "HEVC SPS", |
| 540 | "sps_max_sub_layers_minus1", |
| 541 | i64::from(max_sub_layers_minus1), |
| 542 | 0, |
| 543 | MAX_SUB_LAYERS_MINUS1, |
| 544 | )?; |
| 545 | r.read_bit()?; // sps_temporal_id_nesting_flag |
| 546 | let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?; |
| 547 | let id = r.read_ue()?; |
| 548 | check_range("HEVC SPS", "sps_seq_parameter_set_id", i64::from(id), 0, 15)?; |
| 549 | let chroma_format_idc = r.read_ue()?; |
| 550 | if chroma_format_idc > 3 { |
| 551 | return Err(Error::corrupt(format!( |
| 552 | "HEVC SPS: chroma_format_idc = {chroma_format_idc}" |
| 553 | ))); |
| 554 | } |
| 555 | let separate_colour_plane = if chroma_format_idc == 3 { |
| 556 | r.read_bit()? |
| 557 | } else { |
| 558 | false |
| 559 | }; |
| 560 | let pic_width_in_luma_samples = r.read_ue()?; |
| 561 | let pic_height_in_luma_samples = r.read_ue()?; |
| 562 | // A dimension is a bit width elsewhere (slice_segment_address is |
| 563 | // Ceil(Log2(PicSizeInCtbsY)) bits), so an absurd one is refused here |
| 564 | // rather than turned into an absurd shift there. |
| 565 | if pic_width_in_luma_samples == 0 |
| 566 | || pic_height_in_luma_samples == 0 |
| 567 | || pic_width_in_luma_samples > 65_536 |
| 568 | || pic_height_in_luma_samples > 65_536 |
| 569 | { |
| 570 | return Err(Error::corrupt(format!( |
| 571 | "HEVC SPS: picture size {pic_width_in_luma_samples}x{pic_height_in_luma_samples}" |
| 572 | ))); |
| 573 | } |
| 574 | let mut conf_win = ConformanceWindow::default(); |
| 575 | if r.read_bit()? { |
| 576 | conf_win = ConformanceWindow { |
| 577 | left: r.read_ue()?, |
| 578 | right: r.read_ue()?, |
| 579 | top: r.read_ue()?, |
| 580 | bottom: r.read_ue()?, |
| 581 | }; |
| 582 | } |
| 583 | // The window is in chroma units (7-18 to 7-21) and must leave a picture. |
| 584 | let (sub_w, sub_h) = match chroma_format_idc { |
| 585 | 1 => (2u64, 2u64), |
| 586 | 2 => (2, 1), |
| 587 | _ => (1, 1), |
| 588 | }; |
| 589 | let crop_w = sub_w * (u64::from(conf_win.left) + u64::from(conf_win.right)); |
| 590 | let crop_h = sub_h * (u64::from(conf_win.top) + u64::from(conf_win.bottom)); |
| 591 | if crop_w >= u64::from(pic_width_in_luma_samples) |
| 592 | || crop_h >= u64::from(pic_height_in_luma_samples) |
| 593 | { |
| 594 | return Err(Error::corrupt(format!( |
| 595 | "HEVC SPS: conformance window {conf_win:?} leaves no picture" |
| 596 | ))); |
| 597 | } |
| 598 | let bit_depth_luma_minus8 = r.read_ue()?; |
| 599 | let bit_depth_chroma_minus8 = r.read_ue()?; |
| 600 | if bit_depth_luma_minus8 > 8 || bit_depth_chroma_minus8 > 8 { |
| 601 | return Err(Error::corrupt("HEVC SPS: bit depth out of range")); |
| 602 | } |
| 603 | let log2_max_poc_lsb_minus4 = r.read_ue()?; |
| 604 | if log2_max_poc_lsb_minus4 > 12 { |
| 605 | return Err(Error::corrupt(format!( |
| 606 | "HEVC SPS: log2_max_pic_order_cnt_lsb_minus4 = {log2_max_poc_lsb_minus4}" |
| 607 | ))); |
| 608 | } |
| 609 | let ordering_info = r.read_bit()?; |
| 610 | let first = if ordering_info { |
| 611 | 0 |
| 612 | } else { |
| 613 | max_sub_layers_minus1 |
| 614 | }; |
| 615 | let mut max_dec_pic_buffering_minus1 = 0; |
| 616 | let mut max_num_reorder_pics = 0; |
| 617 | let mut max_latency_increase_plus1 = 0; |
| 618 | for _ in first..=max_sub_layers_minus1 { |
| 619 | max_dec_pic_buffering_minus1 = r.read_ue()?; |
| 620 | check_range( |
| 621 | "HEVC SPS", |
| 622 | "sps_max_dec_pic_buffering_minus1", |
| 623 | i64::from(max_dec_pic_buffering_minus1), |
| 624 | 0, |
| 625 | MAX_DPB_PICTURES_MINUS1, |
| 626 | )?; |
| 627 | max_num_reorder_pics = r.read_ue()?; |
| 628 | max_latency_increase_plus1 = r.read_ue()?; |
| 629 | } |
| 630 | let log2_min_cb_size_minus3 = r.read_ue()?; |
| 631 | let log2_diff_max_min_cb_size = r.read_ue()?; |
| 632 | let log2_min_tb_size_minus2 = r.read_ue()?; |
| 633 | let log2_diff_max_min_tb_size = r.read_ue()?; |
| 634 | // Block sizes as log2 values, widened so that no sum below can wrap. The |
| 635 | // CTB is 16 to 64 samples (7-10), the minimum TB is below the minimum CB, |
| 636 | // and the largest TB is at most 32 samples and at most the CTB (7-11). |
| 637 | let min_cb_log2 = i64::from(log2_min_cb_size_minus3) + 3; |
| 638 | let ctb_log2 = min_cb_log2 + i64::from(log2_diff_max_min_cb_size); |
| 639 | check_range("HEVC SPS", "CtbLog2SizeY", ctb_log2, 4, 6)?; |
| 640 | let min_tb_log2 = i64::from(log2_min_tb_size_minus2) + 2; |
| 641 | if min_tb_log2 >= min_cb_log2 { |
| 642 | return Err(Error::corrupt(format!( |
| 643 | "HEVC SPS: MinTbLog2SizeY = {min_tb_log2} not below MinCbLog2SizeY = {min_cb_log2}" |
| 644 | ))); |
| 645 | } |
| 646 | let max_tb_log2 = min_tb_log2 + i64::from(log2_diff_max_min_tb_size); |
| 647 | check_range( |
| 648 | "HEVC SPS", |
| 649 | "MaxTbLog2SizeY", |
| 650 | max_tb_log2, |
| 651 | min_tb_log2, |
| 652 | ctb_log2.min(5), |
| 653 | )?; |
| 654 | // 7.4.3.2.1: the coded size is a whole number of minimum coding blocks. A |
| 655 | // coding block at the edge would otherwise run past the picture buffer. |
| 656 | let min_cb = 1u32 << min_cb_log2; |
| 657 | if pic_width_in_luma_samples % min_cb != 0 || pic_height_in_luma_samples % min_cb != 0 { |
| 658 | return Err(Error::corrupt(format!( |
| 659 | "HEVC SPS: picture size {pic_width_in_luma_samples}x{pic_height_in_luma_samples} is not a multiple of the minimum coding block {min_cb}" |
| 660 | ))); |
| 661 | } |
| 662 | let max_transform_hierarchy_depth_inter = r.read_ue()?; |
| 663 | let max_transform_hierarchy_depth_intra = r.read_ue()?; |
| 664 | // 7-12: at most CtbLog2SizeY - MinTbLog2SizeY, which is at most 4. |
| 665 | let max_depth = ctb_log2 - min_tb_log2; |
| 666 | check_range( |
| 667 | "HEVC SPS", |
| 668 | "max_transform_hierarchy_depth_inter", |
| 669 | i64::from(max_transform_hierarchy_depth_inter), |
| 670 | 0, |
| 671 | max_depth, |
| 672 | )?; |
| 673 | check_range( |
| 674 | "HEVC SPS", |
| 675 | "max_transform_hierarchy_depth_intra", |
| 676 | i64::from(max_transform_hierarchy_depth_intra), |
| 677 | 0, |
| 678 | max_depth, |
| 679 | )?; |
| 680 | let scaling_list_enabled = r.read_bit()?; |
| 681 | let mut scaling_list = None; |
| 682 | if scaling_list_enabled && r.read_bit()? { |
| 683 | scaling_list = Some(ScalingList::parse(&mut r)?); |
| 684 | } |
| 685 | let amp_enabled = r.read_bit()?; |
| 686 | let sao_enabled = r.read_bit()?; |
| 687 | let pcm_enabled = r.read_bit()?; |
| 688 | let pcm = if pcm_enabled { |
| 689 | let luma = r.read_bits(4)?; |
| 690 | let chroma = r.read_bits(4)?; |
| 691 | // 7.4.3.2.1: PcmBitDepthY <= BitDepthY, and likewise for chroma. |
| 692 | if luma >= bit_depth_luma_minus8 + 8 || chroma >= bit_depth_chroma_minus8 + 8 { |
| 693 | return Err(Error::corrupt("HEVC SPS: PCM bit depth above the coded bit depth")); |
| 694 | } |
| 695 | Some(( |
| 696 | luma, |
| 697 | chroma, |
| 698 | r.read_ue()?, |
| 699 | r.read_ue()?, |
| 700 | r.read_bit()?, |
| 701 | )) |
| 702 | } else { |
| 703 | None |
| 704 | }; |
| 705 | let num_short_term_ref_pic_sets = r.read_ue()?; |
| 706 | if num_short_term_ref_pic_sets > 64 { |
| 707 | return Err(Error::corrupt("HEVC SPS: num_short_term_ref_pic_sets > 64")); |
| 708 | } |
| 709 | let mut sets = Vec::new(); |
| 710 | for i in 0..num_short_term_ref_pic_sets { |
| 711 | let set = ShortTermRefPicSet::parse(&mut r, i, num_short_term_ref_pic_sets, &sets)?; |
| 712 | sets.push(set); |
| 713 | } |
| 714 | let long_term_ref_pics_present = r.read_bit()?; |
| 715 | let mut num_long_term_ref_pics_sps = 0; |
| 716 | let mut long_term_ref_pics_sps = Vec::new(); |
| 717 | if long_term_ref_pics_present { |
| 718 | num_long_term_ref_pics_sps = r.read_ue()?; |
| 719 | if num_long_term_ref_pics_sps > 32 { |
| 720 | return Err(Error::corrupt(format!( |
| 721 | "HEVC SPS: num_long_term_ref_pics_sps = {num_long_term_ref_pics_sps}" |
| 722 | ))); |
| 723 | } |
| 724 | for _ in 0..num_long_term_ref_pics_sps { |
| 725 | let poc_lsb_lt = r.read_bits(log2_max_poc_lsb_minus4 + 4)?; |
| 726 | let used_by_curr = r.read_bit()?; |
| 727 | long_term_ref_pics_sps.push((poc_lsb_lt, used_by_curr)); |
| 728 | } |
| 729 | } |
| 730 | let temporal_mvp_enabled = r.read_bit()?; |
| 731 | let strong_intra_smoothing = r.read_bit()?; |
| 732 | let vui = if r.read_bit()? { |
| 733 | Some(VuiParameters::parse(&mut r, max_sub_layers_minus1)?) |
| 734 | } else { |
| 735 | None |
| 736 | }; |
| 737 | let extension_flags = parse_extension_flags(&mut r); |
| 738 | let range = if extension_flags & 0x80 != 0 { |
| 739 | SpsRangeExt::parse(&mut r)? |
| 740 | } else { |
| 741 | SpsRangeExt::default() |
| 742 | }; |
| 743 | Ok(Sps { |
| 744 | vps_id, |
| 745 | id, |
| 746 | chroma_format_idc, |
| 747 | separate_colour_plane, |
| 748 | pic_width_in_luma_samples, |
| 749 | pic_height_in_luma_samples, |
| 750 | conf_win, |
| 751 | bit_depth_luma_minus8, |
| 752 | bit_depth_chroma_minus8, |
| 753 | log2_max_poc_lsb_minus4, |
| 754 | max_dec_pic_buffering_minus1, |
| 755 | max_num_reorder_pics, |
| 756 | log2_min_cb_size_minus3, |
| 757 | log2_diff_max_min_cb_size, |
| 758 | log2_min_tb_size_minus2, |
| 759 | log2_diff_max_min_tb_size, |
| 760 | max_transform_hierarchy_depth_inter, |
| 761 | max_transform_hierarchy_depth_intra, |
| 762 | scaling_list_enabled, |
| 763 | scaling_list, |
| 764 | amp_enabled, |
| 765 | sao_enabled, |
| 766 | pcm_enabled, |
| 767 | pcm, |
| 768 | num_short_term_ref_pic_sets, |
| 769 | short_term_ref_pic_sets: sets, |
| 770 | long_term_ref_pics_present, |
| 771 | num_long_term_ref_pics_sps, |
| 772 | long_term_ref_pics_sps, |
| 773 | temporal_mvp_enabled, |
| 774 | strong_intra_smoothing, |
| 775 | ptl, |
| 776 | vui, |
| 777 | max_latency_increase_plus1, |
| 778 | extension_flags, |
| 779 | range, |
| 780 | }) |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | /// Largest `st_ref_pic_set()` this crate carries in either direction; the spec |
| 785 | /// caps `NumNegativePics` and `NumPositivePics` at `sps_max_dec_pic_buffering`, |
| 786 | /// which itself cannot exceed 16. |
| 787 | pub const MAX_ST_REF_PICS: usize = 16; |
| 788 | |
| 789 | /// One `st_ref_pic_set()` (7.3.7), with the POC deltas a decoder needs. |
| 790 | /// |
| 791 | /// A *stateless hardware* decoder is the reason the deltas are here: the driver |
| 792 | /// is handed `RefPicSetStCurrBefore` / `StCurrAfter` as picture lists, so |
| 793 | /// something has to turn `delta_poc_sX_minus1` into actual reference pictures, |
| 794 | /// and that something is the caller of this crate. |
| 795 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 796 | pub struct ShortTermRefPicSet { |
| 797 | /// `NumNegativePics`. |
| 798 | pub num_negative: u32, |
| 799 | /// `NumPositivePics`. |
| 800 | pub num_positive: u32, |
| 801 | /// How many of them have `used_by_curr_pic` set — the count that feeds |
| 802 | /// `NumPicTotalCurr`, which sizes the reference list modification syntax. |
| 803 | pub num_used_by_curr: u32, |
| 804 | /// `DeltaPocS0[i]`, negative, in decreasing order (7-59). |
| 805 | pub delta_poc_s0: [i32; MAX_ST_REF_PICS], |
| 806 | /// `UsedByCurrPicS0[i]`. |
| 807 | pub used_s0: [bool; MAX_ST_REF_PICS], |
| 808 | /// `DeltaPocS1[i]`, positive, in increasing order (7-60). |
| 809 | pub delta_poc_s1: [i32; MAX_ST_REF_PICS], |
| 810 | /// `UsedByCurrPicS1[i]`. |
| 811 | pub used_s1: [bool; MAX_ST_REF_PICS], |
| 812 | } |
| 813 | |
| 814 | impl Default for ShortTermRefPicSet { |
| 815 | fn default() -> ShortTermRefPicSet { |
| 816 | ShortTermRefPicSet { |
| 817 | num_negative: 0, |
| 818 | num_positive: 0, |
| 819 | num_used_by_curr: 0, |
| 820 | delta_poc_s0: [0; MAX_ST_REF_PICS], |
| 821 | used_s0: [false; MAX_ST_REF_PICS], |
| 822 | delta_poc_s1: [0; MAX_ST_REF_PICS], |
| 823 | used_s1: [false; MAX_ST_REF_PICS], |
| 824 | } |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | impl ShortTermRefPicSet { |
| 829 | /// Parse one set. `idx` is `stRpsIdx`; `num_sets` is `num_short_term_ref_pic_sets` |
| 830 | /// (the slice header's set sits at `idx == num_sets`, and only there does 7.3.7 |
| 831 | /// carry `delta_idx_minus1`). `prev` holds the SPS sets already parsed for |
| 832 | /// inter-set prediction. |
| 833 | pub fn parse( |
| 834 | r: &mut BitReader, |
| 835 | idx: u32, |
| 836 | num_sets: u32, |
| 837 | prev: &[ShortTermRefPicSet], |
| 838 | ) -> Result<ShortTermRefPicSet> { |
| 839 | let inter_ref_pic_set_prediction = if idx != 0 { r.read_bit()? } else { false }; |
| 840 | if inter_ref_pic_set_prediction { |
| 841 | let delta_idx_minus1 = if idx == num_sets { |
| 842 | r.read_ue()? |
| 843 | } else { |
| 844 | 0 |
| 845 | }; |
| 846 | // 7-61: RefRpsIdx = stRpsIdx - (delta_idx_minus1 + 1), so delta_idx_minus1 < stRpsIdx. |
| 847 | if delta_idx_minus1 >= idx { |
| 848 | return Err(Error::corrupt("HEVC st_ref_pic_set: delta_idx out of range")); |
| 849 | } |
| 850 | let ref_idx = idx - (delta_idx_minus1 + 1); |
| 851 | let reference = *prev |
| 852 | .get(ref_idx as usize) |
| 853 | .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?; |
| 854 | let delta_rps_sign = r.read_bit()?; |
| 855 | let abs_delta_rps_minus1 = r.read_ue()?; |
| 856 | check_range( |
| 857 | "HEVC st_ref_pic_set", |
| 858 | "abs_delta_rps_minus1", |
| 859 | i64::from(abs_delta_rps_minus1), |
| 860 | 0, |
| 861 | MAX_DELTA_POC_MINUS1, |
| 862 | )?; |
| 863 | let delta_rps = if delta_rps_sign { |
| 864 | -((abs_delta_rps_minus1 + 1) as i32) |
| 865 | } else { |
| 866 | (abs_delta_rps_minus1 + 1) as i32 |
| 867 | }; |
| 868 | let num_delta_pocs = (reference.num_negative + reference.num_positive) as usize; |
| 869 | if num_delta_pocs >= MAX_ST_REF_PICS * 2 { |
| 870 | return Err(Error::corrupt( |
| 871 | "HEVC st_ref_pic_set: reference set too large", |
| 872 | )); |
| 873 | } |
| 874 | let mut used_by_curr = [false; MAX_ST_REF_PICS * 2 + 1]; |
| 875 | let mut use_delta = [true; MAX_ST_REF_PICS * 2 + 1]; |
| 876 | for j in 0..=num_delta_pocs { |
| 877 | used_by_curr[j] = r.read_bit()?; |
| 878 | if !used_by_curr[j] { |
| 879 | use_delta[j] = r.read_bit()?; |
| 880 | } |
| 881 | } |
| 882 | Ok(reference.predict(delta_rps, &used_by_curr, &use_delta)) |
| 883 | } else { |
| 884 | let num_negative = r.read_ue()?; |
| 885 | let num_positive = r.read_ue()?; |
| 886 | if num_negative as usize > MAX_ST_REF_PICS || num_positive as usize > MAX_ST_REF_PICS { |
| 887 | return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures")); |
| 888 | } |
| 889 | let mut set = ShortTermRefPicSet { |
| 890 | num_negative, |
| 891 | num_positive, |
| 892 | ..ShortTermRefPicSet::default() |
| 893 | }; |
| 894 | let mut poc = 0i32; |
| 895 | for i in 0..num_negative as usize { |
| 896 | let delta = read_delta_poc(r)?; |
| 897 | poc -= delta; |
| 898 | set.delta_poc_s0[i] = poc; |
| 899 | set.used_s0[i] = r.read_bit()?; |
| 900 | if set.used_s0[i] { |
| 901 | set.num_used_by_curr += 1; |
| 902 | } |
| 903 | } |
| 904 | let mut poc = 0i32; |
| 905 | for i in 0..num_positive as usize { |
| 906 | let delta = read_delta_poc(r)?; |
| 907 | poc += delta; |
| 908 | set.delta_poc_s1[i] = poc; |
| 909 | set.used_s1[i] = r.read_bit()?; |
| 910 | if set.used_s1[i] { |
| 911 | set.num_used_by_curr += 1; |
| 912 | } |
| 913 | } |
| 914 | Ok(set) |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | /// Derive a set predicted from this one (7-61, 7-62). |
| 919 | /// |
| 920 | /// The two loops per direction are the spec's, and their order is what puts |
| 921 | /// `DeltaPocS0` in decreasing and `DeltaPocS1` in increasing order without a |
| 922 | /// sort: entries derived from the *other* direction of the reference set |
| 923 | /// come first, then the reference picture itself, then the same direction. |
| 924 | fn predict( |
| 925 | &self, |
| 926 | delta_rps: i32, |
| 927 | used_by_curr: &[bool], |
| 928 | use_delta: &[bool], |
| 929 | ) -> ShortTermRefPicSet { |
| 930 | let mut out = ShortTermRefPicSet::default(); |
| 931 | let neg = self.num_negative as usize; |
| 932 | let pos = self.num_positive as usize; |
| 933 | let num_delta_pocs = neg + pos; |
| 934 | |
| 935 | let mut i = 0usize; |
| 936 | for j in (0..pos).rev() { |
| 937 | let d = self.delta_poc_s1[j] + delta_rps; |
| 938 | if d < 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS { |
| 939 | out.delta_poc_s0[i] = d; |
| 940 | out.used_s0[i] = used_by_curr[neg + j]; |
| 941 | i += 1; |
| 942 | } |
| 943 | } |
| 944 | if delta_rps < 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS { |
| 945 | out.delta_poc_s0[i] = delta_rps; |
| 946 | out.used_s0[i] = used_by_curr[num_delta_pocs]; |
| 947 | i += 1; |
| 948 | } |
| 949 | for j in 0..neg { |
| 950 | let d = self.delta_poc_s0[j] + delta_rps; |
| 951 | if d < 0 && use_delta[j] && i < MAX_ST_REF_PICS { |
| 952 | out.delta_poc_s0[i] = d; |
| 953 | out.used_s0[i] = used_by_curr[j]; |
| 954 | i += 1; |
| 955 | } |
| 956 | } |
| 957 | out.num_negative = i as u32; |
| 958 | |
| 959 | let mut i = 0usize; |
| 960 | for j in (0..neg).rev() { |
| 961 | let d = self.delta_poc_s0[j] + delta_rps; |
| 962 | if d > 0 && use_delta[j] && i < MAX_ST_REF_PICS { |
| 963 | out.delta_poc_s1[i] = d; |
| 964 | out.used_s1[i] = used_by_curr[j]; |
| 965 | i += 1; |
| 966 | } |
| 967 | } |
| 968 | if delta_rps > 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS { |
| 969 | out.delta_poc_s1[i] = delta_rps; |
| 970 | out.used_s1[i] = used_by_curr[num_delta_pocs]; |
| 971 | i += 1; |
| 972 | } |
| 973 | for j in 0..pos { |
| 974 | let d = self.delta_poc_s1[j] + delta_rps; |
| 975 | if d > 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS { |
| 976 | out.delta_poc_s1[i] = d; |
| 977 | out.used_s1[i] = used_by_curr[neg + j]; |
| 978 | i += 1; |
| 979 | } |
| 980 | } |
| 981 | out.num_positive = i as u32; |
| 982 | out.num_used_by_curr = out.used_s0[..out.num_negative as usize] |
| 983 | .iter() |
| 984 | .chain(out.used_s1[..out.num_positive as usize].iter()) |
| 985 | .filter(|&&u| u) |
| 986 | .count() as u32; |
| 987 | out |
| 988 | } |
| 989 | |
| 990 | /// Write the set in its non-predicted form (7.3.7), which is always legal. |
| 991 | pub fn write(&self, w: &mut ec_core::BitWriter, idx: u32) { |
| 992 | if idx != 0 { |
| 993 | w.write_bit(false); // inter_ref_pic_set_prediction_flag |
| 994 | } |
| 995 | w.write_ue(self.num_negative); |
| 996 | w.write_ue(self.num_positive); |
| 997 | let mut prev = 0i32; |
| 998 | for i in 0..self.num_negative as usize { |
| 999 | w.write_ue((prev - self.delta_poc_s0[i] - 1).max(0) as u32); |
| 1000 | prev = self.delta_poc_s0[i]; |
| 1001 | w.write_bit(self.used_s0[i]); |
| 1002 | } |
| 1003 | let mut prev = 0i32; |
| 1004 | for i in 0..self.num_positive as usize { |
| 1005 | w.write_ue((self.delta_poc_s1[i] - prev - 1).max(0) as u32); |
| 1006 | prev = self.delta_poc_s1[i]; |
| 1007 | w.write_bit(self.used_s1[i]); |
| 1008 | } |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | /// The picture parameter set (7.3.2.3.1). |
| 1013 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1014 | pub struct Pps { |
| 1015 | /// `pps_pic_parameter_set_id`. |
| 1016 | pub id: u32, |
| 1017 | /// `pps_seq_parameter_set_id`. |
| 1018 | pub sps_id: u32, |
| 1019 | /// `dependent_slice_segments_enabled_flag`. |
| 1020 | pub dependent_slice_segments_enabled: bool, |
| 1021 | /// `output_flag_present_flag`. |
| 1022 | pub output_flag_present: bool, |
| 1023 | /// `num_extra_slice_header_bits`. |
| 1024 | pub num_extra_slice_header_bits: u32, |
| 1025 | /// `sign_data_hiding_enabled_flag`. |
| 1026 | pub sign_data_hiding_enabled: bool, |
| 1027 | /// `cabac_init_present_flag`. |
| 1028 | pub cabac_init_present: bool, |
| 1029 | /// `num_ref_idx_l0_default_active_minus1`. |
| 1030 | pub num_ref_idx_l0_default_active_minus1: u32, |
| 1031 | /// `num_ref_idx_l1_default_active_minus1`. |
| 1032 | pub num_ref_idx_l1_default_active_minus1: u32, |
| 1033 | /// `init_qp_minus26`. |
| 1034 | pub init_qp_minus26: i32, |
| 1035 | /// `constrained_intra_pred_flag`. |
| 1036 | pub constrained_intra_pred: bool, |
| 1037 | /// `transform_skip_enabled_flag`. |
| 1038 | pub transform_skip_enabled: bool, |
| 1039 | /// `cu_qp_delta_enabled_flag`. |
| 1040 | pub cu_qp_delta_enabled: bool, |
| 1041 | /// `diff_cu_qp_delta_depth`. |
| 1042 | pub diff_cu_qp_delta_depth: u32, |
| 1043 | /// `pps_cb_qp_offset`. |
| 1044 | pub cb_qp_offset: i32, |
| 1045 | /// `pps_cr_qp_offset`. |
| 1046 | pub cr_qp_offset: i32, |
| 1047 | /// `pps_slice_chroma_qp_offsets_present_flag`. |
| 1048 | pub slice_chroma_qp_offsets_present: bool, |
| 1049 | /// `weighted_pred_flag`. |
| 1050 | pub weighted_pred: bool, |
| 1051 | /// `weighted_bipred_flag`. |
| 1052 | pub weighted_bipred: bool, |
| 1053 | /// `transquant_bypass_enabled_flag`. |
| 1054 | pub transquant_bypass_enabled: bool, |
| 1055 | /// `tiles_enabled_flag`. |
| 1056 | pub tiles_enabled: bool, |
| 1057 | /// `entropy_coding_sync_enabled_flag` — wavefront parallel processing. |
| 1058 | pub entropy_coding_sync_enabled: bool, |
| 1059 | /// `num_tile_columns_minus1`. |
| 1060 | pub num_tile_columns_minus1: u32, |
| 1061 | /// `num_tile_rows_minus1`. |
| 1062 | pub num_tile_rows_minus1: u32, |
| 1063 | /// `uniform_spacing_flag`. |
| 1064 | pub uniform_spacing: bool, |
| 1065 | /// `column_width_minus1[]`, empty when the spacing is uniform (a decoder |
| 1066 | /// derives the widths then, and so should a caller). |
| 1067 | pub column_width_minus1: Vec<u32>, |
| 1068 | /// `row_height_minus1[]`, empty when the spacing is uniform. |
| 1069 | pub row_height_minus1: Vec<u32>, |
| 1070 | /// `loop_filter_across_tiles_enabled_flag`. |
| 1071 | pub loop_filter_across_tiles_enabled: bool, |
| 1072 | /// `pps_loop_filter_across_slices_enabled_flag`. |
| 1073 | pub loop_filter_across_slices_enabled: bool, |
| 1074 | /// `deblocking_filter_control_present_flag`. |
| 1075 | pub deblocking_filter_control_present: bool, |
| 1076 | /// `deblocking_filter_override_enabled_flag`. |
| 1077 | pub deblocking_filter_override_enabled: bool, |
| 1078 | /// `pps_deblocking_filter_disabled_flag`. |
| 1079 | pub deblocking_filter_disabled: bool, |
| 1080 | /// `pps_beta_offset_div2`. |
| 1081 | pub beta_offset_div2: i32, |
| 1082 | /// `pps_tc_offset_div2`. |
| 1083 | pub tc_offset_div2: i32, |
| 1084 | /// The lists `pps_scaling_list_data_present_flag` sends, which override the SPS |
| 1085 | /// lists. `None` when the PPS sends none. |
| 1086 | pub scaling_list: Option<ScalingList>, |
| 1087 | /// `lists_modification_present_flag`. |
| 1088 | pub lists_modification_present: bool, |
| 1089 | /// `log2_parallel_merge_level_minus2`. |
| 1090 | pub log2_parallel_merge_level_minus2: u32, |
| 1091 | /// `slice_segment_header_extension_present_flag`. |
| 1092 | pub slice_segment_header_extension_present: bool, |
| 1093 | /// The PPS extension flags, same layout as [`Sps::extension_flags`]. |
| 1094 | pub extension_flags: u8, |
| 1095 | /// The `pps_range_extension()` fields (7.3.2.3.2); defaults when absent. |
| 1096 | pub range: PpsRangeExt, |
| 1097 | } |
| 1098 | |
| 1099 | impl Default for Pps { |
| 1100 | fn default() -> Self { |
| 1101 | Pps { |
| 1102 | scaling_list: None, |
| 1103 | id: 0, |
| 1104 | sps_id: 0, |
| 1105 | dependent_slice_segments_enabled: false, |
| 1106 | output_flag_present: false, |
| 1107 | num_extra_slice_header_bits: 0, |
| 1108 | sign_data_hiding_enabled: false, |
| 1109 | cabac_init_present: false, |
| 1110 | num_ref_idx_l0_default_active_minus1: 0, |
| 1111 | num_ref_idx_l1_default_active_minus1: 0, |
| 1112 | init_qp_minus26: 0, |
| 1113 | constrained_intra_pred: false, |
| 1114 | transform_skip_enabled: false, |
| 1115 | cu_qp_delta_enabled: false, |
| 1116 | diff_cu_qp_delta_depth: 0, |
| 1117 | cb_qp_offset: 0, |
| 1118 | cr_qp_offset: 0, |
| 1119 | slice_chroma_qp_offsets_present: false, |
| 1120 | weighted_pred: false, |
| 1121 | weighted_bipred: false, |
| 1122 | transquant_bypass_enabled: false, |
| 1123 | tiles_enabled: false, |
| 1124 | entropy_coding_sync_enabled: false, |
| 1125 | num_tile_columns_minus1: 0, |
| 1126 | num_tile_rows_minus1: 0, |
| 1127 | uniform_spacing: true, |
| 1128 | column_width_minus1: Vec::new(), |
| 1129 | row_height_minus1: Vec::new(), |
| 1130 | loop_filter_across_tiles_enabled: true, |
| 1131 | loop_filter_across_slices_enabled: true, |
| 1132 | deblocking_filter_control_present: false, |
| 1133 | deblocking_filter_override_enabled: false, |
| 1134 | deblocking_filter_disabled: false, |
| 1135 | beta_offset_div2: 0, |
| 1136 | tc_offset_div2: 0, |
| 1137 | lists_modification_present: false, |
| 1138 | log2_parallel_merge_level_minus2: 0, |
| 1139 | slice_segment_header_extension_present: false, |
| 1140 | extension_flags: 0, |
| 1141 | range: Default::default(), |
| 1142 | } |
| 1143 | } |
| 1144 | } |
| 1145 | |
| 1146 | impl Pps { |
| 1147 | /// The RBSP, trailing bits included. |
| 1148 | pub fn to_rbsp(&self) -> Vec<u8> { |
| 1149 | let mut w = BitWriter::with_capacity(32); |
| 1150 | w.write_ue(self.id); |
| 1151 | w.write_ue(self.sps_id); |
| 1152 | w.write_bit(self.dependent_slice_segments_enabled); |
| 1153 | w.write_bit(self.output_flag_present); |
| 1154 | w.write_bits(self.num_extra_slice_header_bits, 3); |
| 1155 | w.write_bit(self.sign_data_hiding_enabled); |
| 1156 | w.write_bit(self.cabac_init_present); |
| 1157 | w.write_ue(self.num_ref_idx_l0_default_active_minus1); |
| 1158 | w.write_ue(self.num_ref_idx_l1_default_active_minus1); |
| 1159 | w.write_se(self.init_qp_minus26); |
| 1160 | w.write_bit(self.constrained_intra_pred); |
| 1161 | w.write_bit(self.transform_skip_enabled); |
| 1162 | w.write_bit(self.cu_qp_delta_enabled); |
| 1163 | if self.cu_qp_delta_enabled { |
| 1164 | w.write_ue(self.diff_cu_qp_delta_depth); |
| 1165 | } |
| 1166 | w.write_se(self.cb_qp_offset); |
| 1167 | w.write_se(self.cr_qp_offset); |
| 1168 | w.write_bit(self.slice_chroma_qp_offsets_present); |
| 1169 | w.write_bit(self.weighted_pred); |
| 1170 | w.write_bit(self.weighted_bipred); |
| 1171 | w.write_bit(self.transquant_bypass_enabled); |
| 1172 | w.write_bit(self.tiles_enabled); |
| 1173 | w.write_bit(self.entropy_coding_sync_enabled); |
| 1174 | if self.tiles_enabled { |
| 1175 | w.write_ue(self.num_tile_columns_minus1); |
| 1176 | w.write_ue(self.num_tile_rows_minus1); |
| 1177 | w.write_bit(self.uniform_spacing); |
| 1178 | if !self.uniform_spacing { |
| 1179 | for &width in &self.column_width_minus1 { |
| 1180 | w.write_ue(width); |
| 1181 | } |
| 1182 | for &height in &self.row_height_minus1 { |
| 1183 | w.write_ue(height); |
| 1184 | } |
| 1185 | } |
| 1186 | w.write_bit(self.loop_filter_across_tiles_enabled); |
| 1187 | } |
| 1188 | w.write_bit(self.loop_filter_across_slices_enabled); |
| 1189 | w.write_bit(self.deblocking_filter_control_present); |
| 1190 | if self.deblocking_filter_control_present { |
| 1191 | w.write_bit(self.deblocking_filter_override_enabled); |
| 1192 | w.write_bit(self.deblocking_filter_disabled); |
| 1193 | if !self.deblocking_filter_disabled { |
| 1194 | w.write_se(self.beta_offset_div2); |
| 1195 | w.write_se(self.tc_offset_div2); |
| 1196 | } |
| 1197 | } |
| 1198 | match &self.scaling_list { |
| 1199 | Some(list) => { |
| 1200 | w.write_bit(true); // pps_scaling_list_data_present_flag |
| 1201 | list.write(&mut w); |
| 1202 | } |
| 1203 | None => w.write_bit(false), |
| 1204 | } |
| 1205 | w.write_bit(self.lists_modification_present); |
| 1206 | w.write_ue(self.log2_parallel_merge_level_minus2); |
| 1207 | w.write_bit(self.slice_segment_header_extension_present); |
| 1208 | write_extension_flags(&mut w, self.extension_flags); |
| 1209 | if self.extension_flags & 0x80 != 0 { |
| 1210 | let r = &self.range; |
| 1211 | if self.transform_skip_enabled { |
| 1212 | w.write_ue(r.log2_max_transform_skip_block_size_minus2); |
| 1213 | } |
| 1214 | w.write_bit(r.cross_component_prediction_enabled); |
| 1215 | w.write_bit(r.chroma_qp_offset_list_enabled); |
| 1216 | if r.chroma_qp_offset_list_enabled { |
| 1217 | w.write_ue(r.diff_cu_chroma_qp_offset_depth); |
| 1218 | w.write_ue(r.cb_qp_offset_list.len() as u32 - 1); |
| 1219 | for (cb, cr) in r.cb_qp_offset_list.iter().zip(&r.cr_qp_offset_list) { |
| 1220 | w.write_se(*cb); |
| 1221 | w.write_se(*cr); |
| 1222 | } |
| 1223 | } |
| 1224 | w.write_ue(r.log2_sao_offset_scale_luma); |
| 1225 | w.write_ue(r.log2_sao_offset_scale_chroma); |
| 1226 | } |
| 1227 | rbsp_trailing_bits(&mut w); |
| 1228 | w.into_bytes() |
| 1229 | } |
| 1230 | |
| 1231 | /// Parse a PPS RBSP. |
| 1232 | pub fn parse(rbsp: &[u8]) -> Result<Pps> { |
| 1233 | let mut r = BitReader::new(rbsp); |
| 1234 | let mut pps = Pps { |
| 1235 | id: r.read_ue()?, |
| 1236 | sps_id: r.read_ue()?, |
| 1237 | ..Pps::default() |
| 1238 | }; |
| 1239 | check_range("HEVC PPS", "pps_pic_parameter_set_id", i64::from(pps.id), 0, 63)?; |
| 1240 | check_range("HEVC PPS", "pps_seq_parameter_set_id", i64::from(pps.sps_id), 0, 15)?; |
| 1241 | pps.dependent_slice_segments_enabled = r.read_bit()?; |
| 1242 | pps.output_flag_present = r.read_bit()?; |
| 1243 | pps.num_extra_slice_header_bits = r.read_bits(3)?; |
| 1244 | pps.sign_data_hiding_enabled = r.read_bit()?; |
| 1245 | pps.cabac_init_present = r.read_bit()?; |
| 1246 | pps.num_ref_idx_l0_default_active_minus1 = r.read_ue()?; |
| 1247 | check_range( |
| 1248 | "HEVC PPS", |
| 1249 | "num_ref_idx_l0_default_active_minus1", |
| 1250 | i64::from(pps.num_ref_idx_l0_default_active_minus1), |
| 1251 | 0, |
| 1252 | 14, |
| 1253 | )?; |
| 1254 | pps.num_ref_idx_l1_default_active_minus1 = r.read_ue()?; |
| 1255 | check_range( |
| 1256 | "HEVC PPS", |
| 1257 | "num_ref_idx_l1_default_active_minus1", |
| 1258 | i64::from(pps.num_ref_idx_l1_default_active_minus1), |
| 1259 | 0, |
| 1260 | 14, |
| 1261 | )?; |
| 1262 | pps.init_qp_minus26 = r.read_se()?; |
| 1263 | // 7-6: -(26 + QpBdOffsetY) to +25. The offset is at most 48 (8 bits of depth |
| 1264 | // above 8 is refused by the SPS), and this PPS parser cannot see the SPS. |
| 1265 | check_range( |
| 1266 | "HEVC PPS", |
| 1267 | "init_qp_minus26", |
| 1268 | i64::from(pps.init_qp_minus26), |
| 1269 | -74, |
| 1270 | 25, |
| 1271 | )?; |
| 1272 | pps.constrained_intra_pred = r.read_bit()?; |
| 1273 | pps.transform_skip_enabled = r.read_bit()?; |
| 1274 | pps.cu_qp_delta_enabled = r.read_bit()?; |
| 1275 | if pps.cu_qp_delta_enabled { |
| 1276 | pps.diff_cu_qp_delta_depth = r.read_ue()?; |
| 1277 | // 7-7: at most log2_diff_max_min_luma_coding_block_size, which is at most 3. |
| 1278 | check_range( |
| 1279 | "HEVC PPS", |
| 1280 | "diff_cu_qp_delta_depth", |
| 1281 | i64::from(pps.diff_cu_qp_delta_depth), |
| 1282 | 0, |
| 1283 | 3, |
| 1284 | )?; |
| 1285 | } |
| 1286 | pps.cb_qp_offset = r.read_se()?; |
| 1287 | check_range("HEVC PPS", "pps_cb_qp_offset", i64::from(pps.cb_qp_offset), -12, 12)?; |
| 1288 | pps.cr_qp_offset = r.read_se()?; |
| 1289 | check_range("HEVC PPS", "pps_cr_qp_offset", i64::from(pps.cr_qp_offset), -12, 12)?; |
| 1290 | pps.slice_chroma_qp_offsets_present = r.read_bit()?; |
| 1291 | pps.weighted_pred = r.read_bit()?; |
| 1292 | pps.weighted_bipred = r.read_bit()?; |
| 1293 | pps.transquant_bypass_enabled = r.read_bit()?; |
| 1294 | pps.tiles_enabled = r.read_bit()?; |
| 1295 | pps.entropy_coding_sync_enabled = r.read_bit()?; |
| 1296 | if pps.tiles_enabled { |
| 1297 | pps.num_tile_columns_minus1 = r.read_ue()?; |
| 1298 | pps.num_tile_rows_minus1 = r.read_ue()?; |
| 1299 | pps.uniform_spacing = r.read_bit()?; |
| 1300 | // The tile count is capped for both spacings: a uniform split would |
| 1301 | // otherwise size its tile arrays from any count the stream names. |
| 1302 | if pps.num_tile_columns_minus1 > 20 || pps.num_tile_rows_minus1 > 22 { |
| 1303 | return Err(Error::corrupt("HEVC PPS: tile count beyond any level")); |
| 1304 | } |
| 1305 | if !pps.uniform_spacing { |
| 1306 | for _ in 0..pps.num_tile_columns_minus1 { |
| 1307 | let value = r.read_ue()?; |
| 1308 | pps.column_width_minus1.push(value); |
| 1309 | } |
| 1310 | for _ in 0..pps.num_tile_rows_minus1 { |
| 1311 | let value = r.read_ue()?; |
| 1312 | pps.row_height_minus1.push(value); |
| 1313 | } |
| 1314 | } |
| 1315 | pps.loop_filter_across_tiles_enabled = r.read_bit()?; |
| 1316 | } |
| 1317 | pps.loop_filter_across_slices_enabled = r.read_bit()?; |
| 1318 | pps.deblocking_filter_control_present = r.read_bit()?; |
| 1319 | if pps.deblocking_filter_control_present { |
| 1320 | pps.deblocking_filter_override_enabled = r.read_bit()?; |
| 1321 | pps.deblocking_filter_disabled = r.read_bit()?; |
| 1322 | if !pps.deblocking_filter_disabled { |
| 1323 | pps.beta_offset_div2 = r.read_se()?; |
| 1324 | check_range( |
| 1325 | "HEVC PPS", |
| 1326 | "pps_beta_offset_div2", |
| 1327 | i64::from(pps.beta_offset_div2), |
| 1328 | -6, |
| 1329 | 6, |
| 1330 | )?; |
| 1331 | pps.tc_offset_div2 = r.read_se()?; |
| 1332 | check_range( |
| 1333 | "HEVC PPS", |
| 1334 | "pps_tc_offset_div2", |
| 1335 | i64::from(pps.tc_offset_div2), |
| 1336 | -6, |
| 1337 | 6, |
| 1338 | )?; |
| 1339 | } |
| 1340 | } |
| 1341 | if r.read_bit()? { |
| 1342 | pps.scaling_list = Some(ScalingList::parse(&mut r)?); |
| 1343 | } |
| 1344 | pps.lists_modification_present = r.read_bit()?; |
| 1345 | pps.log2_parallel_merge_level_minus2 = r.read_ue()?; |
| 1346 | // 7-37: Log2ParMrgLevelY is at most CtbLog2SizeY, which is at most 6. |
| 1347 | check_range( |
| 1348 | "HEVC PPS", |
| 1349 | "log2_parallel_merge_level_minus2", |
| 1350 | i64::from(pps.log2_parallel_merge_level_minus2), |
| 1351 | 0, |
| 1352 | 4, |
| 1353 | )?; |
| 1354 | pps.slice_segment_header_extension_present = r.read_bit()?; |
| 1355 | pps.extension_flags = parse_extension_flags(&mut r); |
| 1356 | if pps.extension_flags & 0x80 != 0 { |
| 1357 | pps.range = PpsRangeExt::parse(&mut r, pps.transform_skip_enabled)?; |
| 1358 | } |
| 1359 | Ok(pps) |
| 1360 | } |
| 1361 | } |
| 1362 | |
| 1363 | /// Writes the `*_extension_present_flag` block packed as [`Sps::extension_flags`]. Only the |
| 1364 | /// flags are written, not the extension bodies that follow them: the decoder never reads an |
| 1365 | /// extension body, and the refusal fixtures need only the flags. |
| 1366 | fn write_extension_flags(w: &mut BitWriter, flags: u8) { |
| 1367 | let present = flags != 0; |
| 1368 | w.write_bit(present); |
| 1369 | if present { |
| 1370 | for bit in 0..4 { |
| 1371 | w.write_bit(flags & (0x80 >> bit) != 0); |
| 1372 | } |
| 1373 | w.write_bits(u32::from(flags & 0x0f), 4); |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | /// The `*_extension_present_flag` block at the end of an SPS or PPS (7.3.2.2.1, 7.3.2.3.1), |
| 1378 | /// packed as [`Sps::extension_flags`]. A truncated tail reads as no extension. |
| 1379 | fn parse_extension_flags(r: &mut BitReader) -> u8 { |
| 1380 | if !matches!(r.read_bit(), Ok(true)) { |
| 1381 | return 0; |
| 1382 | } |
| 1383 | let mut flags = 0u8; |
| 1384 | for bit in 0..4 { |
| 1385 | if matches!(r.read_bit(), Ok(true)) { |
| 1386 | flags |= 0x80 >> bit; |
| 1387 | } |
| 1388 | } |
| 1389 | flags | r.read_bits(4).unwrap_or(0) as u8 |
| 1390 | } |
| 1391 | |
| 1392 | /// `rbsp_trailing_bits()`: a one bit then zeros to the byte boundary. |
| 1393 | pub fn rbsp_trailing_bits(w: &mut BitWriter) { |
| 1394 | w.write_bit(true); |
| 1395 | w.align_to_byte(); |
| 1396 | } |
| 1397 | |
| 1398 | /// `vps_max_sub_layers_minus1` and `sps_max_sub_layers_minus1` (7.4.3.1, 7.4.3.2.1): 0 to 6. |
| 1399 | const MAX_SUB_LAYERS_MINUS1: i64 = 6; |
| 1400 | |
| 1401 | /// `sps_max_dec_pic_buffering_minus1` (7.4.3.2.1): MaxDpbSize - 1, at most 15. |
| 1402 | const MAX_DPB_PICTURES_MINUS1: i64 = 15; |
| 1403 | |
| 1404 | /// `delta_poc_sX_minus1` and `abs_delta_rps_minus1` (7-53, 7-54, 7-61): 0 to 2^15 - 1. |
| 1405 | const MAX_DELTA_POC_MINUS1: i64 = 32_767; |
| 1406 | |
| 1407 | /// Refuse `value` unless `lo <= value <= hi`. The message names the syntax element. |
| 1408 | pub(crate) fn check_range(what: &str, field: &str, value: i64, lo: i64, hi: i64) -> Result<()> { |
| 1409 | if (lo..=hi).contains(&value) { |
| 1410 | Ok(()) |
| 1411 | } else { |
| 1412 | Err(Error::corrupt(format!( |
| 1413 | "{what}: {field} = {value}, outside {lo}..={hi}" |
| 1414 | ))) |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | /// Read a `delta_poc_sX_minus1` and return the delta it stands for, `minus1 + 1`. |
| 1419 | fn read_delta_poc(r: &mut BitReader) -> Result<i32> { |
| 1420 | let minus1 = r.read_ue()?; |
| 1421 | check_range( |
| 1422 | "HEVC st_ref_pic_set", |
| 1423 | "delta_poc_sX_minus1", |
| 1424 | i64::from(minus1), |
| 1425 | 0, |
| 1426 | MAX_DELTA_POC_MINUS1, |
| 1427 | )?; |
| 1428 | Ok(minus1 as i32 + 1) |
| 1429 | } |
| 1430 | |
| 1431 | /// `Ceil( Log2( v ) )`, the width of a `u(v)` field counting `v` values. |
| 1432 | pub fn ceil_log2(v: u32) -> u32 { |
| 1433 | let mut bits = 0; |
| 1434 | while (1u64 << bits) < u64::from(v) { |
| 1435 | bits += 1; |
| 1436 | } |
| 1437 | bits |
| 1438 | } |
| 1439 | |
| 1440 | /// `delta_poc_s0_minus1` / `delta_poc_s1_minus1` (7-53, 7-54): in range 0..=2^15 - 1. |
| 1441 | /// Checked here so the running POC sums in `ShortTermRefPicSet` cannot overflow. |
| 1442 | #[cfg(test)] |
| 1443 | mod tests { |
| 1444 | use super::*; |
| 1445 | use crate::vui::{ColourDescription, VideoSignalType}; |
| 1446 | |
| 1447 | fn sample_sps() -> Sps { |
| 1448 | Sps { |
| 1449 | max_latency_increase_plus1: 0, |
| 1450 | extension_flags: 0, |
| 1451 | range: Default::default(), |
| 1452 | vps_id: 0, |
| 1453 | id: 0, |
| 1454 | chroma_format_idc: 1, |
| 1455 | separate_colour_plane: false, |
| 1456 | pic_width_in_luma_samples: 1920, |
| 1457 | pic_height_in_luma_samples: 1088, |
| 1458 | conf_win: ConformanceWindow { |
| 1459 | left: 0, |
| 1460 | right: 0, |
| 1461 | top: 0, |
| 1462 | bottom: 4, |
| 1463 | }, |
| 1464 | bit_depth_luma_minus8: 0, |
| 1465 | bit_depth_chroma_minus8: 0, |
| 1466 | log2_max_poc_lsb_minus4: 4, |
| 1467 | max_dec_pic_buffering_minus1: 0, |
| 1468 | max_num_reorder_pics: 0, |
| 1469 | log2_min_cb_size_minus3: 0, |
| 1470 | log2_diff_max_min_cb_size: 3, |
| 1471 | log2_min_tb_size_minus2: 0, |
| 1472 | log2_diff_max_min_tb_size: 3, |
| 1473 | max_transform_hierarchy_depth_inter: 0, |
| 1474 | max_transform_hierarchy_depth_intra: 0, |
| 1475 | scaling_list_enabled: false, |
| 1476 | scaling_list: None, |
| 1477 | amp_enabled: false, |
| 1478 | sao_enabled: false, |
| 1479 | pcm_enabled: false, |
| 1480 | pcm: None, |
| 1481 | num_short_term_ref_pic_sets: 0, |
| 1482 | short_term_ref_pic_sets: Vec::new(), |
| 1483 | long_term_ref_pics_present: false, |
| 1484 | num_long_term_ref_pics_sps: 0, |
| 1485 | long_term_ref_pics_sps: Vec::new(), |
| 1486 | temporal_mvp_enabled: false, |
| 1487 | strong_intra_smoothing: true, |
| 1488 | ptl: ProfileTierLevel::main(120), |
| 1489 | vui: Some(VuiParameters { |
| 1490 | sample_aspect_ratio: Some((1, 1)), |
| 1491 | video_signal_type: Some(VideoSignalType { |
| 1492 | video_format: 5, |
| 1493 | video_full_range_flag: false, |
| 1494 | colour_description: Some(ColourDescription { |
| 1495 | colour_primaries: 1, |
| 1496 | transfer_characteristics: 1, |
| 1497 | matrix_coeffs: 1, |
| 1498 | }), |
| 1499 | }), |
| 1500 | chroma_sample_loc: None, |
| 1501 | timing: Some((1, 30)), |
| 1502 | }), |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | #[test] |
| 1507 | fn parameter_sets_round_trip() { |
| 1508 | let vps = Vps { |
| 1509 | id: 0, |
| 1510 | ptl: ProfileTierLevel::main(120), |
| 1511 | max_dec_pic_buffering_minus1: 0, |
| 1512 | max_num_reorder_pics: 0, |
| 1513 | timing: None, |
| 1514 | }; |
| 1515 | assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps); |
| 1516 | |
| 1517 | let sps = sample_sps(); |
| 1518 | let parsed = Sps::parse(&sps.to_rbsp()).unwrap(); |
| 1519 | assert_eq!(parsed, sps); |
| 1520 | // 1080 is cropped back out of the 1088 coded rows. |
| 1521 | assert_eq!(parsed.display_size(), (1920, 1080)); |
| 1522 | assert_eq!(parsed.ctb_size(), 64); |
| 1523 | assert_eq!(parsed.pic_width_in_ctbs(), 30); |
| 1524 | assert_eq!(parsed.pic_height_in_ctbs(), 17); |
| 1525 | |
| 1526 | let pps = Pps { |
| 1527 | entropy_coding_sync_enabled: true, |
| 1528 | init_qp_minus26: 1, |
| 1529 | deblocking_filter_control_present: true, |
| 1530 | deblocking_filter_disabled: true, |
| 1531 | ..Pps::default() |
| 1532 | }; |
| 1533 | assert_eq!(Pps::parse(&pps.to_rbsp()).unwrap(), pps); |
| 1534 | |
| 1535 | // The fields a hardware decoder needs but this family's own encoder |
| 1536 | // never writes: explicit tile geometry and PCM. |
| 1537 | let tiled = Pps { |
| 1538 | tiles_enabled: true, |
| 1539 | num_tile_columns_minus1: 2, |
| 1540 | num_tile_rows_minus1: 1, |
| 1541 | uniform_spacing: false, |
| 1542 | column_width_minus1: vec![9, 19], |
| 1543 | row_height_minus1: vec![7], |
| 1544 | loop_filter_across_tiles_enabled: false, |
| 1545 | cu_qp_delta_enabled: true, |
| 1546 | diff_cu_qp_delta_depth: 2, |
| 1547 | cb_qp_offset: -3, |
| 1548 | cr_qp_offset: 4, |
| 1549 | ..Pps::default() |
| 1550 | }; |
| 1551 | assert_eq!(Pps::parse(&tiled.to_rbsp()).unwrap(), tiled); |
| 1552 | |
| 1553 | let pcm = Sps { |
| 1554 | pcm_enabled: true, |
| 1555 | pcm: Some((7, 7, 0, 2, true)), |
| 1556 | sao_enabled: true, |
| 1557 | ..sample_sps() |
| 1558 | }; |
| 1559 | assert_eq!(Sps::parse(&pcm.to_rbsp()).unwrap(), pcm); |
| 1560 | } |
| 1561 | |
| 1562 | /// Assert `result` is refused with `Error::Corrupt` and that the message names `field`. |
| 1563 | fn refused_naming<T: std::fmt::Debug>(result: Result<T>, field: &str) { |
| 1564 | match result { |
| 1565 | Ok(v) => panic!("accepted, expected {field} to be refused: {v:?}"), |
| 1566 | Err(e) => { |
| 1567 | assert!(matches!(e, Error::Corrupt { .. }), "not Corrupt: {e:?}"); |
| 1568 | assert!(e.to_string().contains(field), "message does not name {field}: {e}"); |
| 1569 | } |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | /// Bits written by `build`, padded to a byte. |
| 1574 | fn bits(build: impl FnOnce(&mut BitWriter)) -> Vec<u8> { |
| 1575 | let mut w = BitWriter::new(); |
| 1576 | build(&mut w); |
| 1577 | w.align_to_byte(); |
| 1578 | w.into_bytes() |
| 1579 | } |
| 1580 | |
| 1581 | fn sps_with(edit: impl FnOnce(&mut Sps)) -> Vec<u8> { |
| 1582 | let mut sps = sample_sps(); |
| 1583 | edit(&mut sps); |
| 1584 | sps.to_rbsp() |
| 1585 | } |
| 1586 | |
| 1587 | #[test] |
| 1588 | fn seven_sub_layers_is_refused_by_name_and_six_is_not() { |
| 1589 | // vps_max_sub_layers_minus1 is bits 12..15 of the VPS RBSP; sps_ is bits 4..7 of the SPS. |
| 1590 | let mut vps = Vps { |
| 1591 | id: 0, |
| 1592 | ptl: ProfileTierLevel::main(120), |
| 1593 | max_dec_pic_buffering_minus1: 0, |
| 1594 | max_num_reorder_pics: 0, |
| 1595 | timing: None, |
| 1596 | } |
| 1597 | .to_rbsp(); |
| 1598 | vps[1] |= 0x0e; |
| 1599 | refused_naming(Vps::parse(&vps), "vps_max_sub_layers_minus1"); |
| 1600 | |
| 1601 | let mut sps = sample_sps().to_rbsp(); |
| 1602 | sps[0] |= 0x0e; |
| 1603 | refused_naming(Sps::parse(&sps), "sps_max_sub_layers_minus1"); |
| 1604 | |
| 1605 | // Six is legal, so the guard must let it through. The rest of this RBSP |
| 1606 | // is then read at the wrong offsets, so the parse may fail later, but not |
| 1607 | // on the sub-layer count. |
| 1608 | let mut sps = sample_sps().to_rbsp(); |
| 1609 | sps[0] |= 0x0c; |
| 1610 | if let Err(e) = Sps::parse(&sps) { |
| 1611 | assert!(!e.to_string().contains("max_sub_layers"), "{e}"); |
| 1612 | } |
| 1613 | } |
| 1614 | |
| 1615 | #[test] |
| 1616 | fn sps_block_sizes_and_depths_are_range_checked() { |
| 1617 | // CtbLog2SizeY outside 4..=6: a 128 CTB, and an 8 CTB. |
| 1618 | refused_naming( |
| 1619 | Sps::parse(&sps_with(|s| s.log2_diff_max_min_cb_size = 4)), |
| 1620 | "CtbLog2SizeY", |
| 1621 | ); |
| 1622 | refused_naming( |
| 1623 | Sps::parse(&sps_with(|s| s.log2_diff_max_min_cb_size = 0)), |
| 1624 | "CtbLog2SizeY", |
| 1625 | ); |
| 1626 | // An absurd minimum CB is refused by name, not by a wrapped sum. |
| 1627 | refused_naming( |
| 1628 | Sps::parse(&sps_with(|s| s.log2_min_cb_size_minus3 = 40)), |
| 1629 | "CtbLog2SizeY", |
| 1630 | ); |
| 1631 | // MinTbLog2SizeY must stay below MinCbLog2SizeY (8): a 8x8 minimum TB is not. |
| 1632 | refused_naming( |
| 1633 | Sps::parse(&sps_with(|s| s.log2_min_tb_size_minus2 = 1)), |
| 1634 | "MinTbLog2SizeY", |
| 1635 | ); |
| 1636 | // MaxTbLog2SizeY is at most 5 (32 samples): a 64 largest TB is not. |
| 1637 | refused_naming( |
| 1638 | Sps::parse(&sps_with(|s| s.log2_diff_max_min_tb_size = 4)), |
| 1639 | "MaxTbLog2SizeY", |
| 1640 | ); |
| 1641 | // max_transform_hierarchy_depth is at most CtbLog2SizeY - MinTbLog2SizeY = 4. |
| 1642 | refused_naming( |
| 1643 | Sps::parse(&sps_with(|s| s.max_transform_hierarchy_depth_inter = 5)), |
| 1644 | "max_transform_hierarchy_depth_inter", |
| 1645 | ); |
| 1646 | refused_naming( |
| 1647 | Sps::parse(&sps_with(|s| s.max_transform_hierarchy_depth_intra = 5)), |
| 1648 | "max_transform_hierarchy_depth_intra", |
| 1649 | ); |
| 1650 | // The depth at its bound is still legal. |
| 1651 | assert!(Sps::parse(&sps_with(|s| s.max_transform_hierarchy_depth_intra = 4)).is_ok()); |
| 1652 | } |
| 1653 | |
| 1654 | #[test] |
| 1655 | fn sps_dpb_size_and_ids_are_range_checked() { |
| 1656 | refused_naming( |
| 1657 | Sps::parse(&sps_with(|s| s.max_dec_pic_buffering_minus1 = 16)), |
| 1658 | "sps_max_dec_pic_buffering_minus1", |
| 1659 | ); |
| 1660 | assert!(Sps::parse(&sps_with(|s| s.max_dec_pic_buffering_minus1 = 15)).is_ok()); |
| 1661 | refused_naming( |
| 1662 | Sps::parse(&sps_with(|s| s.id = 16)), |
| 1663 | "sps_seq_parameter_set_id", |
| 1664 | ); |
| 1665 | } |
| 1666 | |
| 1667 | #[test] |
| 1668 | fn conformance_window_must_leave_a_picture() { |
| 1669 | // 4:2:0 crops two luma rows per chroma-unit offset: 2 * 544 = 1088 leaves nothing. |
| 1670 | refused_naming( |
| 1671 | Sps::parse(&sps_with(|s| { |
| 1672 | s.conf_win = ConformanceWindow { |
| 1673 | left: 0, |
| 1674 | right: 0, |
| 1675 | top: 0, |
| 1676 | bottom: 544, |
| 1677 | } |
| 1678 | })), |
| 1679 | "conformance window", |
| 1680 | ); |
| 1681 | // A huge offset must not wrap the sum either. |
| 1682 | refused_naming( |
| 1683 | Sps::parse(&sps_with(|s| { |
| 1684 | s.conf_win = ConformanceWindow { |
| 1685 | left: 0x7fff_ffff, |
| 1686 | right: 0x7fff_ffff, |
| 1687 | top: 0, |
| 1688 | bottom: 0, |
| 1689 | } |
| 1690 | })), |
| 1691 | "conformance window", |
| 1692 | ); |
| 1693 | } |
| 1694 | |
| 1695 | #[test] |
| 1696 | fn vps_dpb_size_is_range_checked() { |
| 1697 | let vps = Vps { |
| 1698 | id: 0, |
| 1699 | ptl: ProfileTierLevel::main(120), |
| 1700 | max_dec_pic_buffering_minus1: 16, |
| 1701 | max_num_reorder_pics: 0, |
| 1702 | timing: None, |
| 1703 | }; |
| 1704 | refused_naming(Vps::parse(&vps.to_rbsp()), "vps_max_dec_pic_buffering_minus1"); |
| 1705 | } |
| 1706 | |
| 1707 | #[test] |
| 1708 | fn pps_reference_counts_and_qp_are_range_checked() { |
| 1709 | let pps = |edit: fn(&mut Pps)| { |
| 1710 | let mut p = Pps::default(); |
| 1711 | edit(&mut p); |
| 1712 | p.to_rbsp() |
| 1713 | }; |
| 1714 | refused_naming( |
| 1715 | Pps::parse(&pps(|p| p.num_ref_idx_l0_default_active_minus1 = 15)), |
| 1716 | "num_ref_idx_l0_default_active_minus1", |
| 1717 | ); |
| 1718 | refused_naming( |
| 1719 | Pps::parse(&pps(|p| p.num_ref_idx_l1_default_active_minus1 = 15)), |
| 1720 | "num_ref_idx_l1_default_active_minus1", |
| 1721 | ); |
| 1722 | refused_naming( |
| 1723 | Pps::parse(&pps(|p| p.init_qp_minus26 = 26)), |
| 1724 | "init_qp_minus26", |
| 1725 | ); |
| 1726 | refused_naming( |
| 1727 | Pps::parse(&pps(|p| p.init_qp_minus26 = -75)), |
| 1728 | "init_qp_minus26", |
| 1729 | ); |
| 1730 | refused_naming( |
| 1731 | Pps::parse(&pps(|p| p.cb_qp_offset = 13)), |
| 1732 | "pps_cb_qp_offset", |
| 1733 | ); |
| 1734 | refused_naming( |
| 1735 | Pps::parse(&pps(|p| p.cr_qp_offset = -13)), |
| 1736 | "pps_cr_qp_offset", |
| 1737 | ); |
| 1738 | refused_naming( |
| 1739 | Pps::parse(&pps(|p| { |
| 1740 | p.cu_qp_delta_enabled = true; |
| 1741 | p.diff_cu_qp_delta_depth = 4; |
| 1742 | })), |
| 1743 | "diff_cu_qp_delta_depth", |
| 1744 | ); |
| 1745 | refused_naming( |
| 1746 | Pps::parse(&pps(|p| p.log2_parallel_merge_level_minus2 = 5)), |
| 1747 | "log2_parallel_merge_level_minus2", |
| 1748 | ); |
| 1749 | refused_naming(Pps::parse(&pps(|p| p.id = 64)), "pps_pic_parameter_set_id"); |
| 1750 | refused_naming( |
| 1751 | Pps::parse(&pps(|p| p.sps_id = 16)), |
| 1752 | "pps_seq_parameter_set_id", |
| 1753 | ); |
| 1754 | |
| 1755 | // The bounds themselves are legal. |
| 1756 | let edge = Pps { |
| 1757 | num_ref_idx_l0_default_active_minus1: 14, |
| 1758 | num_ref_idx_l1_default_active_minus1: 14, |
| 1759 | init_qp_minus26: -74, |
| 1760 | cb_qp_offset: -12, |
| 1761 | cr_qp_offset: 12, |
| 1762 | cu_qp_delta_enabled: true, |
| 1763 | diff_cu_qp_delta_depth: 3, |
| 1764 | log2_parallel_merge_level_minus2: 4, |
| 1765 | ..Pps::default() |
| 1766 | }; |
| 1767 | assert_eq!(Pps::parse(&edge.to_rbsp()).unwrap(), edge); |
| 1768 | } |
| 1769 | |
| 1770 | #[test] |
| 1771 | fn pps_loop_filter_offsets_are_range_checked() { |
| 1772 | let deblock = |beta: i32, tc: i32| { |
| 1773 | Pps { |
| 1774 | deblocking_filter_control_present: true, |
| 1775 | deblocking_filter_disabled: false, |
| 1776 | beta_offset_div2: beta, |
| 1777 | tc_offset_div2: tc, |
| 1778 | ..Pps::default() |
| 1779 | } |
| 1780 | .to_rbsp() |
| 1781 | }; |
| 1782 | refused_naming(Pps::parse(&deblock(7, 0)), "pps_beta_offset_div2"); |
| 1783 | refused_naming(Pps::parse(&deblock(0, -7)), "pps_tc_offset_div2"); |
| 1784 | assert!(Pps::parse(&deblock(-6, 6)).is_ok()); |
| 1785 | } |
| 1786 | |
| 1787 | #[test] |
| 1788 | fn pps_tile_count_is_capped_for_uniform_spacing_too() { |
| 1789 | let tiled = Pps { |
| 1790 | tiles_enabled: true, |
| 1791 | uniform_spacing: true, |
| 1792 | num_tile_columns_minus1: 21, |
| 1793 | num_tile_rows_minus1: 0, |
| 1794 | ..Pps::default() |
| 1795 | }; |
| 1796 | refused_naming(Pps::parse(&tiled.to_rbsp()), "tile count beyond any level"); |
| 1797 | } |
| 1798 | |
| 1799 | #[test] |
| 1800 | fn st_ref_pic_set_fields_are_range_checked() { |
| 1801 | // Set 0 explicit, one negative picture with delta_poc_s0_minus1 = 32768. |
| 1802 | let too_far = bits(|w| { |
| 1803 | w.write_ue(1); // num_negative_pics |
| 1804 | w.write_ue(0); // num_positive_pics |
| 1805 | w.write_ue(32_768); |
| 1806 | w.write_bit(true); |
| 1807 | }); |
| 1808 | refused_naming( |
| 1809 | ShortTermRefPicSet::parse(&mut BitReader::new(&too_far), 0, 1, &[]), |
| 1810 | "delta_poc_sX_minus1", |
| 1811 | ); |
| 1812 | // The largest legal delta is accepted. |
| 1813 | let largest = bits(|w| { |
| 1814 | w.write_ue(1); |
| 1815 | w.write_ue(0); |
| 1816 | w.write_ue(32_767); |
| 1817 | w.write_bit(true); |
| 1818 | }); |
| 1819 | assert_eq!( |
| 1820 | ShortTermRefPicSet::parse(&mut BitReader::new(&largest), 0, 1, &[]) |
| 1821 | .unwrap() |
| 1822 | .delta_poc_s0[0], |
| 1823 | -32_768 |
| 1824 | ); |
| 1825 | |
| 1826 | // Set 1 predicted from set 0 with delta_idx_minus1 = 1 names a set before set 0. |
| 1827 | // delta_idx_minus1 is only read in the slice header (idx == num_sets), so |
| 1828 | // here num_sets is 1. |
| 1829 | let set0 = ShortTermRefPicSet::default(); |
| 1830 | let bad_idx = bits(|w| { |
| 1831 | w.write_bit(true); // inter_ref_pic_set_prediction_flag |
| 1832 | w.write_ue(1); // delta_idx_minus1 |
| 1833 | }); |
| 1834 | refused_naming( |
| 1835 | ShortTermRefPicSet::parse(&mut BitReader::new(&bad_idx), 1, 1, &[set0]), |
| 1836 | "delta_idx out of range", |
| 1837 | ); |
| 1838 | |
| 1839 | // abs_delta_rps_minus1 = 32768 is past 2^15 - 1. |
| 1840 | let bad_rps = bits(|w| { |
| 1841 | w.write_bit(true); // inter_ref_pic_set_prediction_flag |
| 1842 | w.write_ue(0); // delta_idx_minus1 |
| 1843 | w.write_bit(false); // delta_rps_sign |
| 1844 | w.write_ue(32_768); // abs_delta_rps_minus1 |
| 1845 | }); |
| 1846 | refused_naming( |
| 1847 | ShortTermRefPicSet::parse(&mut BitReader::new(&bad_rps), 1, 2, &[set0]), |
| 1848 | "abs_delta_rps_minus1", |
| 1849 | ); |
| 1850 | } |
| 1851 | |
| 1852 | #[test] |
| 1853 | fn levels_round_up_with_size_and_rate() { |
| 1854 | assert_eq!(ProfileTierLevel::level_for(1920, 1080, 30.0), 120); // 4 |
| 1855 | assert_eq!(ProfileTierLevel::level_for(1920, 1080, 60.0), 123); // 4.1 |
| 1856 | assert_eq!(ProfileTierLevel::level_for(3840, 2160, 30.0), 150); // 5 |
| 1857 | assert_eq!(ProfileTierLevel::level_for(640, 480, 30.0), 90); // 3 |
| 1858 | } |
| 1859 | |
| 1860 | #[test] |
| 1861 | fn ceil_log2_counts_values() { |
| 1862 | assert_eq!(ceil_log2(1), 0); |
| 1863 | assert_eq!(ceil_log2(2), 1); |
| 1864 | assert_eq!(ceil_log2(510), 9); |
| 1865 | assert_eq!(ceil_log2(512), 9); |
| 1866 | assert_eq!(ceil_log2(513), 10); |
| 1867 | } |
| 1868 | } |
| 1869 | |
| 1870 | /// The `sps_range_extension()` flags of 7.3.2.2.2, in bitstream order. |
| 1871 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 1872 | pub struct SpsRangeExt { |
| 1873 | /// `transform_skip_rotation_enabled`. |
| 1874 | pub transform_skip_rotation_enabled: bool, |
| 1875 | /// `transform_skip_context_enabled`. |
| 1876 | pub transform_skip_context_enabled: bool, |
| 1877 | /// `implicit_rdpcm_enabled`. |
| 1878 | pub implicit_rdpcm_enabled: bool, |
| 1879 | /// `explicit_rdpcm_enabled`. |
| 1880 | pub explicit_rdpcm_enabled: bool, |
| 1881 | /// `extended_precision_processing`. |
| 1882 | pub extended_precision_processing: bool, |
| 1883 | /// `intra_smoothing_disabled`. |
| 1884 | pub intra_smoothing_disabled: bool, |
| 1885 | /// `high_precision_offsets_enabled`. |
| 1886 | pub high_precision_offsets_enabled: bool, |
| 1887 | /// `persistent_rice_adaptation_enabled`. |
| 1888 | pub persistent_rice_adaptation_enabled: bool, |
| 1889 | /// `cabac_bypass_alignment_enabled`. |
| 1890 | pub cabac_bypass_alignment_enabled: bool, |
| 1891 | } |
| 1892 | |
| 1893 | impl SpsRangeExt { |
| 1894 | fn parse(r: &mut BitReader) -> Result<Self> { |
| 1895 | Ok(SpsRangeExt { |
| 1896 | transform_skip_rotation_enabled: r.read_bit()?, |
| 1897 | transform_skip_context_enabled: r.read_bit()?, |
| 1898 | implicit_rdpcm_enabled: r.read_bit()?, |
| 1899 | explicit_rdpcm_enabled: r.read_bit()?, |
| 1900 | extended_precision_processing: r.read_bit()?, |
| 1901 | intra_smoothing_disabled: r.read_bit()?, |
| 1902 | high_precision_offsets_enabled: r.read_bit()?, |
| 1903 | persistent_rice_adaptation_enabled: r.read_bit()?, |
| 1904 | cabac_bypass_alignment_enabled: r.read_bit()?, |
| 1905 | }) |
| 1906 | } |
| 1907 | } |
| 1908 | |
| 1909 | /// The `pps_range_extension()` fields of 7.3.2.3.2. The defaults are the inferred values. |
| 1910 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 1911 | pub struct PpsRangeExt { |
| 1912 | /// `log2_max_transform_skip_block_size_minus2` (0 when transform skip is off). |
| 1913 | pub log2_max_transform_skip_block_size_minus2: u32, |
| 1914 | /// `cross_component_prediction_enabled`. |
| 1915 | pub cross_component_prediction_enabled: bool, |
| 1916 | /// `chroma_qp_offset_list_enabled`. |
| 1917 | pub chroma_qp_offset_list_enabled: bool, |
| 1918 | /// `diff_cu_chroma_qp_offset_depth`. |
| 1919 | pub diff_cu_chroma_qp_offset_depth: u32, |
| 1920 | /// `cb_qp_offset_list[i]` for `i` in `0..=chroma_qp_offset_list_len_minus1`. |
| 1921 | pub cb_qp_offset_list: Vec<i32>, |
| 1922 | /// `cr_qp_offset_list[i]`, same length as `cb_qp_offset_list`. |
| 1923 | pub cr_qp_offset_list: Vec<i32>, |
| 1924 | /// `log2_sao_offset_scale_luma`. |
| 1925 | pub log2_sao_offset_scale_luma: u32, |
| 1926 | /// `log2_sao_offset_scale_chroma`. |
| 1927 | pub log2_sao_offset_scale_chroma: u32, |
| 1928 | } |
| 1929 | |
| 1930 | impl PpsRangeExt { |
| 1931 | fn parse(r: &mut BitReader, transform_skip_enabled: bool) -> Result<Self> { |
| 1932 | let mut e = PpsRangeExt::default(); |
| 1933 | if transform_skip_enabled { |
| 1934 | e.log2_max_transform_skip_block_size_minus2 = r.read_ue()?; |
| 1935 | } |
| 1936 | e.cross_component_prediction_enabled = r.read_bit()?; |
| 1937 | e.chroma_qp_offset_list_enabled = r.read_bit()?; |
| 1938 | if e.chroma_qp_offset_list_enabled { |
| 1939 | e.diff_cu_chroma_qp_offset_depth = r.read_ue()?; |
| 1940 | let len = r.read_ue()? + 1; |
| 1941 | if len > 6 { |
| 1942 | return Err(Error::corrupt("HEVC PPS: chroma_qp_offset_list_len_minus1")); |
| 1943 | } |
| 1944 | for _ in 0..len { |
| 1945 | e.cb_qp_offset_list.push(r.read_se()?); |
| 1946 | e.cr_qp_offset_list.push(r.read_se()?); |
| 1947 | } |
| 1948 | } |
| 1949 | e.log2_sao_offset_scale_luma = r.read_ue()?; |
| 1950 | e.log2_sao_offset_scale_chroma = r.read_ue()?; |
| 1951 | Ok(e) |
| 1952 | } |
| 1953 | } |