use super::cu_syntax::{InterPredIdc, PredictionUnit}; use super::motion_field::{PbMotion, SliceMotion, scale_mv, to32}; use super::rps::RefEntry; pub fn derive_amvp(src: &SliceMotion<'_>, pu: &PredictionUnit) -> PbMotion { let mut pred = [false; 2]; let mut ref_idx = [-1i8; 2]; let mut mv = [[0i16; 2]; 2]; for lx in 0..2 { let used = match pu.inter_pred_idc { InterPredIdc::PredL0 => lx == 0, InterPredIdc::PredL1 => lx == 1, InterPredIdc::PredBi => true, }; if !used { continue; } let r = pu.ref_idx[lx] as i8; let mvp = predictor(src, pu, lx, r, usize::from(pu.mvp_flag[lx])); pred[lx] = true; ref_idx[lx] = r; mv[lx] = [ wrap16(mvp[0] + pu.mvd[lx][0]), wrap16(mvp[1] + pu.mvd[lx][1]), ]; } PbMotion::new(pred, ref_idx, mv) } fn predictor( src: &SliceMotion<'_>, pu: &PredictionUnit, lx: usize, ref_idx: i8, flag: usize, ) -> [i32; 2] { let (x, y) = (pu.x as isize, pu.y as isize); let (w, h) = (pu.width as isize, pu.height as isize); let target = src.ref_entry(lx, ref_idx); let target_poc = target.map(|e| e.poc); let a = [src.neighbour(x - 1, y + h), src.neighbour(x - 1, y + h - 1)]; let b = [ src.neighbour(x + w, y - 1), src.neighbour(x + w - 1, y - 1), src.neighbour(x - 1, y - 1), ]; let is_scaled = a.iter().any(Option::is_some); let mv_a = if is_scaled { first_pass(src, &a, lx, target_poc).or_else(|| second_pass(src, &a, lx, target)) } else { first_pass(src, &b, lx, target_poc) }; let mv_b = if is_scaled { first_pass(src, &b, lx, target_poc) } else { second_pass(src, &b, lx, target) }; let mut list: Vec<[i32; 2]> = Vec::with_capacity(3); if let Some(mv) = mv_a { list.push(mv); } if let Some(mv) = mv_b && mv_a != Some(mv) { list.push(mv); } if list.len() < 2 { let (xp, yp) = (pu.x, pu.y); if let Some(mv) = src.temporal_mv(xp, yp, pu.width, pu.height, lx, ref_idx) { list.push(mv); } } list.resize(2, [0, 0]); list.get(flag).copied().unwrap_or([0, 0]) } fn first_pass( src: &SliceMotion<'_>, neighbours: &[Option], lx: usize, target_poc: Option, ) -> Option<[i32; 2]> { let target_poc = target_poc?; for m in neighbours.iter().flatten() { for list in [lx, 1 - lx] { if m.pred[list] && src.ref_poc(list, m.ref_idx[list]) == Some(target_poc) { return Some(to32(m.mv[list])); } } } None } fn second_pass( src: &SliceMotion<'_>, neighbours: &[Option], lx: usize, target: Option, ) -> Option<[i32; 2]> { let target = target?; for m in neighbours.iter().flatten() { for list in [lx, 1 - lx] { if !m.pred[list] { continue; } let Some(r) = src.ref_entry(list, m.ref_idx[list]) else { continue; }; if r.long_term != target.long_term { continue; } let mv = to32(m.mv[list]); if r.long_term || target.long_term { return Some(mv); } return Some(scale_mv(mv, src.cur_poc - r.poc, src.cur_poc - target.poc)); } } None } fn wrap16(v: i32) -> i16 { let u = v.rem_euclid(1 << 16); let signed = if u >= 1 << 15 { u - (1 << 16) } else { u }; signed as i16 }