use super::*; type Pick = Option<(f64, u8, usize, (Vec, Vec), Vec)>; type BestDv = Option<((i32, i32), f64, (usize, usize))>; type PlaneRef<'a> = (&'a [u16], usize, usize, usize); type Winner = (Trial, Trial, Trial, bool, InterInfo); type SplitParts = ([Vec; 2], u8, f64, Option, Option<(i32, i32)>); pub(super) const MV_LAMBDA: f64 = 1.0; pub(super) fn mv_rate_surcharge(mv_bits: f64) -> f64 { (MV_LAMBDA - 1.0) * mv_bits } pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 { if tx_type == TxType::DctDct { 0.0 } else { lambda * 0.0 * bits } } pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; #[cfg(test)] pub(crate) fn take_tx_type_hits() -> [usize; 16] { std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed)) } pub(super) static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; #[cfg(test)] pub(crate) fn take_tx_depth_hits() -> [usize; 3] { std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) } pub(super) static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] = [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; pub(super) fn tx32_depth_search() -> bool { crate::speed::at(&crate::speed::TX32_DEPTH) } pub(super) fn compound_var_tx() -> bool { crate::speed::at(&crate::speed::COMPOUND_VAR_TX) } pub(super) static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; #[cfg(test)] pub(crate) fn take_ref_frame_hits() -> [usize; 8] { std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) } #[cfg(test)] pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] { std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) } pub(super) fn txfm_split_bits(side: usize, depth: usize) -> f64 { let max_tx = side.min(64); let ctx = |tx: usize| { crate::decode::txfm_partition_ctx_rect( crate::decode::TXFM_CTX_INIT, crate::decode::TXFM_CTX_INIT, side, tx, tx, ) }; if depth == 0 { return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); } symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) } pub(super) fn recode_inter_chroma( chroma: &[Plane; 2], (x, y): (usize, usize), side: usize, mv: (i32, i32), refs: [(&[u16], usize, usize, usize); 2], second: Option<((i32, i32), [PlaneRef<'_>; 2])>, search: &Search, set: TxbSet, luma_tx_type: TxType, fctx: &crate::decode::FrameCtx, ) -> Option<[Trial; 2]> { let c = side / 2; let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx); if tx == TxType::DctDct { return None; } Some([0usize, 1].map(|p| match second { Some((mv1, r1)) => mc_trial_compound_typed( &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx, search.deadzone, set, tx, fctx, ), None => mc_trial_typed( &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3, false, search.base_q_idx, search.deadzone, set, tx, fctx, ), })) } pub(super) fn commit_inter_luma( luma: &mut Plane, (x, y): (usize, usize), side: usize, mv: (i32, i32), reference: (&[u16], usize, usize, usize), search: &Search, flat: &Trial, skip: bool, second: Option<((i32, i32), PlaneRef<'_>)>, fctx: &crate::decode::FrameCtx, ) -> (Vec, u8, f64, Vec) { let mut flat_typed: Option = None; let mut flat_type = TxType::DctDct; if !skip && let Some(fset) = inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) { let lambda = search.lambda * 1.0; let cost = |t: &Trial| t.sse + lambda * t.bits; for &tx_type in inter_tx_type_candidates(fset, search.screen) { if tx_type == TxType::DctDct { continue; } let candidate = match second { Some((mv1, ref1)) => mc_trial_compound_typed( luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, search.deadzone, fset, tx_type, fctx, ), None => mc_trial_typed( luma, x, y, side, mv, true, reference.0, reference.1, reference.2, reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type, fctx, ), }; if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) { flat_type = tx_type; flat_typed = Some(candidate); } } } let count = |types: &[TxType]| { for &t in types { INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } }; let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat); let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits) - (flat.sse + search.lambda * flat.bits); let eligible = tx_select() && tx_select_inter() && !skip && side >= 16 && (second.is_none() || compound_var_tx()) && (side != BLOCK || tx32_depth_search()) && x + side <= luma.true_width && y + side <= luma.true_height; if !eligible { luma.commit(x, y, side, flat_ref); count(&[flat_type]); return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]); } let tx = side / 2; let set = luma_set_for( if tx >= 32 { TxbSet::Luma32Inter } else if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter }, search.screen, ); let mut levels = vec![0i32; side * side]; let (mut sse, mut bits) = (0.0, 0.0); let mut units = Vec::with_capacity(4); luma.ctx.tu_split = true; let mut split_types = vec![TxType::DctDct; 4]; for tu_row in 0..2 { for tu_col in 0..2 { let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); let unit = |tx_type: TxType| match second { Some((mv1, ref1)) => mc_trial_compound_typed( luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1, search.base_q_idx, search.deadzone, set, tx_type, fctx, ), None => mc_trial_typed( luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx, ), }; let mut best: Option<(f64, TxType, Trial)> = None; for &tx_type in inter_tx_type_candidates(set, search.screen) { let candidate = unit(tx_type); let cost = candidate.sse + search.lambda * 1.0 * candidate.bits; if best.as_ref().is_none_or(|(b, _, _)| cost < *b) { best = Some((cost, tx_type, candidate)); } } let (_, tx_type, trial) = best.expect("the candidate list is never empty"); split_types[tu_row * 2 + tu_col] = tx_type; sse += trial.sse; bits += trial.bits; for row in 0..tx { levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] .copy_from_slice(&trial.levels[row * tx..][..tx]); } units.push((tu_x, tu_y, trial)); } } luma.ctx.tu_split = false; let split_rate = bits + txfm_split_bits(side, 1); let flat_rate = flat_ref.bits + txfm_split_bits(side, 0); let split_cost = sse + search.lambda * split_lambda_mult() * split_rate; let flat_cost = flat_ref.sse + search.lambda * flat_rate; let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2; let counted = side <= BLOCK; if split_cost < flat_cost { for (tu_x, tu_y, trial) in &units { luma.commit(*tu_x, *tu_y, tx, trial); } if counted { INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } count(&split_types); return (levels, 1, flat_gain + split_cost - flat_cost, split_types); } if counted { INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } luma.commit(x, y, side, flat_ref); count(&[flat_type]); (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]) } pub(super) fn palette_candidates(block: &[u8]) -> Vec { let mut histogram = [0u32; 256]; for &v in block { histogram[usize::from(v)] += 1; } let present: Vec = (0..256u16) .filter(|&v| histogram[usize::from(v)] > 0) .collect(); if present.len() < 2 { return Vec::new(); } let exact = |colors: &[u16]| -> crate::tile::PaletteY { let mut base = [0u16; 8]; base[..colors.len()].copy_from_slice(colors); let map = block .iter() .map(|&v| { colors .iter() .enumerate() .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) .map(|(i, _)| i as u8) .expect("a palette holds at least two colours") }) .collect(); crate::tile::PaletteY { size: colors.len() as u8, colors: base, map, } }; if present.len() <= 8 { return vec![exact(&present)]; } if present.len() > 128 { return Vec::new(); } let (lo, hi) = (i32::from(present[0]), i32::from(present[present.len() - 1])); let mut out = Vec::with_capacity(2); for n in [8usize, 4] { let mut centres: Vec = (0..n) .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) .collect(); for _ in 0..4 { let mut sums = vec![0f64; n]; let mut counts = vec![0u32; n]; for (v, &count) in histogram.iter().enumerate() { if count == 0 { continue; } let k = (0..n) .min_by(|&a, &b| { (centres[a] - v as f64) .abs() .total_cmp(&(centres[b] - v as f64).abs()) }) .expect("n >= 2"); sums[k] += (v as u32 * count) as f64; counts[k] += count; } for k in 0..n { if counts[k] > 0 { centres[k] = sums[k] / f64::from(counts[k]); } } } let mut colors: Vec = centres .iter() .map(|&c| c.round().clamp(0.0, 255.0) as u16) .collect(); colors.sort_unstable(); colors.dedup(); if colors.len() >= 2 { out.push(exact(&colors)); } } out } pub(super) fn angle_delta_on() -> bool { crate::speed::at(&crate::speed::ANGLE) } pub(super) const IBC_HASH: usize = 16; pub(super) const INTRABC_DELAY_SB64: i32 = 4; pub(super) fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 { let mut h: u64 = 0xcbf2_9ce4_8422_2325; for row in 0..IBC_HASH { let base = (y + row) * width + x; for &v in &plane[base..base + IBC_HASH] { h ^= u64::from(v); h = h.wrapping_mul(0x100_0000_01b3); } } h } pub(super) fn ibc_index( table: &mut std::collections::HashMap>, plane: &[u8], width: usize, (x0, y0): (usize, usize), (x1, y1): (usize, usize), ) { let step = 4; if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH { return; } let mut y = y0.next_multiple_of(step); while y + IBC_HASH <= y1 { let mut x = x0.next_multiple_of(step); while x + IBC_HASH <= x1 { table .entry(ibc_hash(plane, width, x, y)) .or_default() .push((x as u32, y as u32)); x += step; } y += step; } } pub(super) struct Ibc { pub(super) table: std::collections::HashMap>, pub(super) tile: (usize, usize, usize, usize), pub(super) last_dv: Option<(i32, i32)>, pub(super) hits: usize, pub(super) lookups: usize, pub(super) found: usize, } impl Ibc { pub(super) fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self { let mut table = std::collections::HashMap::new(); ibc_index( &mut table, source, width, (tile.0, tile.1), (tile.2, tile.3), ); Self { table, tile, last_dv: None, hits: 0, lookups: 0, found: 0, } } pub(super) fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool { let (dr, dc) = (dv.0 / 8, dv.1 / 8); if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 { return false; } let (tx0, ty0, tx1, ty1) = ( self.tile.0 as i32, self.tile.1 as i32, self.tile.2 as i32, self.tile.3 as i32, ); let (sx, sy) = (x as i32 + dc, y as i32 + dr); let (w, h) = (w as i32, h as i32); if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { return false; } let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 }; let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 }; let active_sb_row = (y as i32 - ty0) >> sb_log2; let active_sb_col = (x as i32 - tx0) >> sb_log2; let src_sb_row = (sy + h - 1 - ty0) >> sb_log2; let src_sb_col = (sx + w - 1 - tx0) >> sb_log2; if src_sb_row >= active_sb_row { return false; } let total = ((tx1 - tx0 - 1) >> sb_log2) + 1; if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay { return false; } let wf = (1 + delay) * (active_sb_row - src_sb_row); src_sb_col < active_sb_col - delay + wf } } pub(super) static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; impl Drop for Ibc { fn drop(&mut self) { for (slot, n) in [self.lookups, self.found, self.hits] .into_iter() .enumerate() { IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed); } } } pub(super) fn dv_component_bits(diff: i32) -> f64 { let z = diff.unsigned_abs() as i32 - 1; let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); let class = mv_class_of(z); bits += symbol_bits(&cdf::MV_CLASS, class); let local = z - mv_class_base(class); if class == 0 { bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize); } else { let d = local >> 3; for i in 0..class { bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); } } bits } pub(super) fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 { let diff = (dv.0 - pred.0, dv.1 - pred.1); let joint = match (diff.0 != 0, diff.1 != 0) { (false, false) => 0, (false, true) => 1, (true, false) => 2, (true, true) => 3, }; let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0; if diff.0 != 0 { bits += dv_component_bits(diff.0); } if diff.1 != 0 { bits += dv_component_bits(diff.1); } bits } pub(super) fn ibc_sse( luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize), (sx, sy): (usize, usize), side: usize, ) -> f64 { let mut sse = 0.0f64; let clip = |whole: usize, inside: usize| match true { true => whole.min(inside), false => whole, }; let rows = clip(side, luma.true_height.saturating_sub(y)); let cols = clip(side, luma.true_width.saturating_sub(x)); for row in 0..rows { let src = &luma.source[(y + row) * luma.width + x..][..cols]; let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols]; for (&s, &r) in src.iter().zip(rec) { let d = f64::from(i32::from(s) - i32::from(r)); sse += d * d; } } let half = side / 2; for plane in chroma { let rows = clip(half, plane.true_height.saturating_sub(y / 2)); let cols = clip(half, plane.true_width.saturating_sub(x / 2)); for row in 0..rows { let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols]; let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols]; for (&s, &r) in src.iter().zip(rec) { let d = f64::from(i32::from(s) - i32::from(r)); sse += d * d; } } } sse } pub(super) fn ibc_commit( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), (sx, sy): (usize, usize), side: usize, ) { for row in 0..side { let from = (sy + row) * luma.width + sx; let to = (y + row) * luma.width + x; let copied: Vec = luma.reconstruction[from..from + side].to_vec(); luma.reconstruction[to..to + side].copy_from_slice(&copied); } let half = side / 2; for plane in chroma { for row in 0..half { let from = (sy / 2 + row) * plane.width + sx / 2; let to = (y / 2 + row) * plane.width + x / 2; let copied: Vec = plane.reconstruction[from..from + half].to_vec(); plane.reconstruction[to..to + half].copy_from_slice(&copied); } plane.commit_ctx_zero(x / 2, y / 2, half); } luma.commit_ctx_zero(x, y, side); } pub(super) fn ibc_search( ibc: &mut Ibc, luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize), side: usize, lambda: f64, ) -> BestDv { let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8)); let mut best: BestDv = None; let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut BestDv| { let dv = ((sy as i32 - y as i32) * 8, (sx as i32 - x as i32) * 8); if !ibc.dv_valid(x, y, side, side, dv) { return; } let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred); if best.as_ref().is_none_or(|b| cost < b.1) { *best = Some((dv, cost, (sx, sy))); } }; ibc.lookups += 1; let key = ibc_hash(luma.source, luma.width, x, y); let hits: Vec<(u32, u32)> = ibc .table .get(&key) .map(|h| { let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32)); h[..end].iter().rev().take(32).copied().collect() }) .unwrap_or_default(); for (hx, hy) in hits { consider(&*ibc, hx as usize, hy as usize, &mut best); } if let Some(dv) = ibc.last_dv { let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8); if sx >= 0 && sy >= 0 { consider(&*ibc, sx as usize, sy as usize, &mut best); } } if best.is_some() { ibc.found += 1; } best } pub(super) fn code_square( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, search: &Search, mode_bits: &[f64; 13], tx_select: bool, ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { let (luma_set, chroma_set) = if side == SUPERBLOCK { (TxbSet::Luma64, TxbSet::Chroma32) } else if side == BLOCK { (TxbSet::Luma32, TxbSet::Chroma16) } else if side == 8 { (TxbSet::Luma8, TxbSet::Chroma4) } else { (TxbSet::Luma16, TxbSet::Chroma8) }; let at = At { x, y, side, reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), set: luma_set_for(luma_set, search.screen), }; let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) = luma.search_block(at, search, mode_bits, fctx); let mut luma_tx_types = vec![tx_type]; let mut tx_depth = 0u8; if tx_select && side == SUPERBLOCK { cost += search.lambda * tx_depth_bits(side, 0); } if tx_select && max_tx_depth(side) > 0 { let mut best = ( cost + search.lambda * tx_depth_bits(side, 0), 0usize, luma.snapshot(x, y, side), luma_coeffs, ); let mut best_types = std::mem::take(&mut luma_tx_types); for depth in 1..=max_tx_depth(side) { let (levels, sse, bits, types) = luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx); let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth); let cost_d = sse + search.lambda * split_lambda_mult() * rate; if cost_d < best.0 { best = ( cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side), ); best_types = types; } } luma_tx_types = best_types; luma.restore(x, y, side, &best.2); cost = best.0; tx_depth = best.1 as u8; luma_coeffs = best.3; TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } let mut mode = mode; let mut angle_delta = angle_delta; let mut palette = None; if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { let source: Vec = (y..y + side) .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) .collect(); let kept = luma.snapshot(x, y, side); let on = ( side.min(luma.true_width.saturating_sub(x)), side.min(luma.true_height.saturating_sub(y)), ); for mut pal in palette_candidates(&source) { let n = usize::from(pal.size); crate::decode::palette_replicate(&mut pal.map, side, side, on); let prediction: Vec = pal .map .iter() .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) .collect(); let trial = luma.code_from_prediction( x, y, side, &prediction, false, search.base_q_idx, search.deadzone, luma_set, ); let cost_p = trial.sse + search.lambda * (trial.bits + mode_bits[DC_PRED as usize] + crate::tile::palette_bits(&pal, side, on) + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); if cost_p < cost { cost = cost_p; mode = DC_PRED; angle_delta = 0; tx_depth = 0; luma_coeffs = coeffs(&trial.levels, side.min(BLOCK)); luma.commit(x, y, side, &trial); palette = Some(pal); } } if palette.is_none() { luma.restore(x, y, side, &kept); } } let mut filter_intra: Option = None; if filter_intra_on() && palette.is_none() && let Some(class) = crate::decode::filter_intra_size_class(side) { let row = &cdf::FILTER_INTRA[class]; if mode == DC_PRED { cost += search.lambda * symbol_bits(row, 0); } let one_bits = symbol_bits(row, 1); let kept = luma.snapshot(x, y, side); let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 }; let mut best: Pick = None; for fi in 0..5u8 { for depth in 0..=max_depth { let (levels, sse, bits, _) = luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx); let cost_f = sse + search.lambda * (bits + mode_bits[DC_PRED as usize] + one_bits + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi)) + if tx_select { tx_depth_bits(side, depth) } else { 0.0 }); if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) { best = Some(( cost_f, fi, depth, luma.snapshot(x, y, side), coeffs(&levels, side), )); } } } if let Some((cost_f, fi, depth, snapshot, levels)) = best { cost = cost_f; mode = DC_PRED; angle_delta = 0; tx_depth = depth as u8; luma_coeffs = levels; luma.restore(x, y, side, &snapshot); filter_intra = Some(fi); } else { luma.restore(x, y, side, &kept); } } let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) = search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx); cost += chroma_cost; if let Some(ibc) = ibc && let Some((dv, cost_ibc, src)) = ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) && cost_ibc < cost { ibc_commit(luma, chroma, (x, y), src, side); ibc.last_dv = Some(dv); ibc.hits += 1; return ( BlockCoeffs { skip: true, dv: Some(dv), ..BlockCoeffs::default() }, cost_ibc, ); } if palette.is_some() || filter_intra.is_some() { luma_tx_types = Vec::new(); } ( BlockCoeffs { u, v, luma: luma_coeffs, mode, uv_mode, tx_depth, palette, palette_uv, filter_intra, cfl_alphas, angle_delta_y: angle_delta as i8, luma_tx_types, ..BlockCoeffs::default() }, cost, ) } pub(super) const CHROMA_MODES: [u8; 7] = [ DC_PRED, V_PRED, H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, SMOOTH_H_PRED, PAETH_PRED, ]; pub(super) fn cfl_on() -> bool { crate::speed::at(&crate::speed::CFL) } pub(crate) const SB128_DEFAULT: bool = true; pub(crate) fn sb128_on() -> bool { SB128_DEFAULT } pub(crate) fn lr_unit() -> u32 { if SB128_DEFAULT { 128 } else { 64 } } pub(crate) fn filter_intra_on() -> bool { crate::speed::at(&crate::speed::FILTER_INTRA) } pub(super) fn chroma_top_k() -> Option { crate::speed::at(&crate::speed::CHROMA_K) } pub(crate) const CHROMA_TOP_K: Option = None; pub(super) fn search_chroma( chroma: &mut [Plane; 2], luma: &Plane, (x, y): (usize, usize), side: usize, set: TxbSet, search: &Search, luma_mode: u8, fctx: &crate::decode::FrameCtx, ) -> SplitParts { let at = At { x: x / 2, y: y / 2, side: side / 2, reach: Reach::none(), set, }; let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); u.iter() .zip(v.iter()) .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) .collect() }; let modes: Vec = match chroma_top_k() { Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), _ => CHROMA_MODES.to_vec(), }; let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); let mut best: Option<(f64, u8, Trial, Trial)> = None; for mode in modes { let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; if (V_PRED..=D67_PRED).contains(&mode) { bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); } let tx_type = if at.side >= 32 { TxType::DctDct } else { crate::decode::default_intra_tx_type(mode) }; let u = chroma[0].trial_typed( at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx, ); let v = chroma[1].trial_typed( at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx, ); let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); if best.as_ref().is_none_or(|(b, ..)| cost < *b) { best = Some((cost, mode, u, v)); } } let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); let mut palette_uv = None; if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); let plane_source = |p: &Plane| -> Vec { (at.y..at.y + at.side) .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) .collect() }; let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); let on_uv = crate::decode::palette_onscreen_uv( (side, side), ( side.min(luma.true_width.saturating_sub(x)), side.min(luma.true_height.saturating_sub(y)), ), (at.side, at.side), (1, 1), ); for mut pal in palette_candidates(&u_source) { let n = usize::from(pal.size); crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv); let mut sums = [0u32; 8]; let mut counts = [0u32; 8]; for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { let k = usize::from(i).min(n - 1); sums[k] += u32::from(sample); counts[k] += 1; } let mut v_colors = [0u16; 8]; for k in 0..n { v_colors[k] = (sums[k] + counts[k] / 2) .checked_div(counts[k]) .unwrap_or(0) as u16; } let candidate = crate::tile::PaletteUv { size: pal.size, u_colors: pal.colors, v_colors, map: pal.map, }; let predict = |colors: &[u16; 8]| -> Vec { candidate .map .iter() .map(|&i| colors[usize::from(i).min(n - 1)] as u8) .collect() }; let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); let u_trial = chroma[0].code_from_prediction( at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, ); let v_trial = chroma[1].code_from_prediction( at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, ); let cost_p = u_trial.sse + v_trial.sse + search.lambda * (u_trial.bits + v_trial.bits + crate::tile::palette_uv_bits(&candidate, side, on_uv)); if cost_p < cost { cost = cost_p; mode = DC_PRED; u = u_trial; v = v_trial; palette_uv = Some(candidate); } } } let mut cfl_alphas = None; if side <= 32 && cfl_on() { let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| { i32::from(luma.reconstruction[ly * luma.width + lx]) }); let dc_prediction = |plane: &Plane| -> Vec { let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); let (above, left, corner) = plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf); let mut prediction = vec![0u8; at.side * at.side]; intra_predict_u8( DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction, fctx, ); prediction }; let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])]; let apply = |base: &[u8], alpha: i32| -> Vec { base.iter() .zip(ac.iter()) .map(|(&b, &a)| { (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8 }) .collect() }; let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 { let (mut num, mut den) = (0.0f64, 0.0f64); for row in 0..at.side { for col in 0..at.side { let i = row * at.side + col; let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col]) - f64::from(base[i]); num += d * f64::from(ac[i]); den += f64::from(ac[i]) * f64::from(ac[i]); } } if den == 0.0 { return 0; } let ideal = 64.0 * num / den; let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32); for alpha in [ideal.floor() as i64, ideal.ceil() as i64] { let alpha = alpha.clamp(-16, 16) as i32; if alpha == 0 { continue; } let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha)); if sse < best.0 { best = (sse, alpha); } } best.1 }; let picked = [ pick_alpha(&chroma[0], &bases[0]), pick_alpha(&chroma[1], &bases[1]), ]; if picked != [0, 0] { let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits; let trial = |plane_idx: usize, alpha: i32| -> Trial { let prediction = if alpha == 0 { bases[plane_idx].clone() } else { apply(&bases[plane_idx], alpha) }; chroma[plane_idx].code_from_prediction( at.x, at.y, at.side, &prediction, false, search.base_q_idx, search.deadzone, set, ) }; let combos: [(i32, i32); 3] = [(picked[0], picked[1]), (picked[0], 0), (0, picked[1])]; for &(alpha_u, alpha_v) in &combos { if (alpha_u, alpha_v) == (0, 0) { continue; } let cu = trial(0, alpha_u); let cv = trial(1, alpha_v); let bits = cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits; let cost_cfl = cu.sse + cv.sse + search.lambda * bits; if cost_cfl < cost { cost = cost_cfl; mode = crate::tile::UV_CFL_PRED as u8; u = cu; v = cv; palette_uv = None; cfl_alphas = Some((alpha_u, alpha_v)); } } } } chroma[0].commit(at.x, at.y, at.side, &u); chroma[1].commit(at.x, at.y, at.side, &v); ( [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], mode, cost, palette_uv, cfl_alphas, ) } pub(super) fn leaf_compound_stacks<'a>( grid: &MiGrid, mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, mi_cols: usize, mi_rows: usize, reference_select: bool, golden: Option<&'a Picture>, altref: Option<&'a Picture>, ) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> { if !(reference_select && leaf_compound()) { return Vec::new(); } [ (crate::mvstack::GOLDEN_FRAME, golden), (crate::mvstack::ALTREF_FRAME, altref), ] .into_iter() .filter_map(|(r, pic)| { pic.map(|p| { ( r, p, crate::mvstack::find_mv_stack_compound( grid, mi_row, mi_col, bw4, bh4, (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, grid.sign_bias_table(), &[(0, 0); 7], None, ), ) }) }) .collect() } pub(super) fn code_square_inter( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, search: &Search, mode_bits: &[f64; 13], reference: &Picture, stack: &MvStack, compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], grid: &MiGrid, (mi_row, mi_col): (usize, usize), (mi_rows, mi_cols): (usize, usize), refs: &[Option<&Picture>; 8], fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { let (intra_block, intra_cost) = if search.arf_leaf_intra { code_square( luma, chroma, (x, y), side, search, mode_bits, tx_select() && tx_select_inter(), None, fctx, ) } else { arfmode_hit(0); (BlockCoeffs::default(), f64::INFINITY) }; let luma_set = if side == 8 { TxbSet::Luma8Inter } else { TxbSet::Luma16Inter }; let chroma_set = if side == 8 { TxbSet::Chroma4 } else { TxbSet::Chroma8 }; let skip_bits = |skip: bool| skip_bits_at(stack, skip); let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter); let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); let mv = stack.nearest_mv; let ref_luma = ( &reference.y, reference.width, luma.true_width, luma.true_height, ); let ref_u = ( &reference.u, reference.width / 2, chroma[0].true_width, chroma[0].true_height, ); let ref_v = ( &reference.v, reference.width / 2, chroma[1].true_width, chroma[1].true_height, ); let luma_trial = mc_trial( luma, x, y, side, mv, true, ref_luma.0, ref_luma.1, ref_luma.2, ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, ); let u = mc_trial( &chroma[0], x / 2, y / 2, side / 2, mv, false, ref_u.0, ref_u.1, ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, fctx, ); let v = mc_trial( &chroma[1], x / 2, y / 2, side / 2, mv, false, ref_v.0, ref_v.1, ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, fctx, ); let skip = luma_trial.levels.iter().all(|&l| l == 0) && u.levels.iter().all(|&l| l == 0) && v.levels.iter().all(|&l| l == 0); let inter_cost = luma_trial.sse + u.sse + v.sse + search.lambda * (skip_bits(skip) + intra_inter_bits(true) + single_ref_bits + mode_bits_inter + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); let mut best: (f64, Option) = (inter_cost, None); let nearest_info = InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv, ref_mv_idx: 0, }; let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter; let mut searched_new: Option<(i32, i32)> = None; let mut searched_new_cost: Option = None; let source_block = luma.source_block(x, y, side); if LEAF_NEW_MV { let (seeds, seed_n) = mv_seeds(stack); let found = motion::search( ref_luma.0, ref_luma.1, ref_luma.2, ref_luma.3, &source_block, x, y, side, side, stack.pred_mv, &seeds[..seed_n], search.lambda, fctx, 1, ); let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); searched_new_cost = Some(found.cost); let mv_residual = mv_residual_bits(new_mv, stack.pred_mv); if let Some(mv_bits) = mv_residual { searched_new = Some(new_mv); let (luma_new, u_new, v_new) = if new_mv == mv { (luma_trial.clone(), u.clone(), v.clone()) } else { ( mc_trial( luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2, ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, ), mc_trial( &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1, ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, fctx, ), mc_trial( &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1, ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, fctx, ), ) }; let skip_new = luma_new.levels.iter().all(|&l| l == 0) && u_new.levels.iter().all(|&l| l == 0) && v_new.levels.iter().all(|&l| l == 0); let drl_bits = if stack.entries.len() > 1 { symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) } else { 0.0 }; let cost_new = luma_new.sse + u_new.sse + v_new.sse + search.lambda * (skip_bits(skip_new) + intra_inter_bits(true) + single_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + drl_bits + mv_bits + mv_rate_surcharge(mv_bits) + if skip_new { 0.0 } else { luma_new.bits + u_new.bits + v_new.bits }); if cost_new < best.0 { single_syntax = intra_inter_bits(true) + single_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + drl_bits + mv_bits; best = ( cost_new, Some(( luma_new, u_new, v_new, skip_new, InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv: new_mv, ref_mv_idx: 0, }, )), ); } } } if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() { arfmode_hit(2); } for (ref1, g, cstack) in compound .iter() .filter(|_| leaf_compound() && search.arf_leaf_compound) { let (ref1, g) = (*ref1, *g); let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack); let mode_ctx = cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; let mode_bits_of = |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); let mut ccands: crate::encode::CompCands = vec![ ( cstack.nearest_mv, mode_bits_of(0), InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestNearestMv, mv: cstack.nearest_mv.0, mv1: cstack.nearest_mv.1, ref1: Some(ref1), ref_mv_idx: 0, }, ), ( ((0, 0), (0, 0)), mode_bits_of(6), InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::GlobalGlobalMv, mv: (0, 0), mv1: (0, 0), ref1: Some(ref1), ref_mv_idx: 0, }, ), ]; let cbase = cstack .entries .first() .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); let margin = LEAF_SECOND_NEW_MARGIN; let mut second_new: Option<(i32, i32)> = None; if leaf_second_new_mv() { let skip = margin > 0.0 && searched_new_cost.is_some_and(|last| { motion::cost_at( &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx, ) * margin <= last }); if !skip { let mut seeds = [(0, 0); 4]; let mut seed_n = 1; for e in cstack.entries.iter().take(3) { seeds[seed_n] = e.mv1; seed_n += 1; } let found = motion::search( &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side, side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1), ); second_new = Some(round_to_valid_mv(found.mv, cbase.1)); } } if let Some(new_mv) = searched_new && let Some(b0) = mv_residual_bits(new_mv, cbase.0) { ccands.push(( (new_mv, cstack.nearest_mv.1), mode_bits_of(3) + b0, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewNearestMv, mv: new_mv, mv1: cstack.nearest_mv.1, ref1: Some(ref1), ref_mv_idx: 0, }, )); } if let Some(mv1) = second_new && let Some(b1) = mv_residual_bits(mv1, cbase.1) { ccands.push(( (cstack.nearest_mv.0, mv1), mode_bits_of(2) + b1, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestNewMv, mv: cstack.nearest_mv.0, mv1, ref1: Some(ref1), ref_mv_idx: 0, }, )); if let Some((new_mv, b0)) = searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) { ccands.push(( (new_mv, mv1), mode_bits_of(7) + b0 + b1, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewNewMv, mv: new_mv, mv1, ref1: Some(ref1), ref_mv_idx: 0, }, )); } } ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); ccands.dedup_by_key(|c| c.0); let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); let g_u = ( g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height, ); let g_v = ( g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height, ); for (mvs, bits, info) in ccands { let luma_c = mc_trial_compound( luma, x, y, side, mvs, true, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, search.base_q_idx, search.deadzone, luma_set, fctx, ); let u_c = mc_trial_compound( &chroma[0], x / 2, y / 2, side / 2, mvs, false, (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, search.base_q_idx, search.deadzone, chroma_set, fctx, ); let v_c = mc_trial_compound( &chroma[1], x / 2, y / 2, side / 2, mvs, false, (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, search.base_q_idx, search.deadzone, chroma_set, fctx, ); let skip_c = luma_c.levels.iter().all(|&l| l == 0) && u_c.levels.iter().all(|&l| l == 0) && v_c.levels.iter().all(|&l| l == 0); let cost_c = luma_c.sse + u_c.sse + v_c.sse + search.lambda * (skip_bits(skip_c) + intra_inter_bits(true) + bits + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits }); if cost_c < best.0 { best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info))); } } } let mut motion_won = 0u8; let single = match &best.1 { None => Some(nearest_info), Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info), Some(_) => None, }; if let Some(info) = single.filter(|i| warp_on() && i.ref_frame == crate::mvstack::LAST_FRAME) { let planes = [ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), ]; let warp_alphabet = warp_on() && crate::decode::num_proj_ref( grid, mi_row, mi_col, side / 4, side / 4, mi_cols, mi_rows, info.ref_frame, fctx, ) >= 1; let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet); let mut candidates: Vec<(u8, [Vec; 3])> = Vec::new(); if warp_alphabet && let Some(pred) = warp_prediction( grid, (mi_row, mi_col), (mi_rows, mi_cols), (x, y), side, info.mv, info.ref_frame, planes, fctx, ) { candidates.push((2, pred)); } for (motion, pred) in candidates { let luma_o = luma.code_from_prediction( x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set, ); let u_o = chroma[0].code_from_prediction( x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone, chroma_set, ); let v_o = chroma[1].code_from_prediction( x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone, chroma_set, ); let skip_o = luma_o.levels.iter().all(|&l| l == 0) && u_o.levels.iter().all(|&l| l == 0) && v_o.levels.iter().all(|&l| l == 0); let cost_o = luma_o.sse + u_o.sse + v_o.sse + search.lambda * (skip_bits(skip_o) + single_syntax + mm(motion) + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits }); if cost_o < best.0 + search.lambda * mm(motion_won) { motion_won = motion; best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info))); } } } if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best && cost < intra_cost { let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| { refs[r as usize].map(|g| { ( info.mv1, (g.y.as_slice(), g.width, luma.true_width, luma.true_height), ) }) }); let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0 || (info.ref1.is_some() && second.is_none()) { luma.commit(x, y, side, &luma_new); (luma_new.levels.clone(), 0, 0.0, Vec::new()) } else { commit_inter_luma( luma, (x, y), side, info.mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_new, skip_new, second, fctx, ) }; let [u_new, v_new] = match luma_tx_types.first().copied() { Some(t) => recode_inter_chroma( chroma, (x, y), side, info.mv, [ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), ], info.ref1.filter(|_| motion_won == 0).and_then(|r| { refs[r as usize].map(|g| { ( info.mv1, [ ( g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height, ), ( g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height, ), ], ) }) }), search, chroma_set, t, fctx, ) .unwrap_or([u_new, v_new]), None => [u_new, v_new], }; chroma[0].commit(x / 2, y / 2, side / 2, &u_new); chroma[1].commit(x / 2, y / 2, side / 2, &v_new); return ( BlockCoeffs { angle_delta_y: 0, cfl_alphas: None, filter_intra: None, luma: coeffs(&levels, side), u: coeffs(&u_new.levels, side / 2), v: coeffs(&v_new.levels, side / 2), mode: DC_PRED, uv_mode: DC_PRED, skip: skip_new, eight: None, dv: None, palette: None, palette_uv: None, tx_depth, luma_tx_types, inter: Some(info), motion_mode: motion_won, }, cost + dcost, ); } if inter_cost < intra_cost { let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma( luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx, ); let [u, v] = match luma_tx_types.first().copied() { Some(t) => recode_inter_chroma( chroma, (x, y), side, mv, [ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), ], None, search, chroma_set, t, fctx, ) .unwrap_or([u, v]), None => [u, v], }; chroma[0].commit(x / 2, y / 2, side / 2, &u); chroma[1].commit(x / 2, y / 2, side / 2, &v); ( BlockCoeffs { luma_tx_types, angle_delta_y: 0, cfl_alphas: None, filter_intra: None, luma: coeffs(&levels, side), u: coeffs(&u.levels, side / 2), v: coeffs(&v.levels, side / 2), mode: DC_PRED, uv_mode: DC_PRED, skip, eight: None, dv: None, palette: None, palette_uv: None, tx_depth, motion_mode: 0, inter: Some(InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv, ref_mv_idx: 0, }), }, inter_cost + dcost, ) } else { (intra_block, intra_cost) } }