use super::*; pub(super) fn record_mi( grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option, skip: bool, ) { let info = match inter { Some(info) => MiInfo { is_inter: true, ref_frame: info.ref_frame, ref_frame1: info.ref1.unwrap_or(NO_REF1), mv1: mv16(info.mv1), mv: mv16(info.mv), is_new_mv: matches!( info.mode, InterMode::NewMv | InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv ), size, size_h: size, is_global_mv0: false, is_global_mv1: false, }, None => MiInfo { is_inter: false, ref_frame: -1, ref_frame1: NO_REF1, mv1: (0, 0), mv: (0, 0), is_new_mv: false, size, size_h: size, is_global_mv0: false, is_global_mv1: false, }, }; for dr in 0..usize::from(size) { for dc in 0..usize::from(size) { grid.set(mi_row + dr, mi_col + dc, info); grid.set_skip(mi_row + dr, mi_col + dc, skip); } } } pub(super) fn record_mi_rect( grid: &mut MiGrid, mi_row: usize, mi_col: usize, (w_mi, h_mi): (usize, usize), inter: Option, skip: bool, ) { record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip); let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded"); info.size = w_mi as u8; info.size_h = h_mi as u8; for dr in 0..h_mi { for dc in 0..w_mi { grid.set(mi_row + dr, mi_col + dc, info); grid.set_skip(mi_row + dr, mi_col + dc, skip); } } } pub(super) fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec { let mut out = vec![0u8; side * side]; for row in 0..side { out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]); } out } pub(super) fn snapshot( luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize), side: usize, ) -> crate::encode::CoefPlanes { [ luma.snapshot(x, y, side), chroma[0].snapshot(x / 2, y / 2, side / 2), chroma[1].snapshot(x / 2, y / 2, side / 2), ] } pub(super) fn restore( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, saved: &crate::encode::CoefPlanes, ) { luma.restore(x, y, side, &saved[0]); chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); } pub(super) fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec { 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() { top_k.saturating_sub(1) } else { top_k }); if let Some(dc_entry) = dc_entry { scored.push(dc_entry); } let keep: Vec = scored.into_iter().map(|(_, mode)| mode).collect(); modes.iter().copied().filter(|m| keep.contains(m)).collect() } pub(super) fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] [INTRA_MODE_CTX[usize::from(left_mode)]]; std::array::from_fn(|mode| { let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) } else { 0.0 }; symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) }) } #[derive(Clone, Copy)] pub(super) struct Search<'a> { pub(super) screen: bool, pub(super) base_q_idx: u8, pub(super) deadzone: f64, pub(super) lambda: f64, pub(super) modes: &'a [u8], pub(super) top_k: Option, pub(super) arf_leaf_intra: bool, pub(super) arf_leaf8: bool, pub(super) arf_leaf_compound: bool, } pub(super) fn arfmode() -> u8 { crate::speed::at(&crate::speed::ARFMODE) } pub(super) static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [ std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), ]; pub(super) fn arfmode_hit(which: usize) { ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } pub(super) fn arfmode_hit_and_no() -> bool { arfmode_hit(1); false } pub fn take_arfmode_hits() -> [usize; 3] { [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } pub(super) fn prune_top_k() -> Option { crate::speed::at(&crate::speed::PRUNE_K) } pub(crate) const PRUNE_TOP_K: Option = None; pub(super) fn prune_top_k_inter() -> Option { crate::speed::at(&crate::speed::PRUNE_K_INTER) } pub(crate) const INTER_PRUNE_TOP_K: Option = Some(3); #[cfg(test)] thread_local! { static STAGE_NS: [std::cell::Cell; 4] = const { [ std::cell::Cell::new(0), std::cell::Cell::new(0), std::cell::Cell::new(0), std::cell::Cell::new(0), ] }; } #[cfg(test)] pub(crate) fn stage_start() -> Option { crate::par::stage_times().then(std::time::Instant::now) } #[cfg(test)] pub(crate) fn stage_since(bucket: usize, t: Option) { if let Some(t) = t { stage_add(bucket, t.elapsed()); } } #[cfg(test)] pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); } #[derive(Clone)] pub(super) struct Trial { pub(super) levels: Vec, pub(super) reconstruction: Vec, pub(super) sse: f64, pub(super) bits: f64, } pub(super) fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec { let mut out = vec![0i32; to * to]; for row in 0..to { out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]); } out } pub(super) fn coeffs(levels: &[i32], side: usize) -> Vec { levels .iter() .enumerate() .filter(|&(_, &level)| level != 0) .map(|(i, &level)| Coeff { row: (i / side) as u8, col: (i % side) as u8, level, }) .collect() } pub(super) fn write_tiles( tiles: usize, store: usize, code: F, ) -> Result<(Vec>, Option)> where F: Fn(usize) -> Result<(Vec, Option)> + Sync + Send, { let _t = crate::par::timer(crate::par::S_TILE_WRITE); type Slot = Option, Option)>>; let threads = crate::par::tile_threads().min(tiles); let mut slots: Vec = (0..tiles).map(|_| None).collect(); if threads <= 1 { for (index, slot) in slots.iter_mut().enumerate() { *slot = Some(code(index)); } } else { let bands = crate::par::bands(tiles, threads); let chunks = crate::par::split_bands_mut(&bands, 1, &mut slots); crate::par::scope("ec-av1-tile", |batch| { for (&(from, _), chunk) in bands.iter().zip(chunks) { let code = &code; batch.submit(move || { for (offset, slot) in chunk.iter_mut().enumerate() { *slot = Some(code(from + offset)); } }); } }); } let mut out = Vec::with_capacity(tiles); let mut stored = None; for (index, slot) in slots.into_iter().enumerate() { let (bytes, cdfs) = slot.ok_or_else(|| Error::unsupported("AV1 encode", "a tile was not coded"))??; if index == store { stored = cdfs; } out.push(bytes); } Ok((out, stored)) } pub(super) fn search_tiles( tiles: usize, fctx: &crate::decode::FrameCtx, job: F, ) -> Result> where T: Send, F: Fn(usize, &crate::decode::FrameCtx) -> Result + Sync, { let _t = crate::par::timer(crate::par::S_TILE_SEARCH); let threads = crate::par::tile_threads().min(tiles); if threads <= 1 { return (0..tiles).map(|index| job(index, fctx)).collect(); } type Slot = Option>; let mut slots: Vec> = (0..tiles).map(|_| None).collect(); let bands = crate::par::bands(tiles, threads); let chunks = crate::par::split_bands_mut(&bands, 1, &mut slots); crate::par::scope("ec-av1-tile-search", |batch| { for (&(from, _), chunk) in bands.iter().zip(chunks) { let job = &job; let ctx = crate::decode::filter_ctx_copy(fctx); batch.submit(move || { for (offset, slot) in chunk.iter_mut().enumerate() { *slot = Some(job(from + offset, &ctx)); } }); } }); slots .into_iter() .map(|slot| { slot.ok_or_else(|| Error::unsupported("AV1 encode", "a tile was not searched"))? }) .collect() } pub(super) fn fresh_plane( source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize, ) -> Plane<'_> { Plane { source, reconstruction: vec![128; source.len()], width, height, true_width, true_height, tile_x0: 0, tile_y0: 0, tile_x1: width, tile_y1: height, ctx: CoefCtxMap::default(), } } pub(super) fn fresh_frame_planes<'a>( picture: &Picture, sources: [&'a [u8]; 3], true_width: usize, true_height: usize, ) -> (Plane<'a>, [Plane<'a>; 2]) { let [y, u, v] = sources; let (w, h) = (picture.width, picture.height); ( fresh_plane(y, w, h, true_width, true_height), [ fresh_plane(u, w / 2, h / 2, true_width / 2, true_height / 2), fresh_plane(v, w / 2, h / 2, true_width / 2, true_height / 2), ], ) } pub(super) struct TilePixels { pub(super) luma_rect: (usize, usize, usize, usize), pub(super) chroma_rect: (usize, usize, usize, usize), pub(super) luma: Vec, pub(super) chroma: [Vec; 2], } pub(super) fn take_rect( plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize), ) -> Vec { let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0)); for y in y0..y1 { out.extend_from_slice(&plane[y * stride + x0..y * stride + x1]); } out } pub(super) fn put_rect( plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize), rows: &[u8], ) { let w = x1 - x0; for (row, y) in (y0..y1).enumerate() { plane[y * stride + x0..y * stride + x1].copy_from_slice(&rows[row * w..(row + 1) * w]); } } pub(super) fn tile_info_of( layout: &crate::tile::TileLayout, tile_size_bytes: u32, ) -> ec_av1_syntax::TileInfo { ec_av1_syntax::TileInfo { uniform_spacing: true, cols: layout.cols(), rows: layout.rows(), cols_log2: layout.cols_log2, rows_log2: layout.rows_log2, mi_col_starts: layout.mi_col_starts(), mi_row_starts: layout.mi_row_starts(), context_update_tile_id: layout.largest_tile() as u32, tile_size_bytes, } } pub(super) fn clip_planes_to_tile( luma: &mut Plane<'_>, chroma: &mut [Plane<'_>; 2], rect: crate::tile::TileRect, ) { let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); luma.set_tile(x0, y0, x1, y1); for plane in chroma.iter_mut() { plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); } } pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result { encode_key_frame_with_ctx( picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder(), ) } pub fn encode_key_frame_with_modes( picture: &Picture, base_q_idx: u8, deadzone: f64, modes: &[u8], ) -> Result { encode_key_frame_with_modes_with_ctx( picture, base_q_idx, deadzone, modes, &crate::decode::FrameCtx::for_encoder(), ) } pub fn encode_sequence( pictures: &[Picture], base_q_idx: u8, deadzone: f64, ) -> Result { encode_sequence_with_ctx( pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder(), ) } pub fn encode_key_frame_at_size( picture: &Picture, frame_width: usize, frame_height: usize, base_q_idx: u8, deadzone: f64, ) -> Result { picture.check()?; if frame_width == 0 || frame_height == 0 || frame_width > picture.width || frame_height > picture.height { return Err(Error::unsupported( "AV1 encode", "the declared frame size must be nonzero and fit inside the padded picture", )); } let encoded = encode_key_frame_inner( picture, base_q_idx, deadzone, &KEY_FRAME_MODES, SPLIT_BLOCKS, (frame_width, frame_height), unspecified_color_config(), &crate::decode::FrameCtx::for_encoder(), (0, 0), )?; Ok(crop_encoded(&encoded, frame_width, frame_height)) } pub(crate) fn encode_key_frame_with_ctx( picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx, ) -> Result { encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx) } pub(crate) fn encode_key_frame_with_modes_with_ctx( picture: &Picture, base_q_idx: u8, deadzone: f64, modes: &[u8], fctx: &crate::decode::FrameCtx, ) -> Result { picture.check_even()?; let padded = picture.padded_to(BLOCK); let encoded = encode_key_frame_inner( &padded, base_q_idx, deadzone, modes, SPLIT_BLOCKS, (picture.width, picture.height), unspecified_color_config(), fctx, (0, 0), )?; Ok(crop_encoded(&encoded, picture.width, picture.height)) } pub(crate) fn encode_key_frame_inner( picture: &Picture, base_q_idx: u8, deadzone: f64, modes: &[u8], split_blocks: bool, render: (usize, usize), color_config: ColorConfig, fctx: &crate::decode::FrameCtx, tiles: (u32, u32), ) -> Result { fctx.interp_filter.set(mc::InterpFilterKind::Regular); picture.check()?; if modes.is_empty() { return Err(Error::unsupported( "AV1 encode", "a mode search needs at least one mode to choose from", )); } if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { return Err(Error::unsupported( "AV1 encode", format!("intra mode {bad} is not one the encoder predicts"), )); } let screen = screen_content( &picture.y.iter().map(|&v| v as u8).collect::>(), picture.width, (picture.width).min(render.0), (picture.height).min(render.1), ); crate::tile::arm_pricing_cdfs(None, false); let allow_intrabc = false; let (seq, mut header) = key_frame_headers_seq(render.0, render.1, base_q_idx, color_config, screen)?; header.allow_screen_content_tools = screen; header.reduced_tx_set = !wide_tx_set(screen); header.allow_intrabc = allow_intrabc; header.render_width = render.0 as u32; header.render_height = render.1 as u32; let tx_select = tx_select(); if tx_select { header.tx_mode = TxMode::Select; } let (tile_cols_log2, tile_rows_log2) = tiles; let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); fctx.seg_mi_dims.set(frame_mi_dims); let picture_y8: Vec = picture.y.iter().map(|&v| v as u8).collect(); let picture_u8: Vec = picture.u.iter().map(|&v| v as u8).collect(); let picture_v8: Vec = picture.v.iter().map(|&v| v as u8).collect(); let (mut luma, mut chroma) = fresh_frame_planes( picture, [&picture_y8, &picture_u8, &picture_v8], true_width, true_height, ); let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; let search = Search { base_q_idx, deadzone, lambda: LAMBDA_SCALE * KEY_LAMBDA_FACTOR * step * step, modes, top_k: prune_top_k(), screen, arf_leaf_intra: true, arf_leaf8: true, arf_leaf_compound: true, }; let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); let (cols, rows) = (cols as usize, rows as usize); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); let layout = crate::tile::TileLayout::new( header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2, ); header.tile_info = tile_info_of(&layout, 1); let header_tile_info = header.tile_info.clone(); let (frame_width, frame_height) = (picture.width, picture.height); let search_tile = |index: usize, fctx: &crate::decode::FrameCtx| -> Result<(crate::encode::SbSet, TilePixels)> { crate::tile::arm_pricing_cdfs(None, false); let rect = layout.rect(index); let mut luma = fresh_plane( &picture_y8, frame_width, frame_height, true_width, true_height, ); let mut chroma = [ fresh_plane( &picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2, ), fresh_plane( &picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2, ), ]; clip_planes_to_tile(&mut luma, &mut chroma, rect); let mut above_mode = vec![DC_PRED; cols * 2]; let mut left_mode = vec![DC_PRED; rows * 2]; let mut ibc = allow_intrabc.then(|| { Ibc::new( ( rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4, (rect.mi_col1 as usize * 4).min(true_width), (rect.mi_row1 as usize * 4).min(true_height), ), &picture_y8, frame_width, ) }); let mut coded: Vec<(usize, Superblock, Vec)> = Vec::new(); for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { let mut modes = Vec::with_capacity(4); let mut blocks = Vec::with_capacity(4); let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK); let whole_inside = x64 + SUPERBLOCK <= luma.true_width && y64 + SUPERBLOCK <= luma.true_height; let edge_inside = true && crate::tile::has_half( sb_col as u32 * crate::tile::SB_MI, crate::tile::SB_MI, header.mi_cols, ) && crate::tile::has_half( sb_row as u32 * crate::tile::SB_MI, crate::tile::SB_MI, header.mi_rows, ); let sb64_legal = i64_root() && ibc.is_none() && sb_row * 2 + 1 < rows && sb_col * 2 + 1 < cols && (whole_inside || edge_inside); let mut sb64: Option<(f64, BlockCoeffs, crate::encode::CoefPlanes)> = None; if sb64_legal { I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); let (c64, r64) = (sb_col * 4, sb_row * 4); let (block, cost) = code_square( &mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &search, &mode_bits(above_mode[c64], left_mode[r64]), tx_select, None, fctx, ); let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false); let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base); sb64 = Some((cost, block, after)); } let early64 = sb64.as_ref().is_some_and(|(c, _, _)| { split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda) }); let mut sb_cost = match sb64 { Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true), None => 0.0, }; for quadrant in 0..if early64 { 0 } else { 4 } { let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); if col >= cols || row >= rows { continue; } let (x, y) = (col * BLOCK, row * BLOCK); let (c0, r0) = (col * 2, row * 2); let base = snapshot(&luma, &chroma, (x, y), BLOCK); let (has_cols32, has_rows32) = ( crate::tile::has_half( col as u32 * crate::tile::BLOCK_MI, crate::tile::BLOCK_MI, header.mi_cols, ), crate::tile::has_half( row as u32 * crate::tile::BLOCK_MI, crate::tile::BLOCK_MI, header.mi_rows, ), ); let whole_legal = has_cols32 && has_rows32; let sub_half = |sr: usize, sc: usize| { ( crate::tile::has_half( sc as u32 * crate::tile::SUB_MI, crate::tile::SUB_MI, header.mi_cols, ), crate::tile::has_half( sr as u32 * crate::tile::SUB_MI, crate::tile::SUB_MI, header.mi_rows, ), ) }; let (whole, mut cost_whole) = code_square( &mut luma, &mut chroma, (x, y), BLOCK, &search, &mode_bits(above_mode[c0], left_mode[r0]), tx_select, ibc.as_mut(), fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); let mut split = Vec::with_capacity(4); let mut cost_split = search.lambda * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); let mut split_modes = Vec::with_capacity(4); for sub in 0..4 { let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols { continue; } let (has_cols16, has_rows16) = sub_half(sr, sc); if has_cols16 && has_rows16 { let (block, cost) = code_square( &mut luma, &mut chroma, (x + (sub % 2) * SUB, y + (sub / 2) * SUB), SUB, &search, &mode_bits(above_mode[sc], left_mode[sr]), tx_select, ibc.as_mut(), fctx, ); cost_split += cost; split_modes.push(block.mode); above_mode[sc] = block.mode; left_mode[sr] = block.mode; split.push(block); } else { let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); let mut leaves = Vec::with_capacity(2); for i in 0..4 { let leaf_x = x_sub + (i % 2) * 8; let leaf_y = y_sub + (i / 2) * 8; if leaf_x >= luma.true_width || leaf_y >= luma.true_height { continue; } let (leaf, cost) = code_square( &mut luma, &mut chroma, (leaf_x, leaf_y), 8, &search, &leaf_mode_bits, tx_select, None, fctx, ); cost_split += cost; split_modes.push(leaf.mode); leaves.push(leaf); } split.push(BlockCoeffs { eight: Some(leaves), ..BlockCoeffs::default() }); } } if !whole_legal || (split_blocks && cost_split < cost_whole) { sb_cost += cost_split; modes.extend_from_slice(&split_modes); blocks.push(Quadrant::Split(split)); } else { sb_cost += cost_whole; restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); for cell in 0..2 { above_mode[c0 + cell] = whole.mode; left_mode[r0 + cell] = whole.mode; } modes.push(whole.mode); blocks.push(Quadrant::Whole(whole)); } } let index = sb_row * sb_cols + sb_col; match sb64 { Some((cost64, block, after)) if early64 || cost64 < sb_cost => { restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after); for cell in 0..4 { above_mode[sb_col * 4 + cell] = block.mode; left_mode[sb_row * 4 + cell] = block.mode; } I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); if !whole_inside { I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } let mode = block.mode; coded.push((index, Superblock::Whole(block), vec![mode])); } _ => coded.push((index, Superblock::Split(blocks), modes)), } } } let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); let luma_rect = (x0, y0, x1, y1); let chroma_rect = (x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); let pixels = TilePixels { luma_rect, chroma_rect, luma: take_rect(&luma.reconstruction, frame_width, luma_rect), chroma: [ take_rect(&chroma[0].reconstruction, frame_width / 2, chroma_rect), take_rect(&chroma[1].reconstruction, frame_width / 2, chroma_rect), ], }; Ok((coded, pixels)) }; let searched = search_tiles(layout.count(), fctx, search_tile)?; let mut searched_coded = Vec::with_capacity(searched.len()); for (coded, pixels) in searched { put_rect( &mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma, ); for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) { put_rect( &mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes, ); } searched_coded.push(coded); } let searched = searched_coded; let mut in_order: Vec)>> = (0..sb_cols * sb_rows).map(|_| None).collect(); for (at, superblock, block_modes) in searched.into_iter().flatten() { in_order[at] = Some((superblock, block_modes)); } let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); let mut modes = Vec::with_capacity(cols * rows); for slot in in_order { let (superblock, block_modes) = slot.expect("every superblock belongs to a tile"); superblocks.push(superblock); modes.extend_from_slice(&block_modes); } #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits_sb( &superblocks, base_q_idx, )); let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); cdfs.reduced_tx_set = header.reduced_tx_set; let start_cdfs = CdfSnapshot(cdfs); let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; let code_tiles = |bits: u8, sb_cols: usize, grid: &[u8], units: &[Option]| -> Result>> { let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); crate::tile::arm_sb128(SB128_DEFAULT); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); crate::tile::arm_frame_mi_dims(frame_mi_dims); crate::tile::arm_filter_intra(filter_intra_on()); crate::tile::arm_intrabc(allow_intrabc); crate::tile::arm_pricing_cdfs(None, false); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, &superblocks, tx_select, &mut cdfs, layout.rect(index), )?; Ok((bytes, None)) })?; Ok(out) }; let mut tiles = code_tiles(0, sb_cols, &[], &[])?; pick_and_apply_filters( &mut header, &mut luma, &mut chroma, [&picture_y8, &picture_u8, &picture_v8], !allow_intrabc, &mut tiles, search.lambda, fctx, &[], |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |lf, cdef, h, tiles: &[Vec], lr| { let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); crate::decode::decode_key_frame_tiles_lr( &payloads, &header_tile_info, h.mi_cols, h.mi_rows, base_q_idx, h.frame_width, h.frame_height, seq.enable_filter_intra, cdef, lf, tx_select, h.reduced_tx_set, h.allow_screen_content_tools, h.allow_intrabc, lr, fctx, ) }, )?; let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); header.tile_info.tile_size_bytes = tile_size_bytes; let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq)?); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); let [u, v] = chroma; Ok(Encoded { stream, modes, inter_block_share: 0.0, reconstruction: Picture { width: luma.width, height: luma.height, y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), }, tile, mi_cols: header.mi_cols, mi_rows: header.mi_rows, base_q_idx, tx_select, switchable_motion_mode: false, screen, reduced_tx_set: header.reduced_tx_set, next_cdfs: Box::new(start_cdfs.clone()), start_cdfs: Box::new(start_cdfs), loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, allow_intrabc, delta: header.delta, }) } pub(super) fn pick_and_apply_filters( header: &mut FrameHeader, luma: &mut Plane<'_>, chroma: &mut [Plane<'_>; 2], source: [&[u8]; 3], search: bool, tiles: &mut Vec>, lambda: f64, fctx: &crate::decode::FrameCtx, cdef_owner: &[u32], recode: impl Fn(u8, usize, &[u8], &[Option]) -> Result>>, decode: impl Fn( &LoopFilterParams, &CdefParams, &FrameHeader, &[Vec], &LoopRestorationParams, ) -> Result, ) -> Result<()> { if !search { return Ok(()); } let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); let hdr = header.clone(); let damping = 3 + (header.quantization.base_q_idx >> 6); let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); let none_lr = LoopRestorationParams::default(); crate::decode::clear_filter_replay(); let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); let ft = crate::par::timer(crate::par::S_FILTER); let search_result = crate::filter_search::pick_filters( |lf, cdef| { if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { return Ok(picture); } crate::decode::arm_filter_replay(); let _t = crate::par::timer(crate::par::S_FIRST); decode(lf, cdef, &hdr, tiles, &none_lr) }, source, luma.width, (fw, fh), damping, (sb_cols, sb_rows), lambda, cdef_owner, ); drop(ft); let (lf, cdef, idx_grid, picture) = search_result?; header.loop_filter = lf; header.cdef = cdef; let lr_on = restoration_enabled(); if !idx_grid.is_empty() { *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?; } let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx); #[cfg(test)] let replay_was_used = replayed.is_some(); let (mut filtered, mut stages) = match replayed { Some((picture, stages)) => (picture, stages), None => { fctx.capture_stages.set(lr_on); let picture = if idx_grid.is_empty() && !lr_on { picture } else { let _t = crate::par::timer(crate::par::S_CAPTURE); decode(&lf, &cdef, &hdr, tiles, &none_lr)? }; fctx.capture_stages.set(false); (picture, crate::decode::take_filter_stages(fctx)) } }; #[cfg(test)] if crate::decode::verify_final_replay() && replay_was_used { fctx.capture_stages.set(lr_on); let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?; fctx.capture_stages.set(false); let want_stages = crate::decode::take_filter_stages(fctx); assert!( (want.width, want.height) == (filtered.width, filtered.height) && want.y == filtered.y && want.u == filtered.u && want.v == filtered.v, "the final filter replay is not the capture decode it stands in for", ); let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| { for row in 0..h { let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]); assert!( x == y, "{what}: the replayed filter stages are not the ones the capture \ decode returns (row {row} of {h}, width {w}, stride {stride})", ); } }; match (&want_stages, &stages) { (Some(a), Some(b)) => { assert_eq!(a.stride, b.stride, "the captured plane strides moved"); let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() { region( &a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked", ); region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed"); } } (None, None) => {} _ => panic!("one path captured filter stages and the other did not"), } } let mut lr = LoopRestorationParams::default(); if lr_on { let unit = lr_unit(); let mut want = LoopRestorationParams { loop_restoration_size: [unit, unit, unit], uses_lr: true, lr_unit_shift: u8::from(unit == 128), ..LoopRestorationParams::default() }; want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; let lrt = crate::par::timer(crate::par::S_LR); let units = match stages.take() { Some(stages) => crate::filter_search::pick_restoration( &stages, source[0], luma.width, (fw, fh), &want, lambda, fctx, ), None => Vec::new(), }; drop(lrt); if units.iter().any(Option::is_some) { let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; let _t = crate::par::timer(crate::par::S_CAPTURE); match crate::decode::replay_restoration(&want, &units, fctx) { Some(y) => { #[cfg(test)] let margin = fctx .last_frame_wide_margin .borrow() .as_ref() .map(|p| p.y.clone()); #[cfg(test)] if crate::decode::verify_final_replay() { let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?; assert!( (want_pic.width, want_pic.height) == (filtered.width, filtered.height) && want_pic.u == filtered.u && want_pic.v == filtered.v, "the restoration replay moved a chroma plane or the picture size", ); assert!( want_pic.y == y, "the restoration replay is not the decode of the re-coded tile", ); assert!( (fctx .last_frame_wide_margin .borrow() .as_ref() .map(|p| p.y.clone())) == margin, "the restoration replay's wide-margin luma is not the decode's", ); } filtered.y = y; } None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?, } *tiles = coded; lr = want; } } crate::decode::clear_filter_replay(); header.loop_restoration = lr; let dec_cw = filtered.width.div_ceil(2); let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); crate::filter_search::splice( &mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh, ); crate::filter_search::splice( &mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch, ); crate::filter_search::splice( &mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch, ); Ok(()) } pub(super) const SIZE_GROUP_32: usize = 3; pub(super) const LAST_FRAME: i8 = 1; pub(super) fn inter_mode_bits() -> [f64; 13] { std::array::from_fn(|mode| { let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) } else { 0.0 }; symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) }) } pub(super) fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } } pub(super) fn mv_class_base(class: usize) -> i32 { if class == 0 { 0 } else { 2i32 << (class + 2) } } pub(super) fn mv_class_of(z: i32) -> usize { let mut class = 0; while class < 10 && mv_class_base(class + 1) <= z { class += 1; } class } pub(super) fn mv_component_bits(diff: i32) -> Option { let hp_frame = crate::tile::high_precision_mv(); let mag = diff.unsigned_abs() as i32; let z = mag - 1; if !hp_frame && z & 1 == 0 { return None; } 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); let hp = (local & 1) as usize; if class == 0 { let bit = (local >> 3) & 1; let fr = (local >> 1) & 3; bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); if hp_frame { bits += symbol_bits(&cdf::MV_CLASS0_HP, hp); } } else { let d = local >> 3; let fr = (local >> 1) & 3; for i in 0..class { bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); } bits += symbol_bits(&cdf::MV_FR, fr as usize); if hp_frame { bits += symbol_bits(&cdf::MV_HP, hp); } } Some(bits) } pub(super) fn extra_ref_new_mv() -> bool { crate::speed::at(&crate::speed::EXTRA_REF_NEW) } pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] { let last = order_hint.wrapping_sub(1) & 0x7f; let alt = if has_altref { order_hint.wrapping_sub(2) & 0x7f } else { key_hint }; [last, last, last, key_hint, last, last, alt] } pub(crate) const REFERENCE_SELECT: bool = true; pub(crate) fn reference_select() -> bool { crate::speed::at(&crate::speed::COMPOUND) } pub(super) fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { let mut bits = 0.0; let mut idx = start; while idx < start + 2 && stack.entries.len() > idx + 1 { let advance = idx < target; bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); if !advance { break; } idx += 1; } bits } pub(super) fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { let mut best: Option<(f64, u8)> = None; for idx in 0..3usize { if idx > 0 && stack.entries.len() <= idx { break; } let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); if let Some(b) = mv_residual_bits(mv, base) { let total = b + drl_bits_for(stack, 0, idx); if best.is_none_or(|(t, _)| total < t) { best = Some((total, idx as u8)); } } } best } pub(super) fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { let mut seeds = [(0, 0); 4]; let mut n = 1; for e in stack.entries.iter().take(3) { seeds[n] = e.mv; n += 1; } (seeds, n) } pub(super) fn ref_distance(ref_frame: i8) -> u32 { let (bits, order_hint, hints) = crate::tile::order_hints(); let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize; crate::motion_field::get_relative_dist(bits, order_hint, hints[i]) .unsigned_abs() .max(1) } pub(super) fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option { let diff = (mv.0 - pred.0, mv.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); for d in [diff.0, diff.1] { if d != 0 { bits += mv_component_bits(d)?; } } Some(bits) } pub(crate) const HP_MV_QTHRESH: u8 = 0; pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool { u16::from(base_q_idx) < u16::from(HP_MV_QTHRESH) } pub(super) fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { if crate::tile::high_precision_mv() { return mv; } let round = |m: i32, p: i32| { let diff = m - p; let mag = diff.unsigned_abs() as i32; let even = mag - mag % 2; if even == 0 { p } else { p + even * diff.signum() } }; (round(mv.0, pred.0), round(mv.1, pred.1)) } pub(super) fn mc_trial( plane: &Plane, x: usize, y: usize, side: usize, mv: (i32, i32), luma: bool, reference: &[u16], stride: usize, ref_width: usize, ref_height: usize, skip: bool, base_q_idx: u8, deadzone: f64, set: TxbSet, fctx: &crate::decode::FrameCtx, ) -> Trial { mc_trial_typed( plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx, deadzone, set, TxType::DctDct, fctx, ) } pub(super) fn mc_trial_typed( plane: &Plane, x: usize, y: usize, side: usize, mv: (i32, i32), luma: bool, reference: &[u16], stride: usize, ref_width: usize, ref_height: usize, skip: bool, base_q_idx: u8, deadzone: f64, set: TxbSet, tx_type: TxType, fctx: &crate::decode::FrameCtx, ) -> Trial { let x_q4 = mv_to_q4(x, mv.1, luma); let y_q4 = mv_to_q4(y, mv.0, luma); let mut prediction16 = [0u16; BLOCK * BLOCK]; let prediction16 = &mut prediction16[..side * side]; mc::predict( reference, stride, ref_width, ref_height, x_q4, y_q4, side, side, prediction16, fctx, ); let mut prediction = [0u8; BLOCK * BLOCK]; let prediction = &mut prediction[..side * side]; for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { *dst = src as u8; } plane.code_from_prediction_typed( x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type, ) } pub(super) fn mc_trial_compound( plane: &Plane, x: usize, y: usize, side: usize, mvs: ((i32, i32), (i32, i32)), luma: bool, ref0: (&[u16], usize, usize, usize), ref1: (&[u16], usize, usize, usize), base_q_idx: u8, deadzone: f64, set: TxbSet, fctx: &crate::decode::FrameCtx, ) -> Trial { mc_trial_compound_typed( plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx, ) } pub(super) fn mc_trial_compound_typed( plane: &Plane, x: usize, y: usize, side: usize, (mv0, mv1): ((i32, i32), (i32, i32)), luma: bool, ref0: (&[u16], usize, usize, usize), ref1: (&[u16], usize, usize, usize), base_q_idx: u8, deadzone: f64, set: TxbSet, tx_type: TxType, fctx: &crate::decode::FrameCtx, ) -> Trial { let mut inter0 = [0i32; BLOCK * BLOCK]; let mut inter1 = [0i32; BLOCK * BLOCK]; let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { mc::predict_compound_intermediate( r.0, r.1, r.2, r.3, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), mc::RefScale::UNSCALED, side, side, fctx.interp_filter.get(), fctx.interp_filter.get(), dst, fctx, ); } let mut blended16 = [0u16; BLOCK * BLOCK]; let blended16 = &mut blended16[..side * side]; mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); let mut prediction = [0u8; BLOCK * BLOCK]; let prediction = &mut prediction[..side * side]; for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { *dst = src as u8; } plane.code_from_prediction_typed( x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type, ) } pub(super) fn predict_u8( reference: &[u16], stride: usize, ref_width: usize, ref_height: usize, (x, y): (usize, usize), side: usize, mv: (i32, i32), luma: bool, fctx: &crate::decode::FrameCtx, ) -> Vec { let mut prediction = vec![0u16; side * side]; mc::predict( reference, stride, ref_width, ref_height, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), side, side, &mut prediction, fctx, ); prediction.iter().map(|&v| v as u8).collect() } pub(super) fn predict_compound_u8( ref0: (&[u16], usize, usize, usize), ref1: (&[u16], usize, usize, usize), (x, y): (usize, usize), side: usize, (mv0, mv1): ((i32, i32), (i32, i32)), luma: bool, fctx: &crate::decode::FrameCtx, ) -> Vec { let mut inter = [vec![0i32; side * side], vec![0i32; side * side]]; for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) { mc::predict_compound_intermediate( r.0, r.1, r.2, r.3, mv_to_q4(x, mv.1, luma), mv_to_q4(y, mv.0, luma), mc::RefScale::UNSCALED, side, side, fctx.interp_filter.get(), fctx.interp_filter.get(), dst, fctx, ); } let mut blended = vec![0u16; side * side]; mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx); blended.iter().map(|&v| v as u8).collect() } pub(super) fn search_root_128( luma: &mut Plane, chroma: &mut [Plane; 2], grid: &crate::mvstack::MiGrid, (root_r, root_c): (usize, usize), (rows, cols): (usize, usize), (mi_cols, mi_rows): (u32, u32), search: Search<'_>, tpl_factors: &Option>, sb_q: Option<&Vec>, sb_cols: usize, tpl_cells_x: usize, base_q_idx: u8, dq_res: i32, reference: &Picture, compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> Option<(f64, f64, BlockCoeffs, crate::encode::CoefPlanes)> { const SIDE: usize = SUPERBLOCK * 2; const SIDE_MI: usize = SIDE / 4; let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); let (mi_row, mi_col) = (root_r * 16, root_c * 16); if root_r * 2 + 3 >= rows || root_c * 2 + 3 >= cols || (mi_row + SIDE_MI) as u32 > mi_rows || (mi_col + SIDE_MI) as u32 > mi_cols || x128 + SIDE > luma.true_width || y128 + SIDE > luma.true_height { return None; } let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, (None, Some(f)) => { let mean = (0..16) .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) .sum::() / 16.0; search.lambda * mean } (None, None) => search.lambda, }; let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] .iter() .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) .sum::() / 4.0; let root_search = Search { lambda, ..match sb_q { Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), None => search, } }; let stack = find_mv_stack( grid, mi_row, mi_col, SIDE_MI, SIDE_MI, LAST_FRAME, mi_cols as usize, mi_rows as usize, ); let base = snapshot(luma, chroma, (x128, y128), SIDE); let found = search_skip_64( luma, chroma, (x128, y128), (SIDE, SIDE), &root_search, false, reference, &stack, compound, fctx, ); let (cost, block) = found?; let after = snapshot(luma, chroma, (x128, y128), SIDE); restore(luma, chroma, (x128, y128), SIDE, &base); let dq = if block.skip { 0.0 } else { delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)) }; Some(( cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq), lambda, block, after, )) } pub(super) fn search_root_128_rect( luma: &mut Plane, chroma: &mut [Plane; 2], grid: &mut crate::mvstack::MiGrid, (root_r, root_c): (usize, usize), (rows, cols): (usize, usize), (mi_cols, mi_rows): (u32, u32), search: Search<'_>, tpl_factors: &Option>, sb_q: Option<&Vec>, sb_cols: usize, tpl_cells_x: usize, base_q_idx: u8, dq_res: i32, reference: &Picture, compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], horz: bool, fctx: &crate::decode::FrameCtx, ) -> Option<(f64, f64, [BlockCoeffs; 2], crate::encode::CoefPlanes)> { const SIDE: usize = SUPERBLOCK * 2; const SIDE_MI: usize = SIDE / 4; let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); let (mi_row, mi_col) = (root_r * 16, root_c * 16); if root_r * 2 + 3 >= rows || root_c * 2 + 3 >= cols || (mi_row + SIDE_MI) as u32 > mi_rows || (mi_col + SIDE_MI) as u32 > mi_cols || x128 + SIDE > luma.true_width || y128 + SIDE > luma.true_height { return None; } let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, (None, Some(f)) => { let mean = (0..16) .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) .sum::() / 16.0; search.lambda * mean } (None, None) => search.lambda, }; let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] .iter() .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) .sum::() / 4.0; let root_search = Search { lambda, ..match sb_q { Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), None => search, } }; let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) }; let (w_mi, h_mi) = (w / 4, h / 4); let base = snapshot(luma, chroma, (x128, y128), SIDE); let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI); let mut cost = 0.0f64; let mut halves: Vec = Vec::with_capacity(2); for i in 0..2usize { let (mr, mc) = if horz { (mi_row + i * 16, mi_col) } else { (mi_row, mi_col + i * 16) }; let stack = find_mv_stack( grid, mr, mc, w_mi, h_mi, LAST_FRAME, mi_cols as usize, mi_rows as usize, ); let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound .iter() .map(|&(r, pic, _)| { ( r, pic, crate::mvstack::find_mv_stack_compound( grid, mr, mc, w_mi, h_mi, (LAST_FRAME, r), mi_cols as usize, mi_rows as usize, grid.sign_bias_table(), &[(0, 0); 7], None, ), ) }) .collect(); let found = search_skip_64( luma, chroma, (mc * 4, mr * 4), (w, h), &root_search, false, reference, &stack, &half_compound, fctx, ); match found { Some((c, block)) => { cost += c; record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip); halves.push(block); } None => { restore(luma, chroma, (x128, y128), SIDE, &base); grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); return None; } } } let after = snapshot(luma, chroma, (x128, y128), SIDE); restore(luma, chroma, (x128, y128), SIDE, &base); grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); let symbol = if horz { 1 } else { 2 }; let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?; let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)); Some(( cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq), lambda, [b0, b1], after, )) } pub(super) fn search_skip_64( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), (bw, bh): (usize, usize), search: &Search, residual: bool, reference: &Picture, stack: &MvStack, compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> Option<(f64, BlockCoeffs)> { debug_assert!( (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual, "only a 64 root has a residual arm" ); let sq = bw.min(bh); let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize) .flat_map(|plane| { let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) }; (0..bh / sq).flat_map(move |j| { (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0)) }) }) .collect(); let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits; let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode, mv, ref_mv_idx, }; let mut cands: Vec<(f64, InterInfo)> = vec![ ( not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), info_of(InterMode::NearestMv, stack.nearest_mv, 0), ), ( not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), info_of(InterMode::GlobalMv, (0, 0), 0), ), ]; let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); for idx in 1..=2usize { if let Some(e) = stack.entries.get(idx) { cands.push(( near_bits + drl_bits_for(stack, 1, idx), info_of(InterMode::NearMv, e.mv, idx as u8), )); } } let mut last_new_mv: Option<(i32, i32)> = None; if LEAF_NEW_MV { let source_block = luma.source_block_rect(x, y, bw, bh); let (seeds, seed_n) = mv_seeds(stack); let found = motion::search( &reference.y, reference.width, luma.true_width, luma.true_height, &source_block, x, y, bw, bh, stack.pred_mv, &seeds[..seed_n], search.lambda, fctx, 1, ); let mv = round_to_valid_mv(found.mv, stack.pred_mv); if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { last_new_mv = Some(mv); cands.push(( symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits), info_of(InterMode::NewMv, mv, ref_mv_idx), )); } } let mut best: Option<(f64, f64, InterInfo, Vec)> = None; for (bits, info) in cands { let trials: Vec = units .iter() .map(|&(plane, px, py, s, is_luma)| { let (samples, stride, w, h) = match plane { 0 => ( &reference.y, reference.width, luma.true_width, luma.true_height, ), 1 => ( &reference.u, reference.width / 2, chroma[0].true_width, chroma[0].true_height, ), _ => ( &reference.v, reference.width / 2, chroma[1].true_width, chroma[1].true_height, ), }; let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx); let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; target.code_from_prediction( px, py, s, &prediction, true, search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, ) }) .collect(); let cost = trials.iter().map(|t| t.sse).sum::() + search.lambda * (fixed + bits); if best.as_ref().is_none_or(|b| cost < b.0) { best = Some((cost, fixed + bits, info, trials)); } } for (ref1, g, cstack) in compound.iter().filter(|_| b64_root()) { 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 compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo { ref1: Some(ref1), mv1: mvs.1, ref_frame: crate::mvstack::LAST_FRAME, mode, mv: mvs.0, ref_mv_idx: 0, }; let mut ccands: crate::encode::CompCands = vec![ ( cstack.nearest_mv, mode_bits_of(0), compound_info(InterMode::NearestNearestMv, cstack.nearest_mv), ), ( ((0, 0), (0, 0)), mode_bits_of(6), compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))), ), ]; let cbase = cstack .entries .first() .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); if let Some(new_mv) = last_new_mv && let Some(b0) = mv_residual_bits(new_mv, cbase.0) { let mvs = (new_mv, cstack.nearest_mv.1); ccands.push(( mvs, mode_bits_of(3) + b0, compound_info(InterMode::NewNearestMv, mvs), )); } ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); ccands.dedup_by_key(|c| c.0); for (mvs, bits, info) in ccands { let trials: Vec = units .iter() .map(|&(plane, px, py, s, is_luma)| { let (r0, r1) = match plane { 0 => ( ( reference.y.as_slice(), reference.width, luma.true_width, luma.true_height, ), (g.y.as_slice(), g.width, luma.true_width, luma.true_height), ), 1 => ( ( reference.u.as_slice(), reference.width / 2, chroma[0].true_width, chroma[0].true_height, ), ( g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height, ), ), _ => ( ( reference.v.as_slice(), reference.width / 2, chroma[1].true_width, chroma[1].true_height, ), ( g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height, ), ), }; let prediction = predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx); let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; target.code_from_prediction( px, py, s, &prediction, true, search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, ) }) .collect(); let syntax = fixed - ref_bits + bits; let cost = trials.iter().map(|t| t.sse).sum::() + search.lambda * syntax; if best.as_ref().is_none_or(|b| cost < b.0) { best = Some((cost, syntax, info, trials)); } } } let (skip_cost, syntax, info, skip_trials) = best?; let mut chosen = (skip_cost, true, skip_trials); let mut luma_committed = false; let mut luma_levels: Option<(Vec, u8, Vec)> = None; if residual { let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; let residual_trials = [0usize, 1, 2].map(|plane| { let (target, px, py, s) = if plane == 0 { (&*luma, x, y, bw) } else { (&chroma[plane - 1], x / 2, y / 2, bw / 2) }; target.code_from_prediction( px, py, s, &chosen.2[plane].reconstruction, false, search.base_q_idx, search.deadzone, sets[plane], ) }); let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true); let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum(); let (levels, depth, gain, tx_types) = if b64_root() { let second = info.ref1.and_then(|r1| { compound .iter() .find(|(r, _, _)| *r == r1) .map(|&(_, g, _)| { ( info.mv1, (g.y.as_slice(), g.width, luma.true_width, luma.true_height), ) }) }); luma_committed = true; commit_inter_luma( luma, (x, y), bw, info.mv, ( &reference.y, reference.width, luma.true_width, luma.true_height, ), search, &residual_trials[0], false, second, fctx, ) } else { (residual_trials[0].levels.clone(), 0, 0.0, Vec::new()) }; let cost = residual_trials.iter().map(|t| t.sse).sum::() + search.lambda * (syntax + unskip + coeff_bits) + gain; if cost < skip_cost { B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); if depth == 1 { B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } luma_levels = Some((levels, depth, tx_types)); chosen = (cost, false, residual_trials.to_vec()); } } let (cost, skip, trials) = chosen; for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) { match plane { 0 if skip || !luma_committed => luma.commit(px, py, s, trial), 0 => {} _ => chroma[plane - 1].commit(px, py, s, trial), } } Some(( cost, BlockCoeffs { skip, inter: Some(info), tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d), luma_tx_types: match (skip, &luma_levels) { (false, Some((_, _, types))) => types.clone(), _ => Vec::new(), }, luma: match (skip, &luma_levels) { (true, _) => Vec::new(), (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK), (false, Some((levels, _, _))) => coeffs(levels, BLOCK), (false, None) => coeffs(&trials[0].levels, BLOCK), }, u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) }, v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) }, ..BlockCoeffs::default() }, )) } pub(super) fn search_inter_block( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), search: &Search, mode_bits: &[f64; 13], reference: &Picture, stack: &MvStack, extra: &[(i8, &Picture, &MvStack)], compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], grid: &MiGrid, (mi_row, mi_col): (usize, usize), (mi_rows, mi_cols): (usize, usize), fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx); let skip_bits = |skip: bool| skip_bits_at(stack, skip); let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter); struct Candidate { cost: f64, luma: Trial, u: Trial, v: Trial, mode: u8, skip: bool, inter: Option, mode_bits: f64, } let mut best: Option = None; let mut consider = |candidate: Candidate| { if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { best = Some(candidate); } }; let u_trial = chroma[0].trial( At { x: x / 2, y: y / 2, side: BLOCK / 2, reach: Reach::none(), set: chroma_set, }, DC_PRED, 0, search.base_q_idx, search.deadzone, fctx, ); let v_trial = chroma[1].trial( At { x: x / 2, y: y / 2, side: BLOCK / 2, reach: Reach::none(), set: chroma_set, }, DC_PRED, 0, search.base_q_idx, search.deadzone, fctx, ); let intra_modes: Vec = match search.top_k { Some(k) if k < search.modes.len() => { let scored = luma.intra_scores( At { x, y, side: BLOCK, reach, set: luma_set, }, search.modes, mode_bits, search.lambda, fctx, ); prune_by_sad(search.modes, scored, k) } _ => search.modes.to_vec(), }; if search.arf_leaf_intra { for &mode in &intra_modes { let luma_trial = luma.trial( At { x, y, side: BLOCK, reach, set: luma_set, }, mode, 0, search.base_q_idx, search.deadzone, fctx, ); let u = u_trial.clone(); let v = v_trial.clone(); let cost = luma_trial.sse + u.sse + v.sse + search.lambda * (luma_trial.bits + u.bits + v.bits + mode_bits[usize::from(mode)] + skip_bits(false) + intra_inter_bits(false)); consider(Candidate { cost, luma: luma_trial, u, v, mode, skip: false, inter: None, mode_bits: mode_bits[usize::from(mode)], }); } } else { arfmode_hit(0); } 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 not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ ( stack.nearest_mv, last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: stack.nearest_mv, ref_mv_idx: 0, }, ), ( (0, 0), last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::GlobalMv, mv: (0, 0), ref_mv_idx: 0, }, ), ]; let near_bits = last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); for idx in 1..=2usize { if let Some(e) = stack.entries.get(idx) { cands.push(( e.mv, near_bits + drl_bits(1, idx), InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearMv, mv: e.mv, ref_mv_idx: idx as u8, }, )); } } let source_block = luma.source_block(x, y, BLOCK); let (seeds, seed_n) = mv_seeds(stack); #[cfg(test)] let t = stage_start(); let found = motion::search( ref_luma.0, ref_luma.1, ref_luma.2, ref_luma.3, &source_block, x, y, BLOCK, BLOCK, stack.pred_mv, &seeds[..seed_n], search.lambda, fctx, 1, ); #[cfg(test)] stage_since(0, t); let mv = round_to_valid_mv(found.mv, stack.pred_mv); if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { cands.push(( mv, last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits), InterInfo { ref1: None, mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv, ref_mv_idx, }, )); } let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); for &(ref_frame, g, gstack) in extra { let g_ref_bits = single_ref_bits(ref_frame, gstack); let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); cands.push(( gstack.nearest_mv, g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), InterInfo { ref1: None, mv1: (0, 0), ref_frame, mode: InterMode::NearestMv, mv: gstack.nearest_mv, ref_mv_idx: 0, }, )); cands.push(( (0, 0), g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), InterInfo { ref1: None, mv1: (0, 0), ref_frame, mode: InterMode::GlobalMv, mv: (0, 0), ref_mv_idx: 0, }, )); let searched = extra_ref_new_mv(); let margin = EXTRA_NEW_SKIP_MARGIN; let skip_search = searched && margin > 0.0 && motion::cost_at( &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, BLOCK, BLOCK, gstack.nearest_mv, gstack.pred_mv, search.lambda, fctx, ) * margin <= found.cost; if searched && !skip_search { let (gseeds, gn) = mv_seeds(gstack); #[cfg(test)] let t = stage_start(); let gfound = motion::search( &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, BLOCK, BLOCK, gstack.pred_mv, &gseeds[..gn], search.lambda, fctx, ref_distance(ref_frame), ); #[cfg(test)] stage_since(0, t); let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); extra_new_mvs.push((ref_frame, gmv)); if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { cands.push(( gmv, g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, InterInfo { ref1: None, mv1: (0, 0), ref_frame, mode: InterMode::NewMv, mv: gmv, ref_mv_idx, }, )); } } } let half_new = true; for (ref1, g, cstack) in 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)); if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) { ccands.push(( (mv, cstack.nearest_mv.1), mode_bits_of(3) + b0, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewNearestMv, mv, mv1: cstack.nearest_mv.1, ref1: Some(ref1), ref_mv_idx: 0, }, )); } if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) { 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, }, )); } let base = cbase; if let (Some(b0), Some(b1)) = (mv_residual_bits(mv, base.0), mv_residual_bits(mv1, base.1)) { ccands.push(( (mv, mv1), mode_bits_of(7) + b0 + b1, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewNewMv, 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_trial = mc_trial_compound( luma, x, y, BLOCK, mvs, true, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, ); let u = mc_trial_compound( &chroma[0], x / 2, y / 2, BLOCK / 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 = mc_trial_compound( &chroma[1], x / 2, y / 2, BLOCK / 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 = luma_trial.levels.iter().all(|&l| l == 0) && u.levels.iter().all(|&l| l == 0) && v.levels.iter().all(|&l| l == 0); let cost = luma_trial.sse + u.sse + v.sse + search.lambda * (skip_bits(skip) + intra_inter_bits(true) + bits + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); consider(Candidate { cost, luma: luma_trial, u, v, mode: DC_PRED, skip, mode_bits: bits, inter: Some(info), }); } } cands.sort_by(|a, b| { (a.2.ref_frame, a.0) .cmp(&(b.2.ref_frame, b.0)) .then(a.1.total_cmp(&b.1)) }); cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); for (mv, mode_bits_inter, info) in cands { let (ref_luma, ref_u, ref_v) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { Some(&(_, g, _)) => ( (&g.y, g.width, luma.true_width, luma.true_height), ( &g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height, ), ( &g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height, ), ), None => (ref_luma, ref_u, ref_v), }; let luma_trial = mc_trial( luma, x, y, BLOCK, mv, true, ref_luma.0, ref_luma.1, ref_luma.2, ref_luma.3, false, search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, ); let u = mc_trial( &chroma[0], x / 2, y / 2, BLOCK / 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, BLOCK / 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 cost = luma_trial.sse + u.sse + v.sse + search.lambda * (skip_bits(skip) + intra_inter_bits(true) + mode_bits_inter + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); consider(Candidate { cost, luma: luma_trial, u, v, mode: DC_PRED, skip, mode_bits: mode_bits_inter, inter: Some(info), }); } let best = best.expect("the search offers at least the intra modes"); let mut best = best; let mut motion_won = 0u8; if let Some(info) = best.inter.filter(|i| i.ref1.is_none() && warp_on()) { let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[LAST_FRAME as usize] = Some(reference); for &(r, p, _) in extra { refs[r as usize] = Some(p); } let planes: [(&[u16], usize, usize, usize); 3] = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { Some(&(_, g, _)) => [ (g.y.as_slice(), g.width, luma.true_width, luma.true_height), ( 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, ), ], None => [ (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, 8, 8, mi_cols, mi_rows, info.ref_frame, fctx, ) >= 1; let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, 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), BLOCK, info.mv, info.ref_frame, planes, fctx, ) { candidates.push((2, pred)); } for (motion, pred) in candidates { let luma_trial = luma.code_from_prediction( x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, ); let u = chroma[0].code_from_prediction( x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone, chroma_set, ); let v = chroma[1].code_from_prediction( x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone, chroma_set, ); 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 cost = luma_trial.sse + u.sse + v.sse + search.lambda * (skip_bits(skip) + intra_inter_bits(true) + best.mode_bits + mm(motion) + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); if cost < best.cost + search.lambda * mm(motion_won) { motion_won = motion; best = Candidate { cost, luma: luma_trial, u, v, mode: DC_PRED, skip, mode_bits: best.mode_bits, inter: best.inter, }; } } } let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) { Some(info) => { let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height), None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), }; let second = info.ref1.and_then(|r| { compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| { ( info.mv1, (g.y.as_slice(), g.width, luma.true_width, luma.true_height), ) }) }); match info.ref1.is_some() && second.is_none() { true => { luma.commit(x, y, BLOCK, &best.luma); (best.luma.levels.clone(), 0, 0.0, Vec::new()) } false => commit_inter_luma( luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second, fctx, ), } } None => { luma.commit(x, y, BLOCK, &best.luma); (best.luma.levels.clone(), 0, 0.0, Vec::new()) } }; let [bu, bv] = match ( best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied(), ) { (Some(info), Some(t)) => { let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { Some(&(_, g, _)) => ( ( 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, ), ), None => ( (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 sec = info.ref1.and_then(|r| { compound.iter().find(|(c, _, _)| *c == r).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, ), ], ) }) }); recode_inter_chroma( chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx, ) .unwrap_or([best.u, best.v]) } _ => [best.u, best.v], }; let best = Candidate { u: bu, v: bv, ..best }; chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); ( BlockCoeffs { luma_tx_types, angle_delta_y: 0, cfl_alphas: None, filter_intra: None, luma: coeffs(&levels, BLOCK), u: coeffs(&best.u.levels, BLOCK / 2), v: coeffs(&best.v.levels, BLOCK / 2), mode: best.mode, uv_mode: DC_PRED, skip: best.skip, inter: best.inter, motion_mode: motion_won, eight: None, dv: None, palette: None, palette_uv: None, tx_depth, }, best.cost + dcost, ) }