| 1 | |
| 2 | |
| 3 | use ec_core::{BitReader, Error, Result}; |
| 4 | |
| 5 | use crate::{ |
| 6 | MAX_SEGMENTS, NUM_REF_FRAMES, REFS_PER_FRAME, SEG_LVL_ALT_L, SEG_LVL_ALT_Q, SEG_LVL_MAX, |
| 7 | }; |
| 8 | |
| 9 | |
| 10 | const SYNC_CODE: [u8; 3] = [0x49, 0x83, 0x42]; |
| 11 | |
| 12 | const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 2, 0]; |
| 13 | |
| 14 | const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false]; |
| 15 | |
| 16 | const DEFAULT_REF_DELTAS: [i8; 4] = [1, 0, -1, -1]; |
| 17 | |
| 18 | const MAX_LOOP_FILTER: i32 = 63; |
| 19 | |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 22 | pub enum FrameType { |
| 23 | |
| 24 | Key, |
| 25 | |
| 26 | Inter, |
| 27 | } |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 34 | pub enum ColorSpace { |
| 35 | |
| 36 | Unknown, |
| 37 | |
| 38 | Bt601, |
| 39 | |
| 40 | Bt709, |
| 41 | |
| 42 | Smpte170, |
| 43 | |
| 44 | Smpte240, |
| 45 | |
| 46 | Bt2020, |
| 47 | |
| 48 | Reserved, |
| 49 | |
| 50 | Rgb, |
| 51 | } |
| 52 | |
| 53 | impl ColorSpace { |
| 54 | fn from_code(code: u32) -> ColorSpace { |
| 55 | match code { |
| 56 | 1 => ColorSpace::Bt601, |
| 57 | 2 => ColorSpace::Bt709, |
| 58 | 3 => ColorSpace::Smpte170, |
| 59 | 4 => ColorSpace::Smpte240, |
| 60 | 5 => ColorSpace::Bt2020, |
| 61 | 6 => ColorSpace::Reserved, |
| 62 | 7 => ColorSpace::Rgb, |
| 63 | _ => ColorSpace::Unknown, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | pub fn h273(self) -> Option<(u8, u8, u8)> { |
| 71 | match self { |
| 72 | ColorSpace::Bt601 => Some((5, 6, 6)), |
| 73 | ColorSpace::Bt709 => Some((1, 1, 1)), |
| 74 | ColorSpace::Smpte170 => Some((6, 6, 6)), |
| 75 | ColorSpace::Smpte240 => Some((7, 7, 7)), |
| 76 | ColorSpace::Bt2020 => Some((9, 14, 9)), |
| 77 | ColorSpace::Rgb => Some((1, 13, 0)), |
| 78 | ColorSpace::Unknown | ColorSpace::Reserved => None, |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 88 | #[repr(u8)] |
| 89 | pub enum InterpolationFilter { |
| 90 | |
| 91 | EighttapSmooth = 0, |
| 92 | |
| 93 | Eighttap = 1, |
| 94 | |
| 95 | EighttapSharp = 2, |
| 96 | |
| 97 | Bilinear = 3, |
| 98 | |
| 99 | Switchable = 4, |
| 100 | } |
| 101 | |
| 102 | |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 104 | pub struct LoopFilterParams { |
| 105 | |
| 106 | pub level: u8, |
| 107 | |
| 108 | pub sharpness: u8, |
| 109 | |
| 110 | pub delta_enabled: bool, |
| 111 | |
| 112 | pub delta_update: bool, |
| 113 | |
| 114 | |
| 115 | pub ref_deltas: [i8; 4], |
| 116 | |
| 117 | pub mode_deltas: [i8; 2], |
| 118 | } |
| 119 | |
| 120 | impl Default for LoopFilterParams { |
| 121 | fn default() -> LoopFilterParams { |
| 122 | LoopFilterParams { |
| 123 | level: 0, |
| 124 | sharpness: 0, |
| 125 | delta_enabled: false, |
| 126 | delta_update: false, |
| 127 | ref_deltas: DEFAULT_REF_DELTAS, |
| 128 | mode_deltas: [0; 2], |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | |
| 134 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 135 | pub struct QuantizationParams { |
| 136 | |
| 137 | pub base_q_idx: u8, |
| 138 | |
| 139 | pub delta_q_y_dc: i8, |
| 140 | |
| 141 | pub delta_q_uv_dc: i8, |
| 142 | |
| 143 | pub delta_q_uv_ac: i8, |
| 144 | } |
| 145 | |
| 146 | impl QuantizationParams { |
| 147 | |
| 148 | |
| 149 | |
| 150 | pub fn lossless(&self) -> bool { |
| 151 | self.base_q_idx == 0 |
| 152 | && self.delta_q_y_dc == 0 |
| 153 | && self.delta_q_uv_dc == 0 |
| 154 | && self.delta_q_uv_ac == 0 |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 165 | pub struct SegmentationParams { |
| 166 | |
| 167 | pub enabled: bool, |
| 168 | |
| 169 | pub update_map: bool, |
| 170 | |
| 171 | |
| 172 | pub temporal_update: bool, |
| 173 | |
| 174 | pub update_data: bool, |
| 175 | |
| 176 | |
| 177 | pub abs_or_delta_update: bool, |
| 178 | |
| 179 | |
| 180 | pub tree_probs: [u8; 7], |
| 181 | |
| 182 | |
| 183 | pub pred_probs: [u8; 3], |
| 184 | |
| 185 | |
| 186 | pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS], |
| 187 | |
| 188 | pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS], |
| 189 | } |
| 190 | |
| 191 | |
| 192 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 193 | pub struct TileInfo { |
| 194 | |
| 195 | pub cols_log2: u8, |
| 196 | |
| 197 | pub rows_log2: u8, |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 208 | pub struct FrameHeader { |
| 209 | |
| 210 | |
| 211 | pub profile: u8, |
| 212 | |
| 213 | |
| 214 | pub show_existing_frame: bool, |
| 215 | |
| 216 | |
| 217 | pub frame_to_show_map_idx: u8, |
| 218 | |
| 219 | pub frame_type: FrameType, |
| 220 | |
| 221 | |
| 222 | pub show_frame: bool, |
| 223 | |
| 224 | |
| 225 | pub error_resilient_mode: bool, |
| 226 | |
| 227 | pub intra_only: bool, |
| 228 | |
| 229 | pub frame_is_intra: bool, |
| 230 | |
| 231 | pub bit_depth: u8, |
| 232 | |
| 233 | pub color_space: ColorSpace, |
| 234 | |
| 235 | pub color_range: bool, |
| 236 | |
| 237 | pub subsampling_x: u8, |
| 238 | |
| 239 | pub subsampling_y: u8, |
| 240 | |
| 241 | pub width: u32, |
| 242 | |
| 243 | pub height: u32, |
| 244 | |
| 245 | pub render_width: u32, |
| 246 | |
| 247 | pub render_height: u32, |
| 248 | |
| 249 | |
| 250 | pub refresh_frame_flags: u8, |
| 251 | |
| 252 | pub ref_frame_idx: [u8; REFS_PER_FRAME], |
| 253 | |
| 254 | pub ref_frame_sign_bias: [bool; REFS_PER_FRAME], |
| 255 | |
| 256 | pub allow_high_precision_mv: bool, |
| 257 | |
| 258 | pub interpolation_filter: InterpolationFilter, |
| 259 | |
| 260 | pub reset_frame_context: u8, |
| 261 | |
| 262 | |
| 263 | pub refresh_frame_context: bool, |
| 264 | |
| 265 | pub frame_parallel_decoding_mode: bool, |
| 266 | |
| 267 | pub frame_context_idx: u8, |
| 268 | |
| 269 | pub loop_filter: LoopFilterParams, |
| 270 | |
| 271 | pub quantization: QuantizationParams, |
| 272 | |
| 273 | pub segmentation: SegmentationParams, |
| 274 | |
| 275 | pub tile_info: TileInfo, |
| 276 | |
| 277 | |
| 278 | |
| 279 | pub header_size_in_bytes: u16, |
| 280 | |
| 281 | |
| 282 | pub uncompressed_header_size: u8, |
| 283 | } |
| 284 | |
| 285 | impl FrameHeader { |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | pub fn segment_qindex(&self, segment_id: usize) -> u8 { |
| 293 | let base = self.quantization.base_q_idx as i32; |
| 294 | let seg = &self.segmentation; |
| 295 | if !seg.enabled |
| 296 | || segment_id >= MAX_SEGMENTS |
| 297 | || !seg.feature_enabled[segment_id][SEG_LVL_ALT_Q] |
| 298 | { |
| 299 | return self.quantization.base_q_idx; |
| 300 | } |
| 301 | let data = seg.feature_data[segment_id][SEG_LVL_ALT_Q] as i32; |
| 302 | let q = if seg.abs_or_delta_update { |
| 303 | data |
| 304 | } else { |
| 305 | base + data |
| 306 | }; |
| 307 | q.clamp(0, 255) as u8 |
| 308 | } |
| 309 | |
| 310 | |
| 311 | |
| 312 | pub fn segment_dequant(&self, segment_id: usize) -> SegmentDequant { |
| 313 | let q = self.segment_qindex(segment_id) as i32; |
| 314 | let depth = self.bit_depth; |
| 315 | SegmentDequant { |
| 316 | luma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_y_dc as i32), |
| 317 | luma_ac: crate::quant::ac_q(depth, q), |
| 318 | chroma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_uv_dc as i32), |
| 319 | chroma_ac: crate::quant::ac_q(depth, q + self.quantization.delta_q_uv_ac as i32), |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | pub fn loop_filter_levels(&self, segment_id: usize) -> [[u8; 2]; 4] { |
| 330 | let lf = &self.loop_filter; |
| 331 | let seg = &self.segmentation; |
| 332 | let mut lvl_seg = lf.level as i32; |
| 333 | if seg.enabled |
| 334 | && segment_id < MAX_SEGMENTS |
| 335 | && seg.feature_enabled[segment_id][SEG_LVL_ALT_L] |
| 336 | { |
| 337 | let data = seg.feature_data[segment_id][SEG_LVL_ALT_L] as i32; |
| 338 | let v = if seg.abs_or_delta_update { |
| 339 | data |
| 340 | } else { |
| 341 | lvl_seg + data |
| 342 | }; |
| 343 | lvl_seg = v.clamp(0, MAX_LOOP_FILTER); |
| 344 | } |
| 345 | |
| 346 | if !lf.delta_enabled { |
| 347 | return [[lvl_seg as u8; 2]; 4]; |
| 348 | } |
| 349 | let shift = lvl_seg >> 5; |
| 350 | let mut out = [[0u8; 2]; 4]; |
| 351 | let intra = |
| 352 | (lvl_seg + ((lf.ref_deltas[0] as i32) << shift)).clamp(0, MAX_LOOP_FILTER) as u8; |
| 353 | out[0] = [intra, intra]; |
| 354 | for (reference, levels) in out.iter_mut().enumerate().skip(1) { |
| 355 | for (mode, slot) in levels.iter_mut().enumerate() { |
| 356 | let level = lvl_seg |
| 357 | + ((lf.ref_deltas[reference] as i32) << shift) |
| 358 | + ((lf.mode_deltas[mode] as i32) << shift); |
| 359 | *slot = level.clamp(0, MAX_LOOP_FILTER) as u8; |
| 360 | } |
| 361 | } |
| 362 | out |
| 363 | } |
| 364 | |
| 365 | |
| 366 | pub fn mi_cols(&self) -> u32 { |
| 367 | self.width.div_ceil(8) |
| 368 | } |
| 369 | |
| 370 | |
| 371 | pub fn mi_rows(&self) -> u32 { |
| 372 | self.height.div_ceil(8) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | impl Default for FrameHeader { |
| 377 | fn default() -> FrameHeader { |
| 378 | FrameHeader { |
| 379 | profile: 0, |
| 380 | show_existing_frame: false, |
| 381 | frame_to_show_map_idx: 0, |
| 382 | frame_type: FrameType::Key, |
| 383 | show_frame: true, |
| 384 | error_resilient_mode: false, |
| 385 | intra_only: false, |
| 386 | frame_is_intra: true, |
| 387 | bit_depth: 8, |
| 388 | color_space: ColorSpace::Unknown, |
| 389 | color_range: false, |
| 390 | subsampling_x: 1, |
| 391 | subsampling_y: 1, |
| 392 | width: 0, |
| 393 | height: 0, |
| 394 | render_width: 0, |
| 395 | render_height: 0, |
| 396 | refresh_frame_flags: 0, |
| 397 | ref_frame_idx: [0; REFS_PER_FRAME], |
| 398 | ref_frame_sign_bias: [false; REFS_PER_FRAME], |
| 399 | allow_high_precision_mv: false, |
| 400 | interpolation_filter: InterpolationFilter::Eighttap, |
| 401 | reset_frame_context: 0, |
| 402 | refresh_frame_context: false, |
| 403 | frame_parallel_decoding_mode: false, |
| 404 | frame_context_idx: 0, |
| 405 | loop_filter: LoopFilterParams::default(), |
| 406 | quantization: QuantizationParams::default(), |
| 407 | segmentation: SegmentationParams::default(), |
| 408 | tile_info: TileInfo::default(), |
| 409 | header_size_in_bytes: 0, |
| 410 | uncompressed_header_size: 0, |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | |
| 416 | |
| 417 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 418 | pub struct SegmentDequant { |
| 419 | |
| 420 | pub luma_dc: i16, |
| 421 | |
| 422 | pub luma_ac: i16, |
| 423 | |
| 424 | pub chroma_dc: i16, |
| 425 | |
| 426 | pub chroma_ac: i16, |
| 427 | } |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 435 | struct ColorConfig { |
| 436 | bit_depth: u8, |
| 437 | color_space: ColorSpace, |
| 438 | color_range: bool, |
| 439 | subsampling_x: u8, |
| 440 | subsampling_y: u8, |
| 441 | } |
| 442 | |
| 443 | impl ColorConfig { |
| 444 | |
| 445 | fn apply(&self, h: &mut FrameHeader) { |
| 446 | h.bit_depth = self.bit_depth; |
| 447 | h.color_space = self.color_space; |
| 448 | h.color_range = self.color_range; |
| 449 | h.subsampling_x = self.subsampling_x; |
| 450 | h.subsampling_y = self.subsampling_y; |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | impl Default for ColorConfig { |
| 455 | fn default() -> ColorConfig { |
| 456 | ColorConfig { |
| 457 | bit_depth: 8, |
| 458 | color_space: ColorSpace::Unknown, |
| 459 | color_range: false, |
| 460 | subsampling_x: 1, |
| 461 | subsampling_y: 1, |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | |
| 467 | |
| 468 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 469 | pub struct ReferenceSlot { |
| 470 | |
| 471 | pub valid: bool, |
| 472 | |
| 473 | pub width: u32, |
| 474 | |
| 475 | pub height: u32, |
| 476 | |
| 477 | pub bit_depth: u8, |
| 478 | |
| 479 | pub subsampling_x: u8, |
| 480 | |
| 481 | pub subsampling_y: u8, |
| 482 | } |
| 483 | |
| 484 | |
| 485 | |
| 486 | |
| 487 | |
| 488 | |
| 489 | #[derive(Debug, Clone, Default)] |
| 490 | pub struct Vp9Parser { |
| 491 | refs: [ReferenceSlot; NUM_REF_FRAMES], |
| 492 | segmentation: SegmentationParams, |
| 493 | loop_filter: LoopFilterParams, |
| 494 | color: ColorConfig, |
| 495 | } |
| 496 | |
| 497 | impl Vp9Parser { |
| 498 | |
| 499 | pub fn new() -> Vp9Parser { |
| 500 | Vp9Parser { |
| 501 | refs: [ReferenceSlot::default(); NUM_REF_FRAMES], |
| 502 | segmentation: SegmentationParams::default(), |
| 503 | loop_filter: LoopFilterParams::default(), |
| 504 | color: ColorConfig::default(), |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | |
| 509 | pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] { |
| 510 | &self.refs |
| 511 | } |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | |
| 517 | pub fn parse_frame(&mut self, frame: &[u8]) -> Result<FrameHeader> { |
| 518 | let mut r = BitReader::new(frame); |
| 519 | let mut h = FrameHeader::default(); |
| 520 | |
| 521 | let marker = r.read_bits(2)?; |
| 522 | if marker != 2 { |
| 523 | return Err(Error::corrupt(format!( |
| 524 | "VP9 frame marker is {marker}, expected 2" |
| 525 | ))); |
| 526 | } |
| 527 | let profile_low = r.read_bits(1)?; |
| 528 | let profile_high = r.read_bits(1)?; |
| 529 | h.profile = ((profile_high << 1) | profile_low) as u8; |
| 530 | if h.profile == 3 && r.read_bit()? { |
| 531 | return Err(Error::corrupt("VP9 profile 3 reserved_zero bit is set")); |
| 532 | } |
| 533 | |
| 534 | h.show_existing_frame = r.read_bit()?; |
| 535 | if h.show_existing_frame { |
| 536 | h.frame_to_show_map_idx = r.read_bits(3)? as u8; |
| 537 | let slot = &self.refs[h.frame_to_show_map_idx as usize]; |
| 538 | h.width = slot.width; |
| 539 | h.height = slot.height; |
| 540 | h.render_width = slot.width; |
| 541 | h.render_height = slot.height; |
| 542 | self.color.apply(&mut h); |
| 543 | h.show_frame = true; |
| 544 | h.uncompressed_header_size = header_bytes(&r); |
| 545 | return Ok(h); |
| 546 | } |
| 547 | |
| 548 | h.frame_type = if r.read_bit()? { |
| 549 | FrameType::Inter |
| 550 | } else { |
| 551 | FrameType::Key |
| 552 | }; |
| 553 | h.show_frame = r.read_bit()?; |
| 554 | h.error_resilient_mode = r.read_bit()?; |
| 555 | |
| 556 | if h.frame_type == FrameType::Key { |
| 557 | read_sync_code(&mut r)?; |
| 558 | read_color_config(&mut r, h.profile, &mut self.color)?; |
| 559 | self.color.apply(&mut h); |
| 560 | read_frame_size(&mut r, &mut h)?; |
| 561 | read_render_size(&mut r, &mut h)?; |
| 562 | h.refresh_frame_flags = 0xff; |
| 563 | h.frame_is_intra = true; |
| 564 | } else { |
| 565 | h.intra_only = if h.show_frame { false } else { r.read_bit()? }; |
| 566 | h.frame_is_intra = h.intra_only; |
| 567 | if !h.error_resilient_mode { |
| 568 | h.reset_frame_context = r.read_bits(2)? as u8; |
| 569 | } |
| 570 | if h.intra_only { |
| 571 | read_sync_code(&mut r)?; |
| 572 | if h.profile > 0 { |
| 573 | read_color_config(&mut r, h.profile, &mut self.color)?; |
| 574 | } else { |
| 575 | |
| 576 | self.color = ColorConfig { |
| 577 | bit_depth: 8, |
| 578 | color_space: ColorSpace::Bt601, |
| 579 | color_range: false, |
| 580 | subsampling_x: 1, |
| 581 | subsampling_y: 1, |
| 582 | }; |
| 583 | } |
| 584 | self.color.apply(&mut h); |
| 585 | h.refresh_frame_flags = r.read_bits(8)? as u8; |
| 586 | read_frame_size(&mut r, &mut h)?; |
| 587 | read_render_size(&mut r, &mut h)?; |
| 588 | } else { |
| 589 | |
| 590 | |
| 591 | self.color.apply(&mut h); |
| 592 | h.refresh_frame_flags = r.read_bits(8)? as u8; |
| 593 | for i in 0..REFS_PER_FRAME { |
| 594 | h.ref_frame_idx[i] = r.read_bits(3)? as u8; |
| 595 | h.ref_frame_sign_bias[i] = r.read_bit()?; |
| 596 | } |
| 597 | self.read_frame_size_with_refs(&mut r, &mut h)?; |
| 598 | h.allow_high_precision_mv = r.read_bit()?; |
| 599 | h.interpolation_filter = read_interpolation_filter(&mut r)?; |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | if !h.error_resilient_mode { |
| 604 | h.refresh_frame_context = r.read_bit()?; |
| 605 | h.frame_parallel_decoding_mode = r.read_bit()?; |
| 606 | } else { |
| 607 | h.refresh_frame_context = false; |
| 608 | h.frame_parallel_decoding_mode = true; |
| 609 | } |
| 610 | h.frame_context_idx = r.read_bits(2)? as u8; |
| 611 | |
| 612 | if h.frame_is_intra || h.error_resilient_mode { |
| 613 | |
| 614 | |
| 615 | |
| 616 | self.segmentation = SegmentationParams::default(); |
| 617 | self.loop_filter = LoopFilterParams::default(); |
| 618 | h.frame_context_idx = 0; |
| 619 | } |
| 620 | |
| 621 | self.read_loop_filter_params(&mut r, &mut h)?; |
| 622 | read_quantization_params(&mut r, &mut h)?; |
| 623 | self.read_segmentation_params(&mut r, &mut h)?; |
| 624 | read_tile_info(&mut r, &mut h)?; |
| 625 | h.header_size_in_bytes = r.read_bits(16)? as u16; |
| 626 | if h.header_size_in_bytes == 0 { |
| 627 | return Err(Error::corrupt("VP9 header_size_in_bytes is 0")); |
| 628 | } |
| 629 | h.uncompressed_header_size = header_bytes(&r); |
| 630 | |
| 631 | self.apply_refresh(&h); |
| 632 | Ok(h) |
| 633 | } |
| 634 | |
| 635 | |
| 636 | |
| 637 | fn apply_refresh(&mut self, h: &FrameHeader) { |
| 638 | let slot = ReferenceSlot { |
| 639 | valid: true, |
| 640 | width: h.width, |
| 641 | height: h.height, |
| 642 | bit_depth: h.bit_depth, |
| 643 | subsampling_x: h.subsampling_x, |
| 644 | subsampling_y: h.subsampling_y, |
| 645 | }; |
| 646 | for i in 0..NUM_REF_FRAMES { |
| 647 | if h.refresh_frame_flags & (1 << i) != 0 { |
| 648 | self.refs[i] = slot; |
| 649 | } |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | |
| 654 | |
| 655 | fn read_frame_size_with_refs(&self, r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { |
| 656 | let mut found = false; |
| 657 | for i in 0..REFS_PER_FRAME { |
| 658 | if r.read_bit()? { |
| 659 | let slot = &self.refs[h.ref_frame_idx[i] as usize]; |
| 660 | if !slot.valid { |
| 661 | return Err(Error::corrupt(format!( |
| 662 | "VP9 frame_size_with_refs names empty reference slot {}", |
| 663 | h.ref_frame_idx[i] |
| 664 | ))); |
| 665 | } |
| 666 | h.width = slot.width; |
| 667 | h.height = slot.height; |
| 668 | found = true; |
| 669 | break; |
| 670 | } |
| 671 | } |
| 672 | if !found { |
| 673 | read_frame_size(r, h)?; |
| 674 | } |
| 675 | read_render_size(r, h) |
| 676 | } |
| 677 | |
| 678 | fn read_loop_filter_params( |
| 679 | &mut self, |
| 680 | r: &mut BitReader<'_>, |
| 681 | h: &mut FrameHeader, |
| 682 | ) -> Result<()> { |
| 683 | let lf = &mut self.loop_filter; |
| 684 | lf.level = r.read_bits(6)? as u8; |
| 685 | lf.sharpness = r.read_bits(3)? as u8; |
| 686 | lf.delta_enabled = r.read_bit()?; |
| 687 | lf.delta_update = false; |
| 688 | if lf.delta_enabled { |
| 689 | lf.delta_update = r.read_bit()?; |
| 690 | if lf.delta_update { |
| 691 | for delta in lf.ref_deltas.iter_mut() { |
| 692 | if r.read_bit()? { |
| 693 | *delta = read_signed_magnitude(r, 6)? as i8; |
| 694 | } |
| 695 | } |
| 696 | for delta in lf.mode_deltas.iter_mut() { |
| 697 | if r.read_bit()? { |
| 698 | *delta = read_signed_magnitude(r, 6)? as i8; |
| 699 | } |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | h.loop_filter = *lf; |
| 704 | Ok(()) |
| 705 | } |
| 706 | |
| 707 | fn read_segmentation_params( |
| 708 | &mut self, |
| 709 | r: &mut BitReader<'_>, |
| 710 | h: &mut FrameHeader, |
| 711 | ) -> Result<()> { |
| 712 | let seg = &mut self.segmentation; |
| 713 | seg.enabled = r.read_bit()?; |
| 714 | seg.update_map = false; |
| 715 | seg.temporal_update = false; |
| 716 | seg.update_data = false; |
| 717 | if seg.enabled { |
| 718 | seg.update_map = r.read_bit()?; |
| 719 | if seg.update_map { |
| 720 | for prob in seg.tree_probs.iter_mut() { |
| 721 | *prob = if r.read_bit()? { |
| 722 | r.read_bits(8)? as u8 |
| 723 | } else { |
| 724 | 255 |
| 725 | }; |
| 726 | } |
| 727 | seg.temporal_update = r.read_bit()?; |
| 728 | for prob in seg.pred_probs.iter_mut() { |
| 729 | *prob = if seg.temporal_update && r.read_bit()? { |
| 730 | r.read_bits(8)? as u8 |
| 731 | } else { |
| 732 | 255 |
| 733 | }; |
| 734 | } |
| 735 | } |
| 736 | seg.update_data = r.read_bit()?; |
| 737 | if seg.update_data { |
| 738 | seg.abs_or_delta_update = r.read_bit()?; |
| 739 | for segment in 0..MAX_SEGMENTS { |
| 740 | for feature in 0..SEG_LVL_MAX { |
| 741 | let enabled = r.read_bit()?; |
| 742 | seg.feature_enabled[segment][feature] = enabled; |
| 743 | let mut value = 0i32; |
| 744 | if enabled { |
| 745 | let bits = SEG_FEATURE_BITS[feature]; |
| 746 | if bits > 0 { |
| 747 | value = r.read_bits(bits)? as i32; |
| 748 | } |
| 749 | if SEG_FEATURE_SIGNED[feature] && r.read_bit()? { |
| 750 | value = -value; |
| 751 | } |
| 752 | } |
| 753 | seg.feature_data[segment][feature] = value as i16; |
| 754 | } |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | h.segmentation = *seg; |
| 759 | Ok(()) |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | |
| 764 | |
| 765 | fn header_bytes(r: &BitReader<'_>) -> u8 { |
| 766 | u8::try_from(r.bit_position().div_ceil(8)).unwrap_or(u8::MAX) |
| 767 | } |
| 768 | |
| 769 | fn read_sync_code(r: &mut BitReader<'_>) -> Result<()> { |
| 770 | let code = [ |
| 771 | r.read_bits(8)? as u8, |
| 772 | r.read_bits(8)? as u8, |
| 773 | r.read_bits(8)? as u8, |
| 774 | ]; |
| 775 | if code != SYNC_CODE { |
| 776 | return Err(Error::corrupt(format!( |
| 777 | "VP9 frame sync code is {code:02x?}, expected {SYNC_CODE:02x?}" |
| 778 | ))); |
| 779 | } |
| 780 | Ok(()) |
| 781 | } |
| 782 | |
| 783 | |
| 784 | fn read_color_config(r: &mut BitReader<'_>, profile: u8, c: &mut ColorConfig) -> Result<()> { |
| 785 | c.bit_depth = if profile >= 2 { |
| 786 | if r.read_bit()? { |
| 787 | 12 |
| 788 | } else { |
| 789 | 10 |
| 790 | } |
| 791 | } else { |
| 792 | 8 |
| 793 | }; |
| 794 | c.color_space = ColorSpace::from_code(r.read_bits(3)?); |
| 795 | if c.color_space != ColorSpace::Rgb { |
| 796 | c.color_range = r.read_bit()?; |
| 797 | if profile == 1 || profile == 3 { |
| 798 | c.subsampling_x = r.read_bits(1)? as u8; |
| 799 | c.subsampling_y = r.read_bits(1)? as u8; |
| 800 | if r.read_bit()? { |
| 801 | return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); |
| 802 | } |
| 803 | } else { |
| 804 | c.subsampling_x = 1; |
| 805 | c.subsampling_y = 1; |
| 806 | } |
| 807 | } else { |
| 808 | |
| 809 | c.color_range = true; |
| 810 | if profile == 1 || profile == 3 { |
| 811 | c.subsampling_x = 0; |
| 812 | c.subsampling_y = 0; |
| 813 | if r.read_bit()? { |
| 814 | return Err(Error::corrupt("VP9 color_config reserved_zero bit is set")); |
| 815 | } |
| 816 | } else { |
| 817 | return Err(Error::corrupt(format!( |
| 818 | "VP9 CS_RGB is not allowed in profile {profile}" |
| 819 | ))); |
| 820 | } |
| 821 | } |
| 822 | Ok(()) |
| 823 | } |
| 824 | |
| 825 | |
| 826 | fn read_frame_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { |
| 827 | h.width = r.read_bits(16)? + 1; |
| 828 | h.height = r.read_bits(16)? + 1; |
| 829 | Ok(()) |
| 830 | } |
| 831 | |
| 832 | |
| 833 | fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { |
| 834 | if r.read_bit()? { |
| 835 | h.render_width = r.read_bits(16)? + 1; |
| 836 | h.render_height = r.read_bits(16)? + 1; |
| 837 | } else { |
| 838 | h.render_width = h.width; |
| 839 | h.render_height = h.height; |
| 840 | } |
| 841 | Ok(()) |
| 842 | } |
| 843 | |
| 844 | |
| 845 | fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> { |
| 846 | if r.read_bit()? { |
| 847 | return Ok(InterpolationFilter::Switchable); |
| 848 | } |
| 849 | Ok(match r.read_bits(2)? { |
| 850 | 0 => InterpolationFilter::EighttapSmooth, |
| 851 | 1 => InterpolationFilter::Eighttap, |
| 852 | 2 => InterpolationFilter::EighttapSharp, |
| 853 | _ => InterpolationFilter::Bilinear, |
| 854 | }) |
| 855 | } |
| 856 | |
| 857 | |
| 858 | fn read_quantization_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { |
| 859 | h.quantization.base_q_idx = r.read_bits(8)? as u8; |
| 860 | h.quantization.delta_q_y_dc = read_delta_q(r)?; |
| 861 | h.quantization.delta_q_uv_dc = read_delta_q(r)?; |
| 862 | h.quantization.delta_q_uv_ac = read_delta_q(r)?; |
| 863 | Ok(()) |
| 864 | } |
| 865 | |
| 866 | |
| 867 | fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> { |
| 868 | if r.read_bit()? { |
| 869 | Ok(read_signed_magnitude(r, 4)? as i8) |
| 870 | } else { |
| 871 | Ok(0) |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | |
| 876 | fn read_signed_magnitude(r: &mut BitReader<'_>, n: u32) -> Result<i32> { |
| 877 | let value = r.read_bits(n)? as i32; |
| 878 | Ok(if r.read_bit()? { -value } else { value }) |
| 879 | } |
| 880 | |
| 881 | |
| 882 | fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { |
| 883 | |
| 884 | |
| 885 | |
| 886 | let sb64_cols = h.mi_cols().div_ceil(8); |
| 887 | let (min_log2, max_log2) = tile_cols_log2_bounds(sb64_cols); |
| 888 | let mut cols_log2 = min_log2; |
| 889 | while cols_log2 < max_log2 { |
| 890 | if r.read_bit()? { |
| 891 | cols_log2 += 1; |
| 892 | } else { |
| 893 | break; |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | |
| 898 | |
| 899 | |
| 900 | |
| 901 | let mut rows_log2 = 0u8; |
| 902 | if r.read_bit()? { |
| 903 | rows_log2 = 1 + u8::from(r.read_bit()?); |
| 904 | } |
| 905 | h.tile_info = TileInfo { |
| 906 | cols_log2, |
| 907 | rows_log2, |
| 908 | }; |
| 909 | Ok(()) |
| 910 | } |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) { |
| 919 | const MAX_TILE_WIDTH_B64: u32 = 64; |
| 920 | const MIN_TILE_WIDTH_B64: u32 = 4; |
| 921 | let mut min_log2 = 0u8; |
| 922 | while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols { |
| 923 | min_log2 += 1; |
| 924 | } |
| 925 | let mut max_log2 = 1u8; |
| 926 | while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 { |
| 927 | max_log2 += 1; |
| 928 | } |
| 929 | |
| 930 | let max_log2 = max_log2 - 1; |
| 931 | (min_log2, max_log2) |
| 932 | } |
| 933 | |
| 934 | #[cfg(test)] |
| 935 | mod tests { |
| 936 | use super::*; |
| 937 | |
| 938 | |
| 939 | |
| 940 | |
| 941 | #[test] |
| 942 | fn tile_bounds_match_the_spec_formulas() { |
| 943 | assert_eq!( |
| 944 | tile_cols_log2_bounds(1920u32.div_ceil(8).div_ceil(8)), |
| 945 | (0, 3) |
| 946 | ); |
| 947 | assert_eq!( |
| 948 | tile_cols_log2_bounds(3840u32.div_ceil(8).div_ceil(8)), |
| 949 | (0, 4) |
| 950 | ); |
| 951 | |
| 952 | assert_eq!(tile_cols_log2_bounds(4096).0, 6); |
| 953 | |
| 954 | |
| 955 | assert_eq!(tile_cols_log2_bounds(1), (0, 1)); |
| 956 | } |
| 957 | |
| 958 | #[test] |
| 959 | fn lossless_needs_every_delta_zero() { |
| 960 | let mut q = QuantizationParams::default(); |
| 961 | assert!(q.lossless()); |
| 962 | q.delta_q_uv_ac = -1; |
| 963 | assert!(!q.lossless()); |
| 964 | q.delta_q_uv_ac = 0; |
| 965 | q.base_q_idx = 1; |
| 966 | assert!(!q.lossless()); |
| 967 | } |
| 968 | |
| 969 | #[test] |
| 970 | fn filter_levels_apply_deltas_and_clamp() { |
| 971 | let mut h = FrameHeader { |
| 972 | loop_filter: LoopFilterParams { |
| 973 | level: 32, |
| 974 | delta_enabled: true, |
| 975 | ref_deltas: [1, 0, -1, -1], |
| 976 | mode_deltas: [0, 2], |
| 977 | ..LoopFilterParams::default() |
| 978 | }, |
| 979 | ..FrameHeader::default() |
| 980 | }; |
| 981 | |
| 982 | |
| 983 | let levels = h.loop_filter_levels(0); |
| 984 | assert_eq!(levels[0], [34, 34]); |
| 985 | assert_eq!(levels[3], [30, 34]); |
| 986 | |
| 987 | |
| 988 | |
| 989 | h.segmentation.enabled = true; |
| 990 | h.segmentation.feature_enabled[1][SEG_LVL_ALT_L] = true; |
| 991 | h.segmentation.feature_data[1][SEG_LVL_ALT_L] = -64; |
| 992 | assert_eq!(h.loop_filter_levels(1), [[1, 1], [0, 2], [0, 1], [0, 1]]); |
| 993 | |
| 994 | |
| 995 | h.loop_filter.delta_enabled = false; |
| 996 | assert_eq!(h.loop_filter_levels(0), [[32; 2]; 4]); |
| 997 | } |
| 998 | |
| 999 | #[test] |
| 1000 | fn segment_qindex_is_absolute_or_relative() { |
| 1001 | let mut h = FrameHeader { |
| 1002 | quantization: QuantizationParams { |
| 1003 | base_q_idx: 100, |
| 1004 | ..QuantizationParams::default() |
| 1005 | }, |
| 1006 | ..FrameHeader::default() |
| 1007 | }; |
| 1008 | h.segmentation.enabled = true; |
| 1009 | h.segmentation.feature_enabled[2][SEG_LVL_ALT_Q] = true; |
| 1010 | h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = -20; |
| 1011 | assert_eq!(h.segment_qindex(2), 80); |
| 1012 | assert_eq!(h.segment_qindex(0), 100); |
| 1013 | h.segmentation.abs_or_delta_update = true; |
| 1014 | assert_eq!(h.segment_qindex(2), 0); |
| 1015 | h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = 200; |
| 1016 | assert_eq!(h.segment_qindex(2), 200); |
| 1017 | } |
| 1018 | |
| 1019 | #[test] |
| 1020 | fn truncated_header_is_need_more_not_panic() { |
| 1021 | let mut p = Vp9Parser::new(); |
| 1022 | for len in 0..12 { |
| 1023 | let frame = vec![0x82u8; len]; |
| 1024 | assert!(p.parse_frame(&frame).is_err()); |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | #[test] |
| 1029 | fn bad_marker_and_sync_code_are_corrupt() { |
| 1030 | let mut p = Vp9Parser::new(); |
| 1031 | assert!(matches!( |
| 1032 | p.parse_frame(&[0x00, 0, 0, 0, 0, 0, 0, 0]), |
| 1033 | Err(Error::Corrupt { .. }) |
| 1034 | )); |
| 1035 | |
| 1036 | assert!(matches!( |
| 1037 | p.parse_frame(&[0x80, 0x00, 0x00, 0x00, 0, 0, 0, 0]), |
| 1038 | Err(Error::Corrupt { .. }) |
| 1039 | )); |
| 1040 | } |
| 1041 | } |