use super::*; #[derive(Clone, Copy, Default, PartialEq, Eq)] pub(super) struct CoefCtx { pub(super) level: u8, pub(super) dc: i8, } #[derive(Default)] pub(super) struct CoefCtxMap { pub(super) cells: Vec, pub(super) stride: usize, pub(super) tu_split: bool, } pub(super) struct Plane<'a> { pub(super) source: &'a [u8], pub(super) reconstruction: Vec, pub(super) width: usize, pub(super) height: usize, pub(super) true_width: usize, pub(super) true_height: usize, pub(super) tile_x0: usize, pub(super) tile_y0: usize, pub(super) tile_x1: usize, pub(super) tile_y1: usize, pub(super) ctx: CoefCtxMap, } impl Plane<'_> { pub(super) fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { self.tile_x0 = x0; self.tile_y0 = y0; self.tile_x1 = x1.min(self.width); self.tile_y1 = y1.min(self.height); } pub(super) fn edges_into<'a>( &self, x: usize, y: usize, side: usize, reach: Reach, above_buf: &'a mut [u8; 2 * SUPERBLOCK], left_buf: &'a mut [u8; 2 * SUPERBLOCK], ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option) { let own_across = x + side.min(self.true_width.saturating_sub(x)); let across = if reach.above_right { own_across + side.min(self.true_width.saturating_sub(own_across)) } else { own_across } .min(self.width); let own_down = y + side.min(self.true_height.saturating_sub(y)); let down = if reach.below_left { own_down + side.min(self.true_height.saturating_sub(own_down)) } else { own_down } .min(self.height); let across = across.min(self.tile_x1); let down = down.min(self.tile_y1); let above_n = (y > self.tile_y0 && across > x).then(|| across - x); if let Some(n) = above_n { above_buf[..n].copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]); } let left_n = (x > self.tile_x0 && down > y).then(|| down - y); if let Some(n) = left_n { for (d, row) in left_buf[..n].iter_mut().zip(y..down) { *d = self.reconstruction[row * self.width + x - 1]; } } let corner = (x > self.tile_x0 && y > self.tile_y0) .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); ( above_n.map(|n| &above_buf[..n]), left_n.map(|n| &left_buf[..n]), corner, ) } pub(super) fn trial( &self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx, ) -> Trial { self.trial_typed( at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx, ) } pub(super) fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { let mut sad = 0u32; for row in 0..side { let source = &self.source[(y + row) * self.width + x..][..side]; for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { sad += u32::from(s.abs_diff(p)); } } f64::from(sad) } pub(super) fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { let inside_rows = side.min(self.true_height.saturating_sub(y)); let inside_cols = side.min(self.true_width.saturating_sub(x)); let mut sse = 0u64; for row in 0..inside_rows { let source = &self.source[(y + row) * self.width + x..][..inside_cols]; for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..inside_cols]) { let d = u32::from(s.abs_diff(r)); sse += u64::from(d * d); } } sse as f64 } pub(super) fn trial_typed( &self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, tx_type: TxType, fctx: &crate::decode::FrameCtx, ) -> Trial { let At { x, y, side, reach, .. } = at; let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); let (above, left, corner) = self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); let mut prediction = [0u8; BLOCK * BLOCK]; let prediction = &mut prediction[..side * side]; intra_predict_u8( mode, angle_delta, above, left, corner, side, side, false, false, prediction, fctx, ); let mut residual = [0i32; BLOCK * BLOCK]; let residual = &mut residual[..side * side]; for row in 0..side { for col in 0..side { residual[row * side + col] = i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(prediction[row * side + col]); } } #[cfg(test)] let t = stage_start(); let (levels, rdoq_bits) = if rdoq_on() { let (mut levels, scaled) = forward_and_quantize_typed_scaled( residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, ); let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); let bits = crate::tile::rdoq( &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, LAMBDA_SCALE * RDOQ_LAMBDA_MULT, tx_type, ); (levels, Some(bits)) } else { ( forward_and_quantize_typed( residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, ), None, ) }; let coded = dequant_and_inverse_typed_wh( &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None, ); #[cfg(test)] stage_since(2, t); let reconstruction: Vec = if coded.is_empty() { prediction.to_vec() } else { prediction .iter() .zip(&coded) .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) .collect() }; let sse = self.block_sse(x, y, side, &reconstruction); #[cfg(test)] let t = stage_start(); let bits = if let Some(bits) = rdoq_bits { bits } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); crate::tile::coeff_bits_typed( &levels, at.set, crate::decode::q_ctx_of(base_q_idx), skip_ctx, sign_ctx, tx_type, ) } }; #[cfg(test)] stage_since(3, t); Trial { levels, reconstruction, sse, bits, } } pub(super) fn code_from_prediction( &self, x: usize, y: usize, side: usize, prediction: &[u8], skip: bool, base_q_idx: u8, deadzone: f64, set: TxbSet, ) -> Trial { self.code_from_prediction_typed( x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct, ) } pub(super) fn code_from_prediction_typed( &self, x: usize, y: usize, side: usize, prediction: &[u8], skip: bool, base_q_idx: u8, deadzone: f64, set: TxbSet, tx_type: TxType, ) -> Trial { if skip { let sse = self.block_sse(x, y, side, prediction); return Trial { levels: vec![0i32; side * side], reconstruction: prediction.to_vec(), sse, bits: 0.0, }; } let mut small = [0i32; BLOCK * BLOCK]; let mut big = if side > BLOCK { vec![0i32; side * side] } else { Vec::new() }; let residual: &mut [i32] = if side > BLOCK { &mut big } else { &mut small[..side * side] }; for row in 0..side { for col in 0..side { residual[row * side + col] = i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(prediction[row * side + col]); } } #[cfg(test)] let t = stage_start(); let (levels, rdoq_bits) = if rdoq_on() { let (mut levels, scaled) = forward_and_quantize_typed_scaled( residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, ); let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); let bits = crate::tile::rdoq( &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, LAMBDA_SCALE * RDOQ_LAMBDA_MULT, tx_type, ); (levels, Some(bits)) } else { ( forward_and_quantize_typed( residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, ), None, ) }; let coded = dequant_and_inverse_typed_wh( &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None, ); #[cfg(test)] stage_since(2, t); let reconstruction: Vec = if coded.is_empty() { prediction.to_vec() } else { prediction .iter() .zip(&coded) .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) .collect() }; let sse = self.block_sse(x, y, side, &reconstruction); let levels = if side > BLOCK { coded_corner(&levels, side, BLOCK) } else { levels }; #[cfg(test)] let t = stage_start(); let bits = if let Some(bits) = rdoq_bits { bits } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); crate::tile::coeff_bits_typed( &levels, set, crate::decode::q_ctx_of(base_q_idx), skip_ctx, sign_ctx, tx_type, ) } }; #[cfg(test)] stage_since(3, t); Trial { levels, reconstruction, sse, bits, } } pub(super) fn code_tx_depth( &mut self, at: At, mode: u8, angle_delta: i32, depth: usize, filter_intra: Option, search: &Search, fctx: &crate::decode::FrameCtx, ) -> (Vec, f64, f64, Vec) { let At { x, y, side, reach, .. } = at; let tx = side >> depth; let n = 1usize << depth; let set = luma_set_for( match tx { 32 => TxbSet::Luma32, 16 => TxbSet::Luma16, 8 => TxbSet::Luma8, _ => TxbSet::Luma4, }, search.screen, ); let mut levels = vec![0i32; side * side]; self.ctx.tu_split = n > 1; let (mut sse, mut bits) = (0.0, 0.0); let mut tx_types = vec![TxType::DctDct; n * n]; for tu_row in 0..n { for tu_col in 0..n { let (col_off, row_off) = (tu_col * tx, tu_row * tx); let tu = At { x: x + col_off, y: y + row_off, side: tx, reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), set, }; let trial = match filter_intra { Some(fi) => { let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); let (above, left, corner) = self.edges_into( tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf, ); let mut prediction = vec![0u8; tx * tx]; filter_intra_predict_u8( usize::from(fi), above, left, corner, tx, &mut prediction, fctx, ); self.code_from_prediction( tu.x, tu.y, tx, &prediction, false, search.base_q_idx, search.deadzone, set, ) } None => { let mut best: Option<(f64, TxType, Trial)> = None; for &tx_type in tx_type_candidates(set, search.screen) { let candidate = self.trial_typed( tu, mode, angle_delta, search.base_q_idx, search.deadzone, tx_type, fctx, ); let cost = candidate.sse + search.lambda * candidate.bits + non_dct_surcharge(search.lambda, tx_type, candidate.bits); if best.as_ref().is_none_or(|(best, _, _)| cost < *best) { best = Some((cost, tx_type, candidate)); } } let (_, tx_type, trial) = best.expect("the candidate list is never empty"); tx_types[tu_row * n + tu_col] = tx_type; TX_TYPE_HITS[tx_type as usize] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); trial } }; sse += trial.sse; bits += trial.bits; self.commit(tu.x, tu.y, tx, &trial); for row in 0..tx { levels[(row_off + row) * side + col_off..][..tx] .copy_from_slice(&trial.levels[row * tx..][..tx]); } } } self.ctx.tu_split = false; (levels, sse, bits, tx_types) } pub(super) fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] .copy_from_slice(&trial.reconstruction[row * side..][..side]); } self.commit_ctx(x, y, side, &trial.levels); } pub(super) fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) { if self.ctx.cells.is_empty() { self.ctx.stride = self.width.div_ceil(4); self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)]; } let cul = levels.iter().map(|l| l.unsigned_abs()).sum::().min(7) as u8; let state = CoefCtx { level: cul, dc: match levels[0].signum() { 0 => 0, -1 => -1, _ => 1, }, }; let n = (side / 4).max(1); let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4)); let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4)); for row in 0..rows { let start = (y / 4 + row) * self.ctx.stride + x / 4; let end = (start + cols).min(self.ctx.cells.len()); if start < end { self.ctx.cells[start..end].fill(state); } } } pub(super) fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) { self.commit_ctx(x, y, side, &[0i32]); } pub(super) fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) { if self.ctx.cells.is_empty() { return (0, 0); } let n = (side / 4).max(1); let (cx, cy) = (x / 4, y / 4); let (mut top, mut left) = (0u8, 0u8); let mut vote = 0i32; if y > self.tile_y0 && cy > 0 { for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] { top |= cell.level; vote += i32::from(cell.dc); } } if x > self.tile_x0 && cx > 0 { for row in 0..n { let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1]; left |= cell.level; vote += i32::from(cell.dc); } } let skip_ctx = if set.is_chroma() { usize::from(top != 0) + usize::from(left != 0) } else if self.ctx.tu_split { crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] } else { 0 }; let sign_ctx = match vote.signum() { 0 => 0, -1 => 1, _ => 2, }; (skip_ctx, sign_ctx) } pub(super) fn source_block(&self, x: usize, y: usize, side: usize) -> Vec { rows_of(self.source, self.width, x, y, side) } pub(super) fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec { let mut out = vec![0u8; w * h]; for row in 0..h { out[row * w..][..w].copy_from_slice(&self.source[(y + row) * self.width + x..][..w]); } out } pub(super) fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec, Vec) { ( rows_of(&self.reconstruction, self.width, x, y, side), self.ctx_rows(x, y, side), ) } pub(super) fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec { if self.ctx.cells.is_empty() { return Vec::new(); } let n = (side / 4).max(1); (0..n) .flat_map(|row| { let start = (y / 4 + row) * self.ctx.stride + x / 4; self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec() }) .collect() } pub(super) fn restore( &mut self, x: usize, y: usize, side: usize, saved: &(Vec, Vec), ) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] .copy_from_slice(&saved.0[row * side..][..side]); } if saved.1.is_empty() { return; } let n = (side / 4).max(1); for row in 0..n { let start = (y / 4 + row) * self.ctx.stride + x / 4; let end = (start + n).min(self.ctx.cells.len()); if start < end { self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]); } } } pub(super) fn intra_scores( &self, at: At, modes: &[u8], mode_bits: &[f64; 13], lambda: f64, fctx: &crate::decode::FrameCtx, ) -> Vec<(f64, u8)> { let At { x, y, side, reach, .. } = at; let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); let (above, left, corner) = self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); modes .iter() .map(|&mode| { let mut prediction = vec![0u8; side * side]; intra_predict_u8( mode, 0, above, left, corner, side, side, false, false, &mut prediction, fctx, ); let sad = self.block_sad(x, y, side, &prediction); (sad + lambda * mode_bits[usize::from(mode)], mode) }) .collect() } pub(super) fn search_block( &mut self, at: At, search: &Search, mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, ) -> (Vec, u8, i32, f64, TxType) { let At { x, y, side, reach, .. } = at; let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); let (above, left, corner) = self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); let want_sad = search.top_k.is_some(); let mut scored: Vec<(f64, u8, Vec)> = search .modes .iter() .map(|&mode| { let mut prediction = vec![0u8; side * side]; intra_predict_u8( mode, 0, above, left, corner, side, side, false, false, &mut prediction, fctx, ); let sad = if want_sad { self.block_sad(x, y, side, &prediction) } else { 0.0 }; ( sad + search.lambda * mode_bits[usize::from(mode)], mode, prediction, ) }) .collect(); if let Some(k) = search.top_k && k < scored.len() { let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); let dc_entry = dc_pos.map(|i| scored.remove(i)); scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); scored.truncate(if dc_entry.is_some() { k.saturating_sub(1) } else { k }); if let Some(dc_entry) = dc_entry { scored.push(dc_entry); } } let mut best: Option<(f64, u8, Trial)> = None; for (_, mode, prediction) in scored { let trial = self.code_from_prediction( x, y, side, &prediction, false, search.base_q_idx, search.deadzone, at.set, ); let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); if best .as_ref() .is_none_or(|(best_cost, _, _)| cost < *best_cost) { best = Some((cost, mode, trial)); } } let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode"); let mut angle_delta = 0i32; if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) { let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)]; let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO); let mut prediction = vec![0u8; side * side]; for delta in [-3i32, -2, -1, 1, 2, 3] { intra_predict_u8( mode, delta, above, left, corner, side, side, false, false, &mut prediction, fctx, ); let candidate = self.code_from_prediction( x, y, side, &prediction, false, search.base_q_idx, search.deadzone, at.set, ); let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize) - zero_bits; let cost_d = candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits); if cost_d < cost { cost = cost_d; angle_delta = delta; trial = candidate; } } } let mut tx_type = TxType::DctDct; for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) { let candidate = self.trial_typed( at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx, ); let cost_t = candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]); if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost { cost = cost_t; tx_type = candidate_type; trial = candidate; } } TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.commit(x, y, side, &trial); ( coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type, ) } } #[derive(Clone, Copy)] pub(super) struct At { pub(super) x: usize, pub(super) y: usize, pub(super) side: usize, pub(super) reach: Reach, pub(super) set: TxbSet, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Reach { pub(crate) above_right: bool, pub(crate) below_left: bool, } pub(super) const HAS_TOP_RIGHT: [&[u8]; 4] = [ &[255, 85, 119, 85, 127, 85, 119, 85], &[95, 87], &[ 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, ], &[ 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, ], ]; pub(super) const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ &[84, 16, 84, 0, 84, 16, 84, 0], &[4, 4], &[ 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, ], &[ 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, ], ]; pub(super) const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ &[255, 0, 119, 0, 127, 0, 119, 0], &[15, 7], &[ 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, ], ]; pub(super) const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ &[254, 16, 254, 0, 254, 16, 254, 0], &[14, 14], &[ 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, ], ]; thread_local! { static VERT_AB_PARTITION: std::cell::Cell = const { std::cell::Cell::new(false) }; } pub(crate) struct VertAbGuard(bool); impl Drop for VertAbGuard { fn drop(&mut self) { VERT_AB_PARTITION.with(|c| c.set(self.0)); } } pub(super) const HAS_TR_4X8: [u8; 64] = [ 255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, ]; pub(super) const HAS_BL_4X8: [u8; 64] = [ 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, ]; pub(super) const HAS_TR_8X4: [u8; 64] = [ 255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, ]; pub(super) const HAS_BL_8X4: [u8; 64] = [ 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, ]; pub(super) const HAS_TR_8X16: [u8; 16] = [ 255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119, ]; pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; pub(super) const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; pub(super) const HAS_BL_16X8: [u8; 16] = [ 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0, ]; pub(super) const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; pub(super) const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; pub(super) const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; pub(super) const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; pub(super) const HAS_TR_32X64: [u8; 1] = [127]; pub(super) const HAS_BL_32X64: [u8; 1] = [0]; pub(super) const HAS_TR_64X32: [u8; 1] = [19]; pub(super) const HAS_BL_64X32: [u8; 1] = [34]; pub(super) const HAS_TR_4X16: [u8; 32] = [ 255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, ]; pub(super) const HAS_BL_4X16: [u8; 32] = [ 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, ]; pub(super) const HAS_TR_16X4: [u8; 32] = [ 255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, ]; pub(super) const HAS_BL_16X4: [u8; 32] = [ 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, ]; pub(super) const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; pub(super) const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; pub(super) const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; pub(super) const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; pub(super) const HAS_TR_16X64: [u8; 2] = [255, 127]; pub(super) const HAS_BL_16X64: [u8; 2] = [0, 0]; pub(super) const HAS_TR_64X16: [u8; 2] = [3, 1]; pub(super) const HAS_BL_64X16: [u8; 2] = [42, 42]; pub(super) fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { match (bw, bh) { (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), } } impl Reach { pub(crate) fn of_tu( bw: usize, bh: usize, col_off: usize, row_off: usize, tx_w: usize, tx_h: usize, block: Self, ) -> Self { let wide = bw > 64; Self { above_right: if row_off > 0 { if wide { (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 } else { col_off + tx_w < bw } } else if col_off + tx_w < bw { true } else { block.above_right }, below_left: if wide && col_off > 0 && col_off.is_multiple_of(64) { (row_off % 64) + tx_h < bh.min(64) } else if col_off > 0 { false } else if row_off + tx_h < bh { true } else { block.below_left }, } } pub(crate) fn of_tu_chroma( mi_bw: usize, mi_bh: usize, mi_row: usize, mi_col: usize, sb_mi: usize, col_off: usize, row_off: usize, tx_w: usize, tx_h: usize, ss_x: usize, ss_y: usize, above_avail: bool, below_avail: bool, ) -> Self { if !above_avail && !below_avail { return Self::none(); } let bw_log2 = mi_bw.trailing_zeros() as usize; let bh_log2 = mi_bh.trailing_zeros() as usize; let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; let plane_bw = (mi_bw >> ss_x).max(1) << (2 + ss_x); let plane_bh = (mi_bh >> ss_y).max(1) << (2 + ss_y); let (tr, bl) = Self::plane_reach_tables(mi_bw, mi_bh); Self { above_right: above_avail && (if row_off > 0 { col_off + tx_w < plane_bw } else if col_off + tx_w < plane_bw || blk_row == 0 { true } else if ((blk_col + 1) << bw_log2) >= sb_mi { false } else { Self::bit(tr, (blk_row << (5 - bw_log2)) + blk_col) }), below_left: below_avail && (if col_off > 0 { false } else if row_off + tx_h < plane_bh { true } else if blk_col == 0 { let from_block = (blk_row << bh_log2) >> ss_y; let sb_height = (sb_mi >> ss_y).saturating_sub(from_block); row_off + tx_h < sb_height << (2 + ss_y) } else if ((blk_row + 1) << bh_log2) >= sb_mi { false } else { Self::bit(bl, (blk_row << (5 - bw_log2)) + blk_col) }), } } pub(super) fn plane_reach_tables(mi_bw: usize, mi_bh: usize) -> (&'static [u8], &'static [u8]) { if mi_bw != mi_bh { return rect_reach_tables(mi_bw * 4, mi_bh * 4); } let row = Self::table(mi_bw * 4); if VERT_AB_PARTITION.with(std::cell::Cell::get) && row < HAS_TOP_RIGHT_VERT.len() { (HAS_TOP_RIGHT_VERT[row], HAS_BOTTOM_LEFT_VERT[row]) } else { (HAS_TOP_RIGHT[row], HAS_BOTTOM_LEFT[row]) } } pub(crate) fn of( side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx, ) -> Self { Self { above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx), below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx), } } pub(crate) fn of_rect( bw: usize, bh: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx, ) -> Self { Self { above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx), below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx), } } pub(super) fn top_right_rect( bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx, ) -> bool { let sb_mi: usize = reach_sb_px(fctx) / 4; let (mi_row, mi_col) = (y / 4, x / 4); let bw_log2 = (bw / 4).trailing_zeros() as usize; let bh_log2 = (bh / 4).trailing_zeros() as usize; let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; if blk_row == 0 { return true; } if ((blk_col + 1) << bw_log2) >= sb_mi { return false; } let table = rect_reach_tables(bw, bh).0; Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } pub(super) fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { (blk_row << (5 - bw_log2)) + blk_col } pub(super) fn bottom_left_rect( bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx, ) -> bool { let sb_mi: usize = reach_sb_px(fctx) / 4; let (mi_row, mi_col) = (y / 4, x / 4); let bw_log2 = (bw / 4).trailing_zeros() as usize; let bh_log2 = (bh / 4).trailing_zeros() as usize; let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; if blk_col == 0 { return (blk_row << bh_log2) + (bh / 4) < sb_mi; } if ((blk_row + 1) << bh_log2) >= sb_mi { return false; } let table = rect_reach_tables(bw, bh).1; Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } pub(crate) fn vert_ab_partition() -> VertAbGuard { VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) } pub(crate) fn none() -> Self { Self { above_right: false, below_left: false, } } pub(super) fn top_right( side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx, ) -> bool { let (row, col, per_side) = Self::position(side, x, y, fctx); if row == 0 { return true; } if col + 1 == per_side { return false; } let table_row = Self::table(side); let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { HAS_TOP_RIGHT_VERT[table_row] } else { HAS_TOP_RIGHT[table_row] }; Self::bit( table, (row * Self::table_stride(side) + col) % (table.len() * 8), ) } pub(super) fn bottom_left( side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx, ) -> bool { let (row, col, per_side) = Self::position(side, x, y, fctx); if col == 0 { return row * side + side < reach_sb_px(fctx); } if row + 1 == per_side { return false; } let table_row = Self::table(side); let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { HAS_BOTTOM_LEFT_VERT[table_row] } else { HAS_BOTTOM_LEFT[table_row] }; Self::bit( table, (row * Self::table_stride(side) + col) % (table.len() * 8), ) } pub(super) fn position( side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx, ) -> (usize, usize, usize) { let sb = reach_sb_px(fctx); ((y % sb) / side, (x % sb) / side, sb / side) } pub(super) fn table_stride(side: usize) -> usize { 128 / side } pub(super) fn table(side: usize) -> usize { if side == BLOCK { 1 } else if side == 8 { 2 } else if side == 4 { 3 } else { 0 } } pub(super) fn bit(table: &[u8], index: usize) -> bool { (table[index / 8] >> (index % 8)) & 1 != 0 } } pub(crate) fn warp_on() -> bool { crate::speed::at(&crate::speed::WARP) } pub(super) fn motion_mode_bits( write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool, ) -> f64 { let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else { return 0.0; }; match warp_alphabet { true => crate::tile::motion_mode_symbol_bits(row, motion), false => crate::tile::obmc_symbol_bits(row, motion == 1), } } pub(super) fn warp_prediction( grid: &MiGrid, (mi_row, mi_col): (usize, usize), (mi_rows, mi_cols): (usize, usize), (x, y): (usize, usize), side: usize, mv: (i32, i32), ref_frame: i8, ref_planes: [(&[u16], usize, usize, usize); 3], fctx: &crate::decode::FrameCtx, ) -> Option<[Vec; 3]> { let n4 = side / 4; if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) { return None; } let mut samples = crate::decode::find_samples( grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx, ); if samples.is_empty() { return None; } if samples.len() > 1 { crate::warp::select_samples(mv, &mut samples, side as i32, side as i32); } let params = crate::warp::find_projection( &samples, side as i32, side as i32, mv.1, mv.0, mi_row as i32, mi_col as i32, )?; let mut pred = [ vec![0u16; side * side], vec![0u16; side * side / 4], vec![0u16; side * side / 4], ]; for (i, r) in ref_planes.into_iter().enumerate() { let luma_plane = i == 0; let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) }; let s = if luma_plane { side } else { side / 2 }; mc::predict( r.0, r.1, r.2, r.3, mv_to_q4(px, mv.1, luma_plane), mv_to_q4(py, mv.0, luma_plane), s, s, &mut pred[i], fctx, ); if crate::decode::warp_plane_allowed(s, s) { let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32); crate::warp::warp_affine( ¶ms, r.0, r.2 as i32, r.3 as i32, r.1 as i32, &mut pred[i], px as i32, py as i32, cside, cside, cside, sub, sub, fctx, ); } } let [py_buf, pu_buf, pv_buf] = pred; let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::>(); Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)]) } pub(crate) fn compound_ref_bits((ref0, ref1): (i8, i8), stack: &crate::mvstack::MvStack) -> f64 { use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, }; let (a, a1) = stack.above_refs; let (l, l1) = stack.left_refs; let unidir = is_uni_comp_ref(ref0, ref1); let comp_mode = symbol_bits( &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)], 1, ); let ref_type = symbol_bits( &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)], usize::from(!unidir), ); if unidir { let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME); let p0 = symbol_bits( &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0], usize::from(both_backward), ); if both_backward { return comp_mode + ref_type + p0; } let past_last2 = ref1 != LAST2_FRAME; let p1 = symbol_bits( &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1], usize::from(past_last2), ); let p2 = if past_last2 { symbol_bits( &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2], usize::from(ref1 == GOLDEN_FRAME), ) } else { 0.0 }; return comp_mode + ref_type + p0 + p1 + p2; } let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME; let fwd = symbol_bits( &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0], usize::from(far), ) + if far { symbol_bits( &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2], usize::from(ref0 == GOLDEN_FRAME), ) } else { symbol_bits( &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1], usize::from(ref0 == LAST2_FRAME), ) }; let is_altref = ref1 == ALTREF_FRAME; let bwd = symbol_bits( &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0], usize::from(is_altref), ) + if is_altref { 0.0 } else { symbol_bits( &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1], usize::from(ref1 == ALTREF2_FRAME), ) }; comp_mode + ref_type + fwd + bwd } pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 { let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip); symbol_bits(&cdf::SKIP[ctx], usize::from(skip)) } pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 { let ctx = crate::tile::intra_inter_ctx( stack.above_nbr.is_some(), stack.left_nbr.is_some(), stack.above_nbr.is_some_and(|n| n.is_inter), stack.left_nbr.is_some_and(|n| n.is_inter), ); symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter)) } pub(super) fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 { if !reference_select() { return 0.0; } symbol_bits( &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)], 0, ) } pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 { use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, }; let (a, a1) = stack.above_refs; let (l, l1) = stack.left_refs; let comp_mode = comp_mode_single_bits(stack); let backward = ref_frame >= BWDREF_FRAME; let p1 = symbol_bits( &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0], usize::from(backward), ); if backward { let is_altref = ref_frame == ALTREF_FRAME; let p2 = symbol_bits( &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1], usize::from(is_altref), ); return comp_mode + p1 + p2 + if is_altref { 0.0 } else { symbol_bits( &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5], usize::from(ref_frame == ALTREF2_FRAME), ) }; } let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME; comp_mode + p1 + symbol_bits( &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2], usize::from(far), ) + if far { symbol_bits( &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4], usize::from(ref_frame == GOLDEN_FRAME), ) } else { symbol_bits( &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3], usize::from(ref_frame == LAST2_FRAME), ) } } pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; let width = cdf[symbol] - low; static PRICES: std::sync::OnceLock> = std::sync::OnceLock::new(); PRICES.get_or_init(|| { (0..=32768u32) .map(|w| -(f64::from(w) / 32768.0).log2()) .collect() })[usize::from(width)] } pub(super) fn max_tx_depth(side: usize) -> usize { match side { 8 => 1, 16 | 32 => 2, _ => 0, } } pub(super) fn tx_depth_bits(side: usize, depth: usize) -> f64 { match side { 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), } } pub(crate) fn split_lambda_mult() -> f64 { SPLIT_LAMBDA } pub(super) const SPLIT_LAMBDA: f64 = 1.0;