| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::cell::RefCell; |
| 13 | use std::sync::LazyLock; |
| 14 | |
| 15 | use ec_core::{Error, Result}; |
| 16 | |
| 17 | use crate::cdf; |
| 18 | use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; |
| 19 | use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; |
| 20 | use crate::msac::SymbolEncoder; |
| 21 | use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16}; |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | struct LrPlan { |
| 48 | |
| 49 | unit_size: u32, |
| 50 | |
| 51 | horz_units: u32, |
| 52 | vert_units: u32, |
| 53 | |
| 54 | |
| 55 | units: Vec<Option<crate::restoration::WienerInfo>>, |
| 56 | |
| 57 | |
| 58 | |
| 59 | reference: crate::restoration::WienerInfo, |
| 60 | } |
| 61 | |
| 62 | thread_local! { |
| 63 | static LR_PLAN: std::cell::RefCell<Option<LrPlan>> = const { std::cell::RefCell::new(None) }; |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | pub(crate) fn arm_lr( |
| 69 | unit_size: u32, |
| 70 | horz_units: u32, |
| 71 | vert_units: u32, |
| 72 | units: Vec<Option<crate::restoration::WienerInfo>>, |
| 73 | ) { |
| 74 | LR_PLAN.with(|c| { |
| 75 | *c.borrow_mut() = (!units.is_empty()).then(|| LrPlan { |
| 76 | unit_size, |
| 77 | horz_units, |
| 78 | vert_units, |
| 79 | units, |
| 80 | reference: crate::restoration::WienerInfo::default(), |
| 81 | }); |
| 82 | }); |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) { |
| 90 | LR_PLAN.with(|c| { |
| 91 | let mut plan = c.borrow_mut(); |
| 92 | let Some(plan) = plan.as_mut() else { return }; |
| 93 | let unit = plan.unit_size; |
| 94 | let rcol0 = (mi_col * 4).div_ceil(unit); |
| 95 | let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units); |
| 96 | let rrow0 = (mi_row * 4).div_ceil(unit); |
| 97 | let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units); |
| 98 | for rrow in rrow0..rrow1 { |
| 99 | for rcol in rcol0..rcol1 { |
| 100 | let info = plan.units[(rcol + rrow * plan.horz_units) as usize]; |
| 101 | enc.symbol(usize::from(info.is_some()), &mut cdfs.restore_wiener); |
| 102 | if let Some(info) = info { |
| 103 | crate::restoration::write_wiener_filter( |
| 104 | enc, |
| 105 | false, |
| 106 | &mut plan.reference, |
| 107 | &info, |
| 108 | ); |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | }); |
| 113 | } |
| 114 | |
| 115 | |
| 116 | |
| 117 | const SB_MI_W: u32 = 16; |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 127 | pub(crate) struct TileRect { |
| 128 | pub(crate) sb_col0: u32, |
| 129 | pub(crate) sb_col1: u32, |
| 130 | pub(crate) sb_row0: u32, |
| 131 | pub(crate) sb_row1: u32, |
| 132 | pub(crate) mi_col0: u32, |
| 133 | pub(crate) mi_col1: u32, |
| 134 | pub(crate) mi_row0: u32, |
| 135 | pub(crate) mi_row1: u32, |
| 136 | } |
| 137 | |
| 138 | impl TileRect { |
| 139 | |
| 140 | pub(crate) fn whole(mi_cols: u32, mi_rows: u32) -> Self { |
| 141 | let (cols, rows) = block_grid(mi_cols, mi_rows); |
| 142 | Self { |
| 143 | sb_col0: 0, |
| 144 | sb_col1: cols.div_ceil(2), |
| 145 | sb_row0: 0, |
| 146 | sb_row1: rows.div_ceil(2), |
| 147 | mi_col0: 0, |
| 148 | mi_col1: mi_cols, |
| 149 | mi_row0: 0, |
| 150 | mi_row1: mi_rows, |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | #[derive(Clone, Debug)] |
| 161 | pub(crate) struct TileLayout { |
| 162 | pub(crate) cols_log2: u32, |
| 163 | pub(crate) rows_log2: u32, |
| 164 | |
| 165 | col_starts_sb: Vec<u32>, |
| 166 | |
| 167 | row_starts_sb: Vec<u32>, |
| 168 | mi_cols: u32, |
| 169 | mi_rows: u32, |
| 170 | } |
| 171 | |
| 172 | impl TileLayout { |
| 173 | |
| 174 | pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self { |
| 175 | let (cols32, rows32) = block_grid(mi_cols, mi_rows); |
| 176 | let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2)); |
| 177 | let starts = |total: u32, log2: u32| { |
| 178 | let step = total.div_ceil(1 << log2).max(1); |
| 179 | let mut v: Vec<u32> = (0..total).step_by(step as usize).collect(); |
| 180 | v.push(total); |
| 181 | v |
| 182 | }; |
| 183 | Self { |
| 184 | cols_log2, |
| 185 | rows_log2, |
| 186 | col_starts_sb: starts(sb_cols, cols_log2), |
| 187 | row_starts_sb: starts(sb_rows, rows_log2), |
| 188 | mi_cols, |
| 189 | mi_rows, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | pub(crate) fn cols(&self) -> u32 { |
| 194 | self.col_starts_sb.len() as u32 - 1 |
| 195 | } |
| 196 | |
| 197 | pub(crate) fn rows(&self) -> u32 { |
| 198 | self.row_starts_sb.len() as u32 - 1 |
| 199 | } |
| 200 | |
| 201 | pub(crate) fn count(&self) -> usize { |
| 202 | (self.cols() * self.rows()) as usize |
| 203 | } |
| 204 | |
| 205 | |
| 206 | pub(crate) fn mi_col_starts(&self) -> Vec<u32> { |
| 207 | let mut v: Vec<u32> = self.col_starts_sb[..self.cols() as usize] |
| 208 | .iter() |
| 209 | .map(|sb| sb * SB_MI_W) |
| 210 | .collect(); |
| 211 | v.push(self.mi_cols); |
| 212 | v |
| 213 | } |
| 214 | |
| 215 | pub(crate) fn mi_row_starts(&self) -> Vec<u32> { |
| 216 | let mut v: Vec<u32> = self.row_starts_sb[..self.rows() as usize] |
| 217 | .iter() |
| 218 | .map(|sb| sb * SB_MI_W) |
| 219 | .collect(); |
| 220 | v.push(self.mi_rows); |
| 221 | v |
| 222 | } |
| 223 | |
| 224 | |
| 225 | pub(crate) fn rect(&self, index: usize) -> TileRect { |
| 226 | let (r, c) = (index / self.cols() as usize, index % self.cols() as usize); |
| 227 | let (sb_col0, sb_col1) = (self.col_starts_sb[c], self.col_starts_sb[c + 1]); |
| 228 | let (sb_row0, sb_row1) = (self.row_starts_sb[r], self.row_starts_sb[r + 1]); |
| 229 | TileRect { |
| 230 | sb_col0, |
| 231 | sb_col1, |
| 232 | sb_row0, |
| 233 | sb_row1, |
| 234 | mi_col0: sb_col0 * SB_MI_W, |
| 235 | mi_col1: (sb_col1 * SB_MI_W).min(self.mi_cols), |
| 236 | mi_row0: sb_row0 * SB_MI_W, |
| 237 | mi_row1: (sb_row1 * SB_MI_W).min(self.mi_rows), |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | pub(crate) fn largest_tile(&self) -> usize { |
| 245 | (0..self.count()) |
| 246 | .max_by_key(|&i| { |
| 247 | let t = self.rect(i); |
| 248 | ((t.mi_col1 - t.mi_col0) as u64) * ((t.mi_row1 - t.mi_row0) as u64) |
| 249 | }) |
| 250 | .unwrap_or(0) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | |
| 255 | struct CdefIdxPlan { |
| 256 | |
| 257 | bits: u8, |
| 258 | |
| 259 | sb_cols: usize, |
| 260 | |
| 261 | grid: Vec<u8>, |
| 262 | |
| 263 | |
| 264 | |
| 265 | last: Option<usize>, |
| 266 | } |
| 267 | |
| 268 | thread_local! { |
| 269 | static CDEF_IDX: std::cell::RefCell<Option<CdefIdxPlan>> = |
| 270 | const { std::cell::RefCell::new(None) }; |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec<u8>) { |
| 277 | CDEF_IDX.with(|c| { |
| 278 | *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None }); |
| 279 | }); |
| 280 | } |
| 281 | |
| 282 | thread_local! { |
| 283 | static SIGN_BIAS: std::cell::Cell<crate::mvstack::SignBiasTable> = |
| 284 | const { std::cell::Cell::new(crate::mvstack::NO_SIGN_BIAS) }; |
| 285 | } |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) { |
| 295 | SIGN_BIAS.with(|c| c.set(sign_bias)); |
| 296 | } |
| 297 | |
| 298 | thread_local! { |
| 299 | static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 300 | } |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | pub(crate) fn arm_screen(on: bool) { |
| 310 | SCREEN.with(|c| c.set(on)); |
| 311 | } |
| 312 | |
| 313 | fn screen_armed() -> bool { |
| 314 | SCREEN.with(std::cell::Cell::get) |
| 315 | } |
| 316 | |
| 317 | thread_local! { |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | static INTRABC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | static INTRABC_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> = |
| 330 | const { std::cell::RefCell::new(None) }; |
| 331 | } |
| 332 | |
| 333 | |
| 334 | |
| 335 | pub(crate) fn arm_intrabc(on: bool) { |
| 336 | INTRABC.with(|c| c.set(on)); |
| 337 | } |
| 338 | |
| 339 | fn intrabc_armed() -> bool { |
| 340 | INTRABC.with(std::cell::Cell::get) |
| 341 | } |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | static INTRABC_HITS: [std::sync::atomic::AtomicUsize; 7] = |
| 349 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 350 | |
| 351 | fn note_intrabc(dv: (i32, i32)) { |
| 352 | INTRABC_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 353 | let px = (dv.0.abs() / 8).max(dv.1.abs() / 8).max(1) as usize; |
| 354 | let bucket = (usize::BITS - px.leading_zeros()) as usize; |
| 355 | INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 356 | } |
| 357 | |
| 358 | |
| 359 | |
| 360 | #[allow(dead_code)] |
| 361 | pub(crate) fn take_intrabc_hits() -> [usize; 7] { |
| 362 | std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 363 | } |
| 364 | |
| 365 | thread_local! { |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | static REFERENCE_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 373 | } |
| 374 | |
| 375 | |
| 376 | |
| 377 | pub(crate) fn arm_reference_select(on: bool) { |
| 378 | REFERENCE_SELECT.with(|c| c.set(on)); |
| 379 | } |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | fn record_block_compound(neighbours: &mut Neighbours, at_mi: (usize, usize), side: usize, block: &BlockCoeffs) { |
| 386 | if let Some(r1) = block.inter.and_then(|i| i.ref1) { |
| 387 | neighbours.record_compound_mi(at_mi, side, r1, 0, 1); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool { |
| 394 | let backward = |
| 395 | |r: i8| (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&r); |
| 396 | backward(ref0) == backward(ref1) |
| 397 | } |
| 398 | |
| 399 | thread_local! { |
| 400 | |
| 401 | |
| 402 | |
| 403 | static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> = |
| 404 | const { std::cell::Cell::new((7, 0, [0; 7])) }; |
| 405 | } |
| 406 | |
| 407 | |
| 408 | pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) { |
| 409 | ORDER_HINTS.with(|c| c.set((bits, order_hint, hints))); |
| 410 | } |
| 411 | |
| 412 | |
| 413 | |
| 414 | pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) { |
| 415 | ORDER_HINTS.with(std::cell::Cell::get) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | fn write_compound_ref_frames( |
| 427 | enc: &mut SymbolEncoder, |
| 428 | cdfs: &mut Cdfs, |
| 429 | above: Option<crate::mvstack::NeighbourRef>, |
| 430 | left: Option<crate::mvstack::NeighbourRef>, |
| 431 | above_ref: i8, |
| 432 | left_ref: i8, |
| 433 | (ref0, ref1): (i8, i8), |
| 434 | ) -> Result<()> { |
| 435 | use crate::mvstack::{ |
| 436 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 437 | LAST_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx, |
| 438 | single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, |
| 439 | uni_comp_ref_p1_ctx, |
| 440 | }; |
| 441 | let a = (above_ref > 0).then_some(above_ref); |
| 442 | let l = (left_ref > 0).then_some(left_ref); |
| 443 | let a1 = above.and_then(|n| n.ref1); |
| 444 | let l1 = left.and_then(|n| n.ref1); |
| 445 | let unidir = is_uni_comp_ref(ref0, ref1); |
| 446 | enc.symbol( |
| 447 | usize::from(!unidir), |
| 448 | &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)], |
| 449 | ); |
| 450 | if unidir { |
| 451 | let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME); |
| 452 | enc.symbol( |
| 453 | usize::from(both_backward), |
| 454 | &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0], |
| 455 | ); |
| 456 | if both_backward { |
| 457 | return Ok(()); |
| 458 | } |
| 459 | if ref0 != LAST_FRAME { |
| 460 | return Err(Error::unsupported( |
| 461 | "AV1 tile", |
| 462 | "a unidirectional compound pair this writer does not form", |
| 463 | )); |
| 464 | } |
| 465 | let past_last2 = ref1 != LAST2_FRAME; |
| 466 | enc.symbol( |
| 467 | usize::from(past_last2), |
| 468 | &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1], |
| 469 | ); |
| 470 | if past_last2 { |
| 471 | enc.symbol( |
| 472 | usize::from(ref1 == GOLDEN_FRAME), |
| 473 | &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2], |
| 474 | ); |
| 475 | } |
| 476 | return Ok(()); |
| 477 | } |
| 478 | let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME; |
| 479 | enc.symbol( |
| 480 | usize::from(far), |
| 481 | &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0], |
| 482 | ); |
| 483 | if far { |
| 484 | enc.symbol( |
| 485 | usize::from(ref0 == GOLDEN_FRAME), |
| 486 | &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2], |
| 487 | ); |
| 488 | } else { |
| 489 | enc.symbol( |
| 490 | usize::from(ref0 == LAST2_FRAME), |
| 491 | &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1], |
| 492 | ); |
| 493 | } |
| 494 | let is_altref = ref1 == ALTREF_FRAME; |
| 495 | enc.symbol( |
| 496 | usize::from(is_altref), |
| 497 | &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0], |
| 498 | ); |
| 499 | if !is_altref { |
| 500 | enc.symbol( |
| 501 | usize::from(ref1 == ALTREF2_FRAME), |
| 502 | &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1], |
| 503 | ); |
| 504 | } |
| 505 | Ok(()) |
| 506 | } |
| 507 | |
| 508 | |
| 509 | |
| 510 | |
| 511 | static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 512 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 513 | static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] = |
| 514 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 515 | |
| 516 | |
| 517 | #[cfg(test)] |
| 518 | pub(crate) fn take_compound_mode_hits() -> [usize; 8] { |
| 519 | std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 520 | } |
| 521 | |
| 522 | |
| 523 | |
| 524 | #[cfg(test)] |
| 525 | pub(crate) fn take_compound_pair_hits() -> [usize; 7] { |
| 526 | std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 527 | } |
| 528 | |
| 529 | |
| 530 | |
| 531 | |
| 532 | |
| 533 | static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] = |
| 534 | [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; |
| 535 | |
| 536 | |
| 537 | #[cfg(test)] |
| 538 | pub(crate) fn take_compound_size_hits() -> [usize; 4] { |
| 539 | std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 540 | } |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | #[allow(clippy::too_many_arguments)] |
| 556 | fn write_compound_block( |
| 557 | enc: &mut SymbolEncoder, |
| 558 | cdfs: &mut Cdfs, |
| 559 | neighbours: &Neighbours, |
| 560 | grid: &crate::mvstack::MiGrid, |
| 561 | (mi_row, mi_col): (usize, usize), |
| 562 | (bw4, bh4): (usize, usize), |
| 563 | (has_above, has_left): (bool, bool), |
| 564 | info: InterInfo, |
| 565 | (mi_cols, mi_rows): (usize, usize), |
| 566 | ) -> Result<((i32, i32), (i32, i32), bool)> { |
| 567 | let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else { |
| 568 | return Err(Error::unsupported( |
| 569 | "AV1 tile", |
| 570 | "a compound block needs a second reference and a compound mode", |
| 571 | )); |
| 572 | }; |
| 573 | let above = has_above.then(|| neighbours.above_nbr(mi_col)); |
| 574 | let left = has_left.then(|| neighbours.left_nbr(mi_row)); |
| 575 | write_compound_ref_frames( |
| 576 | enc, |
| 577 | cdfs, |
| 578 | above, |
| 579 | left, |
| 580 | neighbours.above_ref[mi_col], |
| 581 | neighbours.left_ref[mi_row], |
| 582 | (info.ref_frame, ref1), |
| 583 | )?; |
| 584 | let stack = crate::mvstack::find_mv_stack_compound( |
| 585 | grid, |
| 586 | mi_row, |
| 587 | mi_col, |
| 588 | bw4, |
| 589 | bh4, |
| 590 | (info.ref_frame, ref1), |
| 591 | mi_cols, |
| 592 | mi_rows, |
| 593 | grid.sign_bias_table(), |
| 594 | &[(0, 0); 7], |
| 595 | None, |
| 596 | ); |
| 597 | let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)]; |
| 598 | if crate::envflags::env_flag!("EC_TRACE_MODE") { |
| 599 | eprintln!( |
| 600 | "EC_WCOMP mi_row={mi_row} mi_col={mi_col} mode={mode} ref0={} ref1={ref1} ctx={ctx} new_mv_ctx={} ref_mv_ctx={} stack={}", |
| 601 | info.ref_frame, stack.new_mv_ctx, stack.ref_mv_ctx, stack.entries.len() |
| 602 | ); |
| 603 | } |
| 604 | enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]); |
| 605 | |
| 606 | |
| 607 | let mvs = match info.mode { |
| 608 | InterMode::NearestNearestMv => stack.nearest_mv, |
| 609 | InterMode::GlobalGlobalMv => ((0, 0), (0, 0)), |
| 610 | InterMode::NearNearMv => { |
| 611 | |
| 612 | |
| 613 | |
| 614 | let idx = usize::from(info.ref_mv_idx) + 1; |
| 615 | let mut walk = 1usize; |
| 616 | while walk < 3 && stack.entries.len() > walk + 1 { |
| 617 | let advance = walk < idx; |
| 618 | enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]); |
| 619 | if !advance { |
| 620 | break; |
| 621 | } |
| 622 | walk += 1; |
| 623 | } |
| 624 | stack |
| 625 | .entries |
| 626 | .get(idx) |
| 627 | .map_or(stack.near_mv, |e| (e.mv0, e.mv1)) |
| 628 | } |
| 629 | InterMode::NearestNewMv | InterMode::NewNearestMv => { |
| 630 | |
| 631 | |
| 632 | |
| 633 | let base = stack |
| 634 | .entries |
| 635 | .first() |
| 636 | .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 637 | if matches!(info.mode, InterMode::NearestNewMv) { |
| 638 | write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?; |
| 639 | (stack.nearest_mv.0, info.mv1) |
| 640 | } else { |
| 641 | write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?; |
| 642 | (info.mv, stack.nearest_mv.1) |
| 643 | } |
| 644 | } |
| 645 | _ => { |
| 646 | let idx = usize::from(info.ref_mv_idx); |
| 647 | let mut walk = 0usize; |
| 648 | while walk < 2 && stack.entries.len() > walk + 1 { |
| 649 | let advance = walk < idx; |
| 650 | enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]); |
| 651 | if !advance { |
| 652 | break; |
| 653 | } |
| 654 | walk += 1; |
| 655 | } |
| 656 | let base = stack |
| 657 | .entries |
| 658 | .get(idx) |
| 659 | .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 660 | write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?; |
| 661 | write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?; |
| 662 | (info.mv, info.mv1) |
| 663 | } |
| 664 | }; |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | let _ = ORDER_HINTS.with(std::cell::Cell::get); |
| 676 | COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 677 | COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7] |
| 678 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 679 | COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)] |
| 680 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 681 | if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) { |
| 682 | eprintln!( |
| 683 | "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})", |
| 684 | info.mv, info.mv1, mvs.0, mvs.1 |
| 685 | ); |
| 686 | } |
| 687 | |
| 688 | Ok(( |
| 689 | mvs.0, |
| 690 | mvs.1, |
| 691 | matches!( |
| 692 | info.mode, |
| 693 | InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv |
| 694 | ), |
| 695 | )) |
| 696 | } |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | fn write_comp_mode( |
| 705 | enc: &mut SymbolEncoder, |
| 706 | cdfs: &mut Cdfs, |
| 707 | neighbours: &Neighbours, |
| 708 | (mi_r, mi_c): (usize, usize), |
| 709 | (has_above, has_left): (bool, bool), |
| 710 | compound: bool, |
| 711 | ) { |
| 712 | if !REFERENCE_SELECT.with(std::cell::Cell::get) { |
| 713 | return; |
| 714 | } |
| 715 | let above = has_above.then(|| neighbours.above_nbr(mi_c)); |
| 716 | let left = has_left.then(|| neighbours.left_nbr(mi_r)); |
| 717 | let ctx = crate::mvstack::reference_mode_ctx(above, left); |
| 718 | if crate::envflags::env_flag!("EC_TRACE_MODE") { |
| 719 | eprintln!( |
| 720 | "EC_WCM mi=({mi_r},{mi_c}) ctx={ctx} val={} a={:?} l={:?}", |
| 721 | usize::from(compound), |
| 722 | above.map(|n| (n.is_inter, n.ref0, n.ref1)), |
| 723 | left.map(|n| (n.is_inter, n.ref0, n.ref1)) |
| 724 | ); |
| 725 | } |
| 726 | enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]); |
| 727 | } |
| 728 | |
| 729 | |
| 730 | struct CdefIdxGuard; |
| 731 | |
| 732 | impl Drop for CdefIdxGuard { |
| 733 | fn drop(&mut self) { |
| 734 | CDEF_IDX.with(|c| *c.borrow_mut() = None); |
| 735 | LR_PLAN.with(|c| *c.borrow_mut() = None); |
| 736 | SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); |
| 737 | SCREEN.with(|c| c.set(false)); |
| 738 | REFERENCE_SELECT.with(|c| c.set(false)); |
| 739 | INTRABC.with(|c| c.set(false)); |
| 740 | INTRABC_GRID.with(|c| *c.borrow_mut() = None); |
| 741 | ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) { |
| 750 | if skip { |
| 751 | return; |
| 752 | } |
| 753 | CDEF_IDX.with(|c| { |
| 754 | let mut plan = c.borrow_mut(); |
| 755 | let Some(plan) = plan.as_mut() else { return }; |
| 756 | let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16); |
| 757 | if plan.last == Some(sb) { |
| 758 | return; |
| 759 | } |
| 760 | plan.last = Some(sb); |
| 761 | enc.literal( |
| 762 | u32::from(plan.grid.get(sb).copied().unwrap_or(0)), |
| 763 | u32::from(plan.bits), |
| 764 | ); |
| 765 | }); |
| 766 | } |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | fn ec_rng_trace(msg: impl FnOnce() -> String) { |
| 777 | use std::sync::atomic::{AtomicU8, Ordering}; |
| 778 | static ON: AtomicU8 = AtomicU8::new(2); |
| 779 | let on = match ON.load(Ordering::Relaxed) { |
| 780 | 2 => { |
| 781 | let on = u8::from(std::env::var_os("EC_RNG").is_some()); |
| 782 | ON.store(on, Ordering::Relaxed); |
| 783 | on |
| 784 | } |
| 785 | v => v, |
| 786 | }; |
| 787 | if on == 1 { |
| 788 | eprintln!("{}", msg()); |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | |
| 793 | const PARTITION_NONE: usize = 0; |
| 794 | |
| 795 | const PARTITION_SPLIT: usize = 3; |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | |
| 801 | const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9]; |
| 802 | |
| 803 | |
| 804 | |
| 805 | const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8]; |
| 806 | |
| 807 | |
| 808 | pub(crate) const BLOCK_MI: u32 = SB_MI / 2; |
| 809 | |
| 810 | |
| 811 | |
| 812 | pub(crate) const SUB_MI: u32 = BLOCK_MI / 2; |
| 813 | |
| 814 | |
| 815 | |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | pub(crate) fn has_half(pos: u32, side_mi: u32, bound: u32) -> bool { |
| 822 | pos + side_mi / 2 < bound |
| 823 | } |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | pub(crate) fn block_grid(mi_cols: u32, mi_rows: u32) -> (u32, u32) { |
| 832 | (mi_cols.div_ceil(BLOCK_MI), mi_rows.div_ceil(BLOCK_MI)) |
| 833 | } |
| 834 | |
| 835 | const DC_PRED: usize = 0; |
| 836 | |
| 837 | |
| 838 | |
| 839 | const V_PRED: usize = 1; |
| 840 | |
| 841 | |
| 842 | #[cfg(test)] |
| 843 | const H_PRED: usize = 2; |
| 844 | |
| 845 | |
| 846 | const D67_PRED: usize = 8; |
| 847 | |
| 848 | |
| 849 | |
| 850 | const INTRA_MODES: usize = 13; |
| 851 | |
| 852 | |
| 853 | |
| 854 | pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0]; |
| 855 | |
| 856 | |
| 857 | |
| 858 | const ANGLE_DELTA_ZERO: usize = 3; |
| 859 | |
| 860 | const SB_MI: u32 = 16; |
| 861 | |
| 862 | |
| 863 | const NUM_BASE_LEVELS: i32 = 2; |
| 864 | |
| 865 | |
| 866 | const TX_TYPE_DCT_DCT_SET2: usize = 1; |
| 867 | |
| 868 | |
| 869 | const COEFF_BASE_RANGE: i32 = 12; |
| 870 | |
| 871 | |
| 872 | const BR_STEP: i32 = 3; |
| 873 | |
| 874 | |
| 875 | const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE; |
| 876 | |
| 877 | |
| 878 | |
| 879 | const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19); |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { |
| 885 | match base_q_idx { |
| 886 | 0..=20 => 0, |
| 887 | 21..=60 => 1, |
| 888 | 61..=120 => 2, |
| 889 | _ => 3, |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | |
| 894 | |
| 895 | |
| 896 | fn element_prob(cdf: &[u16], element: usize) -> u16 { |
| 897 | cdf[element] - if element > 0 { cdf[element - 1] } else { 0 } |
| 898 | } |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] { |
| 904 | let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); |
| 905 | [32768 - split, 32768, 0] |
| 906 | } |
| 907 | |
| 908 | fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> { |
| 909 | if mi_cols == 0 |
| 910 | || mi_rows == 0 |
| 911 | || !mi_cols.is_multiple_of(SB_MI) |
| 912 | || !mi_rows.is_multiple_of(SB_MI) |
| 913 | { |
| 914 | return Err(Error::unsupported( |
| 915 | "AV1 tile", |
| 916 | "a key frame is written only for frames that are a whole number \ |
| 917 | of 64x64 superblocks", |
| 918 | )); |
| 919 | } |
| 920 | Ok(()) |
| 921 | } |
| 922 | |
| 923 | |
| 924 | |
| 925 | |
| 926 | |
| 927 | |
| 928 | |
| 929 | |
| 930 | |
| 931 | |
| 932 | |
| 933 | pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> { |
| 934 | check_superblocks(mi_cols, mi_rows)?; |
| 935 | let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); |
| 936 | |
| 937 | let mut enc = SymbolEncoder::new(); |
| 938 | for r in 0..sb_rows { |
| 939 | for c in 0..sb_cols { |
| 940 | |
| 941 | |
| 942 | |
| 943 | enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]); |
| 944 | |
| 945 | |
| 946 | |
| 947 | |
| 948 | |
| 949 | let skip_ctx = usize::from(r > 0) + usize::from(c > 0); |
| 950 | enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]); |
| 951 | |
| 952 | |
| 953 | enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]); |
| 954 | |
| 955 | |
| 956 | enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]); |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | } |
| 962 | } |
| 963 | Ok(enc.finish()) |
| 964 | } |
| 965 | |
| 966 | |
| 967 | |
| 968 | |
| 969 | |
| 970 | |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | pub fn dc_key_frame_tile( |
| 979 | mi_cols: u32, |
| 980 | mi_rows: u32, |
| 981 | base_q_idx: u8, |
| 982 | dc_level: i32, |
| 983 | ) -> Result<Vec<u8>> { |
| 984 | check_superblocks(mi_cols, mi_rows)?; |
| 985 | let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize; |
| 986 | dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks]) |
| 987 | } |
| 988 | |
| 989 | |
| 990 | |
| 991 | |
| 992 | |
| 993 | |
| 994 | |
| 995 | |
| 996 | |
| 997 | |
| 998 | |
| 999 | |
| 1000 | |
| 1001 | |
| 1002 | |
| 1003 | |
| 1004 | pub fn dc_key_frame_tile_levels( |
| 1005 | mi_cols: u32, |
| 1006 | mi_rows: u32, |
| 1007 | base_q_idx: u8, |
| 1008 | levels: &[i32], |
| 1009 | ) -> Result<Vec<u8>> { |
| 1010 | check_superblocks(mi_cols, mi_rows)?; |
| 1011 | let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); |
| 1012 | check_levels(levels, (sb_cols * sb_rows) as usize)?; |
| 1013 | let q_ctx = q_ctx_of(base_q_idx); |
| 1014 | let txb_skip_luma_64 = crate::cdf_state::pick( |
| 1015 | q_ctx, |
| 1016 | cdf::TXB_SKIP_LUMA_64_Q0, |
| 1017 | cdf::TXB_SKIP_LUMA_64_Q1, |
| 1018 | cdf::TXB_SKIP_LUMA_64, |
| 1019 | cdf::TXB_SKIP_LUMA_64_Q3, |
| 1020 | ); |
| 1021 | let base_eob_luma_64_dc = crate::cdf_state::pick( |
| 1022 | q_ctx, |
| 1023 | cdf::COEFF_BASE_EOB_LUMA_64_Q0[0], |
| 1024 | cdf::COEFF_BASE_EOB_LUMA_64_Q1[0], |
| 1025 | cdf::COEFF_BASE_EOB_LUMA_64[0], |
| 1026 | cdf::COEFF_BASE_EOB_LUMA_64_Q3[0], |
| 1027 | ); |
| 1028 | let txb_skip_chroma_32_none = crate::cdf_state::pick( |
| 1029 | q_ctx, |
| 1030 | cdf::TXB_SKIP_CHROMA_32_Q0[0], |
| 1031 | cdf::TXB_SKIP_CHROMA_32_Q1[0], |
| 1032 | cdf::TXB_SKIP_CHROMA_32[0], |
| 1033 | cdf::TXB_SKIP_CHROMA_32_Q3[0], |
| 1034 | ); |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | let mut above: Vec<Option<bool>> = vec![None; sb_cols as usize]; |
| 1041 | let mut enc = SymbolEncoder::new(); |
| 1042 | for r in 0..sb_rows { |
| 1043 | let mut left: Option<bool> = None; |
| 1044 | for c in 0..sb_cols { |
| 1045 | let dc_level = levels[(r * sb_cols + c) as usize]; |
| 1046 | let negative = dc_level < 0; |
| 1047 | |
| 1048 | enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]); |
| 1049 | |
| 1050 | |
| 1051 | |
| 1052 | enc.symbol_fixed(0, &cdf::SKIP[0]); |
| 1053 | enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]); |
| 1054 | enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]); |
| 1055 | |
| 1056 | write_dc_coeffs( |
| 1057 | &mut enc, |
| 1058 | dc_level, |
| 1059 | dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)), |
| 1060 | q_ctx, |
| 1061 | &txb_skip_luma_64, |
| 1062 | &base_eob_luma_64_dc, |
| 1063 | ); |
| 1064 | |
| 1065 | |
| 1066 | |
| 1067 | |
| 1068 | |
| 1069 | enc.symbol_fixed(1, &txb_skip_chroma_32_none); |
| 1070 | enc.symbol_fixed(1, &txb_skip_chroma_32_none); |
| 1071 | |
| 1072 | above[c as usize] = Some(negative); |
| 1073 | left = Some(negative); |
| 1074 | } |
| 1075 | } |
| 1076 | Ok(enc.finish()) |
| 1077 | } |
| 1078 | |
| 1079 | |
| 1080 | |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | |
| 1088 | |
| 1089 | |
| 1090 | |
| 1091 | pub fn split_dc_key_frame_tile( |
| 1092 | mi_cols: u32, |
| 1093 | mi_rows: u32, |
| 1094 | base_q_idx: u8, |
| 1095 | levels: &[i32], |
| 1096 | ) -> Result<Vec<u8>> { |
| 1097 | check_superblocks(mi_cols, mi_rows)?; |
| 1098 | let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); |
| 1099 | let (cols, rows) = (sb_cols * 2, sb_rows * 2); |
| 1100 | check_levels(levels, (cols * rows) as usize)?; |
| 1101 | let q_ctx = q_ctx_of(base_q_idx); |
| 1102 | let txb_skip_luma_32 = crate::cdf_state::pick( |
| 1103 | q_ctx, |
| 1104 | cdf::TXB_SKIP_LUMA_32_Q0, |
| 1105 | cdf::TXB_SKIP_LUMA_32_Q1, |
| 1106 | cdf::TXB_SKIP_LUMA_32, |
| 1107 | cdf::TXB_SKIP_LUMA_32_Q3, |
| 1108 | ); |
| 1109 | let base_eob_luma_32 = crate::cdf_state::pick( |
| 1110 | q_ctx, |
| 1111 | cdf::COEFF_BASE_EOB_LUMA_32_Q0[0], |
| 1112 | cdf::COEFF_BASE_EOB_LUMA_32_Q1[0], |
| 1113 | cdf::COEFF_BASE_EOB_LUMA_32[0], |
| 1114 | cdf::COEFF_BASE_EOB_LUMA_32_Q3[0], |
| 1115 | ); |
| 1116 | let txb_skip_chroma_16_0 = crate::cdf_state::pick( |
| 1117 | q_ctx, |
| 1118 | cdf::TXB_SKIP_CHROMA_16_Q0[0], |
| 1119 | cdf::TXB_SKIP_CHROMA_16_Q1[0], |
| 1120 | cdf::TXB_SKIP_CHROMA_16[0], |
| 1121 | cdf::TXB_SKIP_CHROMA_16_Q3[0], |
| 1122 | ); |
| 1123 | |
| 1124 | let mut above: Vec<Option<bool>> = vec![None; cols as usize]; |
| 1125 | let mut left: Vec<Option<bool>> = vec![None; rows as usize]; |
| 1126 | |
| 1127 | let mut enc = SymbolEncoder::new(); |
| 1128 | for sb_r in 0..sb_rows { |
| 1129 | |
| 1130 | |
| 1131 | left.iter_mut().for_each(|l| *l = None); |
| 1132 | for sb_c in 0..sb_cols { |
| 1133 | |
| 1134 | |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0); |
| 1141 | enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]); |
| 1142 | |
| 1143 | for quadrant in 0..4 { |
| 1144 | let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 1145 | let dc_level = levels[(r * cols + c) as usize]; |
| 1146 | let negative = dc_level < 0; |
| 1147 | |
| 1148 | enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]); |
| 1149 | enc.symbol_fixed(0, &cdf::SKIP[0]); |
| 1150 | enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]); |
| 1151 | |
| 1152 | |
| 1153 | enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[DC_PRED]); |
| 1154 | |
| 1155 | write_dc_coeffs( |
| 1156 | &mut enc, |
| 1157 | dc_level, |
| 1158 | dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])), |
| 1159 | q_ctx, |
| 1160 | &txb_skip_luma_32, |
| 1161 | &base_eob_luma_32, |
| 1162 | ); |
| 1163 | enc.symbol_fixed(1, &txb_skip_chroma_16_0); |
| 1164 | enc.symbol_fixed(1, &txb_skip_chroma_16_0); |
| 1165 | |
| 1166 | above[c as usize] = Some(negative); |
| 1167 | left[r as usize] = Some(negative); |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | Ok(enc.finish()) |
| 1172 | } |
| 1173 | |
| 1174 | |
| 1175 | |
| 1176 | |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | |
| 1181 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1182 | pub struct Coeff { |
| 1183 | |
| 1184 | pub row: u8, |
| 1185 | |
| 1186 | pub col: u8, |
| 1187 | |
| 1188 | |
| 1189 | pub level: i32, |
| 1190 | } |
| 1191 | |
| 1192 | |
| 1193 | |
| 1194 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 1195 | pub struct BlockCoeffs { |
| 1196 | |
| 1197 | pub luma: Vec<Coeff>, |
| 1198 | |
| 1199 | pub u: Vec<Coeff>, |
| 1200 | |
| 1201 | pub v: Vec<Coeff>, |
| 1202 | |
| 1203 | |
| 1204 | |
| 1205 | pub mode: u8, |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | pub uv_mode: u8, |
| 1212 | |
| 1213 | |
| 1214 | |
| 1215 | pub skip: bool, |
| 1216 | |
| 1217 | |
| 1218 | |
| 1219 | pub inter: Option<InterInfo>, |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | pub eight: Option<Vec<BlockCoeffs>>, |
| 1227 | |
| 1228 | |
| 1229 | |
| 1230 | |
| 1231 | |
| 1232 | |
| 1233 | pub palette: Option<PaletteY>, |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | |
| 1238 | pub palette_uv: Option<PaletteUv>, |
| 1239 | |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | pub tx_depth: u8, |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | |
| 1250 | |
| 1251 | |
| 1252 | |
| 1253 | |
| 1254 | |
| 1255 | |
| 1256 | |
| 1257 | |
| 1258 | pub dv: Option<(i32, i32)>, |
| 1259 | } |
| 1260 | |
| 1261 | |
| 1262 | |
| 1263 | |
| 1264 | |
| 1265 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 1266 | pub struct PaletteY { |
| 1267 | |
| 1268 | pub size: u8, |
| 1269 | |
| 1270 | pub colors: [u16; 8], |
| 1271 | |
| 1272 | pub map: Vec<u8>, |
| 1273 | } |
| 1274 | |
| 1275 | |
| 1276 | |
| 1277 | |
| 1278 | |
| 1279 | |
| 1280 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 1281 | pub struct PaletteUv { |
| 1282 | |
| 1283 | pub size: u8, |
| 1284 | |
| 1285 | |
| 1286 | |
| 1287 | pub u_colors: [u16; 8], |
| 1288 | |
| 1289 | |
| 1290 | pub v_colors: [u16; 8], |
| 1291 | |
| 1292 | |
| 1293 | pub map: Vec<u8>, |
| 1294 | } |
| 1295 | |
| 1296 | |
| 1297 | |
| 1298 | |
| 1299 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1300 | pub enum InterMode { |
| 1301 | |
| 1302 | NearestMv, |
| 1303 | |
| 1304 | |
| 1305 | NearMv, |
| 1306 | |
| 1307 | |
| 1308 | GlobalMv, |
| 1309 | |
| 1310 | |
| 1311 | NewMv, |
| 1312 | |
| 1313 | |
| 1314 | NearestNearestMv, |
| 1315 | |
| 1316 | |
| 1317 | |
| 1318 | NearNearMv, |
| 1319 | |
| 1320 | |
| 1321 | NearestNewMv, |
| 1322 | |
| 1323 | |
| 1324 | NewNearestMv, |
| 1325 | |
| 1326 | |
| 1327 | GlobalGlobalMv, |
| 1328 | |
| 1329 | |
| 1330 | NewNewMv, |
| 1331 | } |
| 1332 | |
| 1333 | impl InterMode { |
| 1334 | |
| 1335 | |
| 1336 | |
| 1337 | fn compound_index(self) -> Option<usize> { |
| 1338 | match self { |
| 1339 | InterMode::NearestNearestMv => Some(0), |
| 1340 | InterMode::NearNearMv => Some(1), |
| 1341 | InterMode::NearestNewMv => Some(2), |
| 1342 | InterMode::NewNearestMv => Some(3), |
| 1343 | InterMode::GlobalGlobalMv => Some(6), |
| 1344 | InterMode::NewNewMv => Some(7), |
| 1345 | _ => None, |
| 1346 | } |
| 1347 | } |
| 1348 | } |
| 1349 | |
| 1350 | |
| 1351 | |
| 1352 | |
| 1353 | |
| 1354 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1355 | pub struct InterInfo { |
| 1356 | |
| 1357 | pub mode: InterMode, |
| 1358 | |
| 1359 | pub mv: (i32, i32), |
| 1360 | |
| 1361 | |
| 1362 | pub ref_frame: i8, |
| 1363 | |
| 1364 | |
| 1365 | |
| 1366 | |
| 1367 | pub ref_mv_idx: u8, |
| 1368 | |
| 1369 | |
| 1370 | |
| 1371 | pub ref1: Option<i8>, |
| 1372 | |
| 1373 | |
| 1374 | pub mv1: (i32, i32), |
| 1375 | } |
| 1376 | |
| 1377 | impl From<Vec<Coeff>> for BlockCoeffs { |
| 1378 | |
| 1379 | fn from(luma: Vec<Coeff>) -> Self { |
| 1380 | Self { |
| 1381 | luma, |
| 1382 | ..Self::default() |
| 1383 | } |
| 1384 | } |
| 1385 | } |
| 1386 | |
| 1387 | |
| 1388 | const TX32: usize = 32; |
| 1389 | |
| 1390 | const BLOCK: usize = 32; |
| 1391 | |
| 1392 | |
| 1393 | const TX16: usize = 16; |
| 1394 | |
| 1395 | |
| 1396 | const TX8: usize = 8; |
| 1397 | |
| 1398 | const TX4: usize = 4; |
| 1399 | |
| 1400 | |
| 1401 | const SB: usize = 64; |
| 1402 | |
| 1403 | |
| 1404 | const SUB: usize = 16; |
| 1405 | |
| 1406 | |
| 1407 | |
| 1408 | const MI: usize = 4; |
| 1409 | |
| 1410 | |
| 1411 | |
| 1412 | #[derive(Clone, Copy, Default)] |
| 1413 | struct Neighbour { |
| 1414 | |
| 1415 | coded: bool, |
| 1416 | |
| 1417 | |
| 1418 | |
| 1419 | |
| 1420 | level: u8, |
| 1421 | |
| 1422 | dc: Option<bool>, |
| 1423 | } |
| 1424 | |
| 1425 | |
| 1426 | |
| 1427 | |
| 1428 | |
| 1429 | |
| 1430 | |
| 1431 | |
| 1432 | fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> { |
| 1433 | if mi_cols == 0 || mi_rows == 0 { |
| 1434 | return Err(Error::unsupported( |
| 1435 | "AV1 tile", |
| 1436 | "a coefficient key frame needs a nonzero mode-info grid", |
| 1437 | )); |
| 1438 | } |
| 1439 | Ok(()) |
| 1440 | } |
| 1441 | |
| 1442 | |
| 1443 | |
| 1444 | |
| 1445 | |
| 1446 | |
| 1447 | |
| 1448 | |
| 1449 | |
| 1450 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 1451 | pub enum Superblock { |
| 1452 | |
| 1453 | |
| 1454 | |
| 1455 | Whole(BlockCoeffs), |
| 1456 | |
| 1457 | |
| 1458 | Split(Vec<Quadrant>), |
| 1459 | } |
| 1460 | |
| 1461 | |
| 1462 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 1463 | pub enum Quadrant { |
| 1464 | |
| 1465 | |
| 1466 | Whole(BlockCoeffs), |
| 1467 | |
| 1468 | |
| 1469 | Split(Vec<BlockCoeffs>), |
| 1470 | } |
| 1471 | |
| 1472 | impl Quadrant { |
| 1473 | |
| 1474 | pub(crate) fn blocks(&self) -> &[BlockCoeffs] { |
| 1475 | match self { |
| 1476 | Quadrant::Whole(block) => std::slice::from_ref(block), |
| 1477 | Quadrant::Split(blocks) => blocks.as_slice(), |
| 1478 | } |
| 1479 | } |
| 1480 | } |
| 1481 | |
| 1482 | |
| 1483 | |
| 1484 | struct Neighbours { |
| 1485 | |
| 1486 | |
| 1487 | |
| 1488 | |
| 1489 | |
| 1490 | |
| 1491 | tile_row0_mi: usize, |
| 1492 | tile_col0_mi: usize, |
| 1493 | |
| 1494 | above: Vec<[Neighbour; 3]>, |
| 1495 | |
| 1496 | left: Vec<[Neighbour; 3]>, |
| 1497 | |
| 1498 | |
| 1499 | above_mode: Vec<usize>, |
| 1500 | |
| 1501 | left_mode: Vec<usize>, |
| 1502 | |
| 1503 | |
| 1504 | above_side: Vec<usize>, |
| 1505 | |
| 1506 | left_side: Vec<usize>, |
| 1507 | |
| 1508 | |
| 1509 | |
| 1510 | |
| 1511 | |
| 1512 | |
| 1513 | |
| 1514 | |
| 1515 | above_side_mi: Vec<usize>, |
| 1516 | |
| 1517 | left_side_mi: Vec<usize>, |
| 1518 | |
| 1519 | |
| 1520 | |
| 1521 | |
| 1522 | |
| 1523 | above_skip: Vec<bool>, |
| 1524 | |
| 1525 | left_skip: Vec<bool>, |
| 1526 | |
| 1527 | |
| 1528 | |
| 1529 | |
| 1530 | |
| 1531 | above_tx: Vec<u8>, |
| 1532 | |
| 1533 | |
| 1534 | left_tx: Vec<u8>, |
| 1535 | |
| 1536 | |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | above_txfm: Vec<u8>, |
| 1541 | |
| 1542 | left_txfm: Vec<u8>, |
| 1543 | |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | |
| 1548 | |
| 1549 | |
| 1550 | above_palette_size: Vec<u8>, |
| 1551 | |
| 1552 | left_palette_size: Vec<u8>, |
| 1553 | |
| 1554 | |
| 1555 | |
| 1556 | |
| 1557 | |
| 1558 | |
| 1559 | pending_palette: Option<(u8, [u16; 8])>, |
| 1560 | |
| 1561 | above_palette_colors: Vec<[u16; 8]>, |
| 1562 | |
| 1563 | |
| 1564 | |
| 1565 | above_palette_uv_size: Vec<u8>, |
| 1566 | left_palette_uv_size: Vec<u8>, |
| 1567 | above_palette_uv_colors: Vec<[u16; 8]>, |
| 1568 | left_palette_uv_colors: Vec<[u16; 8]>, |
| 1569 | |
| 1570 | pending_palette_uv: Option<(u8, [u16; 8])>, |
| 1571 | |
| 1572 | left_palette_colors: Vec<[u16; 8]>, |
| 1573 | |
| 1574 | |
| 1575 | above_inter: Vec<bool>, |
| 1576 | |
| 1577 | left_inter: Vec<bool>, |
| 1578 | |
| 1579 | |
| 1580 | |
| 1581 | above_ref: Vec<i8>, |
| 1582 | |
| 1583 | left_ref: Vec<i8>, |
| 1584 | |
| 1585 | |
| 1586 | |
| 1587 | |
| 1588 | above_ref1: Vec<Option<i8>>, |
| 1589 | |
| 1590 | left_ref1: Vec<Option<i8>>, |
| 1591 | |
| 1592 | |
| 1593 | |
| 1594 | above_comp_group_idx: Vec<u8>, |
| 1595 | |
| 1596 | left_comp_group_idx: Vec<u8>, |
| 1597 | |
| 1598 | above_compound_idx: Vec<u8>, |
| 1599 | |
| 1600 | left_compound_idx: Vec<u8>, |
| 1601 | |
| 1602 | |
| 1603 | |
| 1604 | |
| 1605 | |
| 1606 | mi_cols: usize, |
| 1607 | mi_rows: usize, |
| 1608 | } |
| 1609 | |
| 1610 | |
| 1611 | |
| 1612 | |
| 1613 | |
| 1614 | #[derive(Clone, Copy, Default)] |
| 1615 | struct Around { |
| 1616 | |
| 1617 | above_coded: bool, |
| 1618 | |
| 1619 | left_coded: bool, |
| 1620 | |
| 1621 | |
| 1622 | dc_vote: i32, |
| 1623 | } |
| 1624 | |
| 1625 | impl Neighbours { |
| 1626 | |
| 1627 | |
| 1628 | |
| 1629 | |
| 1630 | fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self { |
| 1631 | Self { |
| 1632 | tile_row0_mi: 0, |
| 1633 | tile_col0_mi: 0, |
| 1634 | above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)], |
| 1635 | left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], |
| 1636 | above_mode: vec![DC_PRED; cols], |
| 1637 | left_mode: vec![DC_PRED; rows], |
| 1638 | above_side: vec![SB; cols], |
| 1639 | left_side: vec![SB; rows], |
| 1640 | above_side_mi: vec![SB; cols * (SUB / MI)], |
| 1641 | left_side_mi: vec![SB; rows * (SUB / MI)], |
| 1642 | above_skip: vec![false; cols * (SUB / MI)], |
| 1643 | left_skip: vec![false; rows * (SUB / MI)], |
| 1644 | above_inter: vec![false; cols * (SUB / MI)], |
| 1645 | left_inter: vec![false; rows * (SUB / MI)], |
| 1646 | above_ref: vec![-1; cols * (SUB / MI)], |
| 1647 | left_ref: vec![-1; rows * (SUB / MI)], |
| 1648 | above_ref1: vec![None; cols * (SUB / MI)], |
| 1649 | left_ref1: vec![None; rows * (SUB / MI)], |
| 1650 | above_comp_group_idx: vec![0; cols * (SUB / MI)], |
| 1651 | left_comp_group_idx: vec![0; rows * (SUB / MI)], |
| 1652 | above_compound_idx: vec![0; cols * (SUB / MI)], |
| 1653 | left_compound_idx: vec![0; rows * (SUB / MI)], |
| 1654 | above_tx: vec![0; cols * (SUB / MI)], |
| 1655 | left_tx: vec![0; rows * (SUB / MI)], |
| 1656 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], |
| 1657 | left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], |
| 1658 | above_palette_size: vec![0; cols * (SUB / MI)], |
| 1659 | left_palette_size: vec![0; rows * (SUB / MI)], |
| 1660 | pending_palette: None, |
| 1661 | above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], |
| 1662 | above_palette_uv_size: vec![0; cols * (SUB / MI)], |
| 1663 | left_palette_uv_size: vec![0; rows * (SUB / MI)], |
| 1664 | above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)], |
| 1665 | left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)], |
| 1666 | pending_palette_uv: None, |
| 1667 | left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], |
| 1668 | mi_cols, |
| 1669 | mi_rows, |
| 1670 | } |
| 1671 | } |
| 1672 | |
| 1673 | |
| 1674 | |
| 1675 | |
| 1676 | fn set_tile_origin(&mut self, row0_mi: usize, col0_mi: usize) { |
| 1677 | self.tile_row0_mi = row0_mi; |
| 1678 | self.tile_col0_mi = col0_mi; |
| 1679 | } |
| 1680 | |
| 1681 | |
| 1682 | |
| 1683 | fn has_above(&self, mi_r: usize) -> bool { |
| 1684 | mi_r > self.tile_row0_mi |
| 1685 | } |
| 1686 | |
| 1687 | fn has_left(&self, mi_c: usize) -> bool { |
| 1688 | mi_c > self.tile_col0_mi |
| 1689 | } |
| 1690 | |
| 1691 | fn start_row(&mut self) { |
| 1692 | self.left.iter_mut().for_each(|l| *l = Default::default()); |
| 1693 | self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); |
| 1694 | self.left_side.iter_mut().for_each(|s| *s = SB); |
| 1695 | self.left_side_mi.iter_mut().for_each(|s| *s = SB); |
| 1696 | self.left_skip.iter_mut().for_each(|s| *s = false); |
| 1697 | self.left_inter.iter_mut().for_each(|i| *i = false); |
| 1698 | self.left_ref.iter_mut().for_each(|r| *r = -1); |
| 1699 | self.left_ref1.iter_mut().for_each(|r| *r = None); |
| 1700 | self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); |
| 1701 | self.left_compound_idx.iter_mut().for_each(|r| *r = 0); |
| 1702 | self.left_tx.iter_mut().for_each(|t| *t = 0); |
| 1703 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); |
| 1704 | self.left_palette_size.iter_mut().for_each(|s| *s = 0); |
| 1705 | self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0); |
| 1706 | self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]); |
| 1707 | } |
| 1708 | |
| 1709 | |
| 1710 | |
| 1711 | |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | |
| 1716 | fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) { |
| 1717 | |
| 1718 | |
| 1719 | |
| 1720 | let above_ok = r % 16 != 0; |
| 1721 | let above_is_palette = r > 0 && self.above_palette_size[c] > 0; |
| 1722 | let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { |
| 1723 | (usize::from(self.above_palette_size[c]), self.above_palette_colors[c]) |
| 1724 | } else { |
| 1725 | (0, [0u16; 8]) |
| 1726 | }; |
| 1727 | let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 { |
| 1728 | (usize::from(self.left_palette_size[r]), self.left_palette_colors[r]) |
| 1729 | } else { |
| 1730 | (0, [0u16; 8]) |
| 1731 | }; |
| 1732 | let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); |
| 1733 | let mut cache = Vec::with_capacity(16); |
| 1734 | let push_dedup = |cache: &mut Vec<u16>, v: u16| { |
| 1735 | if cache.last() != Some(&v) { |
| 1736 | cache.push(v); |
| 1737 | } |
| 1738 | }; |
| 1739 | let (mut ai, mut li) = (0usize, 0usize); |
| 1740 | while ai < above_n && li < left_n { |
| 1741 | let (va, vl) = (above_colors[ai], left_colors[li]); |
| 1742 | if vl < va { |
| 1743 | push_dedup(&mut cache, vl); |
| 1744 | li += 1; |
| 1745 | } else { |
| 1746 | push_dedup(&mut cache, va); |
| 1747 | ai += 1; |
| 1748 | if vl == va { |
| 1749 | li += 1; |
| 1750 | } |
| 1751 | } |
| 1752 | } |
| 1753 | while ai < above_n { |
| 1754 | push_dedup(&mut cache, above_colors[ai]); |
| 1755 | ai += 1; |
| 1756 | } |
| 1757 | while li < left_n { |
| 1758 | push_dedup(&mut cache, left_colors[li]); |
| 1759 | li += 1; |
| 1760 | } |
| 1761 | (ctx, cache) |
| 1762 | } |
| 1763 | |
| 1764 | |
| 1765 | |
| 1766 | |
| 1767 | |
| 1768 | |
| 1769 | fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> { |
| 1770 | let above_ok = r % 16 != 0; |
| 1771 | let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { |
| 1772 | ( |
| 1773 | usize::from(self.above_palette_uv_size[c]), |
| 1774 | self.above_palette_uv_colors[c], |
| 1775 | ) |
| 1776 | } else { |
| 1777 | (0, [0u16; 8]) |
| 1778 | }; |
| 1779 | let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 { |
| 1780 | ( |
| 1781 | usize::from(self.left_palette_uv_size[r]), |
| 1782 | self.left_palette_uv_colors[r], |
| 1783 | ) |
| 1784 | } else { |
| 1785 | (0, [0u16; 8]) |
| 1786 | }; |
| 1787 | let mut cache = Vec::with_capacity(16); |
| 1788 | let push_dedup = |cache: &mut Vec<u16>, v: u16| { |
| 1789 | if cache.last() != Some(&v) { |
| 1790 | cache.push(v); |
| 1791 | } |
| 1792 | }; |
| 1793 | let (mut ai, mut li) = (0usize, 0usize); |
| 1794 | while ai < above_n && li < left_n { |
| 1795 | let (va, vl) = (above_colors[ai], left_colors[li]); |
| 1796 | if vl < va { |
| 1797 | push_dedup(&mut cache, vl); |
| 1798 | li += 1; |
| 1799 | } else { |
| 1800 | push_dedup(&mut cache, va); |
| 1801 | ai += 1; |
| 1802 | if vl == va { |
| 1803 | li += 1; |
| 1804 | } |
| 1805 | } |
| 1806 | } |
| 1807 | while ai < above_n { |
| 1808 | push_dedup(&mut cache, above_colors[ai]); |
| 1809 | ai += 1; |
| 1810 | } |
| 1811 | while li < left_n { |
| 1812 | push_dedup(&mut cache, left_colors[li]); |
| 1813 | li += 1; |
| 1814 | } |
| 1815 | cache |
| 1816 | } |
| 1817 | |
| 1818 | |
| 1819 | |
| 1820 | |
| 1821 | fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { |
| 1822 | for cell in 0..(side / MI).max(1) { |
| 1823 | if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { |
| 1824 | *e = size; |
| 1825 | if size > 0 { |
| 1826 | self.above_palette_uv_colors[c + cell] = colors; |
| 1827 | } |
| 1828 | } |
| 1829 | if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { |
| 1830 | *e = size; |
| 1831 | if size > 0 { |
| 1832 | self.left_palette_uv_colors[r + cell] = colors; |
| 1833 | } |
| 1834 | } |
| 1835 | } |
| 1836 | } |
| 1837 | |
| 1838 | |
| 1839 | |
| 1840 | |
| 1841 | fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { |
| 1842 | for cell in 0..(side / MI).max(1) { |
| 1843 | if let Some(e) = self.above_palette_size.get_mut(c + cell) { |
| 1844 | *e = size; |
| 1845 | if size > 0 { |
| 1846 | self.above_palette_colors[c + cell] = colors; |
| 1847 | } |
| 1848 | } |
| 1849 | if let Some(e) = self.left_palette_size.get_mut(r + cell) { |
| 1850 | *e = size; |
| 1851 | if size > 0 { |
| 1852 | self.left_palette_colors[r + cell] = colors; |
| 1853 | } |
| 1854 | } |
| 1855 | } |
| 1856 | } |
| 1857 | |
| 1858 | |
| 1859 | |
| 1860 | |
| 1861 | |
| 1862 | fn record_txfm(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, w_px: usize, h_px: usize) { |
| 1863 | for i in 0..h_px / MI { |
| 1864 | if let Some(cell) = self.left_txfm.get_mut(mi_r + i) { |
| 1865 | *cell = tx_px as u8; |
| 1866 | } |
| 1867 | } |
| 1868 | for i in 0..w_px / MI { |
| 1869 | if let Some(cell) = self.above_txfm.get_mut(mi_c + i) { |
| 1870 | *cell = tx_px as u8; |
| 1871 | } |
| 1872 | } |
| 1873 | } |
| 1874 | |
| 1875 | |
| 1876 | |
| 1877 | |
| 1878 | |
| 1879 | |
| 1880 | |
| 1881 | |
| 1882 | |
| 1883 | |
| 1884 | |
| 1885 | |
| 1886 | fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { |
| 1887 | let (has_above, has_left) = (self.has_above(mi_r), self.has_left(mi_c)); |
| 1888 | let mut above = usize::from(self.above_txfm[mi_c]) >= own_side; |
| 1889 | let mut left = usize::from(self.left_txfm[mi_r]) >= own_side; |
| 1890 | if has_above && self.above_inter[mi_c] { |
| 1891 | above = self.above_side_mi[mi_c] >= own_side; |
| 1892 | } |
| 1893 | if has_left && self.left_inter[mi_r] { |
| 1894 | left = self.left_side_mi[mi_r] >= own_side; |
| 1895 | } |
| 1896 | usize::from(has_above && above) + usize::from(has_left && left) |
| 1897 | } |
| 1898 | |
| 1899 | |
| 1900 | |
| 1901 | |
| 1902 | |
| 1903 | fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize { |
| 1904 | usize::from(self.has_above(mi_r) && usize::from(self.above_tx[mi_c]) >= max_tx) |
| 1905 | + usize::from(self.has_left(mi_c) && usize::from(self.left_tx[mi_r]) >= max_tx) |
| 1906 | } |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | |
| 1911 | fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) { |
| 1912 | for cell in 0..side / MI { |
| 1913 | if mi_r + cell < self.left_tx.len() { |
| 1914 | self.left_tx[mi_r + cell] = tx_px as u8; |
| 1915 | } |
| 1916 | if mi_c + cell < self.above_tx.len() { |
| 1917 | self.above_tx[mi_c + cell] = tx_px as u8; |
| 1918 | } |
| 1919 | } |
| 1920 | } |
| 1921 | |
| 1922 | |
| 1923 | |
| 1924 | |
| 1925 | fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize { |
| 1926 | let mut top = 0u8; |
| 1927 | let mut left = 0u8; |
| 1928 | for cell in 0..side_mi { |
| 1929 | top |= self.above[mi_c + cell][0].level; |
| 1930 | left |= self.left[mi_r + cell][0].level; |
| 1931 | } |
| 1932 | crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] |
| 1933 | } |
| 1934 | |
| 1935 | |
| 1936 | |
| 1937 | fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) { |
| 1938 | let state = neighbour_state(grid); |
| 1939 | for cell in 0..tx_px / MI { |
| 1940 | if mi_r + cell < self.mi_rows { |
| 1941 | self.left[mi_r + cell][0] = state; |
| 1942 | } |
| 1943 | if mi_c + cell < self.mi_cols { |
| 1944 | self.above[mi_c + cell][0] = state; |
| 1945 | } |
| 1946 | } |
| 1947 | } |
| 1948 | |
| 1949 | |
| 1950 | |
| 1951 | |
| 1952 | |
| 1953 | |
| 1954 | |
| 1955 | |
| 1956 | fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) { |
| 1957 | self.record_planes(at, side, mode, grids, true); |
| 1958 | } |
| 1959 | |
| 1960 | |
| 1961 | |
| 1962 | |
| 1963 | |
| 1964 | |
| 1965 | fn record_planes( |
| 1966 | &mut self, |
| 1967 | at: (usize, usize), |
| 1968 | side: usize, |
| 1969 | mode: usize, |
| 1970 | grids: &[Vec<i32>; 3], |
| 1971 | luma: bool, |
| 1972 | ) { |
| 1973 | let (r, c) = at; |
| 1974 | for cell in 0..side / SUB { |
| 1975 | self.above_mode[c + cell] = mode; |
| 1976 | self.left_mode[r + cell] = mode; |
| 1977 | self.above_side[c + cell] = side; |
| 1978 | self.left_side[r + cell] = side; |
| 1979 | } |
| 1980 | self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma); |
| 1981 | } |
| 1982 | |
| 1983 | |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | |
| 1989 | |
| 1990 | fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) { |
| 1991 | self.record_mi_planes(at_mi, side, grids, true); |
| 1992 | } |
| 1993 | |
| 1994 | |
| 1995 | fn record_mi_planes( |
| 1996 | &mut self, |
| 1997 | at_mi: (usize, usize), |
| 1998 | side: usize, |
| 1999 | grids: &[Vec<i32>; 3], |
| 2000 | luma: bool, |
| 2001 | ) { |
| 2002 | let (mi_r, mi_c) = at_mi; |
| 2003 | if screen_armed() { |
| 2004 | let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8])); |
| 2005 | self.record_palette_y(at_mi, side, size, colors); |
| 2006 | let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8])); |
| 2007 | self.record_palette_uv(at_mi, side, uv_size, uv_colors); |
| 2008 | } |
| 2009 | let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); |
| 2010 | let side_mi = side / MI; |
| 2011 | for cell in 0..side_mi { |
| 2012 | self.left_side_mi[mi_r + cell] = side; |
| 2013 | self.above_side_mi[mi_c + cell] = side; |
| 2014 | } |
| 2015 | |
| 2016 | |
| 2017 | |
| 2018 | |
| 2019 | |
| 2020 | |
| 2021 | let round_up_even = |n: usize| n.div_ceil(2) * 2; |
| 2022 | let bound_h = [ |
| 2023 | self.mi_rows, |
| 2024 | round_up_even(self.mi_rows), |
| 2025 | round_up_even(self.mi_rows), |
| 2026 | ]; |
| 2027 | let bound_w = [ |
| 2028 | self.mi_cols, |
| 2029 | round_up_even(self.mi_cols), |
| 2030 | round_up_even(self.mi_cols), |
| 2031 | ]; |
| 2032 | for cell in 0..side_mi { |
| 2033 | let keep_left = self.left[mi_r + cell][0]; |
| 2034 | let keep_above = self.above[mi_c + cell][0]; |
| 2035 | self.left[mi_r + cell] = std::array::from_fn(|plane| { |
| 2036 | if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) { |
| 2037 | states[plane] |
| 2038 | } else { |
| 2039 | Default::default() |
| 2040 | } |
| 2041 | }); |
| 2042 | self.above[mi_c + cell] = std::array::from_fn(|plane| { |
| 2043 | if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) { |
| 2044 | states[plane] |
| 2045 | } else { |
| 2046 | Default::default() |
| 2047 | } |
| 2048 | }); |
| 2049 | if !luma { |
| 2050 | self.left[mi_r + cell][0] = keep_left; |
| 2051 | self.above[mi_c + cell][0] = keep_above; |
| 2052 | } |
| 2053 | } |
| 2054 | } |
| 2055 | |
| 2056 | |
| 2057 | |
| 2058 | |
| 2059 | fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { |
| 2060 | let (r, c) = at; |
| 2061 | self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame); |
| 2062 | } |
| 2063 | |
| 2064 | |
| 2065 | |
| 2066 | |
| 2067 | |
| 2068 | |
| 2069 | fn record_compound_mi( |
| 2070 | &mut self, |
| 2071 | (mi_r, mi_c): (usize, usize), |
| 2072 | side: usize, |
| 2073 | ref1: i8, |
| 2074 | comp_group_idx: u8, |
| 2075 | compound_idx: u8, |
| 2076 | ) { |
| 2077 | for cell in 0..side / MI { |
| 2078 | self.above_ref1[mi_c + cell] = Some(ref1); |
| 2079 | self.left_ref1[mi_r + cell] = Some(ref1); |
| 2080 | self.above_comp_group_idx[mi_c + cell] = comp_group_idx; |
| 2081 | self.left_comp_group_idx[mi_r + cell] = comp_group_idx; |
| 2082 | self.above_compound_idx[mi_c + cell] = compound_idx; |
| 2083 | self.left_compound_idx[mi_r + cell] = compound_idx; |
| 2084 | } |
| 2085 | } |
| 2086 | |
| 2087 | |
| 2088 | |
| 2089 | fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { |
| 2090 | for cell in 0..side / MI { |
| 2091 | self.above_skip[mi_c + cell] = skip; |
| 2092 | self.left_skip[mi_r + cell] = skip; |
| 2093 | self.above_inter[mi_c + cell] = is_inter; |
| 2094 | self.left_inter[mi_r + cell] = is_inter; |
| 2095 | self.above_ref[mi_c + cell] = ref_frame; |
| 2096 | self.left_ref[mi_r + cell] = ref_frame; |
| 2097 | |
| 2098 | |
| 2099 | |
| 2100 | |
| 2101 | let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; |
| 2102 | self.above_ref1[mi_c + cell] = None; |
| 2103 | self.left_ref1[mi_r + cell] = None; |
| 2104 | self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 }; |
| 2105 | self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 }; |
| 2106 | self.above_compound_idx[mi_c + cell] = u8::from(altref); |
| 2107 | self.left_compound_idx[mi_r + cell] = u8::from(altref); |
| 2108 | } |
| 2109 | } |
| 2110 | |
| 2111 | |
| 2112 | |
| 2113 | |
| 2114 | fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef { |
| 2115 | let is_inter = self.above_inter[mi_c]; |
| 2116 | let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 }; |
| 2117 | let ref1 = self.above_ref1[mi_c]; |
| 2118 | crate::mvstack::NeighbourRef { |
| 2119 | is_inter, |
| 2120 | ref0, |
| 2121 | ref1, |
| 2122 | uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)), |
| 2123 | } |
| 2124 | } |
| 2125 | |
| 2126 | |
| 2127 | fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef { |
| 2128 | let is_inter = self.left_inter[mi_r]; |
| 2129 | let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 }; |
| 2130 | let ref1 = self.left_ref1[mi_r]; |
| 2131 | crate::mvstack::NeighbourRef { |
| 2132 | is_inter, |
| 2133 | ref0, |
| 2134 | ref1, |
| 2135 | uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)), |
| 2136 | } |
| 2137 | } |
| 2138 | |
| 2139 | |
| 2140 | |
| 2141 | |
| 2142 | |
| 2143 | fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] { |
| 2144 | self.around_mi((r * (SUB / MI), c * (SUB / MI)), side) |
| 2145 | } |
| 2146 | |
| 2147 | |
| 2148 | |
| 2149 | fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [Around; 3] { |
| 2150 | let side_mi = side / MI; |
| 2151 | std::array::from_fn(|plane| { |
| 2152 | let mut around = Around::default(); |
| 2153 | for cell in 0..side_mi { |
| 2154 | let (above, left) = ( |
| 2155 | &self.above[mi_c + cell][plane], |
| 2156 | &self.left[mi_r + cell][plane], |
| 2157 | ); |
| 2158 | around.above_coded |= above.coded; |
| 2159 | around.left_coded |= left.coded; |
| 2160 | around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc); |
| 2161 | } |
| 2162 | around |
| 2163 | }) |
| 2164 | } |
| 2165 | |
| 2166 | fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize { |
| 2167 | |
| 2168 | |
| 2169 | |
| 2170 | |
| 2171 | |
| 2172 | |
| 2173 | let (r, c) = at; |
| 2174 | self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side) |
| 2175 | } |
| 2176 | |
| 2177 | |
| 2178 | |
| 2179 | |
| 2180 | |
| 2181 | fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize { |
| 2182 | 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side) |
| 2183 | + usize::from(self.above_side_mi[mi_c] * 2 <= side) |
| 2184 | } |
| 2185 | } |
| 2186 | |
| 2187 | |
| 2188 | |
| 2189 | |
| 2190 | |
| 2191 | |
| 2192 | |
| 2193 | |
| 2194 | |
| 2195 | |
| 2196 | |
| 2197 | |
| 2198 | |
| 2199 | |
| 2200 | |
| 2201 | |
| 2202 | |
| 2203 | |
| 2204 | pub fn sb_coeff_key_frame_tile( |
| 2205 | mi_cols: u32, |
| 2206 | mi_rows: u32, |
| 2207 | base_q_idx: u8, |
| 2208 | superblocks: &[Superblock], |
| 2209 | ) -> Result<Vec<u8>> { |
| 2210 | sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false) |
| 2211 | } |
| 2212 | |
| 2213 | |
| 2214 | |
| 2215 | |
| 2216 | |
| 2217 | |
| 2218 | |
| 2219 | |
| 2220 | |
| 2221 | |
| 2222 | pub fn sb_coeff_key_frame_tile_tx( |
| 2223 | mi_cols: u32, |
| 2224 | mi_rows: u32, |
| 2225 | base_q_idx: u8, |
| 2226 | superblocks: &[Superblock], |
| 2227 | tx_select: bool, |
| 2228 | ) -> Result<Vec<u8>> { |
| 2229 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
| 2230 | sb_coeff_key_frame_tile_cdfs( |
| 2231 | mi_cols, |
| 2232 | mi_rows, |
| 2233 | base_q_idx, |
| 2234 | superblocks, |
| 2235 | tx_select, |
| 2236 | &mut cdfs, |
| 2237 | TileRect::whole(mi_cols, mi_rows), |
| 2238 | ) |
| 2239 | } |
| 2240 | |
| 2241 | |
| 2242 | |
| 2243 | |
| 2244 | |
| 2245 | |
| 2246 | |
| 2247 | |
| 2248 | |
| 2249 | pub(crate) fn sb_coeff_key_frame_tile_cdfs( |
| 2250 | mi_cols: u32, |
| 2251 | mi_rows: u32, |
| 2252 | _base_q_idx: u8, |
| 2253 | superblocks: &[Superblock], |
| 2254 | tx_select: bool, |
| 2255 | cdfs: &mut Cdfs, |
| 2256 | |
| 2257 | |
| 2258 | |
| 2259 | |
| 2260 | tile: TileRect, |
| 2261 | ) -> Result<Vec<u8>> { |
| 2262 | |
| 2263 | let _cdef_idx = CdefIdxGuard; |
| 2264 | check_blocks(mi_cols, mi_rows)?; |
| 2265 | |
| 2266 | |
| 2267 | |
| 2268 | |
| 2269 | if intrabc_armed() { |
| 2270 | |
| 2271 | |
| 2272 | |
| 2273 | |
| 2274 | let grid = crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 2275 | INTRABC_GRID.with(|g| { |
| 2276 | *g.borrow_mut() = Some((grid, mi_cols as usize, mi_rows as usize)); |
| 2277 | }); |
| 2278 | } |
| 2279 | let (cols, rows) = block_grid(mi_cols, mi_rows); |
| 2280 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 2281 | if superblocks.len() != (sb_cols * sb_rows) as usize { |
| 2282 | return Err(Error::unsupported( |
| 2283 | "AV1 tile", |
| 2284 | "a coefficient key frame needs one entry per superblock", |
| 2285 | )); |
| 2286 | } |
| 2287 | let mut coded: Vec<&BlockCoeffs> = Vec::new(); |
| 2288 | for superblock in superblocks { |
| 2289 | match superblock { |
| 2290 | Superblock::Whole(block) => coded.push(block), |
| 2291 | Superblock::Split(quadrants) => { |
| 2292 | for block in quadrants.iter().flat_map(Quadrant::blocks) { |
| 2293 | match &block.eight { |
| 2294 | Some(leaves) => coded.extend(leaves.iter()), |
| 2295 | None => coded.push(block), |
| 2296 | } |
| 2297 | } |
| 2298 | } |
| 2299 | } |
| 2300 | } |
| 2301 | if let Some(bad) = coded |
| 2302 | .into_iter() |
| 2303 | .find(|b| usize::from(b.mode) >= INTRA_MODES) |
| 2304 | { |
| 2305 | return Err(Error::unsupported( |
| 2306 | "AV1 tile", |
| 2307 | format!( |
| 2308 | "intra mode {} is not one of the thirteen a key frame codes", |
| 2309 | bad.mode |
| 2310 | ), |
| 2311 | )); |
| 2312 | } |
| 2313 | |
| 2314 | let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]; |
| 2315 | let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16]; |
| 2316 | let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; |
| 2317 | let scans = [ |
| 2318 | default_scan(TX32), |
| 2319 | default_scan(TX16), |
| 2320 | default_scan(TX8), |
| 2321 | default_scan(TX4), |
| 2322 | ]; |
| 2323 | |
| 2324 | |
| 2325 | |
| 2326 | let mut neighbours = Neighbours::new( |
| 2327 | cols as usize * 2, |
| 2328 | rows as usize * 2, |
| 2329 | mi_cols as usize, |
| 2330 | mi_rows as usize, |
| 2331 | ); |
| 2332 | neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize); |
| 2333 | |
| 2334 | |
| 2335 | |
| 2336 | |
| 2337 | let mut cdfs = cdfs; |
| 2338 | let mut enc = SymbolEncoder::new(); |
| 2339 | for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { |
| 2340 | neighbours.start_row(); |
| 2341 | for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { |
| 2342 | write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); |
| 2343 | let at = (sb_r as usize * 4, sb_c as usize * 4); |
| 2344 | let ctx = neighbours.partition_ctx(at, SB); |
| 2345 | ec_rng_trace(|| { |
| 2346 | format!( |
| 2347 | "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={}", |
| 2348 | at.0 * 4, |
| 2349 | at.1 * 4, |
| 2350 | ctx, |
| 2351 | enc.tell() |
| 2352 | ) |
| 2353 | }); |
| 2354 | |
| 2355 | |
| 2356 | |
| 2357 | |
| 2358 | let (has_cols, has_rows) = ( |
| 2359 | sb_c * SB_MI + SB_MI / 2 < mi_cols, |
| 2360 | sb_r * SB_MI + SB_MI / 2 < mi_rows, |
| 2361 | ); |
| 2362 | |
| 2363 | |
| 2364 | let quadrant_positions: Vec<(usize, usize)> = (0..4) |
| 2365 | .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) |
| 2366 | .filter(|&(r, c)| r < rows && c < cols) |
| 2367 | .map(|(r, c)| (r as usize, c as usize)) |
| 2368 | .collect(); |
| 2369 | |
| 2370 | match &superblocks[(sb_r * sb_cols + sb_c) as usize] { |
| 2371 | Superblock::Whole(block) => { |
| 2372 | if !has_cols || !has_rows { |
| 2373 | return Err(Error::unsupported( |
| 2374 | "AV1 tile", |
| 2375 | "a superblock that is half outside the frame cannot be left whole", |
| 2376 | )); |
| 2377 | } |
| 2378 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]); |
| 2379 | let grids = [ |
| 2380 | level_grid(&block.luma, TX32)?, |
| 2381 | level_grid(&block.u, TX32)?, |
| 2382 | level_grid(&block.v, TX32)?, |
| 2383 | ]; |
| 2384 | write_block( |
| 2385 | &mut enc, |
| 2386 | &mut cdfs, |
| 2387 | &mut neighbours, |
| 2388 | block, |
| 2389 | at, |
| 2390 | SB, |
| 2391 | &whole_planes, |
| 2392 | &grids, |
| 2393 | [&scans[0], &scans[0], &scans[0]], |
| 2394 | |
| 2395 | |
| 2396 | false, |
| 2397 | tx_select, |
| 2398 | &scans, |
| 2399 | )?; |
| 2400 | ec_rng_trace(|| { |
| 2401 | format!( |
| 2402 | "EC_TOK mi_row={} mi_col={} tell={}", |
| 2403 | at.0 * 4, |
| 2404 | at.1 * 4, |
| 2405 | enc.tell() |
| 2406 | ) |
| 2407 | }); |
| 2408 | } |
| 2409 | Superblock::Split(quadrants) => { |
| 2410 | match (has_cols, has_rows) { |
| 2411 | (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]), |
| 2412 | |
| 2413 | |
| 2414 | |
| 2415 | (true, false) => { |
| 2416 | enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); |
| 2417 | } |
| 2418 | (false, true) => { |
| 2419 | enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); |
| 2420 | } |
| 2421 | (false, false) => {} |
| 2422 | } |
| 2423 | if quadrants.len() != quadrant_positions.len() { |
| 2424 | return Err(Error::unsupported( |
| 2425 | "AV1 tile", |
| 2426 | "a split superblock needs one block per quadrant inside the frame", |
| 2427 | )); |
| 2428 | } |
| 2429 | for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) { |
| 2430 | let at = (r * 2, c * 2); |
| 2431 | let ctx = neighbours.partition_ctx(at, BLOCK); |
| 2432 | |
| 2433 | |
| 2434 | |
| 2435 | |
| 2436 | |
| 2437 | |
| 2438 | let (has_cols32, has_rows32) = ( |
| 2439 | has_half(c as u32 * BLOCK_MI, BLOCK_MI, mi_cols), |
| 2440 | has_half(r as u32 * BLOCK_MI, BLOCK_MI, mi_rows), |
| 2441 | ); |
| 2442 | ec_rng_trace(|| { |
| 2443 | format!( |
| 2444 | "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={}", |
| 2445 | at.0 * 4, |
| 2446 | at.1 * 4, |
| 2447 | ctx, |
| 2448 | enc.tell() |
| 2449 | ) |
| 2450 | }); |
| 2451 | match quadrant { |
| 2452 | Quadrant::Whole(block) => { |
| 2453 | if !has_cols32 || !has_rows32 { |
| 2454 | return Err(Error::unsupported( |
| 2455 | "AV1 tile", |
| 2456 | "a 32x32 block that is half outside the true frame \ |
| 2457 | cannot be left whole", |
| 2458 | )); |
| 2459 | } |
| 2460 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]); |
| 2461 | let grids = [ |
| 2462 | level_grid(&block.luma, TX32)?, |
| 2463 | level_grid(&block.u, TX16)?, |
| 2464 | level_grid(&block.v, TX16)?, |
| 2465 | ]; |
| 2466 | write_block( |
| 2467 | &mut enc, |
| 2468 | &mut cdfs, |
| 2469 | &mut neighbours, |
| 2470 | block, |
| 2471 | at, |
| 2472 | BLOCK, |
| 2473 | &split_planes, |
| 2474 | &grids, |
| 2475 | [&scans[0], &scans[1], &scans[1]], |
| 2476 | true, |
| 2477 | tx_select, |
| 2478 | &scans, |
| 2479 | )?; |
| 2480 | ec_rng_trace(|| { |
| 2481 | format!( |
| 2482 | "EC_TOK mi_row={} mi_col={} tell={}", |
| 2483 | at.0 * 4, |
| 2484 | at.1 * 4, |
| 2485 | enc.tell() |
| 2486 | ) |
| 2487 | }); |
| 2488 | } |
| 2489 | Quadrant::Split(blocks) => { |
| 2490 | |
| 2491 | |
| 2492 | |
| 2493 | |
| 2494 | |
| 2495 | |
| 2496 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 2497 | .map(|i| (r * 2 + i / 2, c * 2 + i % 2)) |
| 2498 | .filter(|&(sr, sc)| { |
| 2499 | (sr as u32) * SUB_MI < mi_rows |
| 2500 | && (sc as u32) * SUB_MI < mi_cols |
| 2501 | }) |
| 2502 | .collect(); |
| 2503 | if blocks.len() != sub_positions.len() { |
| 2504 | return Err(Error::unsupported( |
| 2505 | "AV1 tile", |
| 2506 | "a split 32x32 block needs one 16x16 entry per \ |
| 2507 | sub-block inside the true frame", |
| 2508 | )); |
| 2509 | } |
| 2510 | |
| 2511 | |
| 2512 | |
| 2513 | |
| 2514 | |
| 2515 | |
| 2516 | match (has_cols32, has_rows32) { |
| 2517 | (true, true) => { |
| 2518 | enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]); |
| 2519 | } |
| 2520 | (true, false) => { |
| 2521 | enc.symbol_fixed( |
| 2522 | 1, |
| 2523 | &gather(&cdfs.partition_w32[ctx], VERT_ALIKE), |
| 2524 | ); |
| 2525 | } |
| 2526 | (false, true) => { |
| 2527 | enc.symbol_fixed( |
| 2528 | 1, |
| 2529 | &gather(&cdfs.partition_w32[ctx], HORZ_ALIKE), |
| 2530 | ); |
| 2531 | } |
| 2532 | (false, false) => {} |
| 2533 | } |
| 2534 | for (block, (sr, sc)) in blocks.iter().zip(sub_positions) { |
| 2535 | |
| 2536 | |
| 2537 | |
| 2538 | |
| 2539 | let (has_cols16, has_rows16) = ( |
| 2540 | has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), |
| 2541 | has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), |
| 2542 | ); |
| 2543 | let at = (sr, sc); |
| 2544 | let ctx = neighbours.partition_ctx(at, SUB); |
| 2545 | ec_rng_trace(|| { |
| 2546 | format!( |
| 2547 | "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={}", |
| 2548 | at.0 * 4, |
| 2549 | at.1 * 4, |
| 2550 | ctx, |
| 2551 | enc.tell() |
| 2552 | ) |
| 2553 | }); |
| 2554 | if has_cols16 && has_rows16 { |
| 2555 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]); |
| 2556 | let grids = [ |
| 2557 | level_grid(&block.luma, TX16)?, |
| 2558 | level_grid(&block.u, TX8)?, |
| 2559 | level_grid(&block.v, TX8)?, |
| 2560 | ]; |
| 2561 | write_block( |
| 2562 | &mut enc, |
| 2563 | &mut cdfs, |
| 2564 | &mut neighbours, |
| 2565 | block, |
| 2566 | at, |
| 2567 | SUB, |
| 2568 | &sub_planes, |
| 2569 | &grids, |
| 2570 | [&scans[1], &scans[2], &scans[2]], |
| 2571 | true, |
| 2572 | tx_select, |
| 2573 | &scans, |
| 2574 | )?; |
| 2575 | ec_rng_trace(|| { |
| 2576 | format!( |
| 2577 | "EC_TOK mi_row={} mi_col={} tell={}", |
| 2578 | at.0 * 4, |
| 2579 | at.1 * 4, |
| 2580 | enc.tell() |
| 2581 | ) |
| 2582 | }); |
| 2583 | continue; |
| 2584 | } |
| 2585 | |
| 2586 | |
| 2587 | |
| 2588 | |
| 2589 | |
| 2590 | |
| 2591 | |
| 2592 | if !has_cols16 && !has_rows16 { |
| 2593 | return Err(Error::unsupported( |
| 2594 | "AV1 tile", |
| 2595 | "a 16x16 block whose true edge cuts through both \ |
| 2596 | axes needs a rectangular transform this writer \ |
| 2597 | does not code yet", |
| 2598 | )); |
| 2599 | } |
| 2600 | if has_cols16 { |
| 2601 | enc.symbol_fixed( |
| 2602 | 1, |
| 2603 | &gather(&cdfs.partition_w16[ctx], VERT_ALIKE), |
| 2604 | ); |
| 2605 | } else { |
| 2606 | enc.symbol_fixed( |
| 2607 | 1, |
| 2608 | &gather(&cdfs.partition_w16[ctx], HORZ_ALIKE), |
| 2609 | ); |
| 2610 | } |
| 2611 | let leaves = block.eight.as_ref().ok_or_else(|| { |
| 2612 | Error::unsupported( |
| 2613 | "AV1 tile", |
| 2614 | "a 16x16 block the true frame edge cuts through \ |
| 2615 | needs its `eight` leaves populated", |
| 2616 | ) |
| 2617 | })?; |
| 2618 | let (mi_row0, mi_col0) = |
| 2619 | (sr as u32 * SUB_MI, sc as u32 * SUB_MI); |
| 2620 | let leaf_positions: Vec<(u32, u32)> = (0..4) |
| 2621 | .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) |
| 2622 | .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) |
| 2623 | .collect(); |
| 2624 | if leaves.len() != leaf_positions.len() { |
| 2625 | return Err(Error::unsupported( |
| 2626 | "AV1 tile", |
| 2627 | "a straddling 16x16 block needs one `eight` entry \ |
| 2628 | per 8x8 leaf inside the true frame", |
| 2629 | )); |
| 2630 | } |
| 2631 | |
| 2632 | |
| 2633 | |
| 2634 | |
| 2635 | |
| 2636 | |
| 2637 | let mut prev_leaf: Option<((usize, usize), usize)> = None; |
| 2638 | for (leaf, (mr, mc)) in leaves.iter().zip(leaf_positions) { |
| 2639 | let leaf_mi = (mr as usize, mc as usize); |
| 2640 | |
| 2641 | |
| 2642 | |
| 2643 | |
| 2644 | |
| 2645 | |
| 2646 | |
| 2647 | let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); |
| 2648 | ec_rng_trace(|| { |
| 2649 | format!( |
| 2650 | "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={}", |
| 2651 | leaf_mi.0, |
| 2652 | leaf_mi.1, |
| 2653 | leaf_ctx, |
| 2654 | enc.tell() |
| 2655 | ) |
| 2656 | }); |
| 2657 | enc.symbol( |
| 2658 | PARTITION_NONE, |
| 2659 | &mut cdfs.partition_w8[leaf_ctx], |
| 2660 | ); |
| 2661 | let grids = [ |
| 2662 | level_grid(&leaf.luma, TX8)?, |
| 2663 | level_grid(&leaf.u, TX4)?, |
| 2664 | level_grid(&leaf.v, TX4)?, |
| 2665 | ]; |
| 2666 | let leaf_mode = write_leaf8( |
| 2667 | &mut enc, |
| 2668 | &mut cdfs, |
| 2669 | &mut neighbours, |
| 2670 | leaf, |
| 2671 | at, |
| 2672 | leaf_mi, |
| 2673 | &grids, |
| 2674 | [&scans[2], &scans[3], &scans[3]], |
| 2675 | prev_leaf, |
| 2676 | tx_select, |
| 2677 | &scans, |
| 2678 | )?; |
| 2679 | prev_leaf = Some((leaf_mi, leaf_mode)); |
| 2680 | ec_rng_trace(|| { |
| 2681 | format!( |
| 2682 | "EC_TOK mi_row={} mi_col={} tell={}", |
| 2683 | leaf_mi.0, |
| 2684 | leaf_mi.1, |
| 2685 | enc.tell() |
| 2686 | ) |
| 2687 | }); |
| 2688 | } |
| 2689 | |
| 2690 | |
| 2691 | |
| 2692 | |
| 2693 | |
| 2694 | |
| 2695 | |
| 2696 | |
| 2697 | |
| 2698 | |
| 2699 | |
| 2700 | |
| 2701 | |
| 2702 | |
| 2703 | |
| 2704 | if let Some((_, mode)) = prev_leaf { |
| 2705 | neighbours.above_mode[at.1] = mode; |
| 2706 | neighbours.left_mode[at.0] = mode; |
| 2707 | } |
| 2708 | } |
| 2709 | } |
| 2710 | } |
| 2711 | } |
| 2712 | } |
| 2713 | } |
| 2714 | } |
| 2715 | } |
| 2716 | Ok(enc.finish()) |
| 2717 | } |
| 2718 | |
| 2719 | |
| 2720 | |
| 2721 | |
| 2722 | fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) { |
| 2723 | let l = crate::decode::ceil_log2(n as u32); |
| 2724 | let m = (1usize << l) - n; |
| 2725 | if value < m { |
| 2726 | enc.literal(value as u32, l - 1); |
| 2727 | } else { |
| 2728 | enc.literal(((value + m) >> 1) as u32, l - 1); |
| 2729 | enc.literal(((value + m) & 1) as u32, 1); |
| 2730 | } |
| 2731 | } |
| 2732 | |
| 2733 | |
| 2734 | |
| 2735 | |
| 2736 | |
| 2737 | |
| 2738 | |
| 2739 | |
| 2740 | fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) { |
| 2741 | let n = colors.len(); |
| 2742 | let mut cached: Vec<u16> = Vec::with_capacity(n); |
| 2743 | for &c in cache { |
| 2744 | if cached.len() >= n { |
| 2745 | break; |
| 2746 | } |
| 2747 | let take = colors.contains(&c); |
| 2748 | enc.literal(u32::from(take), 1); |
| 2749 | if take { |
| 2750 | cached.push(c); |
| 2751 | } |
| 2752 | } |
| 2753 | let transmitted: Vec<u16> = colors |
| 2754 | .iter() |
| 2755 | .copied() |
| 2756 | .filter(|c| !cached.contains(c)) |
| 2757 | .collect(); |
| 2758 | if transmitted.is_empty() { |
| 2759 | return; |
| 2760 | } |
| 2761 | enc.literal(u32::from(transmitted[0]), 8); |
| 2762 | if transmitted.len() == 1 { |
| 2763 | return; |
| 2764 | } |
| 2765 | |
| 2766 | |
| 2767 | |
| 2768 | |
| 2769 | let fits = |extra: u32| -> bool { |
| 2770 | let mut bits = 5 + extra; |
| 2771 | let mut range = 255i32 - i32::from(transmitted[0]); |
| 2772 | for w in transmitted.windows(2) { |
| 2773 | let delta = i32::from(w[1]) - i32::from(w[0]); |
| 2774 | if delta - 1 >= (1i32 << bits) { |
| 2775 | return false; |
| 2776 | } |
| 2777 | range -= delta; |
| 2778 | bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); |
| 2779 | } |
| 2780 | true |
| 2781 | }; |
| 2782 | let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3); |
| 2783 | enc.literal(extra, 2); |
| 2784 | let mut bits = 5 + extra; |
| 2785 | let mut range = 255i32 - i32::from(transmitted[0]); |
| 2786 | for w in transmitted.windows(2) { |
| 2787 | let delta = i32::from(w[1]) - i32::from(w[0]); |
| 2788 | enc.literal((delta - 1) as u32, bits); |
| 2789 | range -= delta; |
| 2790 | bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); |
| 2791 | } |
| 2792 | } |
| 2793 | |
| 2794 | |
| 2795 | |
| 2796 | |
| 2797 | |
| 2798 | |
| 2799 | |
| 2800 | |
| 2801 | |
| 2802 | |
| 2803 | |
| 2804 | |
| 2805 | |
| 2806 | |
| 2807 | fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) { |
| 2808 | let n = u_colors.len(); |
| 2809 | let mut cached: Vec<u16> = Vec::with_capacity(n); |
| 2810 | for &c in cache { |
| 2811 | if cached.len() >= n { |
| 2812 | break; |
| 2813 | } |
| 2814 | let take = u_colors.contains(&c); |
| 2815 | enc.literal(u32::from(take), 1); |
| 2816 | if take { |
| 2817 | PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2818 | cached.push(c); |
| 2819 | } |
| 2820 | } |
| 2821 | let transmitted: Vec<u16> = u_colors |
| 2822 | .iter() |
| 2823 | .copied() |
| 2824 | .filter(|c| !cached.contains(c)) |
| 2825 | .collect(); |
| 2826 | if !transmitted.is_empty() { |
| 2827 | enc.literal(u32::from(transmitted[0]), 8); |
| 2828 | if transmitted.len() > 1 { |
| 2829 | let fits = |extra: u32| -> bool { |
| 2830 | let mut bits = 5 + extra; |
| 2831 | let mut range = 256i32 - i32::from(transmitted[0]); |
| 2832 | for w in transmitted.windows(2) { |
| 2833 | let delta = i32::from(w[1]) - i32::from(w[0]); |
| 2834 | if delta >= (1i32 << bits) { |
| 2835 | return false; |
| 2836 | } |
| 2837 | range -= delta; |
| 2838 | bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); |
| 2839 | } |
| 2840 | true |
| 2841 | }; |
| 2842 | let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3); |
| 2843 | enc.literal(extra, 2); |
| 2844 | let mut bits = 5 + extra; |
| 2845 | let mut range = 256i32 - i32::from(transmitted[0]); |
| 2846 | for w in transmitted.windows(2) { |
| 2847 | let delta = i32::from(w[1]) - i32::from(w[0]); |
| 2848 | enc.literal(delta as u32, bits); |
| 2849 | range -= delta; |
| 2850 | bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); |
| 2851 | } |
| 2852 | } |
| 2853 | } |
| 2854 | enc.literal(0, 1); |
| 2855 | for &v in v_colors { |
| 2856 | enc.literal(u32::from(v), 8); |
| 2857 | } |
| 2858 | } |
| 2859 | |
| 2860 | |
| 2861 | |
| 2862 | |
| 2863 | |
| 2864 | fn write_color_index_map( |
| 2865 | enc: &mut SymbolEncoder, |
| 2866 | idx_cdfs: &mut [[u16; 9]; 5], |
| 2867 | map: &[u8], |
| 2868 | side: usize, |
| 2869 | n: usize, |
| 2870 | ) { |
| 2871 | write_uniform(enc, usize::from(map[0]), n); |
| 2872 | for i in 1..(2 * side - 1) { |
| 2873 | for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() { |
| 2874 | let (row, col) = (i - j, j); |
| 2875 | let (ctx, color_order) = |
| 2876 | crate::decode::palette_color_index_context(map, side, row, col, n); |
| 2877 | let want = map[row * side + col]; |
| 2878 | let symbol = color_order[..n] |
| 2879 | .iter() |
| 2880 | .position(|&c| c == want) |
| 2881 | .expect("every colour index is in the block\'s own palette"); |
| 2882 | enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]); |
| 2883 | } |
| 2884 | } |
| 2885 | } |
| 2886 | |
| 2887 | |
| 2888 | |
| 2889 | |
| 2890 | |
| 2891 | |
| 2892 | |
| 2893 | pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 { |
| 2894 | let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { |
| 2895 | return f64::INFINITY; |
| 2896 | }; |
| 2897 | let n = usize::from(pal.size); |
| 2898 | let mut enc = SymbolEncoder::pricer(); |
| 2899 | let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0]; |
| 2900 | enc.symbol(1, &mut mode_cdf); |
| 2901 | let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx]; |
| 2902 | enc.symbol(n - 2, &mut size_cdf); |
| 2903 | write_palette_colors_y(&mut enc, &pal.colors[..n], &[]); |
| 2904 | let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2]; |
| 2905 | write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n); |
| 2906 | enc.bits() |
| 2907 | } |
| 2908 | |
| 2909 | |
| 2910 | |
| 2911 | |
| 2912 | pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { |
| 2913 | let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { |
| 2914 | return f64::INFINITY; |
| 2915 | }; |
| 2916 | let n = usize::from(pal.size); |
| 2917 | let mut enc = SymbolEncoder::pricer(); |
| 2918 | let mut mode_cdf = cdf::PALETTE_UV_MODE[0]; |
| 2919 | enc.symbol(1, &mut mode_cdf); |
| 2920 | let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx]; |
| 2921 | enc.symbol(n - 2, &mut size_cdf); |
| 2922 | write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]); |
| 2923 | let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2]; |
| 2924 | write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n); |
| 2925 | enc.bits() |
| 2926 | } |
| 2927 | |
| 2928 | |
| 2929 | |
| 2930 | |
| 2931 | |
| 2932 | |
| 2933 | |
| 2934 | |
| 2935 | |
| 2936 | |
| 2937 | |
| 2938 | |
| 2939 | fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) { |
| 2940 | const INTRABC_DELAY_PIXELS: i32 = 256; |
| 2941 | let n4 = side / MI; |
| 2942 | let stack_pred = INTRABC_GRID.with(|g| { |
| 2943 | let g = g.borrow(); |
| 2944 | g.as_ref().map(|(grid, mi_cols, mi_rows)| { |
| 2945 | let stack = crate::mvstack::find_mv_stack( |
| 2946 | grid, mi_r, mi_c, n4, n4, 0, |
| 2947 | *mi_cols, *mi_rows, |
| 2948 | ); |
| 2949 | if stack.nearest_mv == (0, 0) { |
| 2950 | stack.near_mv |
| 2951 | } else { |
| 2952 | stack.nearest_mv |
| 2953 | } |
| 2954 | }) |
| 2955 | }); |
| 2956 | let mut pred = stack_pred.unwrap_or((0, 0)); |
| 2957 | if pred == (0, 0) { |
| 2958 | |
| 2959 | |
| 2960 | |
| 2961 | |
| 2962 | |
| 2963 | let sb_mi = 16i32; |
| 2964 | let sb_px = sb_mi * MI as i32; |
| 2965 | pred = if (mi_r as i32) < sb_mi { |
| 2966 | (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8) |
| 2967 | } else { |
| 2968 | (-sb_px * 8, 0) |
| 2969 | }; |
| 2970 | } |
| 2971 | ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8) |
| 2972 | } |
| 2973 | |
| 2974 | |
| 2975 | |
| 2976 | |
| 2977 | fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) { |
| 2978 | INTRABC_GRID.with(|g| { |
| 2979 | let mut g = g.borrow_mut(); |
| 2980 | let Some((grid, _, _)) = g.as_mut() else { |
| 2981 | return; |
| 2982 | }; |
| 2983 | let info = crate::mvstack::MiInfo { |
| 2984 | is_inter: dv.is_some(), |
| 2985 | ref_frame: 0, |
| 2986 | ref_frame1: crate::mvstack::NO_REF1, |
| 2987 | mv: crate::mvstack::mv16(dv.unwrap_or((0, 0))), |
| 2988 | mv1: (0, 0), |
| 2989 | is_new_mv: dv.is_some(), |
| 2990 | is_global_mv0: false, |
| 2991 | is_global_mv1: false, |
| 2992 | size: n4 as u8, |
| 2993 | size_h: n4 as u8, |
| 2994 | }; |
| 2995 | for r in mi_r..mi_r + n4 { |
| 2996 | for c in mi_c..mi_c + n4 { |
| 2997 | grid.set(r, c, info); |
| 2998 | } |
| 2999 | } |
| 3000 | }); |
| 3001 | } |
| 3002 | |
| 3003 | |
| 3004 | |
| 3005 | |
| 3006 | |
| 3007 | |
| 3008 | fn write_dv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> { |
| 3009 | let mag = diff.unsigned_abs() as i32; |
| 3010 | if mag % 8 != 0 { |
| 3011 | return Err(Error::unsupported( |
| 3012 | "AV1 tile", |
| 3013 | "a block vector is coded at full-pel precision only", |
| 3014 | )); |
| 3015 | } |
| 3016 | enc.symbol(usize::from(diff < 0), &mut c.sign); |
| 3017 | let z = mag - 1; |
| 3018 | let class = mv_class_of(z); |
| 3019 | enc.symbol(class, &mut c.class); |
| 3020 | let local = z - mv_class_base(class); |
| 3021 | if class == 0 { |
| 3022 | enc.symbol(((local >> 3) & 1) as usize, &mut c.class0_bit); |
| 3023 | } else { |
| 3024 | let d = local >> 3; |
| 3025 | for i in 0..class { |
| 3026 | enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]); |
| 3027 | } |
| 3028 | } |
| 3029 | Ok(()) |
| 3030 | } |
| 3031 | |
| 3032 | |
| 3033 | |
| 3034 | fn write_dv(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, dv: (i32, i32), pred: (i32, i32)) -> Result<()> { |
| 3035 | let diff = (dv.0 - pred.0, dv.1 - pred.1); |
| 3036 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 3037 | (false, false) => 0, |
| 3038 | (false, true) => 1, |
| 3039 | (true, false) => 2, |
| 3040 | (true, true) => 3, |
| 3041 | }; |
| 3042 | enc.symbol(joint, &mut cdfs.dv_joint); |
| 3043 | if diff.0 != 0 { |
| 3044 | write_dv_component(enc, &mut cdfs.dv_comp[0], diff.0)?; |
| 3045 | } |
| 3046 | if diff.1 != 0 { |
| 3047 | write_dv_component(enc, &mut cdfs.dv_comp[1], diff.1)?; |
| 3048 | } |
| 3049 | Ok(()) |
| 3050 | } |
| 3051 | |
| 3052 | |
| 3053 | |
| 3054 | |
| 3055 | |
| 3056 | |
| 3057 | |
| 3058 | fn write_intrabc_block( |
| 3059 | enc: &mut SymbolEncoder, |
| 3060 | cdfs: &mut Cdfs, |
| 3061 | neighbours: &mut Neighbours, |
| 3062 | dv: (i32, i32), |
| 3063 | mi: (usize, usize), |
| 3064 | side: usize, |
| 3065 | ) -> Result<()> { |
| 3066 | let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]); |
| 3067 | enc.symbol(1, &mut cdfs.skip[skip_ctx]); |
| 3068 | write_cdef_idx(enc, mi, true); |
| 3069 | enc.symbol(1, &mut cdfs.intrabc); |
| 3070 | write_dv(enc, cdfs, dv, intrabc_dv_pred(mi.0, mi.1, side))?; |
| 3071 | note_intrabc(dv); |
| 3072 | |
| 3073 | |
| 3074 | |
| 3075 | |
| 3076 | |
| 3077 | |
| 3078 | |
| 3079 | let empty: [Vec<i32>; 3] = [vec![0], vec![0], vec![0]]; |
| 3080 | for cell in 0..(side / SUB).max(1) { |
| 3081 | let (r, c) = (mi.0 / (SUB / MI), mi.1 / (SUB / MI)); |
| 3082 | neighbours.above_mode[c + cell] = DC_PRED; |
| 3083 | neighbours.left_mode[r + cell] = DC_PRED; |
| 3084 | neighbours.above_side[c + cell] = side; |
| 3085 | neighbours.left_side[r + cell] = side; |
| 3086 | } |
| 3087 | neighbours.record_mi_planes(mi, side, &empty, true); |
| 3088 | neighbours.record_tx(mi, side, side.min(64)); |
| 3089 | for cell in 0..side / MI { |
| 3090 | neighbours.above_skip[mi.1 + cell] = true; |
| 3091 | neighbours.left_skip[mi.0 + cell] = true; |
| 3092 | } |
| 3093 | Ok(()) |
| 3094 | } |
| 3095 | |
| 3096 | fn write_intra_mode( |
| 3097 | enc: &mut SymbolEncoder, |
| 3098 | cdfs: &mut Cdfs, |
| 3099 | neighbours: &mut Neighbours, |
| 3100 | block: &BlockCoeffs, |
| 3101 | above_mode: usize, |
| 3102 | left_mode: usize, |
| 3103 | cfl: bool, |
| 3104 | |
| 3105 | |
| 3106 | mi: (usize, usize), |
| 3107 | |
| 3108 | |
| 3109 | side: usize, |
| 3110 | ) -> usize { |
| 3111 | let mode = usize::from(block.mode); |
| 3112 | |
| 3113 | |
| 3114 | |
| 3115 | |
| 3116 | let skip_ctx = usize::from(neighbours.above_skip[mi.1]) + usize::from(neighbours.left_skip[mi.0]); |
| 3117 | enc.symbol(0, &mut cdfs.skip[skip_ctx]); |
| 3118 | write_cdef_idx(enc, mi, false); |
| 3119 | |
| 3120 | |
| 3121 | if intrabc_armed() { |
| 3122 | enc.symbol(0, &mut cdfs.intrabc); |
| 3123 | } |
| 3124 | enc.symbol( |
| 3125 | mode, |
| 3126 | &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], |
| 3127 | ); |
| 3128 | ec_rng_trace(|| format!("EC_YMODE mode={mode} tell={} rng={}", enc.tell(), enc.rng())); |
| 3129 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 3130 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); |
| 3131 | } |
| 3132 | |
| 3133 | |
| 3134 | let uv_mode = usize::from(block.uv_mode); |
| 3135 | if cfl { |
| 3136 | enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); |
| 3137 | } else { |
| 3138 | enc.symbol(uv_mode, &mut cdfs.uv_mode_no_cfl[mode]); |
| 3139 | } |
| 3140 | |
| 3141 | |
| 3142 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 3143 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); |
| 3144 | } |
| 3145 | |
| 3146 | |
| 3147 | |
| 3148 | |
| 3149 | |
| 3150 | |
| 3151 | |
| 3152 | write_palette_syntax( |
| 3153 | enc, |
| 3154 | cdfs, |
| 3155 | neighbours, |
| 3156 | block.palette.as_ref(), |
| 3157 | block.palette_uv.as_ref(), |
| 3158 | mode, |
| 3159 | uv_mode, |
| 3160 | mi, |
| 3161 | side, |
| 3162 | ); |
| 3163 | mode |
| 3164 | } |
| 3165 | |
| 3166 | |
| 3167 | |
| 3168 | |
| 3169 | |
| 3170 | |
| 3171 | |
| 3172 | |
| 3173 | |
| 3174 | |
| 3175 | |
| 3176 | |
| 3177 | |
| 3178 | |
| 3179 | #[allow(clippy::too_many_arguments)] |
| 3180 | fn write_palette_syntax( |
| 3181 | enc: &mut SymbolEncoder, |
| 3182 | cdfs: &mut Cdfs, |
| 3183 | neighbours: &mut Neighbours, |
| 3184 | palette: Option<&PaletteY>, |
| 3185 | palette_uv: Option<&PaletteUv>, |
| 3186 | mode: usize, |
| 3187 | uv_mode: usize, |
| 3188 | mi: (usize, usize), |
| 3189 | side: usize, |
| 3190 | ) { |
| 3191 | if !screen_armed() { |
| 3192 | return; |
| 3193 | } |
| 3194 | let palette = palette.filter(|_| mode == DC_PRED); |
| 3195 | let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED); |
| 3196 | if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) { |
| 3197 | let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi); |
| 3198 | let uv_cache = neighbours.palette_uv_cache(mi); |
| 3199 | if mode == DC_PRED { |
| 3200 | enc.symbol( |
| 3201 | usize::from(palette.is_some()), |
| 3202 | &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx], |
| 3203 | ); |
| 3204 | } |
| 3205 | if let Some(pal) = palette { |
| 3206 | let n = usize::from(pal.size); |
| 3207 | enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]); |
| 3208 | write_palette_colors_y(enc, &pal.colors[..n], &cache); |
| 3209 | } |
| 3210 | if uv_mode == DC_PRED { |
| 3211 | enc.symbol( |
| 3212 | usize::from(palette_uv.is_some()), |
| 3213 | &mut cdfs.palette_uv_mode[usize::from(palette.is_some())], |
| 3214 | ); |
| 3215 | } |
| 3216 | if let Some(pal) = palette_uv { |
| 3217 | let n = usize::from(pal.size); |
| 3218 | enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]); |
| 3219 | write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache); |
| 3220 | } |
| 3221 | |
| 3222 | |
| 3223 | if let Some(pal) = palette { |
| 3224 | let n = usize::from(pal.size); |
| 3225 | write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n); |
| 3226 | note_palette(n); |
| 3227 | } |
| 3228 | if let Some(pal) = palette_uv { |
| 3229 | let n = usize::from(pal.size); |
| 3230 | write_color_index_map( |
| 3231 | enc, |
| 3232 | &mut cdfs.palette_uv_color_index[n - 2], |
| 3233 | &pal.map, |
| 3234 | palette_uv_side(side), |
| 3235 | n, |
| 3236 | ); |
| 3237 | note_palette_uv(n); |
| 3238 | } |
| 3239 | } |
| 3240 | neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); |
| 3241 | neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors)); |
| 3242 | } |
| 3243 | |
| 3244 | |
| 3245 | |
| 3246 | |
| 3247 | |
| 3248 | pub(crate) fn palette_uv_side(side: usize) -> usize { |
| 3249 | (side / 2).max(4) |
| 3250 | } |
| 3251 | |
| 3252 | |
| 3253 | |
| 3254 | |
| 3255 | |
| 3256 | static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] = |
| 3257 | [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; |
| 3258 | |
| 3259 | fn note_palette(n: usize) { |
| 3260 | PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3261 | PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3262 | } |
| 3263 | |
| 3264 | |
| 3265 | |
| 3266 | static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] = |
| 3267 | [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; |
| 3268 | |
| 3269 | fn note_palette_uv(n: usize) { |
| 3270 | PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3271 | PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3272 | } |
| 3273 | |
| 3274 | |
| 3275 | |
| 3276 | |
| 3277 | |
| 3278 | static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize = |
| 3279 | std::sync::atomic::AtomicUsize::new(0); |
| 3280 | |
| 3281 | |
| 3282 | #[cfg(test)] |
| 3283 | pub(crate) fn take_palette_uv_cache_hits() -> usize { |
| 3284 | PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 3285 | } |
| 3286 | |
| 3287 | |
| 3288 | #[cfg(test)] |
| 3289 | pub(crate) fn take_palette_uv_hits() -> [usize; 9] { |
| 3290 | std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3291 | } |
| 3292 | |
| 3293 | |
| 3294 | |
| 3295 | #[cfg(test)] |
| 3296 | pub(crate) fn take_palette_hits() -> [usize; 9] { |
| 3297 | std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3298 | } |
| 3299 | |
| 3300 | |
| 3301 | |
| 3302 | |
| 3303 | #[allow(clippy::too_many_arguments)] |
| 3304 | fn write_block( |
| 3305 | enc: &mut SymbolEncoder, |
| 3306 | cdfs: &mut Cdfs, |
| 3307 | neighbours: &mut Neighbours, |
| 3308 | block: &BlockCoeffs, |
| 3309 | at: (usize, usize), |
| 3310 | side: usize, |
| 3311 | planes: &[TxbSet; 3], |
| 3312 | grids: &[Vec<i32>; 3], |
| 3313 | scans: [&Vec<u16>; 3], |
| 3314 | cfl: bool, |
| 3315 | |
| 3316 | |
| 3317 | |
| 3318 | |
| 3319 | tx_select: bool, |
| 3320 | all_scans: &[Vec<u16>; 4], |
| 3321 | ) -> Result<()> { |
| 3322 | let (r, c) = at; |
| 3323 | let at_mi = (r * (SUB / MI), c * (SUB / MI)); |
| 3324 | if let Some(dv) = block.dv { |
| 3325 | write_intrabc_block(enc, cdfs, neighbours, dv, at_mi, side)?; |
| 3326 | record_intrabc_mi(at_mi.0, at_mi.1, side / MI, Some(dv)); |
| 3327 | return Ok(()); |
| 3328 | } |
| 3329 | let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]); |
| 3330 | let mode = write_intra_mode( |
| 3331 | enc, |
| 3332 | cdfs, |
| 3333 | neighbours, |
| 3334 | block, |
| 3335 | above_mode, |
| 3336 | left_mode, |
| 3337 | cfl, |
| 3338 | at_mi, |
| 3339 | side, |
| 3340 | ); |
| 3341 | let split = if tx_select { |
| 3342 | let tx = write_luma_select( |
| 3343 | enc, |
| 3344 | cdfs, |
| 3345 | neighbours, |
| 3346 | at_mi, |
| 3347 | side, |
| 3348 | usize::from(block.tx_depth), |
| 3349 | &grids[0], |
| 3350 | mode, |
| 3351 | all_scans, |
| 3352 | )?; |
| 3353 | tx < side |
| 3354 | } else { |
| 3355 | false |
| 3356 | }; |
| 3357 | write_block_planes( |
| 3358 | enc, |
| 3359 | cdfs, |
| 3360 | planes, |
| 3361 | grids, |
| 3362 | &scans, |
| 3363 | &neighbours.around(at, side), |
| 3364 | mode, |
| 3365 | tx_select, |
| 3366 | ); |
| 3367 | neighbours.record_planes(at, side, mode, grids, !split); |
| 3368 | clear_skip_band(neighbours, at_mi, side); |
| 3369 | record_intrabc_mi(at_mi.0, at_mi.1, side / MI, None); |
| 3370 | Ok(()) |
| 3371 | } |
| 3372 | |
| 3373 | |
| 3374 | |
| 3375 | |
| 3376 | fn clear_skip_band(neighbours: &mut Neighbours, mi: (usize, usize), side: usize) { |
| 3377 | if !intrabc_armed() { |
| 3378 | return; |
| 3379 | } |
| 3380 | for cell in 0..side / MI { |
| 3381 | neighbours.above_skip[mi.1 + cell] = false; |
| 3382 | neighbours.left_skip[mi.0 + cell] = false; |
| 3383 | } |
| 3384 | } |
| 3385 | |
| 3386 | |
| 3387 | |
| 3388 | |
| 3389 | |
| 3390 | |
| 3391 | |
| 3392 | |
| 3393 | |
| 3394 | #[allow(clippy::too_many_arguments)] |
| 3395 | fn write_leaf8( |
| 3396 | enc: &mut SymbolEncoder, |
| 3397 | cdfs: &mut Cdfs, |
| 3398 | neighbours: &mut Neighbours, |
| 3399 | block: &BlockCoeffs, |
| 3400 | outer_at: (usize, usize), |
| 3401 | leaf_mi: (usize, usize), |
| 3402 | grids: &[Vec<i32>; 3], |
| 3403 | scans: [&Vec<u16>; 3], |
| 3404 | prev_leaf: Option<((usize, usize), usize)>, |
| 3405 | tx_select: bool, |
| 3406 | all_scans: &[Vec<u16>; 4], |
| 3407 | ) -> Result<usize> { |
| 3408 | let (r, c) = outer_at; |
| 3409 | if let Some(dv) = block.dv { |
| 3410 | write_intrabc_block(enc, cdfs, neighbours, dv, leaf_mi, 8)?; |
| 3411 | record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, Some(dv)); |
| 3412 | return Ok(DC_PRED); |
| 3413 | } |
| 3414 | let mut above_mode = neighbours.above_mode[c]; |
| 3415 | let mut left_mode = neighbours.left_mode[r]; |
| 3416 | |
| 3417 | |
| 3418 | |
| 3419 | |
| 3420 | if let Some(((pr, pc), pmode)) = prev_leaf { |
| 3421 | if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { |
| 3422 | above_mode = pmode; |
| 3423 | } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { |
| 3424 | left_mode = pmode; |
| 3425 | } |
| 3426 | } |
| 3427 | |
| 3428 | |
| 3429 | |
| 3430 | |
| 3431 | |
| 3432 | |
| 3433 | |
| 3434 | let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8); |
| 3435 | let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; |
| 3436 | let split = if tx_select { |
| 3437 | let tx = write_luma_select( |
| 3438 | enc, |
| 3439 | cdfs, |
| 3440 | neighbours, |
| 3441 | leaf_mi, |
| 3442 | 8, |
| 3443 | usize::from(block.tx_depth), |
| 3444 | &grids[0], |
| 3445 | mode, |
| 3446 | all_scans, |
| 3447 | )?; |
| 3448 | tx < 8 |
| 3449 | } else { |
| 3450 | false |
| 3451 | }; |
| 3452 | write_block_planes( |
| 3453 | enc, |
| 3454 | cdfs, |
| 3455 | &planes, |
| 3456 | grids, |
| 3457 | &scans, |
| 3458 | &neighbours.around_mi(leaf_mi, 8), |
| 3459 | mode, |
| 3460 | tx_select, |
| 3461 | ); |
| 3462 | neighbours.record_mi_planes(leaf_mi, 8, grids, !split); |
| 3463 | clear_skip_band(neighbours, leaf_mi, 8); |
| 3464 | record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, None); |
| 3465 | Ok(mode) |
| 3466 | } |
| 3467 | |
| 3468 | |
| 3469 | |
| 3470 | #[allow(clippy::too_many_arguments)] |
| 3471 | fn write_block_planes( |
| 3472 | enc: &mut SymbolEncoder, |
| 3473 | cdfs: &mut Cdfs, |
| 3474 | planes: &[TxbSet; 3], |
| 3475 | grids: &[Vec<i32>; 3], |
| 3476 | scans: &[&Vec<u16>; 3], |
| 3477 | around: &[Around; 3], |
| 3478 | mode: usize, |
| 3479 | |
| 3480 | |
| 3481 | skip_luma: bool, |
| 3482 | ) { |
| 3483 | for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() { |
| 3484 | if plane == 0 && skip_luma { |
| 3485 | continue; |
| 3486 | } |
| 3487 | |
| 3488 | |
| 3489 | |
| 3490 | |
| 3491 | let skip_ctx = if plane == 0 { |
| 3492 | 0 |
| 3493 | } else { |
| 3494 | usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded) |
| 3495 | }; |
| 3496 | write_coeffs( |
| 3497 | enc, |
| 3498 | &mut cdfs.txb(planes[plane], mode), |
| 3499 | grid, |
| 3500 | scan, |
| 3501 | skip_ctx, |
| 3502 | dc_sign_ctx(around[plane].dc_vote), |
| 3503 | Some(plane), |
| 3504 | ); |
| 3505 | ec_rng_trace(|| { |
| 3506 | format!( |
| 3507 | "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", |
| 3508 | grid.iter().filter(|&&l| l != 0).count(), |
| 3509 | enc.tell() |
| 3510 | ) |
| 3511 | }); |
| 3512 | } |
| 3513 | } |
| 3514 | |
| 3515 | |
| 3516 | |
| 3517 | |
| 3518 | |
| 3519 | |
| 3520 | #[allow(clippy::too_many_arguments)] |
| 3521 | fn write_luma_tus( |
| 3522 | enc: &mut SymbolEncoder, |
| 3523 | cdfs: &mut Cdfs, |
| 3524 | neighbours: &mut Neighbours, |
| 3525 | at_mi: (usize, usize), |
| 3526 | side: usize, |
| 3527 | tx: usize, |
| 3528 | grid: &[i32], |
| 3529 | mode: usize, |
| 3530 | scans: &[Vec<u16>; 4], |
| 3531 | |
| 3532 | |
| 3533 | inter: bool, |
| 3534 | ) -> Result<()> { |
| 3535 | if tx < side && side > 32 { |
| 3536 | |
| 3537 | |
| 3538 | |
| 3539 | return Err(Error::unsupported( |
| 3540 | "AV1 tile", |
| 3541 | "a 64x64 block's split luma transform is not written yet", |
| 3542 | )); |
| 3543 | } |
| 3544 | let coeff_side = tx.min(32); |
| 3545 | let n = side / tx; |
| 3546 | let set = match (tx, inter) { |
| 3547 | (32, false) => TxbSet::Luma32, |
| 3548 | (16, false) => TxbSet::Luma16, |
| 3549 | (8, false) => TxbSet::Luma8, |
| 3550 | (4, false) => TxbSet::Luma4, |
| 3551 | (32, true) => TxbSet::Luma32Inter, |
| 3552 | (16, true) => TxbSet::Luma16Inter, |
| 3553 | (8, true) => TxbSet::Luma8Inter, |
| 3554 | (4, true) => TxbSet::Luma4Inter, |
| 3555 | _ => TxbSet::Luma64, |
| 3556 | }; |
| 3557 | let scan = match coeff_side { |
| 3558 | 32 => &scans[0], |
| 3559 | 16 => &scans[1], |
| 3560 | 8 => &scans[2], |
| 3561 | _ => &scans[3], |
| 3562 | }; |
| 3563 | let (mi_r, mi_c) = at_mi; |
| 3564 | for tu_row in 0..n { |
| 3565 | for tu_col in 0..n { |
| 3566 | let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI)); |
| 3567 | let unit = if n == 1 { |
| 3568 | grid.to_vec() |
| 3569 | } else { |
| 3570 | (0..tx) |
| 3571 | .flat_map(|row| { |
| 3572 | grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec() |
| 3573 | }) |
| 3574 | .collect() |
| 3575 | }; |
| 3576 | |
| 3577 | |
| 3578 | |
| 3579 | let skip_ctx = if n == 1 { |
| 3580 | 0 |
| 3581 | } else { |
| 3582 | neighbours.luma_skip_ctx(tu_mi, tx / MI) |
| 3583 | }; |
| 3584 | let around = neighbours.around_mi(tu_mi, tx)[0]; |
| 3585 | write_coeffs( |
| 3586 | enc, |
| 3587 | &mut cdfs.txb(set, mode), |
| 3588 | &unit, |
| 3589 | scan, |
| 3590 | skip_ctx, |
| 3591 | dc_sign_ctx(around.dc_vote), |
| 3592 | Some(0), |
| 3593 | ); |
| 3594 | if n > 1 { |
| 3595 | neighbours.record_mi_luma(tu_mi, tx, &unit); |
| 3596 | } |
| 3597 | } |
| 3598 | } |
| 3599 | Ok(()) |
| 3600 | } |
| 3601 | |
| 3602 | |
| 3603 | |
| 3604 | |
| 3605 | |
| 3606 | |
| 3607 | |
| 3608 | |
| 3609 | |
| 3610 | |
| 3611 | |
| 3612 | |
| 3613 | #[allow(clippy::too_many_arguments)] |
| 3614 | fn write_luma_select( |
| 3615 | enc: &mut SymbolEncoder, |
| 3616 | cdfs: &mut Cdfs, |
| 3617 | neighbours: &mut Neighbours, |
| 3618 | at_mi: (usize, usize), |
| 3619 | side: usize, |
| 3620 | depth: usize, |
| 3621 | grid: &[i32], |
| 3622 | mode: usize, |
| 3623 | scans: &[Vec<u16>; 4], |
| 3624 | ) -> Result<usize> { |
| 3625 | let max_tx = side.min(64); |
| 3626 | let ctx = neighbours.tx_size_ctx(at_mi, max_tx); |
| 3627 | match max_tx { |
| 3628 | 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]), |
| 3629 | 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]), |
| 3630 | 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]), |
| 3631 | 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]), |
| 3632 | _ => { |
| 3633 | return Err(Error::unsupported( |
| 3634 | "AV1 tile", |
| 3635 | "a tx_depth symbol is only coded at 8/16/32/64", |
| 3636 | )); |
| 3637 | } |
| 3638 | } |
| 3639 | let tx = max_tx >> depth; |
| 3640 | write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false)?; |
| 3641 | neighbours.record_tx(at_mi, side, tx); |
| 3642 | Ok(tx) |
| 3643 | } |
| 3644 | |
| 3645 | |
| 3646 | |
| 3647 | |
| 3648 | |
| 3649 | |
| 3650 | |
| 3651 | |
| 3652 | |
| 3653 | |
| 3654 | |
| 3655 | |
| 3656 | |
| 3657 | |
| 3658 | |
| 3659 | #[allow(clippy::too_many_arguments)] |
| 3660 | fn write_tx_syntax_inter( |
| 3661 | enc: &mut SymbolEncoder, |
| 3662 | cdfs: &mut Cdfs, |
| 3663 | neighbours: &mut Neighbours, |
| 3664 | at_mi: (usize, usize), |
| 3665 | side: usize, |
| 3666 | is_inter: bool, |
| 3667 | skip: bool, |
| 3668 | depth: usize, |
| 3669 | ) -> usize { |
| 3670 | let max_tx = side.min(64); |
| 3671 | let (mi_r, mi_c) = at_mi; |
| 3672 | if is_inter { |
| 3673 | if !skip { |
| 3674 | let ctx = txfm_partition_ctx_rect( |
| 3675 | neighbours.above_txfm[mi_c], |
| 3676 | neighbours.left_txfm[mi_r], |
| 3677 | side, |
| 3678 | max_tx, |
| 3679 | max_tx, |
| 3680 | ); |
| 3681 | enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]); |
| 3682 | if depth == 0 { |
| 3683 | neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx); |
| 3684 | return max_tx; |
| 3685 | } |
| 3686 | |
| 3687 | |
| 3688 | |
| 3689 | |
| 3690 | |
| 3691 | |
| 3692 | let tx = max_tx / 2; |
| 3693 | for row in (0..max_tx / MI).step_by(tx / MI) { |
| 3694 | for col in (0..max_tx / MI).step_by(tx / MI) { |
| 3695 | let unit = (mi_r + row, mi_c + col); |
| 3696 | |
| 3697 | |
| 3698 | |
| 3699 | debug_assert!( |
| 3700 | unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols, |
| 3701 | "a split inter transform unit past the frame edge" |
| 3702 | ); |
| 3703 | let ctx = txfm_partition_ctx_rect( |
| 3704 | neighbours.above_txfm[unit.1], |
| 3705 | neighbours.left_txfm[unit.0], |
| 3706 | side, |
| 3707 | tx, |
| 3708 | tx, |
| 3709 | ); |
| 3710 | enc.symbol(0, &mut cdfs.txfm_partition[ctx]); |
| 3711 | neighbours.record_txfm(unit, tx, tx, tx); |
| 3712 | } |
| 3713 | } |
| 3714 | return tx; |
| 3715 | } |
| 3716 | neighbours.record_txfm(at_mi, side, side, side); |
| 3717 | return max_tx; |
| 3718 | } |
| 3719 | let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx); |
| 3720 | match max_tx { |
| 3721 | 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]), |
| 3722 | 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]), |
| 3723 | 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]), |
| 3724 | _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]), |
| 3725 | } |
| 3726 | let tx = max_tx >> depth; |
| 3727 | neighbours.record_txfm(at_mi, tx, side, side); |
| 3728 | tx |
| 3729 | } |
| 3730 | |
| 3731 | |
| 3732 | |
| 3733 | fn neighbour_state(grid: &[i32]) -> Neighbour { |
| 3734 | Neighbour { |
| 3735 | coded: grid.iter().any(|&l| l != 0), |
| 3736 | level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8, |
| 3737 | dc: (grid[0] != 0).then_some(grid[0] < 0), |
| 3738 | } |
| 3739 | } |
| 3740 | |
| 3741 | |
| 3742 | |
| 3743 | |
| 3744 | |
| 3745 | |
| 3746 | |
| 3747 | |
| 3748 | |
| 3749 | pub fn split_coeff_key_frame_tile( |
| 3750 | mi_cols: u32, |
| 3751 | mi_rows: u32, |
| 3752 | base_q_idx: u8, |
| 3753 | blocks: &[BlockCoeffs], |
| 3754 | ) -> Result<Vec<u8>> { |
| 3755 | check_blocks(mi_cols, mi_rows)?; |
| 3756 | let (cols, rows) = block_grid(mi_cols, mi_rows); |
| 3757 | if blocks.len() != (cols * rows) as usize { |
| 3758 | return Err(Error::unsupported( |
| 3759 | "AV1 tile", |
| 3760 | "a coefficient key frame needs one coefficient set per 32x32 block", |
| 3761 | )); |
| 3762 | } |
| 3763 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 3764 | let superblocks: Vec<Superblock> = (0..sb_rows) |
| 3765 | .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c))) |
| 3766 | .map(|(sb_r, sb_c)| { |
| 3767 | Superblock::Split( |
| 3768 | (0..4) |
| 3769 | .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) |
| 3770 | .filter(|&(r, c)| r < rows && c < cols) |
| 3771 | .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone())) |
| 3772 | .collect(), |
| 3773 | ) |
| 3774 | }) |
| 3775 | .collect(); |
| 3776 | sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks) |
| 3777 | } |
| 3778 | |
| 3779 | |
| 3780 | |
| 3781 | fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> { |
| 3782 | let mut grid = vec![0i32; side * side]; |
| 3783 | for coeff in coeffs { |
| 3784 | if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side { |
| 3785 | return Err(Error::unsupported( |
| 3786 | "AV1 tile", |
| 3787 | "a coefficient sits outside the transform of its plane", |
| 3788 | )); |
| 3789 | } |
| 3790 | if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL { |
| 3791 | return Err(Error::unsupported( |
| 3792 | "AV1 tile", |
| 3793 | format!( |
| 3794 | "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero" |
| 3795 | ), |
| 3796 | )); |
| 3797 | } |
| 3798 | let pos = usize::from(coeff.row) * side + usize::from(coeff.col); |
| 3799 | if grid[pos] != 0 { |
| 3800 | return Err(Error::unsupported( |
| 3801 | "AV1 tile", |
| 3802 | "two coefficients of one block share a position", |
| 3803 | )); |
| 3804 | } |
| 3805 | grid[pos] = coeff.level; |
| 3806 | } |
| 3807 | Ok(grid) |
| 3808 | } |
| 3809 | |
| 3810 | |
| 3811 | |
| 3812 | |
| 3813 | |
| 3814 | |
| 3815 | |
| 3816 | |
| 3817 | fn default_scan(side: usize) -> Vec<u16> { |
| 3818 | let mut scan = Vec::with_capacity(side * side); |
| 3819 | for d in 0..(2 * side - 1) { |
| 3820 | let lo = d.saturating_sub(side - 1); |
| 3821 | let hi = d.min(side - 1); |
| 3822 | let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16); |
| 3823 | if d % 2 == 0 { |
| 3824 | scan.extend(diagonal.rev()); |
| 3825 | } else { |
| 3826 | scan.extend(diagonal); |
| 3827 | } |
| 3828 | } |
| 3829 | scan |
| 3830 | } |
| 3831 | |
| 3832 | |
| 3833 | |
| 3834 | |
| 3835 | |
| 3836 | |
| 3837 | |
| 3838 | |
| 3839 | |
| 3840 | |
| 3841 | |
| 3842 | |
| 3843 | |
| 3844 | |
| 3845 | |
| 3846 | |
| 3847 | |
| 3848 | |
| 3849 | |
| 3850 | |
| 3851 | |
| 3852 | |
| 3853 | |
| 3854 | |
| 3855 | #[cfg(test)] |
| 3856 | fn dense(coeffs: &[Coeff], side: usize) -> Vec<i32> { |
| 3857 | let mut grid = vec![0i32; side * side]; |
| 3858 | for c in coeffs { |
| 3859 | grid[usize::from(c.row) * side + usize::from(c.col)] = c.level; |
| 3860 | } |
| 3861 | grid |
| 3862 | } |
| 3863 | |
| 3864 | #[cfg(test)] |
| 3865 | pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 { |
| 3866 | let q_ctx = crate::decode::q_ctx_of(base_q_idx); |
| 3867 | superblocks |
| 3868 | .iter() |
| 3869 | .map(|sb| match sb { |
| 3870 | |
| 3871 | |
| 3872 | |
| 3873 | Superblock::Whole(block) if !block.skip => { |
| 3874 | coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx) |
| 3875 | + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx) |
| 3876 | + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx) |
| 3877 | } |
| 3878 | Superblock::Whole(_) => 0.0, |
| 3879 | Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx), |
| 3880 | }) |
| 3881 | .sum() |
| 3882 | } |
| 3883 | |
| 3884 | #[cfg(test)] |
| 3885 | pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { |
| 3886 | let q_ctx = crate::decode::q_ctx_of(base_q_idx); |
| 3887 | fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 { |
| 3888 | if let Some(leaves) = &block.eight { |
| 3889 | return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum(); |
| 3890 | } |
| 3891 | if block.skip { |
| 3892 | return 0.0; |
| 3893 | } |
| 3894 | let inter = block.inter.is_some(); |
| 3895 | let (luma, chroma) = match (side, inter) { |
| 3896 | (32, false) => (TxbSet::Luma32, TxbSet::Chroma16), |
| 3897 | (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16), |
| 3898 | (16, false) => (TxbSet::Luma16, TxbSet::Chroma8), |
| 3899 | (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8), |
| 3900 | (_, false) => (TxbSet::Luma8, TxbSet::Chroma4), |
| 3901 | (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4), |
| 3902 | }; |
| 3903 | coeff_bits(&dense(&block.luma, side), luma, q_ctx) |
| 3904 | + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx) |
| 3905 | + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx) |
| 3906 | } |
| 3907 | blocks |
| 3908 | .iter() |
| 3909 | .map(|q| { |
| 3910 | let side = match q { |
| 3911 | Quadrant::Whole(_) => 32, |
| 3912 | Quadrant::Split(_) => 16, |
| 3913 | }; |
| 3914 | q.blocks().iter().map(|b| block_bits(b, side, q_ctx)).sum::<f64>() |
| 3915 | }) |
| 3916 | .sum() |
| 3917 | } |
| 3918 | |
| 3919 | #[cfg(test)] |
| 3920 | pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { |
| 3921 | coeff_bits(grid, TxbSet::Luma32, 2) |
| 3922 | } |
| 3923 | |
| 3924 | |
| 3925 | |
| 3926 | |
| 3927 | |
| 3928 | |
| 3929 | |
| 3930 | |
| 3931 | |
| 3932 | |
| 3933 | |
| 3934 | pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { |
| 3935 | |
| 3936 | |
| 3937 | static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| { |
| 3938 | [ |
| 3939 | default_scan(TX4), |
| 3940 | default_scan(TX8), |
| 3941 | default_scan(TX16), |
| 3942 | default_scan(TX32), |
| 3943 | ] |
| 3944 | }); |
| 3945 | |
| 3946 | |
| 3947 | |
| 3948 | |
| 3949 | |
| 3950 | |
| 3951 | |
| 3952 | |
| 3953 | thread_local! { |
| 3954 | static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> = |
| 3955 | const { RefCell::new([None, None, None, None]) }; |
| 3956 | } |
| 3957 | PRICING.with_borrow_mut(|slots| { |
| 3958 | let slot = slots[q_ctx.min(3)] |
| 3959 | .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx)))); |
| 3960 | let (pristine, scratch) = (&mut slot.0, &mut slot.1); |
| 3961 | let src = pristine.txb(set, DC_PRED); |
| 3962 | let mut coding = scratch.txb(set, DC_PRED); |
| 3963 | coding.txb_skip.copy_from_slice(src.txb_skip); |
| 3964 | coding.eob_pt.copy_from_slice(src.eob_pt); |
| 3965 | if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) { |
| 3966 | dst.copy_from_slice(src); |
| 3967 | } |
| 3968 | *coding.eob_extra = *src.eob_extra; |
| 3969 | *coding.base = *src.base; |
| 3970 | *coding.base_eob = *src.base_eob; |
| 3971 | *coding.br = *src.br; |
| 3972 | *coding.dc_sign = *src.dc_sign; |
| 3973 | if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { |
| 3974 | dst.copy_from_slice(src); |
| 3975 | } |
| 3976 | let scan = match coding.side { |
| 3977 | TX4 => &SCANS[0], |
| 3978 | TX8 => &SCANS[1], |
| 3979 | TX16 => &SCANS[2], |
| 3980 | _ => &SCANS[3], |
| 3981 | }; |
| 3982 | let mut enc = SymbolEncoder::pricer(); |
| 3983 | write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); |
| 3984 | enc.bits() |
| 3985 | }) |
| 3986 | } |
| 3987 | |
| 3988 | |
| 3989 | |
| 3990 | |
| 3991 | |
| 3992 | |
| 3993 | |
| 3994 | pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { |
| 3995 | |
| 3996 | |
| 3997 | static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2)); |
| 3998 | let cdfs = &*CDFS; |
| 3999 | let cdf: &[u16] = match side { |
| 4000 | SB => &cdfs.partition_w64[0], |
| 4001 | BLOCK => &cdfs.partition_w32[0], |
| 4002 | TX8 => &cdfs.partition_w8[0], |
| 4003 | _ => &cdfs.partition_w16[0], |
| 4004 | }; |
| 4005 | let symbol = if split { |
| 4006 | PARTITION_SPLIT |
| 4007 | } else { |
| 4008 | PARTITION_NONE |
| 4009 | }; |
| 4010 | crate::encode::symbol_bits(cdf, symbol) |
| 4011 | } |
| 4012 | |
| 4013 | |
| 4014 | |
| 4015 | |
| 4016 | |
| 4017 | |
| 4018 | |
| 4019 | |
| 4020 | |
| 4021 | #[allow(clippy::too_many_arguments)] |
| 4022 | fn write_coeffs( |
| 4023 | enc: &mut SymbolEncoder, |
| 4024 | coding: &mut TxbTables, |
| 4025 | grid: &[i32], |
| 4026 | scan: &[u16], |
| 4027 | skip_ctx: usize, |
| 4028 | sign_ctx: usize, |
| 4029 | plane: Option<usize>, |
| 4030 | ) { |
| 4031 | if let Some(plane) = plane { |
| 4032 | ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell())); |
| 4033 | } |
| 4034 | let side = coding.side; |
| 4035 | |
| 4036 | |
| 4037 | |
| 4038 | |
| 4039 | |
| 4040 | |
| 4041 | let eob = if grid.iter().all(|&level| level == 0) { |
| 4042 | 0 |
| 4043 | } else { |
| 4044 | scan.iter() |
| 4045 | .rposition(|&pos| grid[pos as usize] != 0) |
| 4046 | .map_or(0, |i| i + 1) |
| 4047 | }; |
| 4048 | enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]); |
| 4049 | if plane.is_some() { |
| 4050 | ec_rng_trace(|| { |
| 4051 | format!( |
| 4052 | "EC_TXBSKIP ctx={skip_ctx} eob0={} tell={} rng={}", |
| 4053 | usize::from(eob == 0), |
| 4054 | enc.tell(), |
| 4055 | enc.rng() |
| 4056 | ) |
| 4057 | }); |
| 4058 | } |
| 4059 | if eob == 0 { |
| 4060 | return; |
| 4061 | } |
| 4062 | |
| 4063 | |
| 4064 | |
| 4065 | if let Some(tx_type) = coding.tx_type.as_deref_mut() { |
| 4066 | enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type); |
| 4067 | if plane.is_some() { |
| 4068 | ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng())); |
| 4069 | } |
| 4070 | } |
| 4071 | |
| 4072 | write_eob(enc, coding, eob, plane); |
| 4073 | |
| 4074 | for scan_idx in (0..eob).rev() { |
| 4075 | let pos = scan[scan_idx] as usize; |
| 4076 | let (row, col) = (pos / side, pos % side); |
| 4077 | let level = grid[pos].abs(); |
| 4078 | if scan_idx == eob - 1 { |
| 4079 | let ctx = eob_coeff_ctx(scan_idx, side * side); |
| 4080 | let sym = (level.min(NUM_BASE_LEVELS + 1) - 1) as usize; |
| 4081 | enc.symbol(sym, &mut coding.base_eob[ctx]); |
| 4082 | if plane.is_some() { |
| 4083 | ec_rng_trace(|| { |
| 4084 | format!( |
| 4085 | "EC_BASEEOB scan_idx={scan_idx} ctx={ctx} level={} tell={}", |
| 4086 | sym + 1, |
| 4087 | enc.tell() |
| 4088 | ) |
| 4089 | }); |
| 4090 | } |
| 4091 | } else { |
| 4092 | let ctx = base_ctx(grid, side, row, col); |
| 4093 | let sym = level.min(NUM_BASE_LEVELS + 1) as usize; |
| 4094 | enc.symbol(sym, &mut coding.base[ctx]); |
| 4095 | if plane.is_some() { |
| 4096 | ec_rng_trace(|| { |
| 4097 | format!( |
| 4098 | "EC_BASE scan_idx={scan_idx} ctx={ctx} level={sym} tell={}", |
| 4099 | enc.tell() |
| 4100 | ) |
| 4101 | }); |
| 4102 | } |
| 4103 | } |
| 4104 | if level > NUM_BASE_LEVELS { |
| 4105 | let ctx = br_ctx(grid, side, row, col); |
| 4106 | let mut remaining = level - (NUM_BASE_LEVELS + 1); |
| 4107 | let mut sent = 0; |
| 4108 | while sent < COEFF_BASE_RANGE { |
| 4109 | let k = remaining.min(BR_STEP); |
| 4110 | enc.symbol(k as usize, &mut coding.br[ctx]); |
| 4111 | if plane.is_some() { |
| 4112 | ec_rng_trace(|| { |
| 4113 | format!( |
| 4114 | "EC_BR scan_idx={scan_idx} ctx={ctx} k={k} tell={}", |
| 4115 | enc.tell() |
| 4116 | ) |
| 4117 | }); |
| 4118 | } |
| 4119 | if k < BR_STEP { |
| 4120 | break; |
| 4121 | } |
| 4122 | remaining -= k; |
| 4123 | sent += BR_STEP; |
| 4124 | } |
| 4125 | } |
| 4126 | } |
| 4127 | |
| 4128 | |
| 4129 | |
| 4130 | for &pos in &scan[..eob] { |
| 4131 | let level = grid[pos as usize]; |
| 4132 | if level == 0 { |
| 4133 | continue; |
| 4134 | } |
| 4135 | if pos == 0 { |
| 4136 | enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]); |
| 4137 | if plane.is_some() { |
| 4138 | ec_rng_trace(|| { |
| 4139 | format!( |
| 4140 | "EC_DCSIGN ctx={sign_ctx} neg={} tell={}", |
| 4141 | usize::from(level < 0), |
| 4142 | enc.tell() |
| 4143 | ) |
| 4144 | }); |
| 4145 | } |
| 4146 | } else { |
| 4147 | enc.literal(u32::from(level < 0), 1); |
| 4148 | } |
| 4149 | |
| 4150 | |
| 4151 | if level.abs() > MAX_BR_LEVEL { |
| 4152 | write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32); |
| 4153 | if plane.is_some() { |
| 4154 | ec_rng_trace(|| format!("EC_GOLOMB tell={}", enc.tell())); |
| 4155 | } |
| 4156 | } |
| 4157 | } |
| 4158 | if let Some(plane) = plane { |
| 4159 | ec_rng_trace(|| format!("EC_PLANE plane={plane} eob={eob} tell_after={}", enc.tell())); |
| 4160 | } |
| 4161 | } |
| 4162 | |
| 4163 | |
| 4164 | |
| 4165 | |
| 4166 | fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize, plane: Option<usize>) { |
| 4167 | |
| 4168 | |
| 4169 | const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; |
| 4170 | |
| 4171 | const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; |
| 4172 | |
| 4173 | let group = GROUP_START |
| 4174 | .iter() |
| 4175 | .rposition(|&start| start <= eob) |
| 4176 | .expect("the first group starts at zero"); |
| 4177 | |
| 4178 | |
| 4179 | enc.symbol(group - 1, coding.eob_pt); |
| 4180 | if let Some(plane) = plane { |
| 4181 | ec_rng_trace(|| { |
| 4182 | format!( |
| 4183 | "EC_EOBPT plane={plane} eob_pt={group} tell={} rng={}", |
| 4184 | enc.tell(), |
| 4185 | enc.rng() |
| 4186 | ) |
| 4187 | }); |
| 4188 | } |
| 4189 | |
| 4190 | let bits = OFFSET_BITS[group]; |
| 4191 | if bits > 0 { |
| 4192 | let offset = (eob - GROUP_START[group]) as u32; |
| 4193 | let top = (offset >> (bits - 1)) & 1; |
| 4194 | enc.symbol(top as usize, &mut coding.eob_extra[group - 3]); |
| 4195 | if let Some(plane) = plane { |
| 4196 | ec_rng_trace(|| { |
| 4197 | format!( |
| 4198 | "EC_EOBEXTRA plane={plane} eob_ctx={} top={top} tell={}", |
| 4199 | group - 3, |
| 4200 | enc.tell() |
| 4201 | ) |
| 4202 | }); |
| 4203 | } |
| 4204 | if bits > 1 { |
| 4205 | enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1); |
| 4206 | if let Some(plane) = plane { |
| 4207 | ec_rng_trace(|| { |
| 4208 | format!( |
| 4209 | "EC_EOBBITS plane={plane} eob_extra={offset} tell={}", |
| 4210 | enc.tell() |
| 4211 | ) |
| 4212 | }); |
| 4213 | } |
| 4214 | } |
| 4215 | } |
| 4216 | } |
| 4217 | |
| 4218 | |
| 4219 | |
| 4220 | |
| 4221 | pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) { |
| 4222 | let x = value + 1; |
| 4223 | let length = 32 - x.leading_zeros(); |
| 4224 | for _ in 0..length - 1 { |
| 4225 | enc.literal(0, 1); |
| 4226 | } |
| 4227 | for i in (0..length).rev() { |
| 4228 | enc.literal((x >> i) & 1, 1); |
| 4229 | } |
| 4230 | } |
| 4231 | |
| 4232 | |
| 4233 | |
| 4234 | fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize { |
| 4235 | match scan_idx { |
| 4236 | 0 => 0, |
| 4237 | i if i <= area / 8 => 1, |
| 4238 | i if i <= area / 4 => 2, |
| 4239 | _ => 3, |
| 4240 | } |
| 4241 | } |
| 4242 | |
| 4243 | |
| 4244 | |
| 4245 | |
| 4246 | |
| 4247 | fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { |
| 4248 | if row == 0 && col == 0 { |
| 4249 | return 0; |
| 4250 | } |
| 4251 | |
| 4252 | |
| 4253 | |
| 4254 | |
| 4255 | let p = row * side + col; |
| 4256 | let mag: i32 = if row + 2 < side && col + 2 < side { |
| 4257 | [p + side, p + 1, p + side + 1, p + 2 * side, p + 2] |
| 4258 | .iter() |
| 4259 | .map(|&i| grid[i].abs().min(3)) |
| 4260 | .sum() |
| 4261 | } else { |
| 4262 | [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] |
| 4263 | .iter() |
| 4264 | .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3)) |
| 4265 | .sum() |
| 4266 | }; |
| 4267 | let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize; |
| 4268 | (((mag + 1) >> 1).min(4) as usize) + offset |
| 4269 | } |
| 4270 | |
| 4271 | |
| 4272 | |
| 4273 | |
| 4274 | fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { |
| 4275 | let p = row * side + col; |
| 4276 | let mag: i32 = if row + 1 < side && col + 1 < side { |
| 4277 | grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs() |
| 4278 | } else { |
| 4279 | [(1, 0), (0, 1), (1, 1)] |
| 4280 | .iter() |
| 4281 | .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs()) |
| 4282 | .sum() |
| 4283 | }; |
| 4284 | let mag = (((mag + 1) >> 1).min(6)) as usize; |
| 4285 | if row == 0 && col == 0 { |
| 4286 | mag |
| 4287 | } else if row < 2 && col < 2 { |
| 4288 | mag + 7 |
| 4289 | } else { |
| 4290 | mag + 14 |
| 4291 | } |
| 4292 | } |
| 4293 | |
| 4294 | |
| 4295 | |
| 4296 | fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 { |
| 4297 | if row >= side || col >= side { |
| 4298 | 0 |
| 4299 | } else { |
| 4300 | grid[row * side + col] |
| 4301 | } |
| 4302 | } |
| 4303 | |
| 4304 | |
| 4305 | fn check_levels(levels: &[i32], blocks: usize) -> Result<()> { |
| 4306 | if levels.len() != blocks { |
| 4307 | return Err(Error::unsupported( |
| 4308 | "AV1 tile", |
| 4309 | "a DC-only key frame needs one level per coded block", |
| 4310 | )); |
| 4311 | } |
| 4312 | if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) { |
| 4313 | return Err(Error::unsupported( |
| 4314 | "AV1 tile", |
| 4315 | "a DC-only key frame is written for levels -14..=14 without zero; \ |
| 4316 | wider levels need the Golomb tail", |
| 4317 | )); |
| 4318 | } |
| 4319 | Ok(()) |
| 4320 | } |
| 4321 | |
| 4322 | |
| 4323 | |
| 4324 | |
| 4325 | |
| 4326 | |
| 4327 | |
| 4328 | fn write_dc_coeffs( |
| 4329 | enc: &mut SymbolEncoder, |
| 4330 | dc_level: i32, |
| 4331 | sign_ctx: usize, |
| 4332 | q_ctx: usize, |
| 4333 | txb_skip: &[u16], |
| 4334 | base_eob: &[u16], |
| 4335 | ) { |
| 4336 | use crate::cdf_state::pick; |
| 4337 | let level = dc_level.abs(); |
| 4338 | let eob_pt = pick( |
| 4339 | q_ctx, |
| 4340 | cdf::EOB_PT_1024_LUMA_Q0, |
| 4341 | cdf::EOB_PT_1024_LUMA_Q1, |
| 4342 | cdf::EOB_PT_1024_LUMA, |
| 4343 | cdf::EOB_PT_1024_LUMA_Q3, |
| 4344 | ); |
| 4345 | let br = pick( |
| 4346 | q_ctx, |
| 4347 | cdf::COEFF_BR_LUMA_32_Q0, |
| 4348 | cdf::COEFF_BR_LUMA_32_Q1, |
| 4349 | cdf::COEFF_BR_LUMA_32, |
| 4350 | cdf::COEFF_BR_LUMA_32_Q3, |
| 4351 | ); |
| 4352 | enc.symbol_fixed(0, txb_skip); |
| 4353 | enc.symbol_fixed(0, &eob_pt); |
| 4354 | enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob); |
| 4355 | if level > NUM_BASE_LEVELS { |
| 4356 | let mut remaining = level - (NUM_BASE_LEVELS + 1); |
| 4357 | let mut sent = 0; |
| 4358 | while sent < COEFF_BASE_RANGE { |
| 4359 | let k = remaining.min(BR_STEP); |
| 4360 | enc.symbol_fixed(k as usize, &br[0]); |
| 4361 | if k < BR_STEP { |
| 4362 | break; |
| 4363 | } |
| 4364 | remaining -= k; |
| 4365 | sent += BR_STEP; |
| 4366 | } |
| 4367 | } |
| 4368 | |
| 4369 | enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]); |
| 4370 | } |
| 4371 | |
| 4372 | |
| 4373 | |
| 4374 | |
| 4375 | |
| 4376 | |
| 4377 | |
| 4378 | fn dc_vote(dc: Option<bool>) -> i32 { |
| 4379 | match dc { |
| 4380 | None => 0, |
| 4381 | Some(true) => -1, |
| 4382 | Some(false) => 1, |
| 4383 | } |
| 4384 | } |
| 4385 | |
| 4386 | |
| 4387 | fn dc_sign_ctx(vote: i32) -> usize { |
| 4388 | match vote.signum() { |
| 4389 | 0 => 0, |
| 4390 | -1 => 1, |
| 4391 | _ => 2, |
| 4392 | } |
| 4393 | } |
| 4394 | |
| 4395 | |
| 4396 | |
| 4397 | |
| 4398 | |
| 4399 | fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inter: bool) -> usize { |
| 4400 | match (has_above, has_left) { |
| 4401 | (true, true) => { |
| 4402 | let (above_intra, left_intra) = (!above_inter, !left_inter); |
| 4403 | if above_intra && left_intra { |
| 4404 | 3 |
| 4405 | } else { |
| 4406 | usize::from(above_intra || left_intra) |
| 4407 | } |
| 4408 | } |
| 4409 | (true, false) => 2 * usize::from(!above_inter), |
| 4410 | (false, true) => 2 * usize::from(!left_inter), |
| 4411 | (false, false) => 0, |
| 4412 | } |
| 4413 | } |
| 4414 | |
| 4415 | |
| 4416 | |
| 4417 | fn mv_class_base(class: usize) -> i32 { |
| 4418 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 4419 | } |
| 4420 | |
| 4421 | |
| 4422 | |
| 4423 | |
| 4424 | fn mv_class_of(z: i32) -> usize { |
| 4425 | let mut class = 0; |
| 4426 | while class < 10 && mv_class_base(class + 1) <= z { |
| 4427 | class += 1; |
| 4428 | } |
| 4429 | class |
| 4430 | } |
| 4431 | |
| 4432 | |
| 4433 | |
| 4434 | |
| 4435 | |
| 4436 | |
| 4437 | |
| 4438 | |
| 4439 | |
| 4440 | |
| 4441 | |
| 4442 | |
| 4443 | fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> { |
| 4444 | debug_assert_ne!(diff, 0); |
| 4445 | let sign = diff < 0; |
| 4446 | enc.symbol(usize::from(sign), &mut c.sign); |
| 4447 | let mag = diff.unsigned_abs() as i32; |
| 4448 | let z = mag - 1; |
| 4449 | if z & 1 == 0 { |
| 4450 | return Err(Error::unsupported( |
| 4451 | "AV1 tile", |
| 4452 | "a motion vector component needs eighth-pel precision, which \ |
| 4453 | allow_high_precision_mv off does not carry", |
| 4454 | )); |
| 4455 | } |
| 4456 | let class = mv_class_of(z); |
| 4457 | enc.symbol(class, &mut c.class); |
| 4458 | let local = z - mv_class_base(class); |
| 4459 | if class == 0 { |
| 4460 | let bit = (local >> 3) & 1; |
| 4461 | let fr = (local >> 1) & 3; |
| 4462 | enc.symbol(bit as usize, &mut c.class0_bit); |
| 4463 | enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]); |
| 4464 | } else { |
| 4465 | let d = local >> 3; |
| 4466 | let fr = (local >> 1) & 3; |
| 4467 | for i in 0..class { |
| 4468 | enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]); |
| 4469 | } |
| 4470 | enc.symbol(fr as usize, &mut c.fr); |
| 4471 | } |
| 4472 | |
| 4473 | |
| 4474 | Ok(()) |
| 4475 | } |
| 4476 | |
| 4477 | |
| 4478 | |
| 4479 | |
| 4480 | fn write_mv( |
| 4481 | enc: &mut SymbolEncoder, |
| 4482 | mv_comp: &mut [MvComponentCdfs; 2], |
| 4483 | mv_joint: &mut [u16; 5], |
| 4484 | mv: (i32, i32), |
| 4485 | pred: (i32, i32), |
| 4486 | ) -> Result<()> { |
| 4487 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 4488 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 4489 | (false, false) => 0, |
| 4490 | (false, true) => 1, |
| 4491 | (true, false) => 2, |
| 4492 | (true, true) => 3, |
| 4493 | }; |
| 4494 | enc.symbol(joint, mv_joint); |
| 4495 | if diff.0 != 0 { |
| 4496 | write_mv_component(enc, &mut mv_comp[0], diff.0)?; |
| 4497 | } |
| 4498 | if diff.1 != 0 { |
| 4499 | write_mv_component(enc, &mut mv_comp[1], diff.1)?; |
| 4500 | } |
| 4501 | Ok(()) |
| 4502 | } |
| 4503 | |
| 4504 | |
| 4505 | |
| 4506 | fn block_ref(block: &BlockCoeffs) -> i8 { |
| 4507 | block.inter.map_or(-1, |i| i.ref_frame) |
| 4508 | } |
| 4509 | |
| 4510 | |
| 4511 | |
| 4512 | |
| 4513 | |
| 4514 | |
| 4515 | |
| 4516 | fn write_single_ref( |
| 4517 | enc: &mut SymbolEncoder, |
| 4518 | cdfs: &mut Cdfs, |
| 4519 | ref_frame: i8, |
| 4520 | above_ref: i8, |
| 4521 | above_ref1: Option<i8>, |
| 4522 | left_ref: i8, |
| 4523 | left_ref1: Option<i8>, |
| 4524 | ) { |
| 4525 | REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4526 | use crate::mvstack::{ |
| 4527 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 4528 | single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, |
| 4529 | single_ref_p5_ctx, single_ref_p6_ctx, |
| 4530 | }; |
| 4531 | let above = (above_ref > 0).then_some(above_ref); |
| 4532 | let left = (left_ref > 0).then_some(left_ref); |
| 4533 | |
| 4534 | |
| 4535 | |
| 4536 | |
| 4537 | |
| 4538 | let backward = ref_frame >= BWDREF_FRAME; |
| 4539 | enc.symbol( |
| 4540 | usize::from(backward), |
| 4541 | &mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0], |
| 4542 | ); |
| 4543 | if backward { |
| 4544 | let is_altref = ref_frame == ALTREF_FRAME; |
| 4545 | enc.symbol( |
| 4546 | usize::from(is_altref), |
| 4547 | &mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1], |
| 4548 | ); |
| 4549 | if !is_altref { |
| 4550 | enc.symbol( |
| 4551 | usize::from(ref_frame == ALTREF2_FRAME), |
| 4552 | &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5], |
| 4553 | ); |
| 4554 | } |
| 4555 | return; |
| 4556 | } |
| 4557 | let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME; |
| 4558 | enc.symbol( |
| 4559 | usize::from(far), |
| 4560 | &mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2], |
| 4561 | ); |
| 4562 | if far { |
| 4563 | enc.symbol( |
| 4564 | usize::from(ref_frame == GOLDEN_FRAME), |
| 4565 | &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4], |
| 4566 | ); |
| 4567 | } else { |
| 4568 | enc.symbol( |
| 4569 | usize::from(ref_frame == LAST2_FRAME), |
| 4570 | &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3], |
| 4571 | ); |
| 4572 | } |
| 4573 | } |
| 4574 | |
| 4575 | |
| 4576 | |
| 4577 | |
| 4578 | |
| 4579 | |
| 4580 | static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 4581 | std::sync::atomic::AtomicUsize::new(0), |
| 4582 | std::sync::atomic::AtomicUsize::new(0), |
| 4583 | std::sync::atomic::AtomicUsize::new(0), |
| 4584 | std::sync::atomic::AtomicUsize::new(0), |
| 4585 | ]; |
| 4586 | static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 4587 | std::sync::atomic::AtomicUsize::new(0), |
| 4588 | std::sync::atomic::AtomicUsize::new(0), |
| 4589 | std::sync::atomic::AtomicUsize::new(0), |
| 4590 | std::sync::atomic::AtomicUsize::new(0), |
| 4591 | ]; |
| 4592 | |
| 4593 | |
| 4594 | |
| 4595 | static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [ |
| 4596 | std::sync::atomic::AtomicUsize::new(0), |
| 4597 | std::sync::atomic::AtomicUsize::new(0), |
| 4598 | std::sync::atomic::AtomicUsize::new(0), |
| 4599 | std::sync::atomic::AtomicUsize::new(0), |
| 4600 | std::sync::atomic::AtomicUsize::new(0), |
| 4601 | std::sync::atomic::AtomicUsize::new(0), |
| 4602 | std::sync::atomic::AtomicUsize::new(0), |
| 4603 | ]; |
| 4604 | |
| 4605 | |
| 4606 | #[cfg(test)] |
| 4607 | pub(crate) fn take_ref_hits() -> [usize; 7] { |
| 4608 | std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4609 | } |
| 4610 | |
| 4611 | |
| 4612 | fn note_inter_mode(mode: usize, drl: usize) { |
| 4613 | INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4614 | DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4615 | } |
| 4616 | |
| 4617 | |
| 4618 | #[cfg(test)] |
| 4619 | pub(crate) fn take_inter_mode_hits() -> [usize; 4] { |
| 4620 | [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4621 | } |
| 4622 | |
| 4623 | |
| 4624 | #[cfg(test)] |
| 4625 | pub(crate) fn take_drl_hits() -> [usize; 4] { |
| 4626 | [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4627 | } |
| 4628 | |
| 4629 | |
| 4630 | |
| 4631 | |
| 4632 | |
| 4633 | |
| 4634 | |
| 4635 | fn write_drl_idx( |
| 4636 | enc: &mut SymbolEncoder, |
| 4637 | cdfs: &mut Cdfs, |
| 4638 | stack: &crate::mvstack::MvStack, |
| 4639 | start: usize, |
| 4640 | target: usize, |
| 4641 | ) { |
| 4642 | let mut idx = start; |
| 4643 | while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 4644 | let advance = idx < target; |
| 4645 | enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]); |
| 4646 | if !advance { |
| 4647 | return; |
| 4648 | } |
| 4649 | idx += 1; |
| 4650 | } |
| 4651 | } |
| 4652 | |
| 4653 | |
| 4654 | |
| 4655 | |
| 4656 | |
| 4657 | |
| 4658 | |
| 4659 | |
| 4660 | |
| 4661 | |
| 4662 | |
| 4663 | |
| 4664 | |
| 4665 | |
| 4666 | |
| 4667 | fn write_inter_mode( |
| 4668 | enc: &mut SymbolEncoder, |
| 4669 | cdfs: &mut Cdfs, |
| 4670 | info: InterInfo, |
| 4671 | stack: &crate::mvstack::MvStack, |
| 4672 | ) -> Result<((i32, i32), bool)> { |
| 4673 | let idx = usize::from(info.ref_mv_idx); |
| 4674 | if info.mode.compound_index().is_some() { |
| 4675 | return Err(Error::unsupported( |
| 4676 | "AV1 tile", |
| 4677 | "a compound mode is written by `write_compound_block`, not here", |
| 4678 | )); |
| 4679 | } |
| 4680 | match info.mode { |
| 4681 | InterMode::NewMv => { |
| 4682 | enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); |
| 4683 | write_drl_idx(enc, cdfs, stack, 0, idx); |
| 4684 | let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 4685 | write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?; |
| 4686 | note_inter_mode(3, idx); |
| 4687 | Ok((info.mv, true)) |
| 4688 | } |
| 4689 | InterMode::GlobalMv => { |
| 4690 | enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); |
| 4691 | enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); |
| 4692 | note_inter_mode(2, 0); |
| 4693 | Ok(((0, 0), false)) |
| 4694 | } |
| 4695 | InterMode::NearestMv => { |
| 4696 | enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); |
| 4697 | enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); |
| 4698 | enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); |
| 4699 | note_inter_mode(0, 0); |
| 4700 | Ok((stack.nearest_mv, false)) |
| 4701 | } |
| 4702 | InterMode::NearMv => { |
| 4703 | enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); |
| 4704 | enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); |
| 4705 | enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); |
| 4706 | |
| 4707 | let idx = idx.max(1); |
| 4708 | write_drl_idx(enc, cdfs, stack, 1, idx); |
| 4709 | let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv); |
| 4710 | note_inter_mode(1, idx); |
| 4711 | Ok((mv, false)) |
| 4712 | } |
| 4713 | _ => unreachable!("compound modes are refused above"), |
| 4714 | } |
| 4715 | } |
| 4716 | |
| 4717 | |
| 4718 | |
| 4719 | |
| 4720 | |
| 4721 | |
| 4722 | |
| 4723 | |
| 4724 | |
| 4725 | |
| 4726 | |
| 4727 | |
| 4728 | |
| 4729 | |
| 4730 | |
| 4731 | |
| 4732 | |
| 4733 | |
| 4734 | |
| 4735 | |
| 4736 | |
| 4737 | |
| 4738 | |
| 4739 | |
| 4740 | |
| 4741 | |
| 4742 | |
| 4743 | |
| 4744 | |
| 4745 | pub fn sb_coeff_inter_frame_tile( |
| 4746 | mi_cols: u32, |
| 4747 | mi_rows: u32, |
| 4748 | base_q_idx: u8, |
| 4749 | blocks: &[Quadrant], |
| 4750 | ) -> Result<Vec<u8>> { |
| 4751 | sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false) |
| 4752 | } |
| 4753 | |
| 4754 | |
| 4755 | |
| 4756 | |
| 4757 | |
| 4758 | |
| 4759 | |
| 4760 | |
| 4761 | |
| 4762 | |
| 4763 | pub fn sb_coeff_inter_frame_tile_tx( |
| 4764 | mi_cols: u32, |
| 4765 | mi_rows: u32, |
| 4766 | base_q_idx: u8, |
| 4767 | blocks: &[Quadrant], |
| 4768 | tx_select: bool, |
| 4769 | ) -> Result<Vec<u8>> { |
| 4770 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
| 4771 | sb_coeff_inter_frame_tile_cdfs( |
| 4772 | mi_cols, |
| 4773 | mi_rows, |
| 4774 | base_q_idx, |
| 4775 | blocks, |
| 4776 | tx_select, |
| 4777 | &mut cdfs, |
| 4778 | TileRect::whole(mi_cols, mi_rows), |
| 4779 | &mut MiGrid::new(mi_cols as usize, mi_rows as usize), |
| 4780 | ) |
| 4781 | } |
| 4782 | |
| 4783 | |
| 4784 | |
| 4785 | |
| 4786 | |
| 4787 | |
| 4788 | pub(crate) fn sb_coeff_inter_frame_tile_cdfs( |
| 4789 | mi_cols: u32, |
| 4790 | mi_rows: u32, |
| 4791 | _base_q_idx: u8, |
| 4792 | blocks: &[Quadrant], |
| 4793 | tx_select: bool, |
| 4794 | cdfs: &mut Cdfs, |
| 4795 | |
| 4796 | tile: TileRect, |
| 4797 | |
| 4798 | |
| 4799 | grid: &mut MiGrid, |
| 4800 | ) -> Result<Vec<u8>> { |
| 4801 | |
| 4802 | let _cdef_idx = CdefIdxGuard; |
| 4803 | check_blocks(mi_cols, mi_rows)?; |
| 4804 | |
| 4805 | |
| 4806 | |
| 4807 | |
| 4808 | let (cols, rows) = block_grid(mi_cols, mi_rows); |
| 4809 | if blocks.len() != (cols * rows) as usize { |
| 4810 | return Err(Error::unsupported( |
| 4811 | "AV1 tile", |
| 4812 | "an inter frame needs one entry per 32x32 block inside the true frame", |
| 4813 | )); |
| 4814 | } |
| 4815 | let coded: Vec<&BlockCoeffs> = blocks.iter().flat_map(Quadrant::blocks).collect(); |
| 4816 | if let Some(bad) = coded |
| 4817 | .into_iter() |
| 4818 | .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES) |
| 4819 | { |
| 4820 | return Err(Error::unsupported( |
| 4821 | "AV1 tile", |
| 4822 | format!( |
| 4823 | "intra mode {} is not one of the thirteen this writer codes", |
| 4824 | bad.mode |
| 4825 | ), |
| 4826 | )); |
| 4827 | } |
| 4828 | |
| 4829 | |
| 4830 | |
| 4831 | const SIZE_GROUP_32: usize = 3; |
| 4832 | |
| 4833 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 4834 | let mut neighbours = Neighbours::new( |
| 4835 | cols as usize * 2, |
| 4836 | rows as usize * 2, |
| 4837 | mi_cols as usize, |
| 4838 | mi_rows as usize, |
| 4839 | ); |
| 4840 | neighbours.set_tile_origin(tile.mi_row0 as usize, tile.mi_col0 as usize); |
| 4841 | |
| 4842 | |
| 4843 | |
| 4844 | |
| 4845 | |
| 4846 | |
| 4847 | |
| 4848 | let mut grid = &mut *grid; |
| 4849 | grid.set_tile_bounds( |
| 4850 | tile.mi_row0 as usize, |
| 4851 | tile.mi_col0 as usize, |
| 4852 | tile.mi_row1 as usize, |
| 4853 | tile.mi_col1 as usize, |
| 4854 | ); |
| 4855 | grid.set_sign_bias(SIGN_BIAS.with(std::cell::Cell::get)); |
| 4856 | let mut cdfs = cdfs; |
| 4857 | let mut enc = SymbolEncoder::new(); |
| 4858 | |
| 4859 | |
| 4860 | |
| 4861 | |
| 4862 | let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16]; |
| 4863 | let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16]; |
| 4864 | let scan32 = default_scan(TX32); |
| 4865 | let scan16 = default_scan(TX16); |
| 4866 | let scan8 = default_scan(TX8); |
| 4867 | let scan4 = default_scan(TX4); |
| 4868 | |
| 4869 | |
| 4870 | let all_scans = [ |
| 4871 | scan32.clone(), |
| 4872 | scan16.clone(), |
| 4873 | scan8.clone(), |
| 4874 | scan4.clone(), |
| 4875 | ]; |
| 4876 | let zero_grids = [ |
| 4877 | vec![0i32; TX32 * TX32], |
| 4878 | vec![0i32; TX16 * TX16], |
| 4879 | vec![0i32; TX16 * TX16], |
| 4880 | ]; |
| 4881 | |
| 4882 | for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { |
| 4883 | neighbours.start_row(); |
| 4884 | for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { |
| 4885 | write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); |
| 4886 | let sb_at = (sb_r as usize * 4, sb_c as usize * 4); |
| 4887 | let sb_ctx = neighbours.partition_ctx(sb_at, SB); |
| 4888 | |
| 4889 | |
| 4890 | |
| 4891 | |
| 4892 | |
| 4893 | |
| 4894 | |
| 4895 | let (has_cols, has_rows) = ( |
| 4896 | sb_c * SB_MI + SB_MI / 2 < mi_cols, |
| 4897 | sb_r * SB_MI + SB_MI / 2 < mi_rows, |
| 4898 | ); |
| 4899 | match (has_cols, has_rows) { |
| 4900 | (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]), |
| 4901 | (true, false) => { |
| 4902 | enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)); |
| 4903 | } |
| 4904 | (false, true) => { |
| 4905 | enc.symbol_fixed(1, &gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)); |
| 4906 | } |
| 4907 | (false, false) => {} |
| 4908 | } |
| 4909 | |
| 4910 | for quadrant in 0..4 { |
| 4911 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 4912 | |
| 4913 | |
| 4914 | |
| 4915 | |
| 4916 | if r32 >= rows || c32 >= cols { |
| 4917 | continue; |
| 4918 | } |
| 4919 | let site = &blocks[(r32 * cols + c32) as usize]; |
| 4920 | let at = (r32 as usize * 2, c32 as usize * 2); |
| 4921 | let ctx32 = neighbours.partition_ctx(at, BLOCK); |
| 4922 | |
| 4923 | |
| 4924 | |
| 4925 | |
| 4926 | let (has_cols32, has_rows32) = ( |
| 4927 | has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols), |
| 4928 | has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), |
| 4929 | ); |
| 4930 | let block = match site { |
| 4931 | Quadrant::Whole(block) => { |
| 4932 | if !has_cols32 || !has_rows32 { |
| 4933 | return Err(Error::unsupported( |
| 4934 | "AV1 tile", |
| 4935 | "a 32x32 block that is half outside the true frame \ |
| 4936 | cannot be left whole", |
| 4937 | )); |
| 4938 | } |
| 4939 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]); |
| 4940 | block |
| 4941 | } |
| 4942 | Quadrant::Split(sub_blocks) => { |
| 4943 | |
| 4944 | |
| 4945 | |
| 4946 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 4947 | .map(|i| (r32 as usize * 2 + i / 2, c32 as usize * 2 + i % 2)) |
| 4948 | .filter(|&(sr, sc)| { |
| 4949 | (sr as u32) * SUB_MI < mi_rows && (sc as u32) * SUB_MI < mi_cols |
| 4950 | }) |
| 4951 | .collect(); |
| 4952 | if sub_blocks.len() != sub_positions.len() { |
| 4953 | return Err(Error::unsupported( |
| 4954 | "AV1 tile", |
| 4955 | "a split 32x32 inter-frame block needs one 16x16 entry \ |
| 4956 | per sub-block inside the true frame", |
| 4957 | )); |
| 4958 | } |
| 4959 | |
| 4960 | |
| 4961 | match (has_cols32, has_rows32) { |
| 4962 | (true, true) => { |
| 4963 | enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx32]); |
| 4964 | } |
| 4965 | (true, false) => { |
| 4966 | enc.symbol_fixed( |
| 4967 | 1, |
| 4968 | &gather(&cdfs.partition_w32[ctx32], VERT_ALIKE), |
| 4969 | ); |
| 4970 | } |
| 4971 | (false, true) => { |
| 4972 | enc.symbol_fixed( |
| 4973 | 1, |
| 4974 | &gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE), |
| 4975 | ); |
| 4976 | } |
| 4977 | (false, false) => {} |
| 4978 | } |
| 4979 | for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) { |
| 4980 | |
| 4981 | |
| 4982 | |
| 4983 | |
| 4984 | |
| 4985 | |
| 4986 | let (has_cols16, has_rows16) = ( |
| 4987 | has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), |
| 4988 | has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), |
| 4989 | ); |
| 4990 | if !has_cols16 && !has_rows16 { |
| 4991 | return Err(Error::unsupported( |
| 4992 | "AV1 tile", |
| 4993 | "a 16x16 inter-frame block whose true edge cuts through \ |
| 4994 | both axes needs a rectangular transform this writer \ |
| 4995 | does not code yet", |
| 4996 | )); |
| 4997 | } |
| 4998 | let at16 = (sr, sc); |
| 4999 | if has_cols16 && has_rows16 { |
| 5000 | let ctx16 = neighbours.partition_ctx(at16, SUB); |
| 5001 | |
| 5002 | |
| 5003 | |
| 5004 | |
| 5005 | |
| 5006 | |
| 5007 | |
| 5008 | |
| 5009 | if let Some(leaves) = &leaf.eight { |
| 5010 | if leaves.len() != 4 { |
| 5011 | return Err(Error::unsupported( |
| 5012 | "AV1 tile", |
| 5013 | "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves", |
| 5014 | )); |
| 5015 | } |
| 5016 | enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]); |
| 5017 | let (mi_row0, mi_col0) = |
| 5018 | (sr as u32 * SUB_MI, sc as u32 * SUB_MI); |
| 5019 | for (i, leaf8) in leaves.iter().enumerate() { |
| 5020 | let leaf_mi = ( |
| 5021 | (mi_row0 + (i as u32 / 2) * 2) as usize, |
| 5022 | (mi_col0 + (i as u32 % 2) * 2) as usize, |
| 5023 | ); |
| 5024 | let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); |
| 5025 | enc.symbol( |
| 5026 | PARTITION_NONE, |
| 5027 | &mut cdfs.partition_w8[leaf_ctx], |
| 5028 | ); |
| 5029 | let (skip, is_inter) = write_inter_frame_leaf8( |
| 5030 | &mut enc, |
| 5031 | &mut cdfs, |
| 5032 | &mut neighbours, |
| 5033 | &mut grid, |
| 5034 | mi_cols, |
| 5035 | mi_rows, |
| 5036 | leaf8, |
| 5037 | leaf_mi, |
| 5038 | &scan8, |
| 5039 | &scan4, |
| 5040 | tx_select, |
| 5041 | &all_scans, |
| 5042 | )?; |
| 5043 | let _ = (skip, is_inter); |
| 5044 | } |
| 5045 | continue; |
| 5046 | } |
| 5047 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]); |
| 5048 | write_inter_frame_leaf( |
| 5049 | &mut enc, |
| 5050 | &mut cdfs, |
| 5051 | &mut neighbours, |
| 5052 | &mut grid, |
| 5053 | mi_cols, |
| 5054 | mi_rows, |
| 5055 | leaf, |
| 5056 | at16, |
| 5057 | &scan16, |
| 5058 | &scan8, |
| 5059 | tx_select, |
| 5060 | &all_scans, |
| 5061 | )?; |
| 5062 | } else { |
| 5063 | let ctx16 = neighbours.partition_ctx(at16, SUB); |
| 5064 | if has_cols16 { |
| 5065 | enc.symbol_fixed( |
| 5066 | 1, |
| 5067 | &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE), |
| 5068 | ); |
| 5069 | } else { |
| 5070 | enc.symbol_fixed( |
| 5071 | 1, |
| 5072 | &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE), |
| 5073 | ); |
| 5074 | } |
| 5075 | let leaves = leaf.eight.as_ref().ok_or_else(|| { |
| 5076 | Error::unsupported( |
| 5077 | "AV1 tile", |
| 5078 | "a 16x16 inter-frame block the true frame edge cuts \ |
| 5079 | through needs its `eight` leaves populated", |
| 5080 | ) |
| 5081 | })?; |
| 5082 | let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); |
| 5083 | let leaf_positions: Vec<(u32, u32)> = (0..4) |
| 5084 | .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) |
| 5085 | .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) |
| 5086 | .collect(); |
| 5087 | if leaves.len() != leaf_positions.len() { |
| 5088 | return Err(Error::unsupported( |
| 5089 | "AV1 tile", |
| 5090 | "a straddling 16x16 inter-frame block needs one \ |
| 5091 | `eight` entry per 8x8 leaf inside the true frame", |
| 5092 | )); |
| 5093 | } |
| 5094 | for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) { |
| 5095 | let leaf_mi = (mr as usize, mc as usize); |
| 5096 | let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); |
| 5097 | enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]); |
| 5098 | let (skip, is_inter) = write_inter_frame_leaf8( |
| 5099 | &mut enc, |
| 5100 | &mut cdfs, |
| 5101 | &mut neighbours, |
| 5102 | &mut grid, |
| 5103 | mi_cols, |
| 5104 | mi_rows, |
| 5105 | leaf8, |
| 5106 | leaf_mi, |
| 5107 | &scan8, |
| 5108 | &scan4, |
| 5109 | tx_select, |
| 5110 | &all_scans, |
| 5111 | )?; |
| 5112 | let _ = (skip, is_inter); |
| 5113 | } |
| 5114 | |
| 5115 | |
| 5116 | |
| 5117 | |
| 5118 | |
| 5119 | |
| 5120 | } |
| 5121 | } |
| 5122 | continue; |
| 5123 | } |
| 5124 | }; |
| 5125 | |
| 5126 | let (r, c) = at; |
| 5127 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 5128 | let has_above = neighbours.has_above(mi_r); |
| 5129 | let has_left = neighbours.has_left(mi_c); |
| 5130 | let skip_ctx = usize::from(neighbours.above_skip[mi_c]) |
| 5131 | + usize::from(neighbours.left_skip[mi_r]); |
| 5132 | enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); |
| 5133 | write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip); |
| 5134 | |
| 5135 | let is_inter = block.inter.is_some(); |
| 5136 | let (above_inter, left_inter) = |
| 5137 | (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); |
| 5138 | let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); |
| 5139 | enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); |
| 5140 | |
| 5141 | let mode_for_tx; |
| 5142 | if let Some(info) = block.inter { |
| 5143 | write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some()); |
| 5144 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); |
| 5145 | if info.ref1.is_some() { |
| 5146 | let (mv, mv1, is_new_mv) = write_compound_block( |
| 5147 | &mut enc, &mut cdfs, &neighbours, &grid, (mi_row, mi_col), (8, 8), |
| 5148 | (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), |
| 5149 | )?; |
| 5150 | for dr in 0..8 { |
| 5151 | for dc in 0..8 { |
| 5152 | grid.set(mi_row + dr, mi_col + dc, MiInfo { |
| 5153 | is_inter: true, |
| 5154 | ref_frame: info.ref_frame, |
| 5155 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 5156 | mv1: mv16(mv1), |
| 5157 | mv: mv16(mv), |
| 5158 | is_new_mv, |
| 5159 | size: 8, |
| 5160 | size_h: 8, |
| 5161 | is_global_mv0: false, |
| 5162 | is_global_mv1: false, |
| 5163 | }); |
| 5164 | } |
| 5165 | } |
| 5166 | mode_for_tx = 0; |
| 5167 | } else { |
| 5168 | write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.above_ref1[mi_c], neighbours.left_ref[mi_r], neighbours.left_ref1[mi_r]); |
| 5169 | |
| 5170 | let stack = find_mv_stack( |
| 5171 | &grid, |
| 5172 | mi_row, |
| 5173 | mi_col, |
| 5174 | 8, |
| 5175 | 8, |
| 5176 | info.ref_frame, |
| 5177 | mi_cols as usize, |
| 5178 | mi_rows as usize, |
| 5179 | ); |
| 5180 | |
| 5181 | let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?; |
| 5182 | grid.set( |
| 5183 | mi_row, |
| 5184 | mi_col, |
| 5185 | MiInfo { |
| 5186 | is_inter: true, |
| 5187 | ref_frame: info.ref_frame, |
| 5188 | ref_frame1: NO_REF1, |
| 5189 | mv1: (0, 0), |
| 5190 | mv: mv16(mv), |
| 5191 | is_new_mv, |
| 5192 | size: 8, |
| 5193 | size_h: 8, |
| 5194 | is_global_mv0: false, |
| 5195 | is_global_mv1: false, |
| 5196 | }, |
| 5197 | ); |
| 5198 | for dr in 0..8 { |
| 5199 | for dc in 0..8 { |
| 5200 | if dr == 0 && dc == 0 { |
| 5201 | continue; |
| 5202 | } |
| 5203 | grid.set( |
| 5204 | mi_row + dr, |
| 5205 | mi_col + dc, |
| 5206 | MiInfo { |
| 5207 | is_inter: true, |
| 5208 | ref_frame: info.ref_frame, |
| 5209 | ref_frame1: NO_REF1, |
| 5210 | mv1: (0, 0), |
| 5211 | mv: mv16(mv), |
| 5212 | is_new_mv, |
| 5213 | size: 8, |
| 5214 | size_h: 8, |
| 5215 | is_global_mv0: false, |
| 5216 | is_global_mv1: false, |
| 5217 | }, |
| 5218 | ); |
| 5219 | } |
| 5220 | } |
| 5221 | mode_for_tx = 0; |
| 5222 | } |
| 5223 | } else { |
| 5224 | let mode = usize::from(block.mode); |
| 5225 | enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]); |
| 5226 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 5227 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); |
| 5228 | } |
| 5229 | let uv_mode = usize::from(block.uv_mode); |
| 5230 | enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); |
| 5231 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 5232 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); |
| 5233 | } |
| 5234 | mode_for_tx = mode; |
| 5235 | |
| 5236 | |
| 5237 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); |
| 5238 | write_palette_syntax( |
| 5239 | &mut enc, |
| 5240 | &mut cdfs, |
| 5241 | &mut neighbours, |
| 5242 | block.palette.as_ref(), |
| 5243 | block.palette_uv.as_ref(), |
| 5244 | mode, |
| 5245 | uv_mode, |
| 5246 | (mi_row, mi_col), |
| 5247 | BLOCK, |
| 5248 | ); |
| 5249 | for dr in 0..8 { |
| 5250 | for dc in 0..8 { |
| 5251 | grid.set( |
| 5252 | mi_row + dr, |
| 5253 | mi_col + dc, |
| 5254 | MiInfo { |
| 5255 | is_inter: false, |
| 5256 | ref_frame: -1, |
| 5257 | ref_frame1: NO_REF1, |
| 5258 | mv1: (0, 0), |
| 5259 | mv: (0, 0), |
| 5260 | is_new_mv: false, |
| 5261 | size: 8, |
| 5262 | size_h: 8, |
| 5263 | is_global_mv0: false, |
| 5264 | is_global_mv1: false, |
| 5265 | }, |
| 5266 | ); |
| 5267 | } |
| 5268 | } |
| 5269 | } |
| 5270 | |
| 5271 | let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); |
| 5272 | let tx = if tx_select { |
| 5273 | write_tx_syntax_inter( |
| 5274 | &mut enc, |
| 5275 | &mut cdfs, |
| 5276 | &mut neighbours, |
| 5277 | at_mi, |
| 5278 | BLOCK, |
| 5279 | is_inter, |
| 5280 | block.skip, |
| 5281 | usize::from(block.tx_depth), |
| 5282 | ) |
| 5283 | } else { |
| 5284 | BLOCK |
| 5285 | }; |
| 5286 | let split = tx < BLOCK; |
| 5287 | if block.skip { |
| 5288 | neighbours.record(at, BLOCK, mode_for_tx, &zero_grids); |
| 5289 | } else { |
| 5290 | let grids = [ |
| 5291 | level_grid(&block.luma, TX32)?, |
| 5292 | level_grid(&block.u, TX16)?, |
| 5293 | level_grid(&block.v, TX16)?, |
| 5294 | ]; |
| 5295 | if split { |
| 5296 | write_luma_tus( |
| 5297 | &mut enc, |
| 5298 | &mut cdfs, |
| 5299 | &mut neighbours, |
| 5300 | at_mi, |
| 5301 | BLOCK, |
| 5302 | tx, |
| 5303 | &grids[0], |
| 5304 | mode_for_tx, |
| 5305 | &all_scans, |
| 5306 | is_inter, |
| 5307 | )?; |
| 5308 | } |
| 5309 | write_block_planes( |
| 5310 | &mut enc, |
| 5311 | &mut cdfs, |
| 5312 | if is_inter { |
| 5313 | &inter_planes |
| 5314 | } else { |
| 5315 | &intra_planes |
| 5316 | }, |
| 5317 | &grids, |
| 5318 | &[&scan32, &scan16, &scan16], |
| 5319 | &neighbours.around(at, BLOCK), |
| 5320 | mode_for_tx, |
| 5321 | split, |
| 5322 | ); |
| 5323 | neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); |
| 5324 | } |
| 5325 | neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block)); |
| 5326 | record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block); |
| 5327 | } |
| 5328 | } |
| 5329 | } |
| 5330 | Ok(enc.finish()) |
| 5331 | } |
| 5332 | |
| 5333 | |
| 5334 | |
| 5335 | |
| 5336 | |
| 5337 | |
| 5338 | |
| 5339 | |
| 5340 | |
| 5341 | |
| 5342 | |
| 5343 | #[allow(clippy::too_many_arguments)] |
| 5344 | fn write_inter_frame_leaf( |
| 5345 | enc: &mut SymbolEncoder, |
| 5346 | cdfs: &mut Cdfs, |
| 5347 | neighbours: &mut Neighbours, |
| 5348 | grid: &mut MiGrid, |
| 5349 | mi_cols: u32, |
| 5350 | mi_rows: u32, |
| 5351 | block: &BlockCoeffs, |
| 5352 | at: (usize, usize), |
| 5353 | scan16: &Vec<u16>, |
| 5354 | scan8: &Vec<u16>, |
| 5355 | tx_select: bool, |
| 5356 | all_scans: &[Vec<u16>; 4], |
| 5357 | ) -> Result<()> { |
| 5358 | if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { |
| 5359 | return Err(Error::unsupported( |
| 5360 | "AV1 tile", |
| 5361 | format!( |
| 5362 | "intra mode {} is not one of the thirteen this writer codes", |
| 5363 | block.mode |
| 5364 | ), |
| 5365 | )); |
| 5366 | } |
| 5367 | |
| 5368 | |
| 5369 | const SIZE_GROUP_16: usize = 2; |
| 5370 | |
| 5371 | let (r, c) = at; |
| 5372 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| 5373 | let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); |
| 5374 | enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); |
| 5375 | write_cdef_idx(enc, (mi_r, mi_c), block.skip); |
| 5376 | |
| 5377 | let (has_above, has_left) = (neighbours.has_above(mi_r), neighbours.has_left(mi_c)); |
| 5378 | let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); |
| 5379 | let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); |
| 5380 | let is_inter = block.inter.is_some(); |
| 5381 | enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); |
| 5382 | |
| 5383 | let mode_for_tx; |
| 5384 | if let Some(info) = block.inter { |
| 5385 | write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some()); |
| 5386 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); |
| 5387 | if info.ref1.is_some() { |
| 5388 | let n = SUB_MI as usize; |
| 5389 | let (mv, mv1, is_new_mv) = write_compound_block( |
| 5390 | enc, cdfs, neighbours, grid, (mi_row, mi_col), (n, n), |
| 5391 | (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), |
| 5392 | )?; |
| 5393 | for dr in 0..n { |
| 5394 | for dc in 0..n { |
| 5395 | grid.set(mi_row + dr, mi_col + dc, MiInfo { |
| 5396 | is_inter: true, |
| 5397 | ref_frame: info.ref_frame, |
| 5398 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 5399 | mv1: mv16(mv1), |
| 5400 | mv: mv16(mv), |
| 5401 | is_new_mv, |
| 5402 | size: n as u8, |
| 5403 | size_h: n as u8, |
| 5404 | is_global_mv0: false, |
| 5405 | is_global_mv1: false, |
| 5406 | }); |
| 5407 | } |
| 5408 | } |
| 5409 | mode_for_tx = 0; |
| 5410 | } else { |
| 5411 | write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.above_ref1[mi_c], neighbours.left_ref[mi_r], neighbours.left_ref1[mi_r]); |
| 5412 | |
| 5413 | let stack = find_mv_stack( |
| 5414 | grid, |
| 5415 | mi_row, |
| 5416 | mi_col, |
| 5417 | SUB_MI as usize, |
| 5418 | SUB_MI as usize, |
| 5419 | info.ref_frame, |
| 5420 | mi_cols as usize, |
| 5421 | mi_rows as usize, |
| 5422 | ); |
| 5423 | |
| 5424 | let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; |
| 5425 | for dr in 0..SUB_MI as usize { |
| 5426 | for dc in 0..SUB_MI as usize { |
| 5427 | grid.set( |
| 5428 | mi_row + dr, |
| 5429 | mi_col + dc, |
| 5430 | MiInfo { |
| 5431 | is_inter: true, |
| 5432 | ref_frame: info.ref_frame, |
| 5433 | ref_frame1: NO_REF1, |
| 5434 | mv1: (0, 0), |
| 5435 | mv: mv16(mv), |
| 5436 | is_new_mv, |
| 5437 | size: SUB_MI as usize as u8, |
| 5438 | size_h: SUB_MI as usize as u8, |
| 5439 | is_global_mv0: false, |
| 5440 | is_global_mv1: false, |
| 5441 | }, |
| 5442 | ); |
| 5443 | } |
| 5444 | } |
| 5445 | mode_for_tx = 0; |
| 5446 | } |
| 5447 | } else { |
| 5448 | let mode = usize::from(block.mode); |
| 5449 | enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]); |
| 5450 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 5451 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); |
| 5452 | } |
| 5453 | let uv_mode = usize::from(block.uv_mode); |
| 5454 | enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); |
| 5455 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 5456 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); |
| 5457 | } |
| 5458 | mode_for_tx = mode; |
| 5459 | |
| 5460 | |
| 5461 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); |
| 5462 | write_palette_syntax( |
| 5463 | enc, |
| 5464 | cdfs, |
| 5465 | neighbours, |
| 5466 | block.palette.as_ref(), |
| 5467 | block.palette_uv.as_ref(), |
| 5468 | mode, |
| 5469 | uv_mode, |
| 5470 | (mi_row, mi_col), |
| 5471 | SUB, |
| 5472 | ); |
| 5473 | for dr in 0..SUB_MI as usize { |
| 5474 | for dc in 0..SUB_MI as usize { |
| 5475 | grid.set( |
| 5476 | mi_row + dr, |
| 5477 | mi_col + dc, |
| 5478 | MiInfo { |
| 5479 | is_inter: false, |
| 5480 | ref_frame: -1, |
| 5481 | ref_frame1: NO_REF1, |
| 5482 | mv1: (0, 0), |
| 5483 | mv: (0, 0), |
| 5484 | is_new_mv: false, |
| 5485 | size: SUB_MI as usize as u8, |
| 5486 | size_h: SUB_MI as usize as u8, |
| 5487 | is_global_mv0: false, |
| 5488 | is_global_mv1: false, |
| 5489 | }, |
| 5490 | ); |
| 5491 | } |
| 5492 | } |
| 5493 | } |
| 5494 | |
| 5495 | let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); |
| 5496 | let tx = if tx_select { |
| 5497 | write_tx_syntax_inter( |
| 5498 | enc, |
| 5499 | cdfs, |
| 5500 | neighbours, |
| 5501 | at_mi, |
| 5502 | SUB, |
| 5503 | is_inter, |
| 5504 | block.skip, |
| 5505 | usize::from(block.tx_depth), |
| 5506 | ) |
| 5507 | } else { |
| 5508 | SUB |
| 5509 | }; |
| 5510 | let split = tx < SUB; |
| 5511 | if block.skip { |
| 5512 | let zero_grids = [ |
| 5513 | vec![0i32; TX16 * TX16], |
| 5514 | vec![0i32; TX8 * TX8], |
| 5515 | vec![0i32; TX8 * TX8], |
| 5516 | ]; |
| 5517 | neighbours.record(at, SUB, mode_for_tx, &zero_grids); |
| 5518 | } else { |
| 5519 | let grids = [ |
| 5520 | level_grid(&block.luma, TX16)?, |
| 5521 | level_grid(&block.u, TX8)?, |
| 5522 | level_grid(&block.v, TX8)?, |
| 5523 | ]; |
| 5524 | if split { |
| 5525 | write_luma_tus( |
| 5526 | enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter, |
| 5527 | )?; |
| 5528 | } |
| 5529 | write_block_planes( |
| 5530 | enc, |
| 5531 | cdfs, |
| 5532 | if is_inter { |
| 5533 | &[TxbSet::Luma16Inter, TxbSet::Chroma8, TxbSet::Chroma8] |
| 5534 | } else { |
| 5535 | &[TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8] |
| 5536 | }, |
| 5537 | &grids, |
| 5538 | &[scan16, scan8, scan8], |
| 5539 | &neighbours.around(at, SUB), |
| 5540 | mode_for_tx, |
| 5541 | split, |
| 5542 | ); |
| 5543 | neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); |
| 5544 | } |
| 5545 | neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block)); |
| 5546 | record_block_compound(neighbours, (mi_r, mi_c), SUB, block); |
| 5547 | Ok(()) |
| 5548 | } |
| 5549 | |
| 5550 | |
| 5551 | |
| 5552 | |
| 5553 | |
| 5554 | |
| 5555 | |
| 5556 | |
| 5557 | |
| 5558 | |
| 5559 | |
| 5560 | |
| 5561 | |
| 5562 | |
| 5563 | |
| 5564 | |
| 5565 | |
| 5566 | |
| 5567 | #[allow(clippy::too_many_arguments)] |
| 5568 | fn write_inter_frame_leaf8( |
| 5569 | enc: &mut SymbolEncoder, |
| 5570 | cdfs: &mut Cdfs, |
| 5571 | neighbours: &mut Neighbours, |
| 5572 | grid: &mut MiGrid, |
| 5573 | mi_cols: u32, |
| 5574 | mi_rows: u32, |
| 5575 | block: &BlockCoeffs, |
| 5576 | leaf_mi: (usize, usize), |
| 5577 | scan8: &Vec<u16>, |
| 5578 | scan4: &Vec<u16>, |
| 5579 | tx_select: bool, |
| 5580 | all_scans: &[Vec<u16>; 4], |
| 5581 | ) -> Result<(bool, bool)> { |
| 5582 | if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { |
| 5583 | return Err(Error::unsupported( |
| 5584 | "AV1 tile", |
| 5585 | format!( |
| 5586 | "intra mode {} is not one of the thirteen this writer codes", |
| 5587 | block.mode |
| 5588 | ), |
| 5589 | )); |
| 5590 | } |
| 5591 | |
| 5592 | |
| 5593 | const SIZE_GROUP_8: usize = 1; |
| 5594 | |
| 5595 | |
| 5596 | |
| 5597 | |
| 5598 | |
| 5599 | |
| 5600 | |
| 5601 | let above_skip = neighbours.above_skip[leaf_mi.1]; |
| 5602 | let left_skip = neighbours.left_skip[leaf_mi.0]; |
| 5603 | let above_inter = neighbours.above_inter[leaf_mi.1]; |
| 5604 | let left_inter = neighbours.left_inter[leaf_mi.0]; |
| 5605 | let skip_ctx = usize::from(above_skip) + usize::from(left_skip); |
| 5606 | enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); |
| 5607 | write_cdef_idx(enc, leaf_mi, block.skip); |
| 5608 | |
| 5609 | let (has_above, has_left) = (neighbours.has_above(leaf_mi.0), neighbours.has_left(leaf_mi.1)); |
| 5610 | let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); |
| 5611 | let is_inter = block.inter.is_some(); |
| 5612 | enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); |
| 5613 | |
| 5614 | let mode_for_tx; |
| 5615 | if let Some(info) = block.inter { |
| 5616 | write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), info.ref1.is_some()); |
| 5617 | let (mi_row, mi_col) = leaf_mi; |
| 5618 | if info.ref1.is_some() { |
| 5619 | let (mv, mv1, is_new_mv) = write_compound_block( |
| 5620 | enc, cdfs, neighbours, grid, (mi_row, mi_col), (2, 2), |
| 5621 | (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), |
| 5622 | )?; |
| 5623 | for dr in 0..2 { |
| 5624 | for dc in 0..2 { |
| 5625 | grid.set(mi_row + dr, mi_col + dc, MiInfo { |
| 5626 | is_inter: true, |
| 5627 | ref_frame: info.ref_frame, |
| 5628 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 5629 | mv1: mv16(mv1), |
| 5630 | mv: mv16(mv), |
| 5631 | is_new_mv, |
| 5632 | size: 2, |
| 5633 | size_h: 2, |
| 5634 | is_global_mv0: false, |
| 5635 | is_global_mv1: false, |
| 5636 | }); |
| 5637 | } |
| 5638 | } |
| 5639 | mode_for_tx = 0; |
| 5640 | } else { |
| 5641 | write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.above_ref1[leaf_mi.1], neighbours.left_ref[leaf_mi.0], neighbours.left_ref1[leaf_mi.0]); |
| 5642 | |
| 5643 | let stack = find_mv_stack( |
| 5644 | grid, |
| 5645 | mi_row, |
| 5646 | mi_col, |
| 5647 | 2, |
| 5648 | 2, |
| 5649 | info.ref_frame, |
| 5650 | mi_cols as usize, |
| 5651 | mi_rows as usize, |
| 5652 | ); |
| 5653 | |
| 5654 | let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; |
| 5655 | for dr in 0..2 { |
| 5656 | for dc in 0..2 { |
| 5657 | grid.set( |
| 5658 | mi_row + dr, |
| 5659 | mi_col + dc, |
| 5660 | MiInfo { |
| 5661 | is_inter: true, |
| 5662 | ref_frame: info.ref_frame, |
| 5663 | ref_frame1: NO_REF1, |
| 5664 | mv1: (0, 0), |
| 5665 | mv: mv16(mv), |
| 5666 | is_new_mv, |
| 5667 | size: 2, |
| 5668 | size_h: 2, |
| 5669 | is_global_mv0: false, |
| 5670 | is_global_mv1: false, |
| 5671 | }, |
| 5672 | ); |
| 5673 | } |
| 5674 | } |
| 5675 | mode_for_tx = 0; |
| 5676 | } |
| 5677 | } else { |
| 5678 | let mode = usize::from(block.mode); |
| 5679 | enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]); |
| 5680 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 5681 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); |
| 5682 | } |
| 5683 | let uv_mode = usize::from(block.uv_mode); |
| 5684 | enc.symbol(uv_mode, &mut cdfs.uv_mode_cfl[mode]); |
| 5685 | if (V_PRED..=D67_PRED).contains(&uv_mode) { |
| 5686 | enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); |
| 5687 | } |
| 5688 | mode_for_tx = mode; |
| 5689 | |
| 5690 | |
| 5691 | let (mi_row, mi_col) = leaf_mi; |
| 5692 | write_palette_syntax( |
| 5693 | enc, |
| 5694 | cdfs, |
| 5695 | neighbours, |
| 5696 | block.palette.as_ref(), |
| 5697 | block.palette_uv.as_ref(), |
| 5698 | mode, |
| 5699 | uv_mode, |
| 5700 | leaf_mi, |
| 5701 | 8, |
| 5702 | ); |
| 5703 | for dr in 0..2 { |
| 5704 | for dc in 0..2 { |
| 5705 | grid.set( |
| 5706 | mi_row + dr, |
| 5707 | mi_col + dc, |
| 5708 | MiInfo { |
| 5709 | is_inter: false, |
| 5710 | ref_frame: -1, |
| 5711 | ref_frame1: NO_REF1, |
| 5712 | mv1: (0, 0), |
| 5713 | mv: (0, 0), |
| 5714 | is_new_mv: false, |
| 5715 | size: 2, |
| 5716 | size_h: 2, |
| 5717 | is_global_mv0: false, |
| 5718 | is_global_mv1: false, |
| 5719 | }, |
| 5720 | ); |
| 5721 | } |
| 5722 | } |
| 5723 | } |
| 5724 | |
| 5725 | let planes = if is_inter { |
| 5726 | [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4] |
| 5727 | } else { |
| 5728 | [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4] |
| 5729 | }; |
| 5730 | let tx = if tx_select { |
| 5731 | write_tx_syntax_inter( |
| 5732 | enc, |
| 5733 | cdfs, |
| 5734 | neighbours, |
| 5735 | leaf_mi, |
| 5736 | 8, |
| 5737 | is_inter, |
| 5738 | block.skip, |
| 5739 | usize::from(block.tx_depth), |
| 5740 | ) |
| 5741 | } else { |
| 5742 | 8 |
| 5743 | }; |
| 5744 | let split = tx < 8; |
| 5745 | if block.skip { |
| 5746 | let zero_grids = [ |
| 5747 | vec![0i32; TX8 * TX8], |
| 5748 | vec![0i32; TX4 * TX4], |
| 5749 | vec![0i32; TX4 * TX4], |
| 5750 | ]; |
| 5751 | neighbours.record_mi(leaf_mi, 8, &zero_grids); |
| 5752 | neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block)); |
| 5753 | record_block_compound(neighbours, leaf_mi, 8, block); |
| 5754 | } else { |
| 5755 | let grids = [ |
| 5756 | level_grid(&block.luma, TX8)?, |
| 5757 | level_grid(&block.u, TX4)?, |
| 5758 | level_grid(&block.v, TX4)?, |
| 5759 | ]; |
| 5760 | if split { |
| 5761 | write_luma_tus( |
| 5762 | enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter, |
| 5763 | )?; |
| 5764 | } |
| 5765 | write_block_planes( |
| 5766 | enc, |
| 5767 | cdfs, |
| 5768 | &planes, |
| 5769 | &grids, |
| 5770 | &[scan8, scan4, scan4], |
| 5771 | &neighbours.around_mi(leaf_mi, 8), |
| 5772 | mode_for_tx, |
| 5773 | split, |
| 5774 | ); |
| 5775 | neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); |
| 5776 | neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block)); |
| 5777 | record_block_compound(neighbours, leaf_mi, 8, block); |
| 5778 | } |
| 5779 | Ok((block.skip, is_inter)) |
| 5780 | } |
| 5781 | |
| 5782 | #[cfg(test)] |
| 5783 | mod tests { |
| 5784 | use super::*; |
| 5785 | use crate::frame::frame_obu; |
| 5786 | use crate::obu::temporal_delimiter; |
| 5787 | use crate::sequence::sequence_header_obu; |
| 5788 | use ec_av1_syntax::sequence::SequenceHeader; |
| 5789 | use ec_av1_syntax::{ |
| 5790 | FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, |
| 5791 | TxMode, |
| 5792 | }; |
| 5793 | use std::io::Write; |
| 5794 | use std::process::{Command, Stdio}; |
| 5795 | |
| 5796 | |
| 5797 | |
| 5798 | |
| 5799 | |
| 5800 | fn sequence_64() -> SequenceHeader { |
| 5801 | let mut seq = crate::sequence::tests::sample_1080p(); |
| 5802 | seq.frame_width_bits = 7; |
| 5803 | seq.frame_height_bits = 7; |
| 5804 | seq.max_frame_width = 64; |
| 5805 | seq.max_frame_height = 64; |
| 5806 | seq.use_128x128_superblock = false; |
| 5807 | seq.enable_filter_intra = false; |
| 5808 | seq.enable_cdef = false; |
| 5809 | seq.enable_restoration = false; |
| 5810 | seq.enable_superres = false; |
| 5811 | seq.seq_force_screen_content_tools = 0; |
| 5812 | seq.seq_force_integer_mv = 0; |
| 5813 | seq |
| 5814 | } |
| 5815 | |
| 5816 | |
| 5817 | |
| 5818 | |
| 5819 | fn flat_key_frame() -> FrameHeader { |
| 5820 | FrameHeader { |
| 5821 | frame_type: FrameType::Key, |
| 5822 | frame_is_intra: true, |
| 5823 | show_frame: true, |
| 5824 | error_resilient_mode: true, |
| 5825 | disable_cdf_update: true, |
| 5826 | allow_screen_content_tools: false, |
| 5827 | force_integer_mv: true, |
| 5828 | refresh_frame_flags: 0xFF, |
| 5829 | primary_ref_frame: PRIMARY_REF_NONE, |
| 5830 | frame_width: 64, |
| 5831 | frame_height: 64, |
| 5832 | upscaled_width: 64, |
| 5833 | render_width: 64, |
| 5834 | render_height: 64, |
| 5835 | mi_cols: 16, |
| 5836 | mi_rows: 16, |
| 5837 | tile_info: TileInfo { |
| 5838 | uniform_spacing: true, |
| 5839 | cols: 1, |
| 5840 | rows: 1, |
| 5841 | cols_log2: 0, |
| 5842 | rows_log2: 0, |
| 5843 | mi_col_starts: vec![0, 16], |
| 5844 | mi_row_starts: vec![0, 16], |
| 5845 | context_update_tile_id: 0, |
| 5846 | tile_size_bytes: 1, |
| 5847 | }, |
| 5848 | quantization: QuantizationParams { |
| 5849 | base_q_idx: 100, |
| 5850 | ..QuantizationParams::default() |
| 5851 | }, |
| 5852 | loop_filter: LoopFilterParams::default(), |
| 5853 | tx_mode: TxMode::Largest, |
| 5854 | reduced_tx_set: false, |
| 5855 | ..FrameHeader::default() |
| 5856 | } |
| 5857 | } |
| 5858 | |
| 5859 | |
| 5860 | |
| 5861 | |
| 5862 | |
| 5863 | |
| 5864 | |
| 5865 | |
| 5866 | fn have_ffmpeg() -> bool { |
| 5867 | let present = Command::new("ffmpeg") |
| 5868 | .arg("-version") |
| 5869 | .stdout(Stdio::null()) |
| 5870 | .stderr(Stdio::null()) |
| 5871 | .status() |
| 5872 | .is_ok_and(|s| s.success()); |
| 5873 | assert!( |
| 5874 | present |
| 5875 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 5876 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 5877 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 5878 | ); |
| 5879 | present |
| 5880 | } |
| 5881 | |
| 5882 | |
| 5883 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> { |
| 5884 | let mut child = Command::new("ffmpeg") |
| 5885 | .args([ |
| 5886 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 5887 | ]) |
| 5888 | .stdin(Stdio::piped()) |
| 5889 | .stdout(Stdio::piped()) |
| 5890 | .stderr(Stdio::piped()) |
| 5891 | .spawn() |
| 5892 | .expect("ffmpeg failed to start"); |
| 5893 | |
| 5894 | |
| 5895 | |
| 5896 | |
| 5897 | |
| 5898 | |
| 5899 | |
| 5900 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 5901 | let payload = stream.to_vec(); |
| 5902 | let writer = std::thread::spawn(move || { |
| 5903 | let _ = stdin.write_all(&payload); |
| 5904 | }); |
| 5905 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 5906 | writer.join().expect("ffmpeg stdin writer thread"); |
| 5907 | assert!( |
| 5908 | out.status.success(), |
| 5909 | "ffmpeg refused the stream: {}", |
| 5910 | String::from_utf8_lossy(&out.stderr) |
| 5911 | ); |
| 5912 | assert_eq!( |
| 5913 | out.stdout.len(), |
| 5914 | w * h * 3 / 2, |
| 5915 | "expected one 4:2:0 frame, ffmpeg said: {}", |
| 5916 | String::from_utf8_lossy(&out.stderr) |
| 5917 | ); |
| 5918 | out.stdout |
| 5919 | } |
| 5920 | |
| 5921 | #[test] |
| 5922 | fn flat_key_frame_decodes_to_mid_grey() { |
| 5923 | if !have_ffmpeg() { |
| 5924 | eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH"); |
| 5925 | return; |
| 5926 | } |
| 5927 | let seq = sequence_64(); |
| 5928 | let header = flat_key_frame(); |
| 5929 | let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap(); |
| 5930 | |
| 5931 | let mut stream = temporal_delimiter(); |
| 5932 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 5933 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 5934 | |
| 5935 | let planes = ffmpeg_decode(&stream, 64, 64); |
| 5936 | |
| 5937 | |
| 5938 | |
| 5939 | for (i, &s) in planes.iter().enumerate() { |
| 5940 | assert_eq!(s, 128, "sample {i} of the decoded frame"); |
| 5941 | } |
| 5942 | } |
| 5943 | |
| 5944 | |
| 5945 | |
| 5946 | const Q_IDX: u8 = 100; |
| 5947 | |
| 5948 | |
| 5949 | fn decode_dc_frame(dc_level: i32) -> Vec<u8> { |
| 5950 | let seq = sequence_64(); |
| 5951 | let mut header = flat_key_frame(); |
| 5952 | header.quantization.base_q_idx = Q_IDX; |
| 5953 | let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap(); |
| 5954 | let mut stream = temporal_delimiter(); |
| 5955 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 5956 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 5957 | ffmpeg_decode(&stream, 64, 64) |
| 5958 | } |
| 5959 | |
| 5960 | |
| 5961 | |
| 5962 | |
| 5963 | |
| 5964 | |
| 5965 | |
| 5966 | |
| 5967 | |
| 5968 | |
| 5969 | const DECODED_AT_Q100: [(i32, u8); 28] = [ |
| 5970 | (1, 128), |
| 5971 | (2, 128), |
| 5972 | (3, 129), |
| 5973 | (4, 129), |
| 5974 | (5, 129), |
| 5975 | (6, 129), |
| 5976 | (7, 129), |
| 5977 | (8, 129), |
| 5978 | (9, 130), |
| 5979 | (10, 130), |
| 5980 | (11, 130), |
| 5981 | (12, 130), |
| 5982 | (13, 130), |
| 5983 | (14, 131), |
| 5984 | (-1, 128), |
| 5985 | (-2, 128), |
| 5986 | (-3, 128), |
| 5987 | (-4, 127), |
| 5988 | (-5, 127), |
| 5989 | (-6, 127), |
| 5990 | (-7, 127), |
| 5991 | (-8, 127), |
| 5992 | (-9, 126), |
| 5993 | (-10, 126), |
| 5994 | (-11, 126), |
| 5995 | (-12, 126), |
| 5996 | (-13, 126), |
| 5997 | (-14, 126), |
| 5998 | ]; |
| 5999 | |
| 6000 | #[test] |
| 6001 | fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() { |
| 6002 | if !have_ffmpeg() { |
| 6003 | eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg"); |
| 6004 | return; |
| 6005 | } |
| 6006 | let mut seen = Vec::new(); |
| 6007 | for (level, want) in DECODED_AT_Q100 { |
| 6008 | let planes = decode_dc_frame(level); |
| 6009 | let (luma, chroma) = planes.split_at(64 * 64); |
| 6010 | for (i, &sample) in luma.iter().enumerate() { |
| 6011 | assert_eq!(sample, want, "luma sample {i} at dc level {level}"); |
| 6012 | } |
| 6013 | |
| 6014 | |
| 6015 | |
| 6016 | for (i, &sample) in chroma.iter().enumerate() { |
| 6017 | assert_eq!(sample, 128, "chroma sample {i} at dc level {level}"); |
| 6018 | } |
| 6019 | seen.push((level, want)); |
| 6020 | } |
| 6021 | |
| 6022 | |
| 6023 | |
| 6024 | for w in seen.windows(2) { |
| 6025 | let ((prev_level, prev), (level, value)) = (w[0], w[1]); |
| 6026 | if prev_level.signum() != level.signum() { |
| 6027 | continue; |
| 6028 | } |
| 6029 | if level > 0 { |
| 6030 | assert!( |
| 6031 | value >= prev, |
| 6032 | "level {level} decoded below level {prev_level}" |
| 6033 | ); |
| 6034 | assert!(value >= 128, "a positive level darkened the picture"); |
| 6035 | } else { |
| 6036 | assert!( |
| 6037 | value <= prev, |
| 6038 | "level {level} decoded above level {prev_level}" |
| 6039 | ); |
| 6040 | assert!(value <= 128, "a negative level brightened the picture"); |
| 6041 | } |
| 6042 | } |
| 6043 | assert!( |
| 6044 | DECODED_AT_Q100.iter().any(|&(_, v)| v > 128) |
| 6045 | && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128), |
| 6046 | "the pinned table has to move the picture both ways" |
| 6047 | ); |
| 6048 | } |
| 6049 | |
| 6050 | |
| 6051 | |
| 6052 | fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> { |
| 6053 | let (w, h) = (64 * sb_cols, 64 * sb_rows); |
| 6054 | let (seq, mut header) = frame_of(w, h); |
| 6055 | |
| 6056 | |
| 6057 | header.disable_cdf_update = true; |
| 6058 | let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap(); |
| 6059 | let mut stream = temporal_delimiter(); |
| 6060 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 6061 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 6062 | ffmpeg_decode(&stream, w as usize, h as usize) |
| 6063 | } |
| 6064 | |
| 6065 | |
| 6066 | |
| 6067 | fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) { |
| 6068 | let mut seq = sequence_64(); |
| 6069 | seq.max_frame_width = w; |
| 6070 | seq.max_frame_height = h; |
| 6071 | let mut header = flat_key_frame(); |
| 6072 | |
| 6073 | header.disable_cdf_update = false; |
| 6074 | header.frame_width = w; |
| 6075 | header.frame_height = h; |
| 6076 | header.upscaled_width = w; |
| 6077 | header.render_width = w; |
| 6078 | header.render_height = h; |
| 6079 | header.mi_cols = w / 4; |
| 6080 | header.mi_rows = h / 4; |
| 6081 | header.tile_info.mi_col_starts = vec![0, header.mi_cols]; |
| 6082 | header.tile_info.mi_row_starts = vec![0, header.mi_rows]; |
| 6083 | header.quantization.base_q_idx = Q_IDX; |
| 6084 | (seq, header) |
| 6085 | } |
| 6086 | |
| 6087 | fn decoded_value(level: i32) -> u8 { |
| 6088 | DECODED_AT_Q100 |
| 6089 | .iter() |
| 6090 | .find(|&&(l, _)| l == level) |
| 6091 | .map(|&(_, v)| v) |
| 6092 | .expect("the level is in the pinned table") |
| 6093 | } |
| 6094 | |
| 6095 | |
| 6096 | |
| 6097 | |
| 6098 | |
| 6099 | fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 { |
| 6100 | match (above, left) { |
| 6101 | (None, None) => 128, |
| 6102 | (Some(a), None) => a, |
| 6103 | (None, Some(l)) => l, |
| 6104 | (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8, |
| 6105 | } |
| 6106 | } |
| 6107 | |
| 6108 | |
| 6109 | |
| 6110 | |
| 6111 | fn dc_residual(level: i32) -> i32 { |
| 6112 | i32::from(decoded_value(level)) - 128 |
| 6113 | } |
| 6114 | |
| 6115 | |
| 6116 | |
| 6117 | |
| 6118 | |
| 6119 | |
| 6120 | |
| 6121 | #[test] |
| 6122 | fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() { |
| 6123 | if !have_ffmpeg() { |
| 6124 | eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg"); |
| 6125 | return; |
| 6126 | } |
| 6127 | |
| 6128 | |
| 6129 | |
| 6130 | |
| 6131 | for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] { |
| 6132 | let planes = decode_level_grid(&levels, 2, 2); |
| 6133 | let (luma, chroma) = planes.split_at(128 * 128); |
| 6134 | |
| 6135 | |
| 6136 | |
| 6137 | let mut recon = [0u8; 4]; |
| 6138 | for (block, level) in levels.iter().enumerate() { |
| 6139 | let (br, bc) = (block / 2, block % 2); |
| 6140 | let above = (br > 0).then(|| recon[block - 2]); |
| 6141 | let left = (bc > 0).then(|| recon[block - 1]); |
| 6142 | let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level)) |
| 6143 | .clamp(0, 255) as u8; |
| 6144 | recon[block] = want; |
| 6145 | for y in 0..64 { |
| 6146 | for x in 0..64 { |
| 6147 | let i = (br * 64 + y) * 128 + bc * 64 + x; |
| 6148 | assert_eq!( |
| 6149 | luma[i], want, |
| 6150 | "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}" |
| 6151 | ); |
| 6152 | } |
| 6153 | } |
| 6154 | } |
| 6155 | for (i, &sample) in chroma.iter().enumerate() { |
| 6156 | assert_eq!(sample, 128, "chroma sample {i} of {levels:?}"); |
| 6157 | } |
| 6158 | } |
| 6159 | } |
| 6160 | |
| 6161 | |
| 6162 | |
| 6163 | |
| 6164 | |
| 6165 | |
| 6166 | const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [ |
| 6167 | (1, 0), |
| 6168 | (2, 1), |
| 6169 | (3, 1), |
| 6170 | (4, 1), |
| 6171 | (5, 2), |
| 6172 | (6, 2), |
| 6173 | (7, 3), |
| 6174 | (8, 3), |
| 6175 | (9, 3), |
| 6176 | (10, 4), |
| 6177 | (11, 4), |
| 6178 | (12, 4), |
| 6179 | (13, 5), |
| 6180 | (14, 5), |
| 6181 | (-1, 0), |
| 6182 | (-2, -1), |
| 6183 | (-3, -1), |
| 6184 | (-4, -1), |
| 6185 | (-5, -2), |
| 6186 | (-6, -2), |
| 6187 | (-7, -2), |
| 6188 | (-8, -3), |
| 6189 | (-9, -3), |
| 6190 | (-10, -4), |
| 6191 | (-11, -4), |
| 6192 | (-12, -4), |
| 6193 | (-13, -5), |
| 6194 | (-14, -5), |
| 6195 | ]; |
| 6196 | |
| 6197 | fn split_residual(level: i32) -> i32 { |
| 6198 | SPLIT_RESIDUAL_AT_Q100 |
| 6199 | .iter() |
| 6200 | .find(|&&(l, _)| l == level) |
| 6201 | .map(|&(_, r)| r) |
| 6202 | .expect("the level is in the pinned table") |
| 6203 | } |
| 6204 | |
| 6205 | |
| 6206 | |
| 6207 | |
| 6208 | |
| 6209 | |
| 6210 | |
| 6211 | #[test] |
| 6212 | fn a_split_superblock_decodes_each_quadrant_on_its_own_level() { |
| 6213 | if !have_ffmpeg() { |
| 6214 | eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg"); |
| 6215 | return; |
| 6216 | } |
| 6217 | |
| 6218 | |
| 6219 | |
| 6220 | let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1]; |
| 6221 | let planes = decode_split_grid(&levels, 2, 2); |
| 6222 | let (luma, chroma) = planes.split_at(128 * 128); |
| 6223 | |
| 6224 | let mut recon = [0i32; 16]; |
| 6225 | for (block, level) in levels.iter().enumerate() { |
| 6226 | let (br, bc) = (block / 4, block % 4); |
| 6227 | let above = (br > 0).then(|| recon[block - 4] as u8); |
| 6228 | let left = (bc > 0).then(|| recon[block - 1] as u8); |
| 6229 | let want = |
| 6230 | (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255); |
| 6231 | recon[block] = want; |
| 6232 | for y in 0..32 { |
| 6233 | for x in 0..32 { |
| 6234 | let i = (br * 32 + y) * 128 + bc * 32 + x; |
| 6235 | assert_eq!( |
| 6236 | i32::from(luma[i]), |
| 6237 | want, |
| 6238 | "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \ |
| 6239 | column {bc}" |
| 6240 | ); |
| 6241 | } |
| 6242 | } |
| 6243 | } |
| 6244 | for (i, &sample) in chroma.iter().enumerate() { |
| 6245 | assert_eq!(sample, 128, "chroma sample {i}"); |
| 6246 | } |
| 6247 | } |
| 6248 | |
| 6249 | |
| 6250 | fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> { |
| 6251 | let (w, h) = (64 * sb_cols, 64 * sb_rows); |
| 6252 | let (seq, mut header) = frame_of(w, h); |
| 6253 | |
| 6254 | |
| 6255 | header.disable_cdf_update = true; |
| 6256 | let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap(); |
| 6257 | let mut stream = temporal_delimiter(); |
| 6258 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 6259 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 6260 | ffmpeg_decode(&stream, w as usize, h as usize) |
| 6261 | } |
| 6262 | |
| 6263 | #[test] |
| 6264 | fn a_level_grid_that_does_not_cover_the_frame_is_refused() { |
| 6265 | assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err()); |
| 6266 | assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err()); |
| 6267 | assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err()); |
| 6268 | assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err()); |
| 6269 | assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err()); |
| 6270 | } |
| 6271 | |
| 6272 | #[test] |
| 6273 | fn dc_levels_the_base_syntax_cannot_carry_are_refused() { |
| 6274 | assert!(dc_key_frame_tile(16, 16, 100, 0).is_err()); |
| 6275 | assert!(dc_key_frame_tile(16, 16, 100, 15).is_err()); |
| 6276 | assert!(dc_key_frame_tile(16, 16, 100, -15).is_err()); |
| 6277 | } |
| 6278 | |
| 6279 | #[test] |
| 6280 | fn partial_superblocks_are_refused() { |
| 6281 | assert!(flat_key_frame_tile(16, 20).is_err()); |
| 6282 | assert!(flat_key_frame_tile(0, 16).is_err()); |
| 6283 | } |
| 6284 | |
| 6285 | |
| 6286 | |
| 6287 | fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> { |
| 6288 | let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect(); |
| 6289 | let [luma, u, v] = decode_coeff_planes(&blocks); |
| 6290 | for (name, plane) in [("U", &u), ("V", &v)] { |
| 6291 | for (y, row) in plane.iter().enumerate() { |
| 6292 | for (x, &s) in row.iter().enumerate() { |
| 6293 | assert_eq!( |
| 6294 | s, 128, |
| 6295 | "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \ |
| 6296 | DC prediction with no coded neighbour is mid-grey" |
| 6297 | ); |
| 6298 | } |
| 6299 | } |
| 6300 | } |
| 6301 | luma |
| 6302 | } |
| 6303 | |
| 6304 | |
| 6305 | |
| 6306 | |
| 6307 | fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] { |
| 6308 | let (seq, header) = frame_of(64, 64); |
| 6309 | let tile = |
| 6310 | split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap(); |
| 6311 | let mut stream = temporal_delimiter(); |
| 6312 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 6313 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 6314 | let planes = ffmpeg_decode(&stream, 64, 64); |
| 6315 | let (luma, chroma) = planes.split_at(64 * 64); |
| 6316 | let (u, v) = chroma.split_at(32 * 32); |
| 6317 | [ |
| 6318 | luma.chunks_exact(64).map(<[u8]>::to_vec).collect(), |
| 6319 | u.chunks_exact(32).map(<[u8]>::to_vec).collect(), |
| 6320 | v.chunks_exact(32).map(<[u8]>::to_vec).collect(), |
| 6321 | ] |
| 6322 | } |
| 6323 | |
| 6324 | |
| 6325 | |
| 6326 | fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> { |
| 6327 | rows[..32].iter().map(|r| r[..32].to_vec()).collect() |
| 6328 | } |
| 6329 | |
| 6330 | |
| 6331 | |
| 6332 | |
| 6333 | |
| 6334 | fn assert_mean_is_mid_grey(block: &[Vec<u8>]) { |
| 6335 | let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum(); |
| 6336 | let mean = f64::from(sum) / (32.0 * 32.0); |
| 6337 | assert!( |
| 6338 | (mean - 128.0).abs() <= 1.0, |
| 6339 | "a block with no DC coefficient averages to its mid-grey prediction, got {mean}" |
| 6340 | ); |
| 6341 | } |
| 6342 | |
| 6343 | |
| 6344 | |
| 6345 | |
| 6346 | |
| 6347 | |
| 6348 | |
| 6349 | #[test] |
| 6350 | fn a_coefficient_off_the_origin_selects_its_own_basis_function() { |
| 6351 | if !have_ffmpeg() { |
| 6352 | eprintln!( |
| 6353 | "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg" |
| 6354 | ); |
| 6355 | return; |
| 6356 | } |
| 6357 | let blocks = vec![ |
| 6358 | vec![Coeff { |
| 6359 | row: 0, |
| 6360 | col: 1, |
| 6361 | level: 12, |
| 6362 | }], |
| 6363 | Vec::new(), |
| 6364 | Vec::new(), |
| 6365 | Vec::new(), |
| 6366 | ]; |
| 6367 | let rows = decode_coeff_quadrants(&blocks); |
| 6368 | let block = top_left_block(&rows); |
| 6369 | |
| 6370 | for (y, row) in block.iter().enumerate() { |
| 6371 | assert_eq!(row, &block[0], "row {y} of a horizontal basis function"); |
| 6372 | } |
| 6373 | assert!( |
| 6374 | block[0][0] > block[0][31], |
| 6375 | "a positive coefficient leans the block towards its left edge: {:?}", |
| 6376 | block[0] |
| 6377 | ); |
| 6378 | for x in 1..32 { |
| 6379 | assert!( |
| 6380 | block[0][x] <= block[0][x - 1], |
| 6381 | "the half-cycle falls from left to right, broke at column {x}: {:?}", |
| 6382 | block[0] |
| 6383 | ); |
| 6384 | } |
| 6385 | assert_mean_is_mid_grey(&block); |
| 6386 | |
| 6387 | |
| 6388 | |
| 6389 | let blocks = vec![ |
| 6390 | vec![Coeff { |
| 6391 | row: 1, |
| 6392 | col: 0, |
| 6393 | level: 12, |
| 6394 | }], |
| 6395 | Vec::new(), |
| 6396 | Vec::new(), |
| 6397 | Vec::new(), |
| 6398 | ]; |
| 6399 | let rows = decode_coeff_quadrants(&blocks); |
| 6400 | let block = top_left_block(&rows); |
| 6401 | for (y, row) in block.iter().enumerate() { |
| 6402 | for (x, &s) in row.iter().enumerate() { |
| 6403 | assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function"); |
| 6404 | } |
| 6405 | } |
| 6406 | assert!( |
| 6407 | block[0][0] > block[31][0], |
| 6408 | "a positive coefficient leans the block up" |
| 6409 | ); |
| 6410 | for y in 1..32 { |
| 6411 | assert!( |
| 6412 | block[y][0] <= block[y - 1][0], |
| 6413 | "the half-cycle falls from top to bottom, broke at row {y}" |
| 6414 | ); |
| 6415 | } |
| 6416 | assert_mean_is_mid_grey(&block); |
| 6417 | } |
| 6418 | |
| 6419 | |
| 6420 | |
| 6421 | |
| 6422 | |
| 6423 | |
| 6424 | |
| 6425 | #[test] |
| 6426 | fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() { |
| 6427 | if !have_ffmpeg() { |
| 6428 | eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group"); |
| 6429 | return; |
| 6430 | } |
| 6431 | let block = vec![ |
| 6432 | Coeff { |
| 6433 | row: 31, |
| 6434 | col: 31, |
| 6435 | level: 5, |
| 6436 | }, |
| 6437 | Coeff { |
| 6438 | row: 5, |
| 6439 | col: 7, |
| 6440 | level: -9, |
| 6441 | }, |
| 6442 | Coeff { |
| 6443 | row: 1, |
| 6444 | col: 1, |
| 6445 | level: 14, |
| 6446 | }, |
| 6447 | Coeff { |
| 6448 | row: 0, |
| 6449 | col: 2, |
| 6450 | level: -3, |
| 6451 | }, |
| 6452 | Coeff { |
| 6453 | row: 2, |
| 6454 | col: 0, |
| 6455 | level: 2, |
| 6456 | }, |
| 6457 | Coeff { |
| 6458 | row: 1, |
| 6459 | col: 2, |
| 6460 | level: -1, |
| 6461 | }, |
| 6462 | ]; |
| 6463 | let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]); |
| 6464 | let block = top_left_block(&rows); |
| 6465 | assert_mean_is_mid_grey(&block); |
| 6466 | assert!( |
| 6467 | block.iter().flatten().any(|&s| s != block[0][0]), |
| 6468 | "six coefficients do not decode to a flat block" |
| 6469 | ); |
| 6470 | |
| 6471 | |
| 6472 | for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] { |
| 6473 | let first = rows[ys.start][xs.start]; |
| 6474 | for y in ys { |
| 6475 | for x in xs.clone() { |
| 6476 | assert_eq!(rows[y][x], first, "the {name} block carries no coefficient"); |
| 6477 | } |
| 6478 | } |
| 6479 | } |
| 6480 | } |
| 6481 | |
| 6482 | |
| 6483 | |
| 6484 | |
| 6485 | |
| 6486 | |
| 6487 | #[test] |
| 6488 | fn the_priced_coefficient_bits_match_the_bytes_written() { |
| 6489 | let scan = default_scan(TX32); |
| 6490 | |
| 6491 | |
| 6492 | |
| 6493 | let mut grids = vec![vec![0i32; TX32 * TX32]; 3]; |
| 6494 | grids[0][0] = -7; |
| 6495 | for (i, &pos) in scan.iter().enumerate().take(400) { |
| 6496 | if i % 7 == 0 { |
| 6497 | grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 }; |
| 6498 | } |
| 6499 | } |
| 6500 | grids[2][0] = 40; |
| 6501 | for (i, &pos) in scan.iter().enumerate().take(64) { |
| 6502 | grids[2][pos as usize] += i as i32 % 23 - 11; |
| 6503 | } |
| 6504 | |
| 6505 | |
| 6506 | |
| 6507 | let mut enc = SymbolEncoder::new(); |
| 6508 | let mut priced = 0.0; |
| 6509 | for grid in &grids { |
| 6510 | write_coeffs( |
| 6511 | &mut enc, |
| 6512 | &mut Cdfs::new(2).txb(TxbSet::Luma32, 0), |
| 6513 | grid, |
| 6514 | &scan, |
| 6515 | 0, |
| 6516 | 0, |
| 6517 | None, |
| 6518 | ); |
| 6519 | priced += luma_32_coeff_bits(grid); |
| 6520 | } |
| 6521 | let spent = enc.finish().len() as f64 * 8.0; |
| 6522 | assert!( |
| 6523 | (priced - spent).abs() / spent < 0.02, |
| 6524 | "priced {priced} bits, wrote {spent}" |
| 6525 | ); |
| 6526 | } |
| 6527 | |
| 6528 | |
| 6529 | |
| 6530 | |
| 6531 | |
| 6532 | |
| 6533 | #[test] |
| 6534 | fn the_price_grows_with_the_levels() { |
| 6535 | let grid = |f: &dyn Fn(&mut Vec<i32>)| { |
| 6536 | let mut g = vec![0i32; TX32 * TX32]; |
| 6537 | f(&mut g); |
| 6538 | luma_32_coeff_bits(&g) |
| 6539 | }; |
| 6540 | let empty = grid(&|_| {}); |
| 6541 | let one = grid(&|g| g[0] = 1); |
| 6542 | let bigger = grid(&|g| g[0] = 30); |
| 6543 | let spread = grid(&|g| { |
| 6544 | for i in 0..TX32 { |
| 6545 | g[i * TX32 + i] = 1; |
| 6546 | } |
| 6547 | }); |
| 6548 | assert!(empty < one, "{empty} {one}"); |
| 6549 | assert!(one < bigger, "{one} {bigger}"); |
| 6550 | assert!(one < spread, "{one} {spread}"); |
| 6551 | |
| 6552 | |
| 6553 | |
| 6554 | assert!( |
| 6555 | empty < 6.0, |
| 6556 | "an empty block is one skip symbol, not {empty}" |
| 6557 | ); |
| 6558 | } |
| 6559 | |
| 6560 | |
| 6561 | |
| 6562 | |
| 6563 | |
| 6564 | |
| 6565 | |
| 6566 | #[test] |
| 6567 | fn every_quadrant_carries_its_own_coefficients() { |
| 6568 | if !have_ffmpeg() { |
| 6569 | eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg"); |
| 6570 | return; |
| 6571 | } |
| 6572 | let blocks = vec![ |
| 6573 | vec![ |
| 6574 | Coeff { |
| 6575 | row: 0, |
| 6576 | col: 1, |
| 6577 | level: 7, |
| 6578 | }, |
| 6579 | Coeff { |
| 6580 | row: 3, |
| 6581 | col: 4, |
| 6582 | level: -14, |
| 6583 | }, |
| 6584 | ], |
| 6585 | vec![ |
| 6586 | Coeff { |
| 6587 | row: 0, |
| 6588 | col: 0, |
| 6589 | level: -6, |
| 6590 | }, |
| 6591 | Coeff { |
| 6592 | row: 2, |
| 6593 | col: 2, |
| 6594 | level: 9, |
| 6595 | }, |
| 6596 | ], |
| 6597 | vec![ |
| 6598 | Coeff { |
| 6599 | row: 0, |
| 6600 | col: 0, |
| 6601 | level: 6, |
| 6602 | }, |
| 6603 | Coeff { |
| 6604 | row: 1, |
| 6605 | col: 0, |
| 6606 | level: -2, |
| 6607 | }, |
| 6608 | Coeff { |
| 6609 | row: 8, |
| 6610 | col: 9, |
| 6611 | level: 3, |
| 6612 | }, |
| 6613 | ], |
| 6614 | vec![ |
| 6615 | Coeff { |
| 6616 | row: 0, |
| 6617 | col: 0, |
| 6618 | level: 11, |
| 6619 | }, |
| 6620 | Coeff { |
| 6621 | row: 16, |
| 6622 | col: 1, |
| 6623 | level: -4, |
| 6624 | }, |
| 6625 | ], |
| 6626 | ]; |
| 6627 | let rows = decode_coeff_quadrants(&blocks); |
| 6628 | assert_mean_is_mid_grey(&top_left_block(&rows)); |
| 6629 | for (name, ys, xs) in [ |
| 6630 | ("top right", 0..32, 32..64), |
| 6631 | ("bottom left", 32..64, 0..32), |
| 6632 | ("bottom right", 32..64, 32..64), |
| 6633 | ] { |
| 6634 | let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect(); |
| 6635 | assert!( |
| 6636 | block.iter().flatten().any(|&s| s != block[0][0]), |
| 6637 | "the {name} block carries coefficients, so it is not flat" |
| 6638 | ); |
| 6639 | } |
| 6640 | } |
| 6641 | |
| 6642 | |
| 6643 | |
| 6644 | fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> { |
| 6645 | rows[..16].iter().map(|r| r[..16].to_vec()).collect() |
| 6646 | } |
| 6647 | |
| 6648 | |
| 6649 | |
| 6650 | fn mean(block: &[Vec<u8>]) -> f64 { |
| 6651 | let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum(); |
| 6652 | let count = block.iter().map(Vec::len).sum::<usize>() as f64; |
| 6653 | f64::from(sum) / count |
| 6654 | } |
| 6655 | |
| 6656 | |
| 6657 | |
| 6658 | |
| 6659 | |
| 6660 | |
| 6661 | #[test] |
| 6662 | fn each_chroma_plane_codes_its_own_basis_function() { |
| 6663 | if !have_ffmpeg() { |
| 6664 | eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg"); |
| 6665 | return; |
| 6666 | } |
| 6667 | let mut blocks = vec![BlockCoeffs::default(); 4]; |
| 6668 | blocks[0].u = vec![Coeff { |
| 6669 | row: 0, |
| 6670 | col: 1, |
| 6671 | level: 12, |
| 6672 | }]; |
| 6673 | blocks[0].v = vec![Coeff { |
| 6674 | row: 1, |
| 6675 | col: 0, |
| 6676 | level: 12, |
| 6677 | }]; |
| 6678 | let [luma, u, v] = decode_coeff_planes(&blocks); |
| 6679 | |
| 6680 | for (y, row) in luma.iter().enumerate() { |
| 6681 | for (x, &s) in row.iter().enumerate() { |
| 6682 | assert_eq!( |
| 6683 | s, 128, |
| 6684 | "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \ |
| 6685 | stays at its mid-grey prediction" |
| 6686 | ); |
| 6687 | } |
| 6688 | } |
| 6689 | |
| 6690 | let u_block = top_left_chroma(&u); |
| 6691 | for (y, row) in u_block.iter().enumerate() { |
| 6692 | assert_eq!( |
| 6693 | row, &u_block[0], |
| 6694 | "row {y} of a horizontal chroma basis function" |
| 6695 | ); |
| 6696 | } |
| 6697 | assert!( |
| 6698 | u_block[0][0] > u_block[0][15], |
| 6699 | "a positive coefficient leans the U block towards its left edge: {:?}", |
| 6700 | u_block[0] |
| 6701 | ); |
| 6702 | |
| 6703 | let v_block = top_left_chroma(&v); |
| 6704 | for (x, &top) in v_block[0].iter().enumerate() { |
| 6705 | assert_eq!( |
| 6706 | top, v_block[0][0], |
| 6707 | "column {x} of a vertical chroma basis function" |
| 6708 | ); |
| 6709 | let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect(); |
| 6710 | assert!( |
| 6711 | column[0] > column[15], |
| 6712 | "a positive coefficient leans the V column towards its top edge: {column:?}" |
| 6713 | ); |
| 6714 | } |
| 6715 | |
| 6716 | for (name, block) in [("U", &u_block), ("V", &v_block)] { |
| 6717 | let mean = mean(block); |
| 6718 | assert!( |
| 6719 | (mean - 128.0).abs() <= 1.0, |
| 6720 | "the {name} block carries no DC, so it averages to its mid-grey prediction, \ |
| 6721 | got {mean}" |
| 6722 | ); |
| 6723 | } |
| 6724 | } |
| 6725 | |
| 6726 | |
| 6727 | |
| 6728 | |
| 6729 | |
| 6730 | |
| 6731 | #[test] |
| 6732 | fn chroma_dc_signs_read_their_neighbours() { |
| 6733 | if !have_ffmpeg() { |
| 6734 | eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg"); |
| 6735 | return; |
| 6736 | } |
| 6737 | let dc = |level| { |
| 6738 | vec![Coeff { |
| 6739 | row: 0, |
| 6740 | col: 0, |
| 6741 | level, |
| 6742 | }] |
| 6743 | }; |
| 6744 | let signs = [8, -8, -8, 8]; |
| 6745 | let blocks: Vec<BlockCoeffs> = signs |
| 6746 | .iter() |
| 6747 | .map(|&level| BlockCoeffs { |
| 6748 | luma: Vec::new(), |
| 6749 | u: dc(level), |
| 6750 | v: dc(-level), |
| 6751 | ..BlockCoeffs::default() |
| 6752 | }) |
| 6753 | .collect(); |
| 6754 | let [luma, u, v] = decode_coeff_planes(&blocks); |
| 6755 | |
| 6756 | for (y, row) in luma.iter().enumerate() { |
| 6757 | for (x, &s) in row.iter().enumerate() { |
| 6758 | assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient"); |
| 6759 | } |
| 6760 | } |
| 6761 | |
| 6762 | |
| 6763 | |
| 6764 | |
| 6765 | |
| 6766 | for (i, &level) in signs.iter().enumerate() { |
| 6767 | let (r, c) = (i / 2, i % 2); |
| 6768 | let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> { |
| 6769 | plane[r * 16..r * 16 + 16] |
| 6770 | .iter() |
| 6771 | .map(|row| row[c * 16..c * 16 + 16].to_vec()) |
| 6772 | .collect() |
| 6773 | }; |
| 6774 | for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] { |
| 6775 | let block = block(plane); |
| 6776 | let mean = mean(&block); |
| 6777 | for (y, row) in block.iter().enumerate() { |
| 6778 | assert_eq!( |
| 6779 | row.iter().collect::<std::collections::HashSet<_>>().len(), |
| 6780 | 1, |
| 6781 | "row {y} of a DC-only {name} block is flat" |
| 6782 | ); |
| 6783 | } |
| 6784 | if i == 0 { |
| 6785 | assert!( |
| 6786 | (want > 0) == (mean > 128.0), |
| 6787 | "{name} block {i} carries a DC of {want}, so it must lean off its \ |
| 6788 | mid-grey prediction that way, got {mean}" |
| 6789 | ); |
| 6790 | } |
| 6791 | } |
| 6792 | } |
| 6793 | assert_ne!(u, v, "the two chroma planes carry opposite DCs"); |
| 6794 | } |
| 6795 | |
| 6796 | |
| 6797 | |
| 6798 | |
| 6799 | fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> { |
| 6800 | rows[block_row * 32..block_row * 32 + 32] |
| 6801 | .iter() |
| 6802 | .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec()) |
| 6803 | .collect() |
| 6804 | } |
| 6805 | |
| 6806 | |
| 6807 | |
| 6808 | |
| 6809 | |
| 6810 | |
| 6811 | |
| 6812 | |
| 6813 | |
| 6814 | #[test] |
| 6815 | fn a_block_gathers_the_cells_its_neighbours_cover() { |
| 6816 | let mut neighbours = Neighbours::new(4, 4, 64, 64); |
| 6817 | let quiet = [ |
| 6818 | vec![0i32; TX16 * TX16], |
| 6819 | vec![0; TX8 * TX8], |
| 6820 | vec![0; TX8 * TX8], |
| 6821 | ]; |
| 6822 | let mut loud = quiet.clone(); |
| 6823 | loud[1][0] = -3; |
| 6824 | |
| 6825 | |
| 6826 | neighbours.record((0, 2), SUB, DC_PRED, &quiet); |
| 6827 | neighbours.record((0, 3), SUB, DC_PRED, &loud); |
| 6828 | let around = neighbours.around((2, 2), BLOCK); |
| 6829 | assert!( |
| 6830 | around[1].above_coded, |
| 6831 | "the coded cell has to reach the block below it" |
| 6832 | ); |
| 6833 | assert_eq!( |
| 6834 | dc_sign_ctx(around[1].dc_vote), |
| 6835 | 1, |
| 6836 | "the one negative DC above the block is what it votes" |
| 6837 | ); |
| 6838 | |
| 6839 | |
| 6840 | |
| 6841 | assert!(!neighbours.above[8][1].coded); |
| 6842 | } |
| 6843 | |
| 6844 | |
| 6845 | fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> { |
| 6846 | let (seq, header) = frame_of(width as u32, height as u32); |
| 6847 | let tile = |
| 6848 | split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap(); |
| 6849 | let mut stream = temporal_delimiter(); |
| 6850 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 6851 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 6852 | let planes = ffmpeg_decode(&stream, width, height); |
| 6853 | planes[..width * height] |
| 6854 | .chunks_exact(width) |
| 6855 | .map(<[u8]>::to_vec) |
| 6856 | .collect() |
| 6857 | } |
| 6858 | |
| 6859 | |
| 6860 | |
| 6861 | fn assert_falls_across(block: &[Vec<u8>], name: &str) { |
| 6862 | for row in block { |
| 6863 | assert_eq!( |
| 6864 | row, &block[0], |
| 6865 | "{name}: every row of the block is the same row" |
| 6866 | ); |
| 6867 | } |
| 6868 | assert!( |
| 6869 | block[0][0] > block[0][31], |
| 6870 | "{name}: the row falls from left to right, got {} then {}", |
| 6871 | block[0][0], |
| 6872 | block[0][31] |
| 6873 | ); |
| 6874 | } |
| 6875 | |
| 6876 | |
| 6877 | |
| 6878 | fn assert_falls_down(block: &[Vec<u8>], name: &str) { |
| 6879 | for (y, row) in block.iter().enumerate() { |
| 6880 | assert!( |
| 6881 | row.iter().all(|&s| s == row[0]), |
| 6882 | "{name}: row {y} of the block is one constant" |
| 6883 | ); |
| 6884 | } |
| 6885 | assert!( |
| 6886 | block[0][0] > block[31][0], |
| 6887 | "{name}: the column falls down the block, got {} then {}", |
| 6888 | block[0][0], |
| 6889 | block[31][0] |
| 6890 | ); |
| 6891 | } |
| 6892 | |
| 6893 | |
| 6894 | fn mean_of(block: &[Vec<u8>]) -> f64 { |
| 6895 | let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum(); |
| 6896 | f64::from(sum) / (block.len() * block[0].len()) as f64 |
| 6897 | } |
| 6898 | |
| 6899 | |
| 6900 | |
| 6901 | fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> { |
| 6902 | let blocks = vec![ |
| 6903 | vec![Coeff { |
| 6904 | row: 0, |
| 6905 | col: 0, |
| 6906 | level, |
| 6907 | }], |
| 6908 | Vec::new(), |
| 6909 | Vec::new(), |
| 6910 | Vec::new(), |
| 6911 | ]; |
| 6912 | top_left_block(&decode_coeff_quadrants(&blocks)) |
| 6913 | } |
| 6914 | |
| 6915 | |
| 6916 | |
| 6917 | |
| 6918 | fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 { |
| 6919 | let mut length = 0; |
| 6920 | while dec.literal(1) == 0 { |
| 6921 | length += 1; |
| 6922 | assert!( |
| 6923 | length < 20, |
| 6924 | "the tail's length prefix runs past twenty bits" |
| 6925 | ); |
| 6926 | } |
| 6927 | let mut x = 1; |
| 6928 | for _ in 0..length { |
| 6929 | x = (x << 1) | dec.literal(1); |
| 6930 | } |
| 6931 | (MAX_BR_LEVEL + 1) as u32 + (x - 1) |
| 6932 | } |
| 6933 | |
| 6934 | |
| 6935 | |
| 6936 | |
| 6937 | |
| 6938 | |
| 6939 | #[test] |
| 6940 | fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() { |
| 6941 | for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300) |
| 6942 | .chain([MAX_LEVEL - 1, MAX_LEVEL]) |
| 6943 | .map(|l| l as u32) |
| 6944 | { |
| 6945 | let mut enc = SymbolEncoder::new(); |
| 6946 | write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32); |
| 6947 | |
| 6948 | |
| 6949 | let data = enc.finish(); |
| 6950 | let mut dec = crate::msac::tests::SymbolDecoder::new(&data); |
| 6951 | assert_eq!( |
| 6952 | read_golomb_level(&mut dec), |
| 6953 | level, |
| 6954 | "the tail of level {level}" |
| 6955 | ); |
| 6956 | } |
| 6957 | } |
| 6958 | |
| 6959 | |
| 6960 | |
| 6961 | |
| 6962 | |
| 6963 | |
| 6964 | |
| 6965 | |
| 6966 | |
| 6967 | |
| 6968 | #[test] |
| 6969 | fn levels_above_the_base_range_tail_carry_a_golomb_tail() { |
| 6970 | if !have_ffmpeg() { |
| 6971 | eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg"); |
| 6972 | return; |
| 6973 | } |
| 6974 | let mut brighter = Vec::new(); |
| 6975 | let mut darker = Vec::new(); |
| 6976 | for level in [10, 14, 18, 31, 60, 400] { |
| 6977 | brighter.push((level, mean_of(&decode_dc_level_block(level)))); |
| 6978 | darker.push((level, mean_of(&decode_dc_level_block(-level)))); |
| 6979 | } |
| 6980 | for pair in brighter.windows(2) { |
| 6981 | let [(low, dim), (high, bright)] = [pair[0], pair[1]]; |
| 6982 | assert!( |
| 6983 | bright > dim, |
| 6984 | "level {high} decodes brighter than level {low}, got {bright} against {dim}" |
| 6985 | ); |
| 6986 | } |
| 6987 | for pair in darker.windows(2) { |
| 6988 | let [(low, bright), (high, dim)] = [pair[0], pair[1]]; |
| 6989 | assert!( |
| 6990 | dim < bright, |
| 6991 | "level -{high} decodes darker than level -{low}, got {dim} against {bright}" |
| 6992 | ); |
| 6993 | } |
| 6994 | let (_, mid) = brighter[0]; |
| 6995 | assert!( |
| 6996 | mid > 128.0 && darker[0].1 < 128.0, |
| 6997 | "a positive level brightens its block and a negative one darkens it, got {mid} and {}", |
| 6998 | darker[0].1 |
| 6999 | ); |
| 7000 | } |
| 7001 | |
| 7002 | |
| 7003 | |
| 7004 | |
| 7005 | |
| 7006 | |
| 7007 | |
| 7008 | |
| 7009 | |
| 7010 | fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> { |
| 7011 | let (seq, header) = frame_of(width as u32, height as u32); |
| 7012 | let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap(); |
| 7013 | let mut stream = temporal_delimiter(); |
| 7014 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 7015 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 7016 | let planes = ffmpeg_decode(&stream, width, height); |
| 7017 | planes[..width * height] |
| 7018 | .chunks_exact(width) |
| 7019 | .map(<[u8]>::to_vec) |
| 7020 | .collect() |
| 7021 | } |
| 7022 | |
| 7023 | |
| 7024 | |
| 7025 | |
| 7026 | |
| 7027 | |
| 7028 | |
| 7029 | |
| 7030 | #[test] |
| 7031 | fn a_whole_superblock_covers_all_four_of_its_quadrants() { |
| 7032 | if !have_ffmpeg() { |
| 7033 | eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg"); |
| 7034 | return; |
| 7035 | } |
| 7036 | let across = BlockCoeffs::from(vec![Coeff { |
| 7037 | row: 0, |
| 7038 | col: 1, |
| 7039 | level: 20, |
| 7040 | }]); |
| 7041 | let down = BlockCoeffs::from(vec![Coeff { |
| 7042 | row: 1, |
| 7043 | col: 0, |
| 7044 | level: 20, |
| 7045 | }]); |
| 7046 | let sbs = [ |
| 7047 | Superblock::Whole(across), |
| 7048 | Superblock::Split(vec![ |
| 7049 | Quadrant::Whole(down.clone()), |
| 7050 | Quadrant::Whole(down.clone()), |
| 7051 | Quadrant::Whole(down.clone()), |
| 7052 | Quadrant::Whole(down), |
| 7053 | ]), |
| 7054 | ]; |
| 7055 | let rows = decode_luma_sb(128, 64, &sbs); |
| 7056 | |
| 7057 | for (y, row) in rows.iter().enumerate() { |
| 7058 | assert_eq!( |
| 7059 | &row[..64], |
| 7060 | &rows[0][..64], |
| 7061 | "row {y} of the whole superblock repeats its first row" |
| 7062 | ); |
| 7063 | } |
| 7064 | let first = &rows[0][..64]; |
| 7065 | assert!( |
| 7066 | first.windows(2).all(|w| w[0] >= w[1]), |
| 7067 | "the whole superblock falls across its sixty-four samples without \ |
| 7068 | restarting: {first:?}" |
| 7069 | ); |
| 7070 | assert!( |
| 7071 | first[0] > first[63], |
| 7072 | "the whole superblock falls from left to right, got {} then {}", |
| 7073 | first[0], |
| 7074 | first[63] |
| 7075 | ); |
| 7076 | for block_row in 0..2 { |
| 7077 | for block_col in 2..4 { |
| 7078 | let block = block_at(&rows, block_row, block_col); |
| 7079 | assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})")); |
| 7080 | } |
| 7081 | } |
| 7082 | } |
| 7083 | |
| 7084 | |
| 7085 | |
| 7086 | |
| 7087 | |
| 7088 | |
| 7089 | #[test] |
| 7090 | fn a_quadrant_splits_into_four_sixteens() { |
| 7091 | if !have_ffmpeg() { |
| 7092 | eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg"); |
| 7093 | return; |
| 7094 | } |
| 7095 | let dc = |level: i32| { |
| 7096 | BlockCoeffs::from(vec![Coeff { |
| 7097 | row: 0, |
| 7098 | col: 0, |
| 7099 | level, |
| 7100 | }]) |
| 7101 | }; |
| 7102 | let levels = [14, 8, -8, -14]; |
| 7103 | let flat = BlockCoeffs::from(Vec::new()); |
| 7104 | let sbs = [Superblock::Split(vec![ |
| 7105 | Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()), |
| 7106 | Quadrant::Whole(flat.clone()), |
| 7107 | Quadrant::Whole(flat.clone()), |
| 7108 | Quadrant::Whole(flat), |
| 7109 | ])]; |
| 7110 | let rows = decode_luma_sb(64, 64, &sbs); |
| 7111 | |
| 7112 | let mut greys = Vec::new(); |
| 7113 | for i in 0..levels.len() { |
| 7114 | let (y0, x0) = ((i / 2) * 16, (i % 2) * 16); |
| 7115 | let grey = rows[y0][x0]; |
| 7116 | for (y, row) in rows.iter().enumerate().skip(y0).take(16) { |
| 7117 | for (x, &sample) in row.iter().enumerate().skip(x0).take(16) { |
| 7118 | assert_eq!( |
| 7119 | sample, grey, |
| 7120 | "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not" |
| 7121 | ); |
| 7122 | } |
| 7123 | } |
| 7124 | greys.push(grey); |
| 7125 | } |
| 7126 | |
| 7127 | |
| 7128 | |
| 7129 | |
| 7130 | let g = |i: usize| i32::from(greys[i]); |
| 7131 | let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2]; |
| 7132 | for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() { |
| 7133 | assert_eq!( |
| 7134 | (g(i) - prediction).signum(), |
| 7135 | level.signum(), |
| 7136 | "the 16x16 block {i} carries level {level}, so it sits on the \ |
| 7137 | {} side of the {prediction} its neighbours predict, not at {}", |
| 7138 | if level > 0 { "bright" } else { "dark" }, |
| 7139 | g(i) |
| 7140 | ); |
| 7141 | } |
| 7142 | assert_eq!( |
| 7143 | greys.iter().collect::<std::collections::HashSet<_>>().len(), |
| 7144 | 4, |
| 7145 | "the four blocks are four different greys, not one: {greys:?}" |
| 7146 | ); |
| 7147 | } |
| 7148 | |
| 7149 | |
| 7150 | |
| 7151 | #[test] |
| 7152 | fn a_whole_superblock_at_the_frame_edge_is_refused() { |
| 7153 | let block = BlockCoeffs::from(vec![Coeff { |
| 7154 | row: 0, |
| 7155 | col: 0, |
| 7156 | level: 4, |
| 7157 | }]); |
| 7158 | let sbs = [ |
| 7159 | Superblock::Split(vec![ |
| 7160 | Quadrant::Whole(block.clone()), |
| 7161 | Quadrant::Whole(block.clone()), |
| 7162 | Quadrant::Whole(block.clone()), |
| 7163 | Quadrant::Whole(block.clone()), |
| 7164 | ]), |
| 7165 | Superblock::Whole(block.clone()), |
| 7166 | ]; |
| 7167 | |
| 7168 | |
| 7169 | let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err(); |
| 7170 | assert!( |
| 7171 | format!("{err}").contains("half outside the frame"), |
| 7172 | "got {err}" |
| 7173 | ); |
| 7174 | } |
| 7175 | |
| 7176 | #[test] |
| 7177 | fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() { |
| 7178 | if !have_ffmpeg() { |
| 7179 | eprintln!( |
| 7180 | "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \ |
| 7181 | ffmpeg" |
| 7182 | ); |
| 7183 | return; |
| 7184 | } |
| 7185 | let blocks: Vec<BlockCoeffs> = (0..6) |
| 7186 | .map(|i| { |
| 7187 | let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) }; |
| 7188 | BlockCoeffs::from(vec![Coeff { |
| 7189 | row, |
| 7190 | col, |
| 7191 | level: 12, |
| 7192 | }]) |
| 7193 | }) |
| 7194 | .collect(); |
| 7195 | let rows = decode_luma_at(96, 64, &blocks); |
| 7196 | for block_row in 0..2 { |
| 7197 | for block_col in 0..3 { |
| 7198 | let name = format!("block ({block_row},{block_col})"); |
| 7199 | let block = block_at(&rows, block_row, block_col); |
| 7200 | if (block_row * 3 + block_col) % 2 == 0 { |
| 7201 | assert_falls_across(&block, &name); |
| 7202 | } else { |
| 7203 | assert_falls_down(&block, &name); |
| 7204 | } |
| 7205 | } |
| 7206 | } |
| 7207 | } |
| 7208 | |
| 7209 | |
| 7210 | |
| 7211 | |
| 7212 | |
| 7213 | |
| 7214 | |
| 7215 | |
| 7216 | |
| 7217 | #[test] |
| 7218 | fn a_frame_that_hangs_off_the_bottom_codes_every_block() { |
| 7219 | if !have_ffmpeg() { |
| 7220 | eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg"); |
| 7221 | return; |
| 7222 | } |
| 7223 | let blocks: Vec<BlockCoeffs> = (0..6) |
| 7224 | .map(|i| { |
| 7225 | let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) }; |
| 7226 | BlockCoeffs::from(vec![Coeff { |
| 7227 | row, |
| 7228 | col, |
| 7229 | level: 12, |
| 7230 | }]) |
| 7231 | }) |
| 7232 | .collect(); |
| 7233 | let rows = decode_luma_at(64, 96, &blocks); |
| 7234 | for block_row in 0..3 { |
| 7235 | for block_col in 0..2 { |
| 7236 | let name = format!("block ({block_row},{block_col})"); |
| 7237 | let block = block_at(&rows, block_row, block_col); |
| 7238 | if (block_row * 2 + block_col) % 2 == 0 { |
| 7239 | assert_falls_across(&block, &name); |
| 7240 | } else { |
| 7241 | assert_falls_down(&block, &name); |
| 7242 | } |
| 7243 | } |
| 7244 | } |
| 7245 | } |
| 7246 | |
| 7247 | |
| 7248 | |
| 7249 | #[test] |
| 7250 | fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() { |
| 7251 | let (_, header) = frame_of(80, 64); |
| 7252 | let blocks = vec![BlockCoeffs::default(); 4]; |
| 7253 | let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks) |
| 7254 | .expect_err("80 is not a whole number of 32x32 blocks"); |
| 7255 | assert!( |
| 7256 | format!("{err}").contains("32x32"), |
| 7257 | "the refusal names the block size, got {err}" |
| 7258 | ); |
| 7259 | } |
| 7260 | |
| 7261 | |
| 7262 | |
| 7263 | |
| 7264 | |
| 7265 | |
| 7266 | |
| 7267 | |
| 7268 | |
| 7269 | |
| 7270 | |
| 7271 | |
| 7272 | #[test] |
| 7273 | fn directional_modes_predict_from_the_neighbours_they_name() { |
| 7274 | if !have_ffmpeg() { |
| 7275 | eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg"); |
| 7276 | return; |
| 7277 | } |
| 7278 | let gradient = BlockCoeffs { |
| 7279 | luma: vec![Coeff { |
| 7280 | row: 1, |
| 7281 | col: 0, |
| 7282 | level: 12, |
| 7283 | }], |
| 7284 | ..BlockCoeffs::default() |
| 7285 | }; |
| 7286 | let blocks = [ |
| 7287 | gradient, |
| 7288 | BlockCoeffs { |
| 7289 | mode: H_PRED as u8, |
| 7290 | ..BlockCoeffs::default() |
| 7291 | }, |
| 7292 | BlockCoeffs { |
| 7293 | mode: V_PRED as u8, |
| 7294 | ..BlockCoeffs::default() |
| 7295 | }, |
| 7296 | BlockCoeffs::default(), |
| 7297 | ]; |
| 7298 | let [luma, ..] = decode_coeff_planes(&blocks); |
| 7299 | |
| 7300 | let source = block_at(&luma, 0, 0); |
| 7301 | for (r, row) in source.iter().enumerate() { |
| 7302 | assert!( |
| 7303 | row.iter().all(|&s| s == row[0]), |
| 7304 | "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}" |
| 7305 | ); |
| 7306 | } |
| 7307 | let profile: Vec<u8> = source.iter().map(|r| r[0]).collect(); |
| 7308 | assert!( |
| 7309 | profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31], |
| 7310 | "the block must fall from top to bottom, got {profile:?}" |
| 7311 | ); |
| 7312 | |
| 7313 | let horizontal = block_at(&luma, 0, 1); |
| 7314 | for (r, row) in horizontal.iter().enumerate() { |
| 7315 | assert!( |
| 7316 | row.iter().all(|&s| s == profile[r]), |
| 7317 | "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}", |
| 7318 | profile[r] |
| 7319 | ); |
| 7320 | } |
| 7321 | |
| 7322 | let vertical = block_at(&luma, 1, 0); |
| 7323 | let bottom = profile[31]; |
| 7324 | assert!( |
| 7325 | vertical.iter().flatten().all(|&s| s == bottom), |
| 7326 | "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \ |
| 7327 | {:?} and {:?}", |
| 7328 | vertical[0], |
| 7329 | vertical[31] |
| 7330 | ); |
| 7331 | } |
| 7332 | |
| 7333 | |
| 7334 | #[test] |
| 7335 | fn an_intra_mode_outside_the_key_frame_set_is_refused() { |
| 7336 | let mut blocks = vec![BlockCoeffs::default(); 4]; |
| 7337 | blocks[2].mode = INTRA_MODES as u8; |
| 7338 | let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks) |
| 7339 | .unwrap_err() |
| 7340 | .to_string(); |
| 7341 | assert!( |
| 7342 | message.contains("intra mode 13"), |
| 7343 | "the refusal must name the mode, got {message}" |
| 7344 | ); |
| 7345 | } |
| 7346 | |
| 7347 | #[test] |
| 7348 | fn coefficients_the_writer_cannot_code_are_refused() { |
| 7349 | let empty = || vec![BlockCoeffs::default(); 4]; |
| 7350 | let cases: [(&str, Vec<BlockCoeffs>); 6] = [ |
| 7351 | ("one set short", vec![BlockCoeffs::default(); 3]), |
| 7352 | ("off the transform", { |
| 7353 | let mut b = empty(); |
| 7354 | b[0].luma = vec![Coeff { |
| 7355 | row: 32, |
| 7356 | col: 0, |
| 7357 | level: 1, |
| 7358 | }]; |
| 7359 | b |
| 7360 | }), |
| 7361 | ("a zero level", { |
| 7362 | let mut b = empty(); |
| 7363 | b[1].luma = vec![Coeff { |
| 7364 | row: 0, |
| 7365 | col: 0, |
| 7366 | level: 0, |
| 7367 | }]; |
| 7368 | b |
| 7369 | }), |
| 7370 | ("a level past the Golomb tail's reach", { |
| 7371 | let mut b = empty(); |
| 7372 | b[2].luma = vec![Coeff { |
| 7373 | row: 0, |
| 7374 | col: 0, |
| 7375 | level: MAX_LEVEL + 1, |
| 7376 | }]; |
| 7377 | b |
| 7378 | }), |
| 7379 | ("two coefficients at one position", { |
| 7380 | let mut b = empty(); |
| 7381 | b[3].luma = vec![ |
| 7382 | Coeff { |
| 7383 | row: 4, |
| 7384 | col: 4, |
| 7385 | level: 1, |
| 7386 | }, |
| 7387 | Coeff { |
| 7388 | row: 4, |
| 7389 | col: 4, |
| 7390 | level: 2, |
| 7391 | }, |
| 7392 | ]; |
| 7393 | b |
| 7394 | }), |
| 7395 | ("off the chroma transform", { |
| 7396 | let mut b = empty(); |
| 7397 | b[0].u = vec![Coeff { |
| 7398 | row: 0, |
| 7399 | col: 16, |
| 7400 | level: 1, |
| 7401 | }]; |
| 7402 | b |
| 7403 | }), |
| 7404 | ]; |
| 7405 | for (name, blocks) in cases { |
| 7406 | assert!( |
| 7407 | split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(), |
| 7408 | "{name} must be refused" |
| 7409 | ); |
| 7410 | } |
| 7411 | } |
| 7412 | |
| 7413 | |
| 7414 | |
| 7415 | |
| 7416 | |
| 7417 | |
| 7418 | #[test] |
| 7419 | fn the_default_scan_walks_every_position_outwards() { |
| 7420 | for side in [TX16, TX32] { |
| 7421 | let area = side * side; |
| 7422 | let scan = default_scan(side); |
| 7423 | assert_eq!(scan.len(), area); |
| 7424 | let mut seen = vec![false; area]; |
| 7425 | for &pos in &scan { |
| 7426 | assert!( |
| 7427 | !seen[pos as usize], |
| 7428 | "position {pos} is scanned twice in {side}x{side}" |
| 7429 | ); |
| 7430 | seen[pos as usize] = true; |
| 7431 | } |
| 7432 | assert_eq!(scan[0], 0, "the scan starts at the DC"); |
| 7433 | |
| 7434 | let mut order = vec![0usize; area]; |
| 7435 | for (i, &pos) in scan.iter().enumerate() { |
| 7436 | order[pos as usize] = i; |
| 7437 | } |
| 7438 | for row in 0..side { |
| 7439 | for col in 0..side { |
| 7440 | for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] { |
| 7441 | let (nr, nc) = (row + dr, col + dc); |
| 7442 | if nr < side && nc < side { |
| 7443 | assert!( |
| 7444 | order[nr * side + nc] > order[row * side + col], |
| 7445 | "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \ |
| 7446 | be scanned after it" |
| 7447 | ); |
| 7448 | } |
| 7449 | } |
| 7450 | } |
| 7451 | } |
| 7452 | } |
| 7453 | } |
| 7454 | |
| 7455 | |
| 7456 | |
| 7457 | |
| 7458 | |
| 7459 | |
| 7460 | #[test] |
| 7461 | fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() { |
| 7462 | for (level, _) in DECODED_AT_Q100 { |
| 7463 | let mut levels = vec![0i32; 64 * 64]; |
| 7464 | levels[0] = level; |
| 7465 | let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX)); |
| 7466 | let want = dc_residual(level); |
| 7467 | assert!( |
| 7468 | residual.iter().all(|&r| r == want), |
| 7469 | "level {level}: want a flat {want}, got {}..{} (first {})", |
| 7470 | residual.iter().min().unwrap(), |
| 7471 | residual.iter().max().unwrap(), |
| 7472 | residual[0] |
| 7473 | ); |
| 7474 | } |
| 7475 | } |
| 7476 | |
| 7477 | |
| 7478 | |
| 7479 | |
| 7480 | |
| 7481 | |
| 7482 | #[test] |
| 7483 | fn the_inverse_transform_reproduces_the_pinned_split_residuals() { |
| 7484 | for (level, want) in SPLIT_RESIDUAL_AT_Q100 { |
| 7485 | let mut levels = vec![0i32; 32 * 32]; |
| 7486 | levels[0] = level; |
| 7487 | let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); |
| 7488 | assert!( |
| 7489 | residual.iter().all(|&r| r == want), |
| 7490 | "level {level}: want a flat {want}, got {}..{} (first {})", |
| 7491 | residual.iter().min().unwrap(), |
| 7492 | residual.iter().max().unwrap(), |
| 7493 | residual[0] |
| 7494 | ); |
| 7495 | } |
| 7496 | } |
| 7497 | |
| 7498 | |
| 7499 | |
| 7500 | |
| 7501 | |
| 7502 | |
| 7503 | #[test] |
| 7504 | fn a_single_ac_coefficient_varies_along_its_own_axis() { |
| 7505 | for side in [4, 8, 16, 32, 64] { |
| 7506 | let mut horizontal = vec![0i32; side * side]; |
| 7507 | horizontal[1] = 100; |
| 7508 | let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX)); |
| 7509 | let mut vertical = vec![0i32; side * side]; |
| 7510 | vertical[side] = 100; |
| 7511 | let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX)); |
| 7512 | for row in 0..side { |
| 7513 | for col in 0..side { |
| 7514 | assert_eq!( |
| 7515 | h[row * side + col], |
| 7516 | h[col], |
| 7517 | "{side}: a first-row coefficient is constant down column {col}" |
| 7518 | ); |
| 7519 | assert_eq!( |
| 7520 | v[row * side + col], |
| 7521 | v[row * side], |
| 7522 | "{side}: a first-column coefficient is constant along row {row}" |
| 7523 | ); |
| 7524 | } |
| 7525 | } |
| 7526 | |
| 7527 | |
| 7528 | |
| 7529 | |
| 7530 | assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies"); |
| 7531 | for row in 0..side { |
| 7532 | for col in 0..side { |
| 7533 | let (a, b) = (h[row * side + col], v[col * side + row]); |
| 7534 | assert!( |
| 7535 | (a - b).abs() <= 1, |
| 7536 | "{side}: transpose at ({row},{col}): {a} vs {b}" |
| 7537 | ); |
| 7538 | } |
| 7539 | } |
| 7540 | } |
| 7541 | } |
| 7542 | |
| 7543 | |
| 7544 | |
| 7545 | |
| 7546 | |
| 7547 | |
| 7548 | #[test] |
| 7549 | fn negating_the_levels_negates_the_residual() { |
| 7550 | for side in [32, 64] { |
| 7551 | for level in [1, 2, 3, 5, 9, 14, 40, 100] { |
| 7552 | let mut levels = vec![0i32; side * side]; |
| 7553 | levels[0] = level; |
| 7554 | levels[1] = -level; |
| 7555 | levels[side + 1] = level * 2; |
| 7556 | let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX)); |
| 7557 | let negated: Vec<i32> = levels.iter().map(|&l| -l).collect(); |
| 7558 | let neg = |
| 7559 | crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX)); |
| 7560 | let worst = pos |
| 7561 | .iter() |
| 7562 | .zip(&neg) |
| 7563 | .map(|(&p, &n)| (p + n).abs()) |
| 7564 | .max() |
| 7565 | .expect("the block is not empty"); |
| 7566 | assert!(worst <= 1, "side {side} level {level}: off by {worst}"); |
| 7567 | } |
| 7568 | } |
| 7569 | } |
| 7570 | |
| 7571 | |
| 7572 | |
| 7573 | |
| 7574 | |
| 7575 | |
| 7576 | |
| 7577 | |
| 7578 | #[test] |
| 7579 | fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() { |
| 7580 | if !have_ffmpeg() { |
| 7581 | eprintln!( |
| 7582 | "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg" |
| 7583 | ); |
| 7584 | return; |
| 7585 | } |
| 7586 | |
| 7587 | |
| 7588 | let coeffs = [ |
| 7589 | (0u8, 0u8, 9i32), |
| 7590 | (0, 1, -14), |
| 7591 | (1, 0, 7), |
| 7592 | (0, 3, 5), |
| 7593 | (3, 0, -3), |
| 7594 | (2, 2, 11), |
| 7595 | (7, 5, -6), |
| 7596 | (31, 31, 4), |
| 7597 | ]; |
| 7598 | let block: BlockCoeffs = coeffs |
| 7599 | .iter() |
| 7600 | .map(|&(row, col, level)| Coeff { row, col, level }) |
| 7601 | .collect::<Vec<_>>() |
| 7602 | .into(); |
| 7603 | let rows = decode_luma_at( |
| 7604 | 64, |
| 7605 | 64, |
| 7606 | &[ |
| 7607 | block, |
| 7608 | BlockCoeffs::default(), |
| 7609 | BlockCoeffs::default(), |
| 7610 | BlockCoeffs::default(), |
| 7611 | ], |
| 7612 | ); |
| 7613 | |
| 7614 | let mut levels = vec![0i32; 32 * 32]; |
| 7615 | for &(row, col, level) in &coeffs { |
| 7616 | levels[usize::from(row) * 32 + usize::from(col)] = level; |
| 7617 | } |
| 7618 | let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); |
| 7619 | for row in 0..32 { |
| 7620 | for col in 0..32 { |
| 7621 | let want = (128 + residual[row * 32 + col]).clamp(0, 255); |
| 7622 | assert_eq!( |
| 7623 | i32::from(rows[row][col]), |
| 7624 | want, |
| 7625 | "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", |
| 7626 | rows[row][col] |
| 7627 | ); |
| 7628 | } |
| 7629 | } |
| 7630 | |
| 7631 | |
| 7632 | let (lo, hi) = ( |
| 7633 | rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(), |
| 7634 | rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(), |
| 7635 | ); |
| 7636 | assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}"); |
| 7637 | } |
| 7638 | |
| 7639 | |
| 7640 | |
| 7641 | |
| 7642 | #[test] |
| 7643 | fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() { |
| 7644 | if !have_ffmpeg() { |
| 7645 | eprintln!( |
| 7646 | "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg" |
| 7647 | ); |
| 7648 | return; |
| 7649 | } |
| 7650 | let coeffs = [ |
| 7651 | (0u8, 0u8, 9i32), |
| 7652 | (0, 1, -14), |
| 7653 | (1, 0, 7), |
| 7654 | (0, 3, 5), |
| 7655 | (3, 0, -3), |
| 7656 | (2, 2, 11), |
| 7657 | (7, 5, -6), |
| 7658 | (15, 15, 4), |
| 7659 | ]; |
| 7660 | let block: BlockCoeffs = coeffs |
| 7661 | .iter() |
| 7662 | .map(|&(row, col, level)| Coeff { row, col, level }) |
| 7663 | .collect::<Vec<_>>() |
| 7664 | .into(); |
| 7665 | let (seq, header) = frame_of(64, 64); |
| 7666 | let quadrants = vec![ |
| 7667 | Quadrant::Split(vec![ |
| 7668 | block, |
| 7669 | BlockCoeffs::default(), |
| 7670 | BlockCoeffs::default(), |
| 7671 | BlockCoeffs::default(), |
| 7672 | ]), |
| 7673 | Quadrant::Whole(BlockCoeffs::default()), |
| 7674 | Quadrant::Whole(BlockCoeffs::default()), |
| 7675 | Quadrant::Whole(BlockCoeffs::default()), |
| 7676 | ]; |
| 7677 | let tile = sb_coeff_key_frame_tile( |
| 7678 | header.mi_cols, |
| 7679 | header.mi_rows, |
| 7680 | Q_IDX, |
| 7681 | &[Superblock::Split(quadrants)], |
| 7682 | ) |
| 7683 | .unwrap(); |
| 7684 | let mut stream = temporal_delimiter(); |
| 7685 | stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); |
| 7686 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); |
| 7687 | let planes = ffmpeg_decode(&stream, 64, 64); |
| 7688 | |
| 7689 | let mut levels = vec![0i32; TX16 * TX16]; |
| 7690 | for &(row, col, level) in &coeffs { |
| 7691 | levels[usize::from(row) * TX16 + usize::from(col)] = level; |
| 7692 | } |
| 7693 | let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX)); |
| 7694 | for row in 0..TX16 { |
| 7695 | for col in 0..TX16 { |
| 7696 | let want = (128 + residual[row * TX16 + col]).clamp(0, 255); |
| 7697 | assert_eq!( |
| 7698 | i32::from(planes[row * 64 + col]), |
| 7699 | want, |
| 7700 | "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", |
| 7701 | planes[row * 64 + col] |
| 7702 | ); |
| 7703 | } |
| 7704 | } |
| 7705 | } |
| 7706 | |
| 7707 | |
| 7708 | |
| 7709 | |
| 7710 | |
| 7711 | #[test] |
| 7712 | fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() { |
| 7713 | if !have_ffmpeg() { |
| 7714 | eprintln!( |
| 7715 | "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg" |
| 7716 | ); |
| 7717 | return; |
| 7718 | } |
| 7719 | let coeffs = [ |
| 7720 | (0u8, 0u8, 12i32), |
| 7721 | (0, 2, -9), |
| 7722 | (2, 0, 6), |
| 7723 | (1, 1, -5), |
| 7724 | (5, 9, 8), |
| 7725 | (31, 0, -4), |
| 7726 | (0, 31, 3), |
| 7727 | ]; |
| 7728 | let block: BlockCoeffs = coeffs |
| 7729 | .iter() |
| 7730 | .map(|&(row, col, level)| Coeff { row, col, level }) |
| 7731 | .collect::<Vec<_>>() |
| 7732 | .into(); |
| 7733 | let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]); |
| 7734 | |
| 7735 | let mut levels = vec![0i32; 64 * 64]; |
| 7736 | for &(row, col, level) in &coeffs { |
| 7737 | levels[usize::from(row) * 64 + usize::from(col)] = level; |
| 7738 | } |
| 7739 | let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX)); |
| 7740 | for row in 0..64 { |
| 7741 | for col in 0..64 { |
| 7742 | let want = (128 + residual[row * 64 + col]).clamp(0, 255); |
| 7743 | assert_eq!( |
| 7744 | i32::from(rows[row][col]), |
| 7745 | want, |
| 7746 | "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", |
| 7747 | rows[row][col] |
| 7748 | ); |
| 7749 | } |
| 7750 | } |
| 7751 | } |
| 7752 | |
| 7753 | |
| 7754 | |
| 7755 | |
| 7756 | |
| 7757 | |
| 7758 | |
| 7759 | |
| 7760 | #[test] |
| 7761 | fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() { |
| 7762 | let mut previous: Option<i32> = None; |
| 7763 | for side in [4usize, 8, 16, 32, 64] { |
| 7764 | let mut levels = vec![0i32; side * side]; |
| 7765 | levels[0] = 100; |
| 7766 | let residual = |
| 7767 | crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX)); |
| 7768 | let dc = residual[0]; |
| 7769 | assert!( |
| 7770 | residual.iter().all(|&r| r == dc), |
| 7771 | "side {side}: a DC coefficient reconstructs flat" |
| 7772 | ); |
| 7773 | if let Some(previous) = previous { |
| 7774 | assert!( |
| 7775 | (dc * 2 - previous).abs() <= 1, |
| 7776 | "side {side}: {dc} is not half of the previous size's {previous}" |
| 7777 | ); |
| 7778 | } |
| 7779 | previous = Some(dc); |
| 7780 | } |
| 7781 | } |
| 7782 | |
| 7783 | |
| 7784 | |
| 7785 | |
| 7786 | |
| 7787 | |
| 7788 | |
| 7789 | |
| 7790 | |
| 7791 | |
| 7792 | |
| 7793 | #[test] |
| 7794 | fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() { |
| 7795 | if !have_ffmpeg() { |
| 7796 | eprintln!( |
| 7797 | "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 7798 | ); |
| 7799 | return; |
| 7800 | } |
| 7801 | |
| 7802 | |
| 7803 | let mut residual = vec![0i32; 32 * 32]; |
| 7804 | for row in 0..32usize { |
| 7805 | for col in 0..32usize { |
| 7806 | let gradient = row as f64 * 2.0 - 32.0; |
| 7807 | let ripple = 25.0 |
| 7808 | * (col as f64 * std::f64::consts::PI / 6.0).sin() |
| 7809 | * (row as f64 * std::f64::consts::PI / 11.0).cos(); |
| 7810 | let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 }; |
| 7811 | residual[row * 32 + col] = (gradient + ripple + patch).round() as i32; |
| 7812 | } |
| 7813 | } |
| 7814 | |
| 7815 | let levels = |
| 7816 | crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5); |
| 7817 | assert!( |
| 7818 | levels.iter().any(|&l| l != 0), |
| 7819 | "the picture quantized away entirely" |
| 7820 | ); |
| 7821 | let coded: Vec<Coeff> = levels |
| 7822 | .iter() |
| 7823 | .enumerate() |
| 7824 | .filter(|&(_, &level)| level != 0) |
| 7825 | .map(|(i, &level)| Coeff { |
| 7826 | row: (i / 32) as u8, |
| 7827 | col: (i % 32) as u8, |
| 7828 | level, |
| 7829 | }) |
| 7830 | .collect(); |
| 7831 | |
| 7832 | let rows = decode_luma_at( |
| 7833 | 64, |
| 7834 | 64, |
| 7835 | &[ |
| 7836 | coded.into(), |
| 7837 | BlockCoeffs::default(), |
| 7838 | BlockCoeffs::default(), |
| 7839 | BlockCoeffs::default(), |
| 7840 | ], |
| 7841 | ); |
| 7842 | let reconstruction = |
| 7843 | crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); |
| 7844 | |
| 7845 | let mut squared = 0.0f64; |
| 7846 | for row in 0..32 { |
| 7847 | for col in 0..32 { |
| 7848 | let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255); |
| 7849 | assert_eq!( |
| 7850 | i32::from(rows[row][col]), |
| 7851 | want, |
| 7852 | "sample ({row},{col}): the decoder and the encoder disagree" |
| 7853 | ); |
| 7854 | let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]); |
| 7855 | squared += error * error; |
| 7856 | } |
| 7857 | } |
| 7858 | let rmse = (squared / 1024.0).sqrt(); |
| 7859 | |
| 7860 | |
| 7861 | |
| 7862 | |
| 7863 | |
| 7864 | let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0; |
| 7865 | assert!( |
| 7866 | rmse < step / 4.0, |
| 7867 | "the decoded picture is {rmse} off, a step being {step}" |
| 7868 | ); |
| 7869 | } |
| 7870 | |
| 7871 | |
| 7872 | |
| 7873 | fn decode_mv_component( |
| 7874 | dec: &mut crate::msac::tests::SymbolDecoder, |
| 7875 | c: &mut MvComponentCdfs, |
| 7876 | ) -> i32 { |
| 7877 | let sign = dec.symbol(&mut c.sign); |
| 7878 | let class = dec.symbol(&mut c.class); |
| 7879 | let local = if class == 0 { |
| 7880 | let bit = dec.symbol(&mut c.class0_bit); |
| 7881 | let fr = dec.symbol(&mut c.class0_fr[bit]); |
| 7882 | (bit << 3) | (fr << 1) | 1 |
| 7883 | } else { |
| 7884 | let mut d = 0; |
| 7885 | for i in 0..class { |
| 7886 | d |= dec.symbol(&mut c.bit[i]) << i; |
| 7887 | } |
| 7888 | let fr = dec.symbol(&mut c.fr); |
| 7889 | (d << 3) | (fr << 1) | 1 |
| 7890 | }; |
| 7891 | let mag = mv_class_base(class) + local as i32 + 1; |
| 7892 | if sign == 1 { -mag } else { mag } |
| 7893 | } |
| 7894 | |
| 7895 | |
| 7896 | |
| 7897 | |
| 7898 | |
| 7899 | |
| 7900 | |
| 7901 | |
| 7902 | |
| 7903 | |
| 7904 | |
| 7905 | |
| 7906 | |
| 7907 | type DecodedBlock = (bool, bool, Option<usize>, (i32, i32)); |
| 7908 | |
| 7909 | |
| 7910 | |
| 7911 | fn decode_inter_sb( |
| 7912 | data: &[u8], |
| 7913 | mi_cols: u32, |
| 7914 | mi_rows: u32, |
| 7915 | wrong_y_mode: bool, |
| 7916 | ) -> (usize, Vec<DecodedBlock>) { |
| 7917 | let mut dec = crate::msac::tests::SymbolDecoder::new(data); |
| 7918 | let mut cdfs = Cdfs::new(2); |
| 7919 | let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 7920 | let mut above_skip = [false; 2]; |
| 7921 | let mut left_skip = [false; 2]; |
| 7922 | let mut above_inter = [false; 2]; |
| 7923 | let mut left_inter = [false; 2]; |
| 7924 | let mut count = 0usize; |
| 7925 | |
| 7926 | count += 1; |
| 7927 | dec.symbol(&mut cdfs.partition_w64[0]); |
| 7928 | |
| 7929 | let mut results = Vec::new(); |
| 7930 | for quadrant in 0..4usize { |
| 7931 | let (r32, c32) = (quadrant / 2, quadrant % 2); |
| 7932 | count += 1; |
| 7933 | dec.symbol(&mut cdfs.partition_w32[0]); |
| 7934 | |
| 7935 | let (has_above, has_left) = (r32 > 0, c32 > 0); |
| 7936 | let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]); |
| 7937 | count += 1; |
| 7938 | let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; |
| 7939 | |
| 7940 | let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]); |
| 7941 | count += 1; |
| 7942 | let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; |
| 7943 | |
| 7944 | let (mode, mv) = if is_inter { |
| 7945 | let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]); |
| 7946 | count += 3; |
| 7947 | assert_eq!( |
| 7948 | dec.symbol(&mut cdfs.single_ref[sr_ctx][0]), |
| 7949 | 0, |
| 7950 | "single_ref p1" |
| 7951 | ); |
| 7952 | assert_eq!( |
| 7953 | dec.symbol(&mut cdfs.single_ref[sr_ctx][2]), |
| 7954 | 0, |
| 7955 | "single_ref p3" |
| 7956 | ); |
| 7957 | assert_eq!( |
| 7958 | dec.symbol(&mut cdfs.single_ref[sr_ctx][3]), |
| 7959 | 0, |
| 7960 | "single_ref p4" |
| 7961 | ); |
| 7962 | |
| 7963 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 7964 | let stack = find_mv_stack( |
| 7965 | &grid, |
| 7966 | mi_row, |
| 7967 | mi_col, |
| 7968 | 8, |
| 7969 | 8, |
| 7970 | 1, |
| 7971 | mi_cols as usize, |
| 7972 | mi_rows as usize, |
| 7973 | ); |
| 7974 | |
| 7975 | count += 1; |
| 7976 | let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0; |
| 7977 | let (mv, is_new_mv) = if new_mv { |
| 7978 | if stack.entries.len() > 1 { |
| 7979 | count += 1; |
| 7980 | dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]); |
| 7981 | } |
| 7982 | count += 1; |
| 7983 | let joint = dec.symbol(&mut cdfs.mv_joint); |
| 7984 | let mut diff = (0, 0); |
| 7985 | if joint == 2 || joint == 3 { |
| 7986 | |
| 7987 | |
| 7988 | count += 4; |
| 7989 | diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]); |
| 7990 | } |
| 7991 | if joint == 1 || joint == 3 { |
| 7992 | count += 4; |
| 7993 | diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]); |
| 7994 | } |
| 7995 | ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true) |
| 7996 | } else { |
| 7997 | count += 2; |
| 7998 | assert_eq!( |
| 7999 | dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]), |
| 8000 | 1, |
| 8001 | "zero_mv" |
| 8002 | ); |
| 8003 | assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv"); |
| 8004 | (stack.nearest_mv, false) |
| 8005 | }; |
| 8006 | for dr in 0..8 { |
| 8007 | for dc in 0..8 { |
| 8008 | grid.set( |
| 8009 | mi_row + dr, |
| 8010 | mi_col + dc, |
| 8011 | MiInfo { |
| 8012 | is_inter: true, |
| 8013 | ref_frame: 1, |
| 8014 | ref_frame1: NO_REF1, |
| 8015 | mv1: (0, 0), |
| 8016 | mv: mv16(mv), |
| 8017 | is_new_mv, |
| 8018 | size: 8, |
| 8019 | size_h: 8, |
| 8020 | is_global_mv0: false, |
| 8021 | is_global_mv1: false, |
| 8022 | }, |
| 8023 | ); |
| 8024 | } |
| 8025 | } |
| 8026 | (None, mv) |
| 8027 | } else { |
| 8028 | count += 1; |
| 8029 | let m = if wrong_y_mode { |
| 8030 | dec.symbol(&mut cdfs.kf_y_mode[0][0]) |
| 8031 | } else { |
| 8032 | dec.symbol(&mut cdfs.y_mode[3]) |
| 8033 | }; |
| 8034 | if (V_PRED..=D67_PRED).contains(&m) { |
| 8035 | count += 1; |
| 8036 | dec.symbol(&mut cdfs.angle_delta[m - V_PRED]); |
| 8037 | } |
| 8038 | count += 1; |
| 8039 | dec.symbol(&mut cdfs.uv_mode_cfl[m]); |
| 8040 | (Some(m), (0, 0)) |
| 8041 | }; |
| 8042 | |
| 8043 | above_skip[c32] = skip; |
| 8044 | left_skip[r32] = skip; |
| 8045 | above_inter[c32] = is_inter; |
| 8046 | left_inter[r32] = is_inter; |
| 8047 | results.push((skip, is_inter, mode, mv)); |
| 8048 | } |
| 8049 | (count, results) |
| 8050 | } |
| 8051 | |
| 8052 | |
| 8053 | |
| 8054 | |
| 8055 | #[test] |
| 8056 | fn an_all_skip_inter_superblock_is_small_and_reads_back() { |
| 8057 | let block = BlockCoeffs { |
| 8058 | inter: Some(InterInfo { |
| 8059 | ref1: None, |
| 8060 | mv1: (0, 0), |
| 8061 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8062 | mode: InterMode::NearestMv, |
| 8063 | mv: (0, 0), |
| 8064 | ref_mv_idx: 0, |
| 8065 | }), |
| 8066 | skip: true, |
| 8067 | ..BlockCoeffs::default() |
| 8068 | }; |
| 8069 | let blocks = vec![ |
| 8070 | Quadrant::Whole(block.clone()), |
| 8071 | Quadrant::Whole(block.clone()), |
| 8072 | Quadrant::Whole(block.clone()), |
| 8073 | Quadrant::Whole(block), |
| 8074 | ]; |
| 8075 | let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap(); |
| 8076 | |
| 8077 | |
| 8078 | assert!( |
| 8079 | data.len() <= 16, |
| 8080 | "an all-skip NEARESTMV superblock took {} bytes", |
| 8081 | data.len() |
| 8082 | ); |
| 8083 | |
| 8084 | let (count, results) = decode_inter_sb(&data, 16, 16, false); |
| 8085 | assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count"); |
| 8086 | for (skip, is_inter, mode, mv) in results { |
| 8087 | assert!(skip); |
| 8088 | assert!(is_inter); |
| 8089 | assert_eq!(mode, None); |
| 8090 | |
| 8091 | |
| 8092 | assert_eq!(mv, (0, 0)); |
| 8093 | } |
| 8094 | } |
| 8095 | |
| 8096 | |
| 8097 | |
| 8098 | |
| 8099 | |
| 8100 | #[test] |
| 8101 | fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() { |
| 8102 | let nearest = BlockCoeffs { |
| 8103 | inter: Some(InterInfo { |
| 8104 | ref1: None, |
| 8105 | mv1: (0, 0), |
| 8106 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8107 | mode: InterMode::NearestMv, |
| 8108 | mv: (0, 0), |
| 8109 | ref_mv_idx: 0, |
| 8110 | }), |
| 8111 | skip: true, |
| 8112 | ..BlockCoeffs::default() |
| 8113 | }; |
| 8114 | let newmv = BlockCoeffs { |
| 8115 | inter: Some(InterInfo { |
| 8116 | ref1: None, |
| 8117 | mv1: (0, 0), |
| 8118 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8119 | mode: InterMode::NewMv, |
| 8120 | mv: (0, 2), |
| 8121 | ref_mv_idx: 0, |
| 8122 | }), |
| 8123 | skip: true, |
| 8124 | ..BlockCoeffs::default() |
| 8125 | }; |
| 8126 | let blocks = vec![ |
| 8127 | Quadrant::Whole(nearest.clone()), |
| 8128 | Quadrant::Whole(nearest.clone()), |
| 8129 | Quadrant::Whole(nearest), |
| 8130 | Quadrant::Whole(newmv), |
| 8131 | ]; |
| 8132 | let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap(); |
| 8133 | |
| 8134 | let (count, results) = decode_inter_sb(&data, 16, 16, false); |
| 8135 | |
| 8136 | |
| 8137 | |
| 8138 | |
| 8139 | assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count"); |
| 8140 | let (skip, is_inter, mode, mv) = results[3]; |
| 8141 | assert!(skip); |
| 8142 | assert!(is_inter); |
| 8143 | assert_eq!(mode, None); |
| 8144 | assert_eq!( |
| 8145 | mv, |
| 8146 | (0, 2), |
| 8147 | "the decoded motion vector must be exactly what was written" |
| 8148 | ); |
| 8149 | } |
| 8150 | |
| 8151 | |
| 8152 | |
| 8153 | |
| 8154 | |
| 8155 | |
| 8156 | |
| 8157 | fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize { |
| 8158 | let mut dec = crate::msac::tests::SymbolDecoder::new(data); |
| 8159 | let mut cdfs = Cdfs::new(2); |
| 8160 | dec.symbol(&mut cdfs.partition_w64[0]); |
| 8161 | dec.symbol(&mut cdfs.partition_w32[0]); |
| 8162 | dec.symbol(&mut cdfs.skip[0]); |
| 8163 | dec.symbol(&mut cdfs.intra_inter[0]); |
| 8164 | if wrong_y_mode { |
| 8165 | dec.symbol(&mut cdfs.kf_y_mode[0][0]) |
| 8166 | } else { |
| 8167 | dec.symbol(&mut cdfs.y_mode[3]) |
| 8168 | } |
| 8169 | } |
| 8170 | |
| 8171 | |
| 8172 | |
| 8173 | |
| 8174 | |
| 8175 | |
| 8176 | |
| 8177 | |
| 8178 | |
| 8179 | |
| 8180 | |
| 8181 | |
| 8182 | |
| 8183 | #[test] |
| 8184 | fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() { |
| 8185 | let block = BlockCoeffs { |
| 8186 | mode: H_PRED as u8, |
| 8187 | skip: true, |
| 8188 | ..BlockCoeffs::default() |
| 8189 | }; |
| 8190 | let blocks = vec![Quadrant::Whole(block); 4]; |
| 8191 | let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap(); |
| 8192 | |
| 8193 | assert_eq!( |
| 8194 | decode_first_block_mode(&data, false), |
| 8195 | H_PRED, |
| 8196 | "the right table reads the mode back exactly" |
| 8197 | ); |
| 8198 | assert_ne!( |
| 8199 | decode_first_block_mode(&data, true), |
| 8200 | H_PRED, |
| 8201 | "KF_Y_MODE's different probabilities must decode a different mode" |
| 8202 | ); |
| 8203 | } |
| 8204 | } |